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.
public class getLocationName {
return
(null==cityName ? "": cityName);
}
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:
//Slower Instantiation
String bad = new String("Yet another string
object");
//Faster Instantiation
String 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:
import java.util.ArrayList;
import java.util.List;
public class Employees {
private List Employees;
public List getEmployees() {
//initialize only when required
if(null == Employees) {
Employees = new ArrayList();
}
return Employees;
}
}
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.
import java.util.ArrayList;
public class arrayVsArrayList {
public static void
main(String[] args) {
int[] myArray = new
int[6];
myArray[7]= 10; //
ArraysOutOfBoundException
//Declaration of
ArrayList. Add and Remove of elements is easy.
ArrayList<Integer>
myArrayList = new ArrayList<>();
myArrayList.add(1);
myArrayList.add(2);
myArrayList.add(3);
myArrayList.add(4);
myArrayList.add(5);
myArrayList.remove(0);
for(int i = 0; i
< myArrayList.size(); i++) {
System.out.println("Element:
" + myArrayList.get(i));
}
//Multi-dimensional
Array
int[][][]
multiArray = new int [3][3][3];
}
}
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:
public class
shutDownHooksDemo {
public static void
main(String[] args) {
for(int
i=0;i<5;i++)
{
try {
if(i==4) {
System.out.println("Inside
Try Block.Exiting without executing Finally block.");
System.exit(0);
}
}
finally {
System.out.println("Inside
Finally Block.");
}
}
}
}
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.
public class shutDownHooksDemo {
public static void main(String[] args) {
for(int i=0;i<5;i++)
{
final int final_i =
i;
try {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if(final_i==4) {
System.out.println("Inside
Try Block.Exiting without executing Finally block.");
System.exit(0);
}
}
});
}
finally {
System.out.println("Inside
Finally Block.");
}
}
}
}
No comments:
Post a Comment