Saturday, February 23, 2013

Runtime Exception in Java

Runtime Exceptions occur mostly due to some programming error, so as a programmer you need to be careful. Runtime exceptions (java.lang.RuntimeException) are unchecked; so compilers don't enforce you to handle them (either catch or throw). 

Below diagram shows the hierarchy of the Exception tree.


 

NullPointerException [api doc]

Thrown when an application attempts to use in null a case where an object is required. 

Below snippet throws NPE :

         String a = null;
         a.toString();

Java 7 adds a new utility class Objects [Java Doc];  Objects class has a method to perform the null check on an object.

           public foo(Bar bar){
                  this.bar = Objects.requireNonNull(bar);
           }

ClassCastException [api doc]

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
        
Java allows you to cast one type to another provided they are compatible. And if the casting is done between two incompatible types (and compiler is unable to detect it); then you get this exception at Runtime. So this Exception is thrown when you try to downcast an object, but the actual type of class is not of that type. 

  1. Let's see below example:
          Object x = new Integer(0);
          System.out.println((String)x);
At compile time the type of x is Object, so x could be reference to String also (as Object is super class). But at execution time the type of x is Integer so its cast to String fails.  
    2.   Another case; you use code written before Java 1.5 with later version and mix Generics :

          List lll = new ArrayList();
          lll.add("sid");
          lll.add(2);
            
          Iterator<String> itr = lll.iterator();
          while(itr.hasNext()){
                System.out.println(" val "+ itr.next());  //Expects String only, but 2 is not
          } 

          String tmp = lll.get(1); //Throws ClassCastException; as type doesn't match

    3.   Casting an incompatible types
         
          class A {...}
          class B extends A {...}
          class C extends A {...}

          You can't cast a B to a C even though they're both of type A's.

IllegalArgumentException [api doc]

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

 This Exception is usually thrown if the arguments of a method are invalid. This way it fails at the earliest if the argument is invalid. This is usually not done for private methods; as class Author can ensure their validity. When argument check fails IllegalArgumentException, NullPointerException or IllegalStateException is thrown. 

   public class IllegalArgumentTest{
        public IllegalArgumentTest ( String name, double age ) {
            if ( name == null ) {
                throw new IllegalArgumentException("Name has no content.");
            }
            if ( age < 18.0f ) {
                 throw new IllegalArgumentException(" Person is not adult");
            }
            fname = name;
            fage = age;
        }
    //other methods..
  }
  You can document these exceptions in @throw clause of the method javadoc as they clearly state method requirement to the caller.

IllegalStateException [api doc]

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

 This Exception is thrown in below situations:
  1. When you try to notify a thread that isn't in waiting state mode.
  2. When you try to run an already running thread. 
  3. When you try to call remove method twice while iterating a Collection (i.e. iterator.remove())
  4. ArrayBlockingQueue.add() throws this Exception if Queue is already full.

And Effective Java says (Item 60, page 248):
Another commonly reused exception is IllegalStateException. This is generally the exception to throw if the invocation is illegal because of the state of the receiving object. For example, this would be the exception to throw if the caller attempted to use some object before it had been properly initialized.

ConcurrentModificationException [api doc]

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
  1. Between creating an iterator and actually iterating the content you shouldn't modify the collection.        
            List<String> list = new ArrayList<String>();
            list.add("a1");
            list.add("a2");
           
            Iterator<String> iterator = list.iterator();
            list.add("a3");  //CME
           
            while(iterator.hasNext()){
                System.out.println(iterator.next());

            }         
  1.  Even if you try to modify list during iteration other than by using iteraot.remove(); you will get this exception.                                                                                                         
                 while(iterator.hasNext()){
                      System.out.println(iterator.next());
                      list.add("d1"); 
//CME

                     list.remove(0);  //CME
                }

UnsupportedOperationException [api doc]

Thrown to indicate that the requested operation is not supported. 

This is used by Collection framework to notify that a particular operation is not supported for the given Object.


        List<String> list = new ArrayList<String>();
        list.add("a1");
        list.add("a2");
       
        List<String> readList =  Collections.unmodifiableList(list);
        readList.add("a3");


