SlideShare uma empresa Scribd logo
1 de 13
JAVA QUICKY
Data Structures Algorithms Concepts
Linked Lists Breadth First Search Bit Manipulation
Binary Trees Depth First Search Singleton Design Pattern
Tries Binary Search Factory Design Pattern
Stacks, Queues Merge Sort Memory (Stack vs Heap)
HEAPS (min, max) Quick Sort Recursion
Vectors / ArrayLists Tree Insert / Find … Big-O Time
Hash Tables
JAVA CORE CONCEPTS
1. Java concurrency in practice: http://jcip.net/
2. CONCURRENT CLASSES: CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet
3. Covariant Return Type
Covariant return type  return type may vary in direction of subclass.
Starting Java5 possible to override method by return type if subclass overrides any method whose return type is
Non-Primitive but it changes its return type to subclass type. Let's take a simple example:
class A {
A get() {return this;}
}
class B extends A {
B get() {return this;} // overloads – not overrides A::get ()
void message() {System.out.println("Welcome to covariant return type");}
public static void main(String args[]) {
new B().get().message();
}
}
Output: Welcome to covariant return type
4. Abstract Class
Abstract class = abstract concept = template. Can’t be instantiated. The subclasses implement methods.
May contain static data. Abstract methods  automatically abstract class and must be declared as such.
A class may be declared abstract even if it has no abstract methods  Prevents intances.
5. Interface vs Abstract class
Abstract class can have instance methods with default behavior. Interface only declares constants and instance
methods, no default behavior. An interface has all public members and no implementation. An abstract class is a
class which may have the usual flavors of class members (private, protected, etc.), but has some abstract
methods.
Feature Interface Abstract class
Multiple inheritance YES NO
Default implementation NO. Just signatures YES - complete or default impl that's
overloadable.
Access Modifiers NO YES
6. public, private, protected, default …
* public: Visible everywhere (across packages). Field visible only if class public
* private: Visible only to method of the class
* protected: Visible in package + subclasses – even subclasses in different package.
* default: What you get by. Visible within package.
7. static
Per class, not per object. Static members usable without instance.
Static methods = final, because overriding done based on the type of the object, and static metho ds are attached
to a class, not an object.
A static method in a super-class can be shadowed by another static method in a subclass, as long as the original
method was not declared final. However, you can't override a static method with a nonstatic method. Can't
change a static method into an instance method in a subclass.
8. Checked / UnChecked Exception
Checked = subclass or = Exception; not RuntimeException. Checked exception are those which the Java
compiler forces you to catch. e.g. IOException thrown by java.io.FileInputStream's read() method is a checked
Exceptions.
Unchecked exceptions are RuntimeException, Error, or their subclasses. With an unchecked exception,
compiler doesn't force client programmers to catch the exception or declare it in a throws clause. Client
programmers don’t know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by
String's charAt() method.
9. What's New in Java 1.5? (ie Java 5) http://www.cs.indiana.edu/classes/jett/sstamm/
1. Generics
2. For/in loop
3. Autoboxing/Unboxing
4. Typesafe Enums
5. Varargs
6. Static Import
7. Annotations (Metadata)
10.Serialization
Mechanism to save state of object by converting it to a byte stream
11.Serialize an object to a file
Implement interface Serializable. Pass instance to ObjectOutputStream which is connected to FileOutputStream.
12.Which methods of Serializable interface should I implement?
Has none.
13.Customize seralization
Implement Externalizable::readExternal and Externalizable::writeExternal.
14.When you serialize, what happens to object references within object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included
object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the
included objects are also serialized alongwith the original obect.
15.Serialization: Note this
All included (contained?) objects are also Serializable. If any of the objects is not serializable then it throws a
NotSerializableException.
16.Static fields during serialization
There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state
2. Base class fields are only handled if the base class itself is Serializable.
3. Transient fields.
17.If I want an object of my class to be thrown as an exception object, what should I do?
Extend from Exception or a subclass of it.
18.If you already inherit, can’t inherit also from “Exception” class!
19.Difference between 2 approaches to exception handling
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
20.Is it necessary that each try block must be followed by a catch block?
No – either “catch” or “finally” block.
21.If I write return at the end of the try block, will the finally block still execute?
Yes.
22.If I write System.exit (0); at the end of the try block, will the finally block still execute?
No in this case the finally block will not execute because when you say System.exit (0); the control immediately
goes out of the program, and thus finally never executes.
23.final, finally, and finalize
• final – declares a constant (like “const” in C++) or method can't be overridden.
• finally – finally block always executes when try block exits – even if unexpected exception occurs. Allows
localizing cleanup code accidentally bypassed by return / continue / break.
• finalize() – method helps garbage collector. Invoked before object is discarded by garbage collector, allowing
it to clean up its state.
24.Difference among String, StringBuffer, and StringBuilder?
 String = immutable; StringBuffer = mutable.
o int x=10; String s1 = “” + x;
o String s2 = Integer.toString(x);
o String s3 = String.valueOf(x);
 StringBuffer: thread-safe, has append(), insert().. Used when mutable char-strings needed.
Disadvantage is, all public methods are synchronized => slow.
 StringBuilder (JDK5+) is designed for single threaded => no sync => faster.
 http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html
25.Exceptions – note this
The Java Language Specification describes how try-catch-finally is executed. Having no catch is equivalent to not
having a catch able to catch the given Throwable.
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
o If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then
…(whatever)…
 But if the run-time type of V is not assignable to the parameter of any catch clause of the try
