Monday, August 19, 2013

Behavior of Object reference when assigned to null and ""

Difference between assigning String reference to null or empty quotes

Instance variables are initialized to a default value each time a new instance is created
But String and other Object references are assigned to null by default.Its always a good practice to assign a value explicitly to variables which increases code readability.

Lets see what happens when we invoke String related methods when String reference is assigned to null or "".

Program 1 :-

public class StringReference {

/**
* @param args
*/
String str1;

public String getStr1() {
return str1;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
StringReference sr = new StringReference();
String strl = sr.getStr1();
System.out.println(strl.length());
}

}
Run the above program it throws nullpointer exception because str1 is a reference and is not pointed to any object. So invoking a reference which doesnt point to an Object will throw null pointer exception.
Output :-
Exception in thread "main" java.lang.NullPointerException
at StringReference.main(StringReference.java:16)

Now lets see assigning String variable to ""

public class StringReference {

/**
* @param args
*/
String str1="";

public String getStr1() {
return str1;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
StringReference sr = new StringReference();
String strl = sr.getStr1();
System.out.println(strl.length());
}

}


Output :- 0

Here Str1="" creates an empty String object

Now Str1 is referring to an object so invoking String related methods liketoUpperCase(),length() etc. will not throw null pointer exception.

Happy Learning

Please provide your valuable comments on this article and share it across your network.



No comments:

Post a Comment

Like and Share