Above snippet will throw UnsupportedOperationException because it's modifying a read only list.

CloneNotSupportedException [api doc]

Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.


Tuesday, February 19, 2013

static keyword in Java

Java allocates memory after instantiation a class, using new operator. But there is one exception to this rule, static keyword.

The static keyword is used with data and methods of the class:
  1. If you want to have only a single piece of storage for a particular field, regardless of how many objects of that class are created, or even if no objects are created.                                    
  2. If you need a method that isn't associated with any particular object.      
static members of the class are also referred to as class data ( and class methods) or in general class members. Class name is the preferred way to refer to static members of the class, though you can use objects as well. You can't apply static keyword to local variables.

 public class StaticDemo {  
      private static int count; // initialized to default value of int i.e. 0  
   
      public static int getCount() {  
           return count++;  
      }  
   
      public static void main(String[] args) {  
           System.out.println(" Count: " + StaticDemo.getCount());  
           StaticDemo sd = new StaticDemo();  
           System.out.println(" Count: " + sd.getCount());  
      }  
 }  
Output :
 Count: 0
 Count: 1

Note, the first call to method, getCount() is using Class name but the second call is through an instance of class. The output returned is consistent. This example proves a point that there is a single storage for static data.

It's debatable if static methods are Object Oriented as you call methods without creating objects. My suggestion, avoid using lots of static methods.

static Initialization and static block

Below 2 are one and same :
       private static int count = 10;  //static initialization

or

       private static int count;
       static{    //static block
          count=10;
       }      

And you can have multiple statements inside a static block.

Order of Execution

Below example demonstrate the order of invocation :

 public class StaticLoadDemo {  
      static {  
           System.out.println("Class StaticDemo loading...");  
      }  
   
      static final int c = 5; // static initialization  
      static int a;  
   
      static { // static block  
           a = c;  
           System.out.println("value :" + a);  
      }  
   
      StaticLoadDemo() {  
           System.out.println("Constructor");  
      }  
   
      public static void main(String[] args) {  
           new StaticLoadDemo();  
      }  
   
      static {  
           System.out.println("final static block");  
      }  
 }  
Output:
Class StaticDemo loading...
value :5
final static block
Constructor

Important Points:
  1. Static block/initialization gets invoked right after class gets loaded. The output of the above class confirms the same.
  2. Static block is called only once (during the lifetime)
  3. If StaticLoadDemo class extends a base class named as Base. Then static blocks of Base class will be invoked first,  followed by subsequent subclasses.
  4. Order of initialization is static first if they haven't been already initialized by previous object creation, and then non-static component.

Inheriting static component

static components are associated with the class and not the individual object. So if a method is static, it doesn't behave polymorphically.
 class Super {  
      public static void printHello() {  
           System.out.println(" hello --base class");  
      }  
 }  
   
 public class Derived extends Super {  
      public static void printHello() {  
           System.out.println(" hello --derived class");  
      }  
   
      public static void main(String[] args) {  
           Super s = new Derived();  
           s.printHello();  
      }  
 }  
Output:
hello--base class

Memory allocation and  de-allocation

static methods (in fact all methods), as well as static data, are stored in the PermGen section of the heap, since they are part of the reflection data (class related data, not instance related data). 
  1. static primitive variables are stored in PermGen (Permanent Generation) space.
  2. If static data references to an Object; then reference is stored on PermGen but the actual object gets stored in heap(young/old generation).
 static members get garbage collected only when class gets unloaded (details here).

---
do post your feedback !!!

Saturday, February 16, 2013

Reflection in Java

Reflection is one of the advanced features of Java through which you can perform operations which wouldn't be possible otherwise. Through this technique, you can discover information about a class at runtime. This is accomplished through a special kind of object called the Class object, which contains information about the class. 

The class, Class(yes, the name of the class is Class) supports the concept of reflection, along with other classes Field, Method, and Constructor from java.lang.reflect package. Using these APIs, class information of any anonymous objects can be completely determined at runtime (without any information at compile time). So the .class file which gets generated after compiling Java source code (or as a stream by downloading it from network), is opened and examined by the runtime environment. 

Reflection is used to support one of most advanced features of Java; Serialization.