statement, then the finally block is executed. Then there is a choice:
* If the finally block completes normally, then the try statement completes abruptly because of a throw of
the value V.
* If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S
(and the throw of value V is discarded and forgotten).
26.Java: http://www.oracle.com/technetwork/topics/newtojava/overview/index.html
27.New loop syntax: for (T e : anArray)
28.Implementing hashCode
If a class overrides equals, it must override hashCode. When both overridden, equals and hashCode must use
the same set of fields. If two objects are equal, then their hashCode values must be equal as well. If object is
immutable, hashCode can be “cached” and “lazy initialized”
[http://www.javapractices.com/topic/TopicAction.do;jsessionid=FC37D716710D81A1F389AE39715B672C?Id=28].
29.Class loader searches $CLASSPATH for A.class, JIT compiling of .class byte-code files
30.javadoc processes comments of type /** ... */
31.Java: no stack objects, all on heap
32.Types (study more)
int, Integer
float, Float
Byte, Double
String - fixed length strings
StringBuffer - variable length strings
StringBuilder
int i = 4;
String s = String.valueOf(i); => s is "4"
int a = Integer.parseInt("4"); => a is 4
"blah" + "blah" => "blahblah"
BigDecimal - string rep for floats for DB storing
<anyObj>.toString()
Arrays cant specify size: Typename[] varname; => array. (Cant say Typename[3] varname)
Also, it just creates array object not elements; Typename[] varname; varname[i] = new Typename;
Out of bounds access: ArrayIndexOutOfBoundsException, Uninit access: NullPointerException
static final int version = 1; // same as "const int version=1;" in C++
33.Assignments make 2 variables refer to same object unlike in C++
34.To copy objects, define and use clone():
class Data implements Cloneable {
public int data = 0;
public Data(int d) { data = d; }
public Object clone() {
Data d = (Data) super.clone();
d.data = data;
return d;
}
}
...
Data a = new Data(1); // a.data is 1
Data b = new Data(2); // b.data is 2
b = a.clone(); // b.data and a.data are 1
a.data = 3; // b.data is 1, a.data is 3
35.JVM continues to execute threads until either of the following occurs:
1. exit method of class "Runtime" gets called and security manager has permitted exit operation.
2. All threads that are not daemon threads died, either by returning from call to run() or by throwing an exception
that propagates beyond run().
36.Two Java primitive types are equal (using the == operator) when they have the same value (e.g., "3 == 3").
However, two object variables are equal if and only if they refer to the same instantiated object--a "shallow"
comparison.
37.To perform a "deep" comparison, the convention is to define a method called equals(). You would rewrite Data
as:
class Data {
public int data = 0;
public Data(int d) { data = d; }
boolean equals(Data d) {
return data == d.data;
}
}
...
Data a = new Data(1);
Data b = new Data(1);
// a.equals(b) is true!!!!
38.Interfaces
o Interface defines protocol of communication between objects. Group of related methods with empty bodies.
o An interface definition contains method declarations or constant definitions.
o Class implementing interface _must_ implement _all_ methods of it.
o Interface can be used anywhere a type can be.
o public interface OperateCar extends Interface1, Interface2 {
int numWheels = 4;
void TurnRight(int startingSpeed, int endingSpeed, int radius);
…
}
o An interface can extend multiple interfaces (multiple “inheritance” not supported in Java).
o All methods in an interface are inherently public => Specifier omitted.
o Interface obviously can’t contain implementation bodies.
o All variables must be initialized and are all public static final.
39.Primitive data-types as objects and seamless conversions: java.lang.Number:
o Byte, Character, Short, Integer, Long, Float, Double, BigInteger, BigDecimal, AtomicInteger, AtomicLong
40.Java Generics: http://docs.oracle.com/javase/tutorial/java/generics/index.html
o There aren't multiple copies of the code--not in source, not in binary, not on disk and not in memory. Single copy
of a Java Generic.
o Even return types can be templatized: boolean same = Util.<Integer, String>compare(p1, p2);
o Bounded type parameters: public <U extends Number> void inspect(U u){ … }
o Multiple bounds: class D <T extends A & B & C> { … }
 Each bound is imposed
 If a bound is a class and other bounds interfaces, the class name must be first in list.
o http://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html
o Integer and Double are subclasses of Number. But, Box<Integer> and Box<Double> are not subtypes of
Box<Number>.
o In generic code, the question mark (?), called the wildcard, represents an unknown type.
 List<? extends String> list2 = new ArrayList<>();
o Bounded wildcards: To write the method that works on lists of Number and the subtypes of Number, such
as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more
restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the
latter matches a list of type Number or any of its subclasses.
o Unbounded wildcards: Consider the following method, printList:
public static void printList(List<Object> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}
The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of
Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they
are not subtypes of List<Object>. To write a generic printList method, use List<?>:
public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
o A lower bounded wildcard restricts unknown type to be a specific type or a super type of that type: List<?
super Integer> list;
o During the type erasure process, the Java compiler erases all type parameters and replaces each with its first
bound if the type parameter is bounded, or Object if the type parameter is unbounded.
o Type Erasure: Java compiler replaces unbounded type parameters with Object and bounded type parameters
with first bound: http://docs.oracle.com/javase/tutorial/java/generics/genTypes.html
o Compiler generated Bridge method to preserve polymorphism when type erasure causes compiler-unanticipated
problems.
o A reifiable type is a type whose type information is fully available at runtime. This includes primitives, non-
generic types, raw types, and invocations of unbound wildcards. Examples of non-reifiable types are
List<String> and List<Number>; the JVM cannot tell the difference between these types at runtime. They
cannot be used in an instanceof expression, for example, or as an element in an array.
41.Packages: To create a package put a package statement with its name at of every source file that contains the
types (classes, interfaces, enumerations, and annotation types) that you want to include in the package.
The package statement must be the first line in the source file. There can be only one package statement in each
source file, and it applies to all types in the file.
42.Once members of a package imported as “static”, they can be used without package name qualification:
import static java.lang.Math.*; // Use sparingly to maintain readability
double r = cos(PI * theta);
Otherwise:
import static java.lang.Math.PI;
double r = Math.cos(Math.PI * theta);
43.public abstract class Graphic { ... }
44.Lambda expressions: A lambda expression consists of:
o (a,b, c): comma-separated list of formal parameters enclosed in parentheses (You may omit the data type of the
parameters in a lambda expression. In addition, you may omit the parentheses if there is only one parameter)
o ->: the arrow 
o statement(s): a body consisting of single expression or a statement block. If single expression, Java returns its
value => don’t need “return” statement.
o {} – but no need of {} for void method.
o Examples:
 email -> System.out.println(email)
 IntegerMath addition = (a, b) -> a + b;
 IntegerMath subtraction = (a, b) -> a - b;
45.Difference between equals() method and == ?
== compares references. object.equals() compares values.
46.Steps in JDBC connection
While making a JDBC connection we go through the following steps :
Step 1 : Register the database driver by using :
Class.forName(" driver classs for that specific database" );
Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);
Step 3: Now Create a query using :
Statement stmt = Connection.Statement("select * from TABLE NAME");
Step 4 : Exceute the query :
stmt.exceuteUpdate();
47.Applet:
* Inherit from Applet class (no file IO, sockets, menu, lifecycle events)
* init() = ctor, start(), stop(), destroy()...dispose()...super.dispose()
* (1) extend JApplet, implement init(), start(), stop(), destroy().
o To deploy, make a JAR package and sign it.
o Launch using (1) JNLP or (2) specify applet launch properties in applet tag.
48.HTML embed applet like img: <applet code=AppletName.class width=w height=h> [<param K-V
params>]</applet>
49.Nested Class:
o Static Nested Classes: Can’t access other members of enclosing class
o Inner Classes: Can access other members of enclosing class even if private
o OuterClass.InnerClass innerObject = outerObject.new InnerClass();
o Shadowing: Inner class member with same name shadows outer class’s member.
 Refer to OuterClass.this.member
