What is the differences between String str1="" and String str2 =null?
When we print str1 there is no output and when we print str2 output is null.
5 Answers
"" is the empty string, null is the null reference.
2 Comments
"" is a String Literal, it will go into the String constants pool. It is not equal to new String()The first is an empty String whereas the second is a null reference to a String.
An empty String is a String with no characters.
A null reference is a reference to a String that is not existent.
3 Comments
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned."" means strings is created in string pool while for second one is nothing exist.
str1 there is no output
because string is empty so its printing nothing to output while second is null so its string value is null.
Comments
The first you are creating a new String object and assigning it "" or empty String. Your variable is pointing to this string object. The second you are not creating a new String object. You are creating a pointer that is not pointing to anything it is null. When you print using "" + yourstring it will print null because of the base Class objects toString() method.
Stringobject with a length of 0, and one is a null reference (i.e. not a reference to an object at all)nullnot being "valid"?