API Details

class Class (from package java.lang) & classes from java.lang.reflect package

The instance of the class, Class represent classes and interfaces in a running Java application. An enum and array are a type of class and annotation is a kind of interface. 

Class API provides a static method to load the class (if it is not already loaded) and return a Class reference. It takes a fully qualified class name as the parameter( including package name).

         //Load and return the reference
         Class<?> c = Class.forName("package.ClassName");
       
        //only load the class
        Class.forName("package.ClassName");

If a class with name ClassName doesn't exist in the package then you will get runtime exception ClassNotFoundException.

So if you want to use type information at runtime, you must first get a reference to the appropriate Class object. But if you already have an object of the given class; then you can get the Class reference by calling getClass method (part of the Object root class).

          //Class<?> is preferred over plain Class; even though they are equivalent
          Class<?> c = obj.getClass();         

There is another alternative to above; by using class literal:
        Class<Integer> c = int.class;
        Class<House> h = House.class; 


Time to walk the talk


import java.lang.reflect.Method;

/**
 * Reflects ArrayList API of Java
 * 
 * @author Siddheshwar
 * 
 */
public class ReflectArrayList {

 public static void main(String[] args) throws Exception {
  Class<?> c = Class.forName("java.util.ArrayList");
  Object object = c.newInstance();

  // get handle of a method
  Method addMethod = c.getDeclaredMethod("add", Object.class);
  // add.setAccessible(true); //if add method is private
  addMethod.invoke(object, new String("sid"));
  addMethod.invoke(object, new String("rai"));

  Class<?> noparams[] = {};
  Method sizeMethod = c.getDeclaredMethod("size", noparams);
  System.out.println("size  of List: "
    + sizeMethod.invoke(object, noparams));

  Method toStringMethod = c.getMethod("toString", noparams);
  System.out.println("values of List : "
    + toStringMethod.invoke(object, null));  //null or noparams
  
 }
} 
 
Output
size  of List: 2
values of List : [sid, rai]

To avoid cluttering the code; I have thrown base Exception. But here is the complete list of Exceptions which will be thrown:
ClassNotFoundException, 
SecurityException, 
NoSuchMethodException, 
IllegalArgumentException, 
IllegalAccessException, 
InvocationTargetException &
InstantiationException

 Above code reflects ArrayList class; few important points:
  1. Class provides methods to return Method, Fields, and Constructors. 
  2. Method API provides a method to dynamically call a method at runtime (envoke spec)
  3. getMethods returns public members from the class/interface and its superclasses/super interfaces whereas getDeclaredMethods returns all methods declared by the class/interface.
  4. To call private method; set accessibility to true; as method.setAccessible(true)
References:

 

Friday, February 15, 2013

final keyword in Java

