Thursday, October 6, 2016

Java tips


1. Prefer returning Empty Collections instead of Null

If a program is returning a collection which does not have any value, make sure an Empty collection is returned rather than Null elements. This saves a lot of “if else” testing on Null Elements.
1public class getLocationName {
2    return (null==cityName ? "": cityName);
3}

2. Use Strings carefully

If two Strings are concatenated using “+” operator in a “for” loop, then it creates a new String Object, every time. This causes wastage of memory and increases performance time. Also, while instantiating a String Object, constructors should be avoided and instantiation should happen directly. For example:
1//Slower Instantiation
2String bad = new String("Yet another string object");
3      
4//Faster Instantiation
5String good = "Yet another string object"

3. Avoid unnecessary Objects

One of the most expensive operations (in terms of Memory Utilization) in Java is Object Creation. Thus it is recommended that Objects should only be created or initialized if necessary. Following code gives an example:
01import java.util.ArrayList;
02import java.util.List;
03 
04public class Employees {
05 
06    private List Employees;
07 
08    public List getEmployees() {
09 
10        //initialize only when required
11        if(null == Employees) {
12            Employees = new ArrayList();
13        }
14        return Employees;
15    }
16}

4. Dilemma between Array and ArrayList

Developers often find it difficult to decide if they should go for Array type data structure of ArrayList type. They both have their strengths and weaknesses. The choice really depends on the requirements.
01import java.util.ArrayList;
02 
03public class arrayVsArrayList {
04 
05    public static void main(String[] args) {
06        int[] myArray = new int[6];
07        myArray[7]= 10// ArraysOutOfBoundException
08 
09        //Declaration of ArrayList. Add and Remove of elements is easy.
10        ArrayList<Integer> myArrayList = new ArrayList<>();
11        myArrayList.add(1);
12        myArrayList.add(2);
13        myArrayList.add(3);
14        myArrayList.add(4);
15        myArrayList.add(5);
16        myArrayList.remove(0);
17         
18        for(int i = 0; i < myArrayList.size(); i++) {
19        System.out.println("Element: " + myArrayList.get(i));
20        }
21         
22        //Multi-dimensional Array
23        int[][][] multiArray = new int [3][3][3];
24    }
25}
  1. Arrays have fixed size but ArrayLists have variable sizes. Since the size of Array is fixed, the memory gets allocated at the time of declaration of Array type variable. Hence, Arrays are very fast. On the other hand, if we are not aware of the size of the data, then ArrayList is More data will lead to ArrayOutOfBoundException and less data will cause wastage of storage space.
  2. It is much easier to Add or Remove elements from ArrayList than Array
  3. Array can be multi-dimensional but ArrayList can be only one dimension.

5. When Finally does not get executed with Try

Consider following code snippet:
01public class shutDownHooksDemo {
02    public static void main(String[] args) {
03        for(int i=0;i<5;i++)
04        {
05            try {
06                if(i==4) {
07                    System.out.println("Inside Try Block.Exiting without executing Finally block.");
08                    System.exit(0);
09                }
10            }
11            finally {
12                System.out.println("Inside Finally Block.");
13            }
14        }
15    }
16}
From the program, it looks like “println” inside finally block will be executed 5 times. But if the program is executed, the user will find that finally block is called only 4 times. In the fifth iteration, exit function is called and finally never gets called the fifth time. The reason is- System.exit halts execution of all the running threads including the current one. Even finally block does not get executed after try when exit is executed.
When System.exit is called, JVM performs two cleanup tasks before shut down:
First, it executes all the shutdown hooks which have been registered with Runtime.addShutdownHook. This is very useful because it releases the resources external to JVM.
Second is related to Finalizers. Either System.runFinalizersOnExit or Runtime.runFinalizersOnExit. The use of finalizers has been deprecated from a long time. Finalizers can run on live objects while they are being manipulated by other threads.This results in undesirable results or even in a deadlock.
01public class shutDownHooksDemo {
02 
03    public static void main(String[] args) {
04            for(int i=0;i<5;i++)
05            {
06                    final int final_i = i;
07                    try {
08                            Runtime.getRuntime().addShutdownHook(
09                                            new Thread() {
10                                            public void run() {
11                                            if(final_i==4) {
12                                            System.out.println("Inside Try Block.Exiting without executing Finally block.");
13                                            System.exit(0);
14                                            }
15                                            }
16                                            });
17                    }
18                    finally {
19                            System.out.println("Inside Finally Block.");
20                    }
21 
22            }
23    }
24}



No comments:

Post a Comment