o Anonymous class: HelloWorld spanishGreeting = new HelloWorld() {
public void greet() {}
public static void main(String[] args) {}
}
50.Java Classloader is part of JRE that dynamically loads Java classes into JVM on demand. The Java run time
system does not need to know about files and file systems because of classloaders. Each Java class must be
loaded by a class loader. When JVM is started, three class loaders are used:
1. Bootstrap class loader: loads core Java libraries located in <JAVA_HOME>/jre/lib dir
2. Extensions class loader:
 loads code in extensions dirs (<JAVA_HOME>/jre/lib/ext) or dir specified by java.ext.dirs system
property
 Implemented by sun.misc.Launcher$ExtClassLoader class
3. System class loader:
 loads code found on java.class.path ($CLASSPATH env var)
 implemented by the sun.misc.Launcher$AppClassLoader class
JAVA MEMORY MANAGEMENT
51.Garbage collection
Identifies and discards objects no longer needed for resource reuse.
GC Roots = local vars, the Main thread, Static vars of main class
52.Finalization
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing
before the object is garbage collected.
53.Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object's finalize() method is
invoked and the object performs an operation which causes it to become accessible to reachable objects.
54.Garbage collector is a daemon thread that runs periodically to reclaim sets of objects. Uses a tree topology to find
recoverable objects. http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html
55.http://www.infoq.com/articles/Java_Garbage_Collection_Distilled,
http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html
56.REFERENCES – subclasses of java.lang.ref.Reference<T>
1) StrongReference – Regular reference: Foo f = new Foo();
2) WeakReference – Isn't strong enough to force referent to stay in memory => en-queued/cleared ASAP
class MyEntry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>
MyEntry<String,String> table = new MyEntry<>();
table = null; // And its probly gone…! Aggressively…
System.gc(); sleep(5000); // If table not dead yet, now for sure it’d be…
3) SoftReference – Like WeakReference but less aggressive => en-queued/cleared as late as possible – ie
either in next cycle of garbage collection or when VM is about to go out of memory => guaranteed cleared
before VM throws OutOfMemoryError…
Object obj = new Object();
SoftReference softRef = new SoftReference(obj /*, ReferenceQueue rq = new ReferenceQueue() */);
obj = null;
Object obj2(softRef.get());
if (obj2 == null) {
// => Garbage collector freed softRef referent!
}
4) PhantomReference – Can’t retrieve referent (get() returns null). Useful only as a signal to know when
referent is already finalized and en-queued in ReferenceQueue (after death!). Use when finalize() method is
not sensible.
public class ConnectionPhantomReference extends PhantomReference {
private DB db;
public ConnectionPhantomReference (Conn c) { db.open(c); … }
public void cleanup() { db.close(); }
}
// Create a daemon thread (Thread.setDaemon(true)) to handle ReferenceQueue<>
5) ReferenceQueue – Supply-able as second arg to ref-ctors. After referent collected, referent value itself en-
queued to supplied ReferenceQueue. This allows performing clean up operations on referent obj.
6) References on reference: https://weblogs.java.net/blog/2006/05/04/understanding-weak-references,
http://docs.oracle.com/javase/6/docs/api/java/lang/ref/Reference.html,
http://docs.oracle.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html,
http://neverfear.org/blog/view/150/Strong_Soft_Weak_and_Phantom_References_Java
57.-XX:GCTimeRatio=99 implies 1% GC time
58.–Xmx<n> is tuning parameter to set Max available heap size for an app; -Xms<n> sets initial heap size
59.Native_Memory = Process_Size – Max_Heap_Size – Max_Perm_Size
60.JAVA HEAP TERMINOLOGY: YOUNG, OLD, PERMANENT GENERATIONS
HotSpot JVM uses following memory-pools for serial garbage collection:
1. http://www.maths.lse.ac.uk/Courses/MA407/gcsurvey.pdf,
http://middlewaremagic.com/weblogic/?tag=young-generation,
http://openjdk.java.net/groups/hotspot/docs/StorageManagement.html,
http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf,
http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1168.pdf,
https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation
2. Young Generation / Eden Space (heap): Pool objects initially allocated into
3. Old Generation / Survivor Space (heap): Objects that survived garbage collection of Eden space
4. Tenured Generation (heap): Pool of objects existed for some time in Survivor space.
5. Permanent Generation (non-heap): Pool of reflective data of VM itself (class, method objects). With
VMs using class data sharing, this generation is divided into read-only and read-write areas.
6. Code Cache (non-heap): memory for compilation and storage of native code (HotSpot JVM)
7. JVM has three generations: young, old and permanent.
Young => most objects
Old => large objects / objects that survived few collections
Permanent => objects convenient to manage (objects describing classes, methods).
61.JAVA MEMORY LEAKS
 Scenario: A long-life class “contains” short-lived large objects (say a map of stuff), map contents may
not be released until the long-life (singleton?) object isn’t released, causing leak = size of map
 Signs: OutOfMemoryError or slowness (frequent gc)
 Detection:
o Invoke JVM with –verbose:gc or –Xloggc: turns on GC logging
o Use free tool: JTune – graphs memory usage over time
o Use paid tool: HeapAudit to understand JVM mem allocations
o Eclipse has profiling filters (Memory Analysis, Exec Time Analysis etc) in Profiling Monitor – nice GUI
o Once convinced memory leak, built-in “hprof” tool – invoke JVM with –Xrunhprof:heap=sites shows
lines of code and allocations. Prints usage breakdown after your kill -3 the program.
 Solution:
o Use WeakReference – For the map in context, use Entry<K,V> object that extends WeakReference<T>
class and overload get().
class WeakHashMap<K,V> implements Map<K,V> {
private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {
private V value; private Entry<K,V> next; …
}
// get below returns a strong reference so you’re not losing value
public V get (Object key) { … go thru Entry-s … return e.value; else return null; }
}
o Also make sure to use ReferenceQueue (WeakReference has ctor that accepts q), GC submits handles
of garbage collected objects back in this q.
JAVA MULTI-THREADING
62.Thread creation
(1) Implement Runnable interface or (2) Inherit from Thread class. Implementing Runnable better if you
anticipate multiple inheritance.
63.Java Thread Safety – Methods/Choices
Different ways to make program thread safe:
1. Synchronization is the easiest and most widely used tool for thread safety in java.
2. Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger
3. Use of locks from java.util.concurrent.locks package.
4. Using thread safe collections, check this post for usage of ConcurrentHashMap for thread safety.
5. Using volatile keyword with variables to make every thread read the data from memory, not read from thread
cache.
64.Java Thread Pool = ExecutorService. See here: here and here!
65.Concurrent Collections: BlockingQueue, ConcurrentMap, ConcurrentHashMap,
ConcurrentNavigableMap, ConcurrentSkipListMap
66.Thread Pools: newFixedThreadPool, newCachedThreadPool, newSingleThreadExecutor,
ScheduledThreadPoolExecutor
67.AtomicInteger has synchronized incrementAndGet, decrementAndGet methods.
68.notify() v/s notifyAll() (Doug Lea in his famous book): If a notify() and Thread.interrupt() happen at the same
time, the notify might actually get lost => dramatic implications. notifyAll() is a safer choice even though you pay
the price of overhead (waking too many threads most of the time).
69.Volatile variable: Single copy of member across threads: If multiple threads update a “volatile” member at the
same time, updates to volatile member reflect immediately to other threads. That is, each thread may make its
own cache of Object’s members other than volatile members.
JAVA COLLECTIONS
70.HashMap / Map
 Map: key-value; no duplicate keys
 SortedMap: keys ordered
 Map = Interface, HashMap implements it
 Multimap: No such thing in Java
71.HashMap / HashTable
1) HashMap – NULLs
2) HashMap – order not guaranteed
3) HashMap – not synchronized; Hashtable is synchronized.
72.Map v/s Hashtable
1. Map = interface, Hashtable = concrete impl.
2. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option.
3. Map = safely remove entries in the midst of iteration; Hashtable = not.
4. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which
returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true
if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The
Map interface eliminates this source of confusion by renaming the method containsValue. Also, this
improves the interface's consistency — containsValue parallels containsKey.
73.Hashtable v/s Collections.synchronizedMap v/s ConcurrentHashMap
1. Hashtable synchronized, old (extends obsolete Dictionary), adapted to fit Map interface; doesn’t scale well.
2. ConcurrentHashMap – concurrent unblocked modifications by several threads; parallel reads; only when entry
not found it (locks? and) rechecks; Bucket locks (2^16) for write and deletion; as performant as HashMap
3. Collections.synchronizedMap – blocking map => consistent but slow, just like Hashtable.
4. http://jcip.net/ (Java concurrency in practice)
5.
Property HashMap Hashtable ConcurrentHashMap
Null values/keys Fine No No
Thread-safe (Synchronized?) No Yes Yes
Lock mechanism NA Whole Map
locked
Portions locked
Iterator Fail-Fast Fail-Safe No
74.BlockingQueue
– is an interface
– Exactly a Producer-Consumer Bounded buffer implementation
– Null elements not allowed, throws NPE
– All implement blocking put() and take() methods
– add() throws exception if it can’t add, offer() returns bool and is preferred!
Following all implement BlockingQueue interface:
o ArrayBlockingQueue – size bound
o DelayQueue – object should ripen (delay) before take()
o LinkedBlockingDeque – elastic size / size optional double ended
o LinkedBlockingQueue – elastic size / size optional
o PriorityBlockingQueue – priority attribute (heap?)
o SynchronousQueue – producer/writer blocked until consumer/reader calls take()
o LinkedTransferQueue –
 http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html