Java's final keyword can be used with lot of entities like local variables, class members (attributes, methods), classes, objects etc. Let's go in detail on each aspect:
  1. data / local variable

    If a data is declared as final then compiler ensures that you can't re-assign another value to it. Compiler also allows you to declare a final data without initializing it. In this case value needs to be initialized before it gets used. The value of a final local variable can be determined at runtime.
    public static void main(String[] args){
            final int a = 123; 
    //declared and assigned

            final String name;
            name = "Sid";  //assigned later
           
            Random r = new Random();
            final int b = r.nextInt(10);
    //not final at compile time
           
            System.out.format("a=%d; name=%s; b=%d", a,name,b);
        }
              Output : a=123; name=Sid; b=1

    Note that, multiple invocations will print different value of b (less than 10, though). So b is run time constant.
  2. class attribute/data member

     final with data members (attributes) of the class behave almost the same way as final data.
    public class FinalTest {
        private final int a =5;
        private final int b;
      // blank final member

        private final int r = new Random().nextInt(10);
           
        public FinalTest(int b) {
            super();
            this.b = b; 
      // Compile fails in absence of this initialization

        }

        public static void main(String[] args){
            FinalTest ft = new FinalTest(5);
            System.out.format("a =%d; b =%d; r=%d", ft.a,ft.b,ft.r);       
        }
    }
    Data member, b is known as blank final. Compiler in this case forces you to initialize blank finals in the constructor. Blank finals provide more flexibility as you can have different value for each object and yet retain its immutable quality.
  3. method argument 

    Arguments can be declared as final to enforce no modification inside the method body. This is a good programming practice but usually, it's not used consistently by developers. But one case where it's mandatory is; when you pass data to the anonymous inner class.
    Read about it in detail #3 of this post
  4. method 

    Methods declared as final can't be overridden. Another reason suggested to make a method final is that it increases efficiency by making method call inline (so eliminating overhead of the method call; particularly useful when the method is small). But in recent JVM versions; hotspot technique can automatically detect this situation and can perform optimization. So its discouraged to declare a method as final to try help the optimizer.
    public class MyClass {
            public void myMethod() {...}
            public final void myFinalMethod() {...}
            private final void myPrivateFinalMethod() {...}
        }
    3rd method is declared as private as well as final. Is that ok?                              
    That's perfectly alright. But point to note here is that private methods can't be overridden so adding final doesn't add any value.  If a method is private it remains private and doesn't get passed down to the sub classes.
  5. class

    A class declared as final can't be subclassed. If there is never a need to make any changes to a class for safety or security reasons class can be declared as final. Declaring a class as final; implicitely makes all methods also as final as there is no way to override them. So just like the previous case, you can still add a final modifier but it doesn't add any value.                                                                                                                                                                                                                                             Final classes from Java API : java.lang.String, java.lang.Math, java.lang.Integer, java.lang.Double, java.lang.Short, java.lang.Void and other java.lang package classes                                          

Thursday, February 14, 2013

Interning String in Java

String class of Java API has a native method, intern().  This method is used for internalizing Java String. It's a process of creating a String pool where String objects with equal values are stored only once.

Method signature: 
public native String intern()

Straight from Java Doc
Returns a canonical representation for the string object.A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.


It follows that for any two strings s and t, 

 s.intern() == t.intern() is true if and only if s.equals(t) is true.


All literal strings and string-valued constant expressions are interned.
public static void main(String[] args){
        String s = "abc";
        String d = "abc".intern();
        String f = new String("abc").intern();
        String g = new String("abc");
       
        System.out.format("  s == d : %b", (s==d));
        System.out.format("; s == f : %b", (s==f));
        System.out.format("; s == g : %b", (s==g));
        System.out.format("; s.equals(f) : %b", s.equals(f));
        System.out.format("; s.equals(g) : %b", s.equals(g));
    }
Ouptput :  s == d : true; s == f : true; s == g : false; s.equals(f) : true; s.equals(g) : true

So all strings except g in above case are interned.


Related Post : Changes to intern() method in Java 7

Wednesday, February 13, 2013

Shallow Copy vs Deep Copy in Java

Copy/Clone mechanism of Java is used to return a new copy of the given object. The copied object will be a new instance, but the exact meaning of copy may depend on several factors.
(Revisit Java clone API: Read about clone basics)

Instead of heading straight to the definition, let's start with an example:


 public class Person {  
           public String name;  
           public int age;  
   
           public Person(String name, int age) {  
                     this.name = name;  
                     this.age = age;  
           }  
 }  


 public class CloneTest implements Cloneable {  
      private Person p;  
      private int a;  
   
      public CloneTest(Person p, int a) {  
           super();  
           this.p = p;  
           this.a = a;  
      }  
   
      public void printData() {  
           System.out.format("\n a = %d; Person : name=%s & age=%d", a, p.name,  
                     p.age);  
      }  
   
      public Object clone() throws CloneNotSupportedException {  
           return super.clone();  
      }  
   
      public static void main(String[] arg) throws CloneNotSupportedException {  
           CloneTest original = new CloneTest(new Person("Sid", 30), 1);  
           CloneTest clone1 = (CloneTest) original.clone();  
   
           // Data after cloning  
           original.printData();  
           clone1.printData();  
   
           clone1.p.age = 60; // modify contained object  
           clone1.a = 2; // modify the attribute  
   
           // Data after changes to cloned object  
           original.printData();  
           clone1.printData();  
      }  
 }  
   

