Wednesday, 25 February 2015

Generics in Java

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time than runtime.
List<Integer> list = new ArrayList<Integer>();
list.add("hello");//Compile Time Error
list.add(32);

----
more you can refer from:-
http://www.javatpoint.com/generics-in-java

for better and deep understanding must use this link:-
http://javarevisited.blogspot.in/2011/09/generics-java-example-tutorial.html

Tuesday, 24 February 2015

What's the use of “enum” in Java

Enum serves as a type of fixed number of constants and can be used at least for two things
constant
public enum Month {
    JANUARY, FEBRUARY, ...
}
This is much better than creating a bunch of integer constants.
creating a singleton
public enum Singleton {
    INSTANCE

   // init
};
You can do quite interesting things with enums, look at here
Also look at the official documentation
---------------------------------------------------------------------------------------------------

Monday, 23 February 2015

Find Out Your Java Heap Memory Size and increase it's Size:-

Find Out Your Java Heap Memory Size:-

It's work in the principle of
Ergonomics in the 5.0 Java TM Virtual Machine
how ever it may vary from VM to VM
http://www.oracle.com/technetwork/java/ergo5-140223.html
-------------------------------------------------------------------
1. Java Memory Overview
A quick review of Java memory structure :

1. Java Heap Size
Place to store objects created by your Java application, this is where Garbage Collection takes place, the memory used by your Java application. For a heavy Java process, insufficient Heap size will cause the popular java.lang.OutOfMemoryError: Java heap space.

-Xms<size> - Set initial Java heap size
-Xmx<size> - Set maximum Java heap size

$ java -Xms512m -Xmx1024m JavaApp
2. Perm Gen Size
Place to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.

-XX:PermSize<size> - Set initial PermGen Size.
-XX:MaxPermSize<size> - Set the maximum PermGen Size.

$ java -XX:PermSize=64m -XX:MaxPermSize=128m JavaApp
3. Java Stack Size
Size of a Java thread. If a project has a lot of threads processing, try reduce this stack size to avoid running out of memory.
-Xss = set java thread stack size

$ java -Xss512k JavaApp

Note
The default value for heap size, perm gen, or stack size is differ from different JVMs. The best practice is always defining your own value.
-----------------------------------------------------------------------------------------
C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadSta
ckSize"
   C:\>java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

    uintx InitialHeapSize                          := 266634176       {product}
    uintx MaxHeapSize                              := 4267704320      {product}
    uintx PermSize                                  = 21757952        {pd product}
    uintx MaxPermSize                               = 85983232        {pd product}
     intx ThreadStackSize                           = 0               {pd product}
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)
Java heap size
InitialHeapSize = 266634176 bytes (256M) and MaxHeapSize = 4266146816 bytes (4068M).
PermGen Size
PermSize = 21757952 bytes (20.75M), MaxPermSize = 85983232 bytes (823. M).
Java Stack Size
ThreadStackSize = 0 kilobytes. (weird…)
The allocated heap memory size is almost same with the ergonomics result :

#ergonomics algorithm
Initial heap size = 16384/64 = 256M
Maximum heap size = 16384/4 = 4096M
------------------------------------------------------
It is possible to increase heap size allocated by the JVM by using command line options Here we have 3 options

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

java -Xms16m -Xmx64m ClassName
------------------------------------------------------------------------------------------------------

How many threads can a Java VM support?

--------------------------------
his depends on the CPU you're using, on the OS
and let's done it by a small program:-
public class CountingOfThread {
    private static Object s = new Object();
    private static int count = 0;
    public static void main(String[] argv){
        for(;;){
            new Thread(new Runnable(){
                    public void run(){
                        synchronized(s){
                            count += 1;
                            System.err.println("New thread #"+count);
                        }
                        for(;;){
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e){
                                System.err.println(e);
                            }
                        }
                    }
                }).start();
        }
    }
}
output:-
New thread #4971
New thread #4972
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Unknown Source)
at DieLikeADog.main(DieLikeADog.java:20)

How Many Ways We can Create Object in Java:-

There are four different ways to create objects in java:
A. Using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
 MyObject object = new MyObject();
B. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Even You can go for this apporach also:-
this.getClass().getClassLoader().loadClass(“com.amar.myobject”).newInstance();
You can read from here

Thursday, 19 February 2015

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?

The contract of the Comparable interface allows for non-consistent behaviour:
It is strongly recommended (though not required) that natural orderings be consistent with equals.
So in theory, it is possible that a class in the JDK had a compareTo not consistent with equals. One good example is BigDecimal.
Below is a contrived example of a comparator that is not consistent with equals (it basically says that all strings are equal).
Output:
size: 1
content: {a=b}
public static void main(String[] args) {
    Map<String, String> brokenMap = new TreeMap<String, String> (new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return 0;
        }
    });

    brokenMap.put("a", "a");
    brokenMap.put("b", "b");
    System.out.println("size: " + brokenMap.size());
    System.out.println("content: " + brokenMap);
}

but see now if you store same entry in hashmap
it will store because a.equals(b) always false. so it will store both a and b.
where as in TreeMap it wont thats the problem. because compare b/w a and b is 0...so
 1 will broke single value will store

Difference between Java Comparator and Comparable interfaces

This post explains the difference between most important java interfaces used for sorting namely Comparator and Comparable.
http://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html
http://www.programcreek.com/2011/12/examples-to-demonstrate-comparable-vs-comparator-in-java/
ComparableComparator
Class whose objects which we need to sort must implement java.lang.Comparable interface compareTo(Object o1) method
E.g.
If we want to sort Employee, our employee class needs to implement above method.
Class whose objects which we need to sort do not need to implement any interface method.
E.g. 
If we want to sort Employee objects using employee name, We write a class EmpSortByName which implements java.lang.Comparable interfacecompare(Object o1,Object o2) method
Sorting logic is in the same class whose objects are being sorted. Hence this is called Natural ordering of objects.Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using name, last name, age etc.
We use Collections.sort(List) method to sorting.
E.g
Collections.sort(list);
We must use the Collections.sort(List, Comparator) for sorting.
E.g.
Collections.sort(list, new EmpSortByName());
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
-----------------------------------------------------------------------------------------------------------------------\
EX:-
public class ComparatorDemo {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Joe", 24),
                new Person("Pete", 18),
                new Person("Chris", 21)
        );
        Collections.sort(people, new LexicographicComparator());
        System.out.println(people);
        Collections.sort(people, new AgeComparator());
        System.out.println(people);
    }
}

class LexicographicComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.name.compareToIgnoreCase(b.name);
    }
}

class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
    }
}

class Person {

    String name;
    int age;

    Person(String n, int a) {
        name = n;
        age = a;
    }

    @Override
    public String toString() {
        return String.format("{name=%s, age=%d}", name, age);
    }
}