Thursday, April 30, 2015

Nested Classes

Types of Nested classes

  1. Member Inner Class ( Non-static Nested Class ).   
  2. Static Nested Class.
  3. Local (nested , inner) Class
  4. Anonymous (nested , inner) Class.
  • If you declare a nested class as static it will called Nested Static Class.
  • Non static nested class are simply referred as Inner Class.
  • For outer class, there is only two access modifier for it, public and package.
  • Inside an interface, the nested class or interface implicitly public and static.

Member Inner Class 

  1. Inner classes cannot have static declarations unless the member is a constant variable.
  2. An inner class may inherit static members that are not constant variables even
    though it cannot declare them. 
  3. Access fields of the enclosing class even if they are declared private. 
  4. Java makes it possible though, for the Inner class to refer to the text field of the Outer class. To do so it has to prefix the text field reference with Outer.this. (the outer class name + .this. + field name). 
  5. If a Java inner class declares fields or methods with the same names as field or methods in its enclosing class, the inner fields or methods are said to shadow over the outer fields or methods.
public class Outer {
  public class Inner {
  }
}
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

Nested Static Class

  1. One of the main benefits of nested static class over inner class is that instance of nested static class is not attached to any enclosing instance of Outer class.
    (You don't need any instance of Outer class to create instance of nested static class in Java)
  2. Non-static variable cannot be referenced from a static context.
  3. They are typically declared as either subclasses of an existing class, or as implementations of some interface.
public class Outer {
    public static class NestedStaticClass {
    }
}
Outer.NestedStaticClass obj = new Outer.NestedStaticClass();

Local Class

  1. You can define a local class inside any block ( method body, for loop, if clause ). 
  2. A local class can access local variables only that are declared final.(local variable is accessed from within inner class; needs to be declared final)
    From Java 8 local classes can also access local variables and parameters of the method the local class is declared in. The parameter will have to be declared final or be effectually final.

    Effectually final means that the variable is never changed after it is initialized.
     
  3. You cannot declare static method in a local class.
     Since you cannot declare a local variable static, you also
     cannot declare a local class static.
class Outer {
public void printText() {
        class Local {
        }
        Local local = new Local();
    }
}

Anonymous Class 

  1. You cannot declare constructors in an anonymous class. 
  2. Anonymous classes are ideal if you have to implement an interface that contains two or more methods.
    Can used in performing additional tasks such as method overloading
  3. Anonymous classes are defined in the new expression itself, so you cannot create multiple objects of an anonymous class. 
  4. An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. 
  5. There are no such things as anonymous interfaces.
  6. You cannot explicitly extend a class or explicitly implement interfaces when defining an
    anonymous class.
public class SuperClass {
  public void doIt() {
    System.out.println("SuperClass doIt()");
  }
}
SuperClass instance = new SuperClass() {
    public void doIt() {
        System.out.println("Anonymous class doIt()");
    }
};

instance.doIt();
Benefits of Nested Classes

The organizational advantage.

The callback advantage.

Implement helper classes.

Implement same interface multiple times inside class.

http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
http://tutorials.jenkov.com/java/nested-classes.html
https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html 
www.javaworld.com/article/2077411/core-java/inner-classes.html 

Tuesday, April 28, 2015

Enumeration vs Iterator vs ListIterator

I found a good article describe the differences in a good description with summary:

Iterator , ListIterator and Enumeration interfaces are mainly used to iterate collection classes .

Enumeration :
java2db Enumeration  iterates Vector and Hashtable .
java2db Reverse iteration is not possible with enumeration.
java2db It cannot add or remove elements  while iteration .
Iterator :
java2db Iterator   iterates the  implementations of  List , Set .
java2db Reverse iteration is not possible  with Iterator .
java2db Iterator cannot add elements , but it can remove elements while iteration .
ListIterator :
java2dbListIterator  iterates  List  implementations (like  ArrayList , LinkedList  etc).
java2dbBoth forward and backward iterations are  possible with ListIterator .
java2dbBoth elements addition  and deletion can possible  with ListIterator .

Syntax for Iterator ListIterator and Enumeration :

Iterator  <Iterator variable  name>=  <set/List variable> . iterator();
while(<Iterator variable  name>.hasNext())  {
<Iterator variable  name> .next();               }
ListIterator <ListIterator variable name>=<list variable>.listIterstor();
while  (<ListIterator variable name>.hasNext() ){
<ListIterator variable name>.next(); }
Enumeration <Enumeration variable name>=<Vector / Hashtable variable>.elements();
while(<Enumeration variable name>.hasMoreElements()) {
<Enumeration variable name>.nextElement(); }

http://java2db.com/java-util/difference-between-iterator-listiterator-and-enumeration-in-java

HashMap vs HashTable

Differences:
  1. HashMap allows null values as key and value whereas HashTable doesn't.
    maps.put(null, 7);
    maps.put(null, 15);
    The key is null and the value of 15 overwrite 7.
  2. HashMap is non synchronized whereas Hashtable is synchronized.
  3. HashTable is the only class other than vector which have method return enumerator to iterate The values.
  4. The iterator in HashMap is fail-fast iterator while the enumerator for Hashtable is not.
Similarities:
Both HashMap and HashTable does not guarantee that the order of the map will remain constant over time. 

When to use HashMap and Hashtable?

1. Single Threaded Application
HashMap should be preferred over Hashtable for the non-threaded applications.
In simple words , use HashMap in unsynchronized or single threaded applications .
2. Multi Threaded Application
We should avoid using HashTable, as the class is now obsolete in latest Jdk 1.8.
Oracle has provided a better replacement of HashTable named ConcurrentHashMap.
For multithreaded application prefer ConcurrentHashMap instead of Hashtable. It would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

HashMapHashTable
SynchronizedNoYes
Thread-SafeNoYes
Null Keys and Null valuesOne null key ,Any null valuesNot permit null keys and values
Iterator typeFail fast iteratorFail safe iterator
PerformanceFastSlow in comparision
Superclass and LegacyAbstractMap , NoDictionary , Yes

ArrayList vs Vector

Similarities
  1. Both allows null and duplicates and index based and backed up by an array internally.
  2. Both are derived from AbstractList and implements List interface.
  3. Both can be iterated with Iterator or ListIterator.
       Get the Enumeration object:
     - Enumeration e = Collections.enumeration(arrayList);
    - Vector can return enumeration of items it hold by calling elements () method.
  4. Both are fail-fast.
    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.

Differences
  1. Vector is synchronized but ArrayList is not.
  2. Whenever Vector crossed the threshold specified it increases itself by value specified in capacityIncrement field while you can increase size of ArrayList by calling ensureCapacity () method.
  3. Vector standard initial size is 10,standard  capacityIncrement is zero
    The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.
  4. ArrayList starts with a default initial capacity of 10,
  5. Java 1.7  ==>  int newCapacity = oldCapacity + (oldCapacity >> 1)
    Java 6 ====>    int newCapacity = (oldCapacity * 3)/2 + 1;
  6. Vector provides a method to get the current capacity but ArrayList doesn't ).
It would be wrong to write a program that depended on this exception for its correctness, the fail-fast behavior of iterators should be used only to detect bugs.

If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html

Set Collection


The "java.util.Set" interface is a subtype of the "java.util.Collection" interface that:
  1. Can not contain duplicates.
  2. Allow one null element.
  • Set Implementations:
  1. java.util.EnumSet
  2. java.util.HashSet
  3. java.util.LinkedHashSet
  4. java.util.TreeSet
  5. java.util.SortedSet

HashSet is unordered collection (Doesn't maintains insertion order) , It changes the order of the  inserted elements.

LinkedHashSet guarantees that the order of the elements during iteration is the same as the order they were inserted.

TreeSet guarantees that the order of the elements when iterated is the sorting order of the elements.

  • Operations:
  1. To add elements to a Set you call its add() method.
  2. You remove elements by calling the remove(Object o) method.
Remove Duplicates from a Collection:
Suppose you have a Collection, c, and you want to create another Collection containing the same elements but with all duplicates eliminated:

Collection<Type> noDups = new HashSet<Type>(c); 

In jdk 8 you can remove duplicate using Lambdas:
c.stream().collect(Collectors.toSet()); // no duplicates

  • Iterate Elements:
//access via Iterator
Iterator iterator = setA.iterator();
while(iterator.hasNext(){
  String element = (String) iterator.next();
}


//access via new for-loop
for(Object object : setA) {
    String element = (String) object;
}
https://docs.oracle.com/javase/tutorial/collections/interfaces/set.html
http://fastlearned.blogspot.com/2012/08/java-collection.html

Map


Collection


Wednesday, April 22, 2015

Stack and Heap memory in java basic knowledge Video

String, Stringbuffer and StringBuilder in java basic knowledge Video

We should always use StringBuilder append() method rather than String "+" operator to avoid cost. 

Note that what "+" operator does is:
  1. create a new string;
  2. make a copy of the left string;
  3. append the right char/string to the end.

So, a series of "+" operation is O(n^2)-time, not O(n).
StringBuilder is smarter and you can think it as a dynamically resizing array of char.
No copies for append() and it can output a String by calling toString() method.

Note: StringBuilder has no synchronization, i.e. it is not thread-safe.
If synchronization is required, it is recommend to use StringBuffer.

http://sophie-notes.blogspot.com/2013/02/java-stringbuilder-vs-string.html

JVM HotSpot memory

The JVM HotSpot memory is split between 3 memory spaces
  • The Java Heap.
  • The PermGen(perm) (permanent generation).
  • The Native Heap (C-Heap).

The Java Heap
  • Stores java objects.
  • Applicable for all JVM vendors.
  • It's usually  divided into generations:a-  The young generation (nursery):Stores short-lived objects that are created and immediately garbage collected.b-  The old generation (tenured):Objects that persist longer are moved to the old generation.
  • Start-up arguments and tuning:
    -Xmx (maximum Heap space) -Xms (minimum Heap size)
PermGen 
  • Keep information for the loaded classes (storing the Java Classes metadata)
  • String Pool which created by String.intern() method.
  • The PermGen space is only applicable to the HotSpot VM.
  • In Java 8, Oracle replaced the PermGen space for the HotSpot VM  with Metaspace.
  • Start-up arguments and tuning
    -XX:MaxPermSize (maximum size)    -XX:PermSize(minimum size)
Native Heap
  • Store third party native code objects.
  • Applicable for all JVM vendors.
Eating memory cases 
  • The more class loaders and classes that you load at runtime, higher demand on the HotSpot VM PermGen space and internal JIT related optimization objects.
  • The more applications you deploy to a single JVM, higher demand on native Heap.
  • Java threads require demand native memory.
  • Data caching not serialized to a disk or database will require extra memory from the OldGen space.
  • The java heap and native heap are in a race, the bigger your Java heap, smaller the native heap.  
Bytecode compilation uses native memory
Java applications run in the virtualized environment of the Java runtime, but the runtime itself is a native program written in a language (such as C) that consumes native resources, including native memory.
Every virtualized resource — including the Java heap and Java threads — must be stored in native memory, along with the data used by the virtual machine as it runs.
both the input (the bytecode) and the output (the executable code) from the JIT must also be stored in native memory.

Note 
 

  • JRockit and HotSpot are merging into one single JVM.
  • JDK 7 contains the first release of this converged JVM, which was one of the first steps was to start removing the PermGen concept in java 8.
  • The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace; similar to the Oracle JRockit and IBM JVM's.
  • Java Metaspace space setting is to be unbounded (dynamic resize) by default.

Manage Memory for permanent generation space (permgen)
If your JDeveloper IDE  is slow, you can increase the memory by: 
Edit the "jdev.con" file located at path "YOUR_Oracle_Home\jdeveloper\jdev\bin​"
and add following line:
AddVMOptionHotspot  -XX:MaxPermSize=1024M

also you can show consumed memory and force for garbage collection by adding the following line:
AddVMOption -DMainWindow.MemoryMonitorOn=true

See the file after modifying:

  • Now you can see a new bar added at Jdeveloper IDE, the arrow points to link that do job for Garbage Collecting:
  • Now you are more far from the error: OutOfMemoryError PermGen Space Error.
  •  JDeveloper 12.1.3 in test can be configured to develop/compile against JDK 8, and introduces support for JDK 8 language features.

http://javaeesupportpatterns.blogspot.com/2011/08/java-heap-space-hotspot-vm.html
https://blogs.oracle.com/henrik/entry/java_7_questions_answers
http://architects.dzone.com/articles/5-tips-proper-java-heap-size
http://architects.dzone.com/articles/5-tips-proper-java-heap-size
http://www.ibm.com/developerworks/linux/library/j-nativememory-linux/index.html
https://sourcevirtues.wordpress.com/2013/01/14/java-heap-space-and-native-heap-problems/

http://waslleysouza.com.br/en/2014/04/increase-the-performance-of-jdeveloper-11g/
http://www.oracle.com/technetwork/developer-tools/jdev/documentation/121300-cert-2164864.html
http://java.dzone.com/articles/java-8-permgen-metaspace
http://en.wikipedia.org/wiki/Java_virtual_machine

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...