Output
 a = 1; Person : name=Sid & age=30  //original Object
 a = 1; Person : name=Sid & age=30  //cloned Object
 a = 1; Person : name=Sid & age=60  //original after changes
 a = 2; Person : name=Sid & age=60  //cloned object after changes


Points To be Noted :
  1. Changes to the cloned Person object is getting reflected in the original object as well.
  2. Changes to the direct attribute(field i.e. a) of the cloned object are not updated in the original object.
     Let's see the same through a diagram :



 So what kind of copy is created by cloning as shown above ??


Shallow Copy 

Shallow copy is a bit-wise copy of an object. The new object has an exact copy of the values in the original object. If any of the fields of the object are references to other objects then only the reference addresses are copied (and not the content). 

In above example: Original as well as Clone1 are pointing to the same Person object, but there is a unique copy for the field, a.

Important point to be noted from the Person class :
Person class doesn't implement Cloneable interface. Is that reason for cloned and original object pointing to the same Person object? 
This can be verified easily with a small tweak:


 public class Person implements Cloneable {  
      public String name;  
      public int age;  
   
      public Person(String name, int age) {  
           this.name = name;  
           this.age = age;  
      }  
   
      public Object clone() throws CloneNotSupportedException {  
           // Person p= new Person(name, age);  
           System.out.println(" This method doesn't get called even");  
           return super.clone();  
      }  
 }  

Now run CloneTest class again and notice the output.

The output is still the same and in fact, Person class' clone() method is not called at all (Print statement put in its clone method is not getting printed.)

This confirms that copying through default clone mechanism is a SOFT COPY

 

Deep Copy

So now it's easy to understand what is a Deep Copy :




Deep Copy copies all fields and makes copies of dynamically allocated memory pointed to by fields. Deep copy occurs when an object is copied along with the objects to which it refers.
 
In our case, the deep copy will have a separate Person object so that changes in Clone1 doesn't get reflected in the Original object.

Can't we achieve it for our CloneTest class ??

Yes, it can be done with a small tweak.


 public class Person implements Cloneable {  
      public String name;  
      public int age;  
   
      public Person(String name, int age) {  
           this.name = name;  
           this.age = age;  
      }  
   
      public Object clone() throws CloneNotSupportedException {  
           return super.clone();  
      }  
 }  


 public class CloneTest implements Cloneable {  
      private Person p;  
      private int a;  
   
      public CloneTest(Person p, int a) {  
           super();  
           this.p = p;  
           this.a = a;  
      }  
   
      public void printData() {  
           System.out.format("\n a = %d; Person : name=%s & age=%d", a, p.name,  
                     p.age);  
      }  
   
      public Object clone() throws CloneNotSupportedException {  
           CloneTest ct = (CloneTest) super.clone();  
           ct.p = (Person) p.clone();  
           return (Object) ct;  
      }  
   
      public static void main(String[] args) throws CloneNotSupportedException {  
           CloneTest original = new CloneTest(new Person("Sid", 30), 1);  
           CloneTest clone1 = (CloneTest) original.clone();  
   
           // Data after cloning  
           original.printData();  
           clone1.printData();  
   
           clone1.p.age = 60; // modify contained object  
           clone1.a = 2; // modify the attribute  
   
           // Data after changes to cloned object  
           original.printData();  
           clone1.printData();  
      }  
 } 

And Output is :
 a = 1; Person : name=Sid & age=30  //original Object
 a = 1; Person : name=Sid & age=30  //cloned Object
 a = 1; Person : name=Sid & age=30  //original after changes
 a = 2; Person : name=Sid & age=60  //cloned object after changes


So now the modified clone() method supports deep copy. Please note that the clone method explicitly clones Person object.


Alternative Techniques

Below are some of the alternatives for creating a clone of objects. 

Copy Constructor or copy factory 
Understanding and successfully implementing Cloneable interface is tricky and risk-prone. So you can use constructors factory method to create the copy of the given object.


     public CloneTest createCloneTest(){  
         Person pt = new Person(p.name, p.age);  
         CloneTest ct = new CloneTest(pt,a);  
         return ct;  
       } 

So you just need to call this method to clone an object of class CloneTest.