public class BlockingQueueExample {
public static void main(String[] args)
throws Exception {
BlockingQueue queue = new
ArrayBlockingQueue(1024);
Producer producer = new
Producer(queue);
Consumer consumer = new
Consumer(queue);
new Thread(producer).start();
new Thread(consumer).start();
Thread.sleep(4000);
}
}
ArrayBlockingQueue<>
http://tutorials.jenkov.com/java-util-
concurrent/blockingqueue.html
public class Producer implements
Runnable{
protected BlockingQueue queue = null;
public Producer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
queue.put("1");
Thread.sleep(1000);
queue.put("2");
Thread.sleep(1000);
queue.put("3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Consumer implements
Runnable{
protected BlockingQueue queue = null;
public Consumer(BlockingQueue queue) {
this.queue = queue;
}
public void run() {
try {
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
PRODUCER CONSUMER BOUNDED-BUFFER IMPL IN JAVA
75.Vector / ArrayList
Vector synchronized.. so.. ArrayList faster. Use CopyOnWriteArrayList<> if modifications expected during iter
76.Swing / Awt
AWT = heavy-weight components. Swings = light-weight components. Swing => faster.
77.Iterator
= java.util.Iterator interface allows traversing collections. Implements Iterator Design Pattern.
78.collections-framework-interfaces
79.CharSequence
80.Concurrent Collections: BlockingQueue, ConcurrentMap, ConcurrentHashMap,
ConcurrentNavigableMap, ConcurrentSkipListMap
81.Collections: http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
o Core collections
o Set: No duplicates
 SortedSet: naturally ordered ascending
 Set.add(e) returns null upon trying to add duplicate e
o List: Ordered sequence; duplicates possible
o Queue: may provide a FIFO interface
 PriorityQueue
o Deque: FIFO or LIFO
o Map: key-value; no duplicate keys
o SortedMap: keys ordered
o Multimap: No such thing in Java
o To remove all: c.removeAll(Collections.singleton(e));
o To remove “null”: c.removeAll(Collections.singleton(null));
o To remove dups:
 Remove duplicates only:
public static <E> Set<E> removeDups(Collection<E> c) {
return new LinkedHashSet<E>(c);
}
 Remove duplicates preserve order:
public static <E> Set<E> removeDups(Collection<E> c) {
return new LinkedHashSet<E>(c);
}
JAVA MISC
82.JAR files, manifest file, creating, modifying them:
http://docs.oracle.com/javase/tutorial/deployment/jar/index.html
83.Reflection API: When programs need to check or modify runtime behavior of applications running in JVM.
o http://docs.oracle.com/javase/tutorial/reflect/index.html
o Class c = Object.getClass()
o Class c = Class.forName("com.duke.MyLocaleServiceProvider");
o Class c = Double.TYPE;
o getSuperClass()
o getClasses()
o getEnclosingClass()
o getDeclaredClasses()
o getDeclaredField(),getDeclaredFields(),getDeclaredMethod(),getDeclaredMethods(),
getDeclaredConstructor(),getDeclaredConstructors()
o … Similar Reflection APIs for Members, Arrays and Enumerated types…
84.SDP (Sockets Direct Protocol) http://docs.oracle.com/javase/tutorial/sdp/index.html
o java.net : Socket, ServerSocket
85.http://en.wikipedia.org/wiki/Java_virtual_machine
86.http://en.wikipedia.org/wiki/Comparison_of_Java_virtual_machines
87. Iterators differ from enumerations in two ways
Iterators allow caller to remove elements from collection during iteration; and Method names are improved.
Enumeration Iterator
---------------- ----------------
hasMoreElement() hasNext()
nextElement() next()
N/A remove()
88.Very good Java resource:
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Mais conteúdo relacionado

Mais procurados

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
priyank09
 
Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39
myrajendra
 

Mais procurados (20)

Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Core java concepts
Core java conceptsCore java concepts
Core java concepts
 
Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 
Power mock
Power mockPower mock
Power mock
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 

Semelhante a JAVA CONCEPTS AND PRACTICES

Semelhante a JAVA CONCEPTS AND PRACTICES (20)

Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Java mcq
Java mcqJava mcq
Java mcq
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
Inheritance
InheritanceInheritance
Inheritance
 
Java basics
Java basicsJava basics
Java basics
 
Java14
Java14Java14
Java14
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
Java tips
Java tipsJava tips
Java tips
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Oops
OopsOops
Oops
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1
Java tut1Java tut1
Java tut1
 

Último

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Último (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

JAVA CONCEPTS AND PRACTICES

  • 1. JAVA QUICKY Data Structures Algorithms Concepts Linked Lists Breadth First Search Bit Manipulation Binary Trees Depth First Search Singleton Design Pattern Tries Binary Search Factory Design Pattern Stacks, Queues Merge Sort Memory (Stack vs Heap) HEAPS (min, max) Quick Sort Recursion Vectors / ArrayLists Tree Insert / Find … Big-O Time Hash Tables JAVA CORE CONCEPTS 1. Java concurrency in practice: http://jcip.net/ 2. CONCURRENT CLASSES: CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet 3. Covariant Return Type Covariant return type  return type may vary in direction of subclass. Starting Java5 possible to override method by return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example: class A { A get() {return this;} } class B extends A { B get() {return this;} // overloads – not overrides A::get () void message() {System.out.println("Welcome to covariant return type");} public static void main(String args[]) { new B().get().message(); } } Output: Welcome to covariant return type 4. Abstract Class Abstract class = abstract concept = template. Can’t be instantiated. The subclasses implement methods. May contain static data. Abstract methods  automatically abstract class and must be declared as such. A class may be declared abstract even if it has no abstract methods  Prevents intances. 5. Interface vs Abstract class Abstract class can have instance methods with default behavior. Interface only declares constants and instance methods, no default behavior. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods. Feature Interface Abstract class Multiple inheritance YES NO Default implementation NO. Just signatures YES - complete or default impl that's overloadable. Access Modifiers NO YES
  • 2. 6. public, private, protected, default … * public: Visible everywhere (across packages). Field visible only if class public * private: Visible only to method of the class * protected: Visible in package + subclasses – even subclasses in different package. * default: What you get by. Visible within package. 7. static Per class, not per object. Static members usable without instance. Static methods = final, because overriding done based on the type of the object, and static metho ds are attached to a class, not an object. A static method in a super-class can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. Can't change a static method into an instance method in a subclass. 8. Checked / UnChecked Exception Checked = subclass or = Exception; not RuntimeException. Checked exception are those which the Java compiler forces you to catch. e.g. IOException thrown by java.io.FileInputStream's read() method is a checked Exceptions. Unchecked exceptions are RuntimeException, Error, or their subclasses. With an unchecked exception, compiler doesn't force client programmers to catch the exception or declare it in a throws clause. Client programmers don’t know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method. 9. What's New in Java 1.5? (ie Java 5) http://www.cs.indiana.edu/classes/jett/sstamm/ 1. Generics 2. For/in loop 3. Autoboxing/Unboxing 4. Typesafe Enums 5. Varargs 6. Static Import 7. Annotations (Metadata) 10.Serialization Mechanism to save state of object by converting it to a byte stream 11.Serialize an object to a file Implement interface Serializable. Pass instance to ObjectOutputStream which is connected to FileOutputStream. 12.Which methods of Serializable interface should I implement? Has none. 13.Customize seralization Implement Externalizable::readExternal and Externalizable::writeExternal. 14.When you serialize, what happens to object references within object? The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect. 15.Serialization: Note this All included (contained?) objects are also Serializable. If any of the objects is not serializable then it throws a NotSerializableException. 16.Static fields during serialization There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of any particular state 2. Base class fields are only handled if the base class itself is Serializable. 3. Transient fields. 17.If I want an object of my class to be thrown as an exception object, what should I do? Extend from Exception or a subclass of it. 18.If you already inherit, can’t inherit also from “Exception” class! 19.Difference between 2 approaches to exception handling 1> try catch block and 2> specifying the candidate exceptions in the throws clause? 20.Is it necessary that each try block must be followed by a catch block? No – either “catch” or “finally” block.
  • 3. 21.If I write return at the end of the try block, will the finally block still execute? Yes. 22.If I write System.exit (0); at the end of the try block, will the finally block still execute? No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. 23.final, finally, and finalize • final – declares a constant (like “const” in C++) or method can't be overridden. • finally – finally block always executes when try block exits – even if unexpected exception occurs. Allows localizing cleanup code accidentally bypassed by return / continue / break. • finalize() – method helps garbage collector. Invoked before object is discarded by garbage collector, allowing it to clean up its state. 24.Difference among String, StringBuffer, and StringBuilder?  String = immutable; StringBuffer = mutable. o int x=10; String s1 = “” + x; o String s2 = Integer.toString(x); o String s3 = String.valueOf(x);  StringBuffer: thread-safe, has append(), insert().. Used when mutable char-strings needed. Disadvantage is, all public methods are synchronized => slow.  StringBuilder (JDK5+) is designed for single threaded => no sync => faster.  http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html 25.Exceptions – note this The Java Language Specification describes how try-catch-finally is executed. Having no catch is equivalent to not having a catch able to catch the given Throwable. If execution of the try block completes abruptly because of a throw of a value V, then there is a choice: o If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …(whatever)…  But if the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice: * If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V. * If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten). 26.Java: http://www.oracle.com/technetwork/topics/newtojava/overview/index.html 27.New loop syntax: for (T e : anArray) 28.Implementing hashCode If a class overrides equals, it must override hashCode. When both overridden, equals and hashCode must use the same set of fields. If two objects are equal, then their hashCode values must be equal as well. If object is immutable, hashCode can be “cached” and “lazy initialized” [http://www.javapractices.com/topic/TopicAction.do;jsessionid=FC37D716710D81A1F389AE39715B672C?Id=28]. 29.Class loader searches $CLASSPATH for A.class, JIT compiling of .class byte-code files 30.javadoc processes comments of type /** ... */ 31.Java: no stack objects, all on heap 32.Types (study more) int, Integer float, Float Byte, Double String - fixed length strings StringBuffer - variable length strings StringBuilder int i = 4; String s = String.valueOf(i); => s is "4" int a = Integer.parseInt("4"); => a is 4 "blah" + "blah" => "blahblah" BigDecimal - string rep for floats for DB storing <anyObj>.toString() Arrays cant specify size: Typename[] varname; => array. (Cant say Typename[3] varname) Also, it just creates array object not elements; Typename[] varname; varname[i] = new Typename;
  • 4. Out of bounds access: ArrayIndexOutOfBoundsException, Uninit access: NullPointerException static final int version = 1; // same as "const int version=1;" in C++ 33.Assignments make 2 variables refer to same object unlike in C++ 34.To copy objects, define and use clone(): class Data implements Cloneable { public int data = 0; public Data(int d) { data = d; } public Object clone() { Data d = (Data) super.clone(); d.data = data; return d; } } ... Data a = new Data(1); // a.data is 1 Data b = new Data(2); // b.data is 2 b = a.clone(); // b.data and a.data are 1 a.data = 3; // b.data is 1, a.data is 3 35.JVM continues to execute threads until either of the following occurs: 1. exit method of class "Runtime" gets called and security manager has permitted exit operation. 2. All threads that are not daemon threads died, either by returning from call to run() or by throwing an exception that propagates beyond run(). 36.Two Java primitive types are equal (using the == operator) when they have the same value (e.g., "3 == 3"). However, two object variables are equal if and only if they refer to the same instantiated object--a "shallow" comparison. 37.To perform a "deep" comparison, the convention is to define a method called equals(). You would rewrite Data as: class Data { public int data = 0; public Data(int d) { data = d; } boolean equals(Data d) { return data == d.data; } } ... Data a = new Data(1); Data b = new Data(1); // a.equals(b) is true!!!! 38.Interfaces o Interface defines protocol of communication between objects. Group of related methods with empty bodies. o An interface definition contains method declarations or constant definitions. o Class implementing interface _must_ implement _all_ methods of it. o Interface can be used anywhere a type can be. o public interface OperateCar extends Interface1, Interface2 { int numWheels = 4; void TurnRight(int startingSpeed, int endingSpeed, int radius); … } o An interface can extend multiple interfaces (multiple “inheritance” not supported in Java). o All methods in an interface are inherently public => Specifier omitted. o Interface obviously can’t contain implementation bodies. o All variables must be initialized and are all public static final.
  • 5. 39.Primitive data-types as objects and seamless conversions: java.lang.Number: o Byte, Character, Short, Integer, Long, Float, Double, BigInteger, BigDecimal, AtomicInteger, AtomicLong 40.Java Generics: http://docs.oracle.com/javase/tutorial/java/generics/index.html o There aren't multiple copies of the code--not in source, not in binary, not on disk and not in memory. Single copy of a Java Generic. o Even return types can be templatized: boolean same = Util.<Integer, String>compare(p1, p2); o Bounded type parameters: public <U extends Number> void inspect(U u){ … } o Multiple bounds: class D <T extends A & B & C> { … }  Each bound is imposed  If a bound is a class and other bounds interfaces, the class name must be first in list. o http://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html o Integer and Double are subclasses of Number. But, Box<Integer> and Box<Double> are not subtypes of Box<Number>. o In generic code, the question mark (?), called the wildcard, represents an unknown type.  List<? extends String> list2 = new ArrayList<>(); o Bounded wildcards: To write the method that works on lists of Number and the subtypes of Number, such as Integer, Double, and Float, you would specify List<? extends Number>. The term List<Number> is more restrictive than List<? extends Number> because the former matches a list of type Number only, whereas the latter matches a list of type Number or any of its subclasses. o Unbounded wildcards: Consider the following method, printList: public static void printList(List<Object> list) { for (Object elem : list) System.out.println(elem + " "); System.out.println(); } The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>. To write a generic printList method, use List<?>: public static void printList(List<?> list) { for (Object elem: list) System.out.print(elem + " "); System.out.println(); } o A lower bounded wildcard restricts unknown type to be a specific type or a super type of that type: List<? super Integer> list; o During the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded. o Type Erasure: Java compiler replaces unbounded type parameters with Object and bounded type parameters with first bound: http://docs.oracle.com/javase/tutorial/java/generics/genTypes.html o Compiler generated Bridge method to preserve polymorphism when type erasure causes compiler-unanticipated problems.
  • 6. o A reifiable type is a type whose type information is fully available at runtime. This includes primitives, non- generic types, raw types, and invocations of unbound wildcards. Examples of non-reifiable types are List<String> and List<Number>; the JVM cannot tell the difference between these types at runtime. They cannot be used in an instanceof expression, for example, or as an element in an array. 41.Packages: To create a package put a package statement with its name at of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package. The package statement must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. 42.Once members of a package imported as “static”, they can be used without package name qualification: import static java.lang.Math.*; // Use sparingly to maintain readability double r = cos(PI * theta); Otherwise: import static java.lang.Math.PI; double r = Math.cos(Math.PI * theta); 43.public abstract class Graphic { ... } 44.Lambda expressions: A lambda expression consists of: o (a,b, c): comma-separated list of formal parameters enclosed in parentheses (You may omit the data type of the parameters in a lambda expression. In addition, you may omit the parentheses if there is only one parameter) o ->: the arrow  o statement(s): a body consisting of single expression or a statement block. If single expression, Java returns its value => don’t need “return” statement. o {} – but no need of {} for void method. o Examples:  email -> System.out.println(email)  IntegerMath addition = (a, b) -> a + b;  IntegerMath subtraction = (a, b) -> a - b; 45.Difference between equals() method and == ? == compares references. object.equals() compares values. 46.Steps in JDBC connection While making a JDBC connection we go through the following steps : Step 1 : Register the database driver by using : Class.forName(" driver classs for that specific database" ); Step 2 : Now create a database connection using : Connection con = DriverManager.getConnection(url,username,password); Step 3: Now Create a query using : Statement stmt = Connection.Statement("select * from TABLE NAME"); Step 4 : Exceute the query : stmt.exceuteUpdate(); 47.Applet: * Inherit from Applet class (no file IO, sockets, menu, lifecycle events) * init() = ctor, start(), stop(), destroy()...dispose()...super.dispose() * (1) extend JApplet, implement init(), start(), stop(), destroy(). o To deploy, make a JAR package and sign it. o Launch using (1) JNLP or (2) specify applet launch properties in applet tag. 48.HTML embed applet like img: <applet code=AppletName.class width=w height=h> [<param K-V params>]</applet> 49.Nested Class: o Static Nested Classes: Can’t access other members of enclosing class o Inner Classes: Can access other members of enclosing class even if private o OuterClass.InnerClass innerObject = outerObject.new InnerClass(); o Shadowing: Inner class member with same name shadows outer class’s member.
  • 7.  Refer to OuterClass.this.member o Anonymous class: HelloWorld spanishGreeting = new HelloWorld() { public void greet() {} public static void main(String[] args) {} } 50.Java Classloader is part of JRE that dynamically loads Java classes into JVM on demand. The Java run time system does not need to know about files and file systems because of classloaders. Each Java class must be loaded by a class loader. When JVM is started, three class loaders are used: 1. Bootstrap class loader: loads core Java libraries located in <JAVA_HOME>/jre/lib dir 2. Extensions class loader:  loads code in extensions dirs (<JAVA_HOME>/jre/lib/ext) or dir specified by java.ext.dirs system property  Implemented by sun.misc.Launcher$ExtClassLoader class 3. System class loader:  loads code found on java.class.path ($CLASSPATH env var)  implemented by the sun.misc.Launcher$AppClassLoader class JAVA MEMORY MANAGEMENT 51.Garbage collection Identifies and discards objects no longer needed for resource reuse. GC Roots = local vars, the Main thread, Static vars of main class 52.Finalization The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. 53.Can an unreachable object become reachable again? An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. 54.Garbage collector is a daemon thread that runs periodically to reclaim sets of objects. Uses a tree topology to find recoverable objects. http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html 55.http://www.infoq.com/articles/Java_Garbage_Collection_Distilled, http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html 56.REFERENCES – subclasses of java.lang.ref.Reference<T> 1) StrongReference – Regular reference: Foo f = new Foo(); 2) WeakReference – Isn't strong enough to force referent to stay in memory => en-queued/cleared ASAP class MyEntry<K,V> extends WeakReference<Object> implements Map.Entry<K,V> MyEntry<String,String> table = new MyEntry<>(); table = null; // And its probly gone…! Aggressively… System.gc(); sleep(5000); // If table not dead yet, now for sure it’d be… 3) SoftReference – Like WeakReference but less aggressive => en-queued/cleared as late as possible – ie either in next cycle of garbage collection or when VM is about to go out of memory => guaranteed cleared before VM throws OutOfMemoryError…
  • 8. Object obj = new Object(); SoftReference softRef = new SoftReference(obj /*, ReferenceQueue rq = new ReferenceQueue() */); obj = null; Object obj2(softRef.get()); if (obj2 == null) { // => Garbage collector freed softRef referent! } 4) PhantomReference – Can’t retrieve referent (get() returns null). Useful only as a signal to know when referent is already finalized and en-queued in ReferenceQueue (after death!). Use when finalize() method is not sensible. public class ConnectionPhantomReference extends PhantomReference { private DB db; public ConnectionPhantomReference (Conn c) { db.open(c); … } public void cleanup() { db.close(); } } // Create a daemon thread (Thread.setDaemon(true)) to handle ReferenceQueue<> 5) ReferenceQueue – Supply-able as second arg to ref-ctors. After referent collected, referent value itself en- queued to supplied ReferenceQueue. This allows performing clean up operations on referent obj. 6) References on reference: https://weblogs.java.net/blog/2006/05/04/understanding-weak-references, http://docs.oracle.com/javase/6/docs/api/java/lang/ref/Reference.html, http://docs.oracle.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html, http://neverfear.org/blog/view/150/Strong_Soft_Weak_and_Phantom_References_Java 57.-XX:GCTimeRatio=99 implies 1% GC time 58.–Xmx<n> is tuning parameter to set Max available heap size for an app; -Xms<n> sets initial heap size 59.Native_Memory = Process_Size – Max_Heap_Size – Max_Perm_Size 60.JAVA HEAP TERMINOLOGY: YOUNG, OLD, PERMANENT GENERATIONS HotSpot JVM uses following memory-pools for serial garbage collection: 1. http://www.maths.lse.ac.uk/Courses/MA407/gcsurvey.pdf, http://middlewaremagic.com/weblogic/?tag=young-generation, http://openjdk.java.net/groups/hotspot/docs/StorageManagement.html, http://java.sun.com/j2se/reference/whitepapers/memorymanagement_whitepaper.pdf, http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1168.pdf, https://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation 2. Young Generation / Eden Space (heap): Pool objects initially allocated into 3. Old Generation / Survivor Space (heap): Objects that survived garbage collection of Eden space 4. Tenured Generation (heap): Pool of objects existed for some time in Survivor space. 5. Permanent Generation (non-heap): Pool of reflective data of VM itself (class, method objects). With VMs using class data sharing, this generation is divided into read-only and read-write areas. 6. Code Cache (non-heap): memory for compilation and storage of native code (HotSpot JVM)
  • 9. 7. JVM has three generations: young, old and permanent. Young => most objects Old => large objects / objects that survived few collections Permanent => objects convenient to manage (objects describing classes, methods). 61.JAVA MEMORY LEAKS  Scenario: A long-life class “contains” short-lived large objects (say a map of stuff), map contents may not be released until the long-life (singleton?) object isn’t released, causing leak = size of map  Signs: OutOfMemoryError or slowness (frequent gc)  Detection: o Invoke JVM with –verbose:gc or –Xloggc: turns on GC logging o Use free tool: JTune – graphs memory usage over time o Use paid tool: HeapAudit to understand JVM mem allocations o Eclipse has profiling filters (Memory Analysis, Exec Time Analysis etc) in Profiling Monitor – nice GUI o Once convinced memory leak, built-in “hprof” tool – invoke JVM with –Xrunhprof:heap=sites shows lines of code and allocations. Prints usage breakdown after your kill -3 the program.  Solution: o Use WeakReference – For the map in context, use Entry<K,V> object that extends WeakReference<T> class and overload get(). class WeakHashMap<K,V> implements Map<K,V> { private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> { private V value; private Entry<K,V> next; … } // get below returns a strong reference so you’re not losing value public V get (Object key) { … go thru Entry-s … return e.value; else return null; } } o Also make sure to use ReferenceQueue (WeakReference has ctor that accepts q), GC submits handles of garbage collected objects back in this q. JAVA MULTI-THREADING 62.Thread creation (1) Implement Runnable interface or (2) Inherit from Thread class. Implementing Runnable better if you anticipate multiple inheritance. 63.Java Thread Safety – Methods/Choices Different ways to make program thread safe: 1. Synchronization is the easiest and most widely used tool for thread safety in java. 2. Use of Atomic Wrapper classes from java.util.concurrent.atomic package. For example AtomicInteger 3. Use of locks from java.util.concurrent.locks package. 4. Using thread safe collections, check this post for usage of ConcurrentHashMap for thread safety. 5. Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache. 64.Java Thread Pool = ExecutorService. See here: here and here! 65.Concurrent Collections: BlockingQueue, ConcurrentMap, ConcurrentHashMap, ConcurrentNavigableMap, ConcurrentSkipListMap 66.Thread Pools: newFixedThreadPool, newCachedThreadPool, newSingleThreadExecutor, ScheduledThreadPoolExecutor
  • 10. 67.AtomicInteger has synchronized incrementAndGet, decrementAndGet methods. 68.notify() v/s notifyAll() (Doug Lea in his famous book): If a notify() and Thread.interrupt() happen at the same time, the notify might actually get lost => dramatic implications. notifyAll() is a safer choice even though you pay the price of overhead (waking too many threads most of the time). 69.Volatile variable: Single copy of member across threads: If multiple threads update a “volatile” member at the same time, updates to volatile member reflect immediately to other threads. That is, each thread may make its own cache of Object’s members other than volatile members. JAVA COLLECTIONS 70.HashMap / Map  Map: key-value; no duplicate keys  SortedMap: keys ordered  Map = Interface, HashMap implements it  Multimap: No such thing in Java 71.HashMap / HashTable 1) HashMap – NULLs 2) HashMap – order not guaranteed 3) HashMap – not synchronized; Hashtable is synchronized. 72.Map v/s Hashtable 1. Map = interface, Hashtable = concrete impl. 2. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. 3. Map = safely remove entries in the midst of iteration; Hashtable = not. 4. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey. 73.Hashtable v/s Collections.synchronizedMap v/s ConcurrentHashMap 1. Hashtable synchronized, old (extends obsolete Dictionary), adapted to fit Map interface; doesn’t scale well. 2. ConcurrentHashMap – concurrent unblocked modifications by several threads; parallel reads; only when entry not found it (locks? and) rechecks; Bucket locks (2^16) for write and deletion; as performant as HashMap 3. Collections.synchronizedMap – blocking map => consistent but slow, just like Hashtable. 4. http://jcip.net/ (Java concurrency in practice) 5. Property HashMap Hashtable ConcurrentHashMap Null values/keys Fine No No Thread-safe (Synchronized?) No Yes Yes Lock mechanism NA Whole Map locked Portions locked Iterator Fail-Fast Fail-Safe No 74.BlockingQueue – is an interface – Exactly a Producer-Consumer Bounded buffer implementation – Null elements not allowed, throws NPE – All implement blocking put() and take() methods – add() throws exception if it can’t add, offer() returns bool and is preferred! Following all implement BlockingQueue interface: o ArrayBlockingQueue – size bound
  • 11. o DelayQueue – object should ripen (delay) before take() o LinkedBlockingDeque – elastic size / size optional double ended o LinkedBlockingQueue – elastic size / size optional o PriorityBlockingQueue – priority attribute (heap?) o SynchronousQueue – producer/writer blocked until consumer/reader calls take() o LinkedTransferQueue –  http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html public class BlockingQueueExample { public static void main(String[] args) throws Exception { BlockingQueue queue = new ArrayBlockingQueue(1024); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); new Thread(producer).start(); new Thread(consumer).start(); Thread.sleep(4000); } } ArrayBlockingQueue<> http://tutorials.jenkov.com/java-util- concurrent/blockingqueue.html public class Producer implements Runnable{ protected BlockingQueue queue = null; public Producer(BlockingQueue queue) { this.queue = queue; } public void run() { try { queue.put("1"); Thread.sleep(1000); queue.put("2"); Thread.sleep(1000); queue.put("3"); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Consumer implements Runnable{ protected BlockingQueue queue = null; public Consumer(BlockingQueue queue) { this.queue = queue; } public void run() { try { System.out.println(queue.take()); System.out.println(queue.take()); System.out.println(queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } } PRODUCER CONSUMER BOUNDED-BUFFER IMPL IN JAVA 75.Vector / ArrayList Vector synchronized.. so.. ArrayList faster. Use CopyOnWriteArrayList<> if modifications expected during iter 76.Swing / Awt AWT = heavy-weight components. Swings = light-weight components. Swing => faster.
  • 12. 77.Iterator = java.util.Iterator interface allows traversing collections. Implements Iterator Design Pattern. 78.collections-framework-interfaces 79.CharSequence 80.Concurrent Collections: BlockingQueue, ConcurrentMap, ConcurrentHashMap, ConcurrentNavigableMap, ConcurrentSkipListMap 81.Collections: http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html o Core collections o Set: No duplicates  SortedSet: naturally ordered ascending  Set.add(e) returns null upon trying to add duplicate e o List: Ordered sequence; duplicates possible o Queue: may provide a FIFO interface  PriorityQueue o Deque: FIFO or LIFO o Map: key-value; no duplicate keys o SortedMap: keys ordered o Multimap: No such thing in Java o To remove all: c.removeAll(Collections.singleton(e)); o To remove “null”: c.removeAll(Collections.singleton(null)); o To remove dups:  Remove duplicates only: public static <E> Set<E> removeDups(Collection<E> c) { return new LinkedHashSet<E>(c); }  Remove duplicates preserve order: public static <E> Set<E> removeDups(Collection<E> c) { return new LinkedHashSet<E>(c); } JAVA MISC 82.JAR files, manifest file, creating, modifying them: http://docs.oracle.com/javase/tutorial/deployment/jar/index.html 83.Reflection API: When programs need to check or modify runtime behavior of applications running in JVM. o http://docs.oracle.com/javase/tutorial/reflect/index.html o Class c = Object.getClass() o Class c = Class.forName("com.duke.MyLocaleServiceProvider"); o Class c = Double.TYPE; o getSuperClass() o getClasses() o getEnclosingClass() o getDeclaredClasses()
  • 13. o getDeclaredField(),getDeclaredFields(),getDeclaredMethod(),getDeclaredMethods(), getDeclaredConstructor(),getDeclaredConstructors() o … Similar Reflection APIs for Members, Arrays and Enumerated types… 84.SDP (Sockets Direct Protocol) http://docs.oracle.com/javase/tutorial/sdp/index.html o java.net : Socket, ServerSocket 85.http://en.wikipedia.org/wiki/Java_virtual_machine 86.http://en.wikipedia.org/wiki/Comparison_of_Java_virtual_machines 87. Iterators differ from enumerations in two ways Iterators allow caller to remove elements from collection during iteration; and Method names are improved. Enumeration Iterator ---------------- ---------------- hasMoreElement() hasNext() nextElement() next() N/A remove() 88.Very good Java resource: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html