-2

I have a class with the two string variable i.e:

String str = null;
String str1="null";

One is a "string value null" and other in other case null object is assigned to a string variable. So what is the difference in both the two assignments and how to check if one is different from other ??

Neeraj
  • 83
  • 2
  • 6

3 Answers3

7

String str = null; means str is a reference of String which points to null.

And String str1="null"; means str1 object which points to String Object which is "null".

First check if object is null or not ? then compare by using equals method. like

if(str==null && str1==null){
   //Both are null and equal
}   

if(str != null && str.equals(str1)){
  //return true;
}
else
{
   //return false;
}  
Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
3

The String "null" is a string of length 4 with the characters n, u, l and l. It can be worked on as any other string.

The null reference isn't a string. Any attempt to use it like a string will result in a NullPointerException.

glglgl
  • 89,107
  • 13
  • 149
  • 217
0

1) String str = null;

Here str has no instance is created because it is assigned to null, so no new memory is consumed in heap

2) String str1="null";

Here str1 string instance is created and "null" is stored as value

Rahul Kishan
  • 314
  • 4
  • 18