Deep copy through Serialization
Deep copy means that your are duplicating the entire web of objects, rather than just the basic object
and its references. Serialization can be used to achieve deep copy.
When you deep copy through Serialization, make sure that all classes in object's graph are Serializable.

 public class Person implements Serializable{ }


 import java.io.ByteArrayInputStream;  
 import java.io.ByteArrayOutputStream;  
 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 import java.io.ObjectOutputStream;  
 import java.io.Serializable;  
   
 public class CloneTest implements Serializable {  
   
      public CloneTest deepCopy(CloneTest t) throws IOException,  
                ClassNotFoundException {  
           ByteArrayOutputStream buf = new ByteArrayOutputStream();  
           ObjectOutputStream o = new ObjectOutputStream(buf);  
           o.writeObject(t);  
   
           ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(  
                     buf.toByteArray()));  
           return (CloneTest) in.readObject();  
      }  
      // no change in other methods except you need to call this method to clone  
 }            

Please note that, buffer is used in deepCopy method instead of file to serialize object. For ObjectOutputStream it's all the  same.

---
keep coding !!!

Wednesday, February 6, 2013

Clone objects in Java

Java's cloning feature returns field-by-field copy of the object. It creates soft copy of the object on which it gets invoked. Below is the complete signature of the method:
protected native Object clone() throws CloneNotSupportedException
This is a native method and hence it's not implemented in Java (but in C/C++). Above method is present in the root class i.e. Object class and not in Cloneable interface.

 To support cloning of a Java object, you need to do below to the class definition.
  1.  Implement Cloneable interface
  2.  and override clone method (from Object class).
Cloneable interface is a marker interface (it doesn't have any method). The purpose of this interface is to tell JVM that this class is eligible for cloning.

By convention, the returned object should be obtained by calling super.clone. The contract from the specification [JavaSE7] -
for any object x the intent is :

Contract 1 
x.clone() != x   should be true

Contract 2
x.clone().getClass() == x.getClass()  should be true, but these are not absolute requirement

Contract 3
x.clone().equals(x) will be true, but its not an absolute requirement.

The contracts are very loose. Another condition is that no constructor are called to achieve it.

 class Student implements Cloneable {  
      private String name;  
      private int age;  
      public Student(String name, int age) {  
           super();  
           this.name = name;  
           this.age = age;  
      }  
      @Override  
      public String toString() {  
           return "Student [name=" + name + ", age=" + age + "]";  
      }  
      public Student clone() throws CloneNotSupportedException {  
           return (Student) super.clone();  
      }  
      public static void main(String[] args) {  
           Student student = new Student("Siddheshwar", 18);  
           System.out.println("Original Student :" + student);  
           try {  
                Student clonedStudent = student.clone();  
                System.out.println("Clonned Student :" + clonedStudent);  
           } catch (CloneNotSupportedException e) {  
                e.printStackTrace();  
           }  
      }  
 }  

Output:
Original Student :Student [name=Siddheshwar, age=18]

Clonned Student :Student [name=Siddheshwar, age=18]

Point to note about above code :
  1. Cloneable interface does not contain the clone method. So you can't clone an object by just implementing this interface. 
  2. You need to have definition of clone method inside class (which implements Cloneable interface). 
  3. If we try to call the clone() method on an object of a class which doesn't implement the Cloneable interface; you will get runtime exception CloneNotSupportedException.
  4. clone() method is a protected method in Object class so you can't call it directly.
  5. It performs shallow clone/copying
  6. If you implementing the deep clone, the same rule applies. You should call super.clone to acquire the correct type of object and then perform the deep cloning operations.

Significance of super.clone() ?
super.clone() method basically calls Object's clone method. To make sure this works correctly ensure that all the super classes obey this rule. It invokes java.lang.Object clone method to ensure that cloned object is constructed properly.

 Final Note

  1. Class implementing Cloneable interface should provide a properly implemented public clone method.
  2. clone method can return specific class type instead of Object. This is because as of Java SE 1.5, covariant return types are legal. This is why above example returns a Student type instead of Object.
  3. Returning subclass type also saves you from casting in the client code.
Related Post : Shallow Copy vs Deep Copy in Java