-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 ??

2
  • 7
    "null" is a string with the word "null" in it, which is entirely different from a null value. Mar 13, 2019 at 12:15
  • 1
    What is null in Java?
    – Pshemo
    Mar 13, 2019 at 12:18

3 Answers 3

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;
}  
3
  • by using equals method . first check that if object is not null then compare by equals() method of String Mar 13, 2019 at 12:18
  • 1
    Yes, that should be part of your answer, since it was in OP's question. :) Mar 13, 2019 at 12:20
  • 1
    you could simplify str!=null && str1!=null&& str.equals(str1) to str != null && str.equals(str1) Mar 13, 2019 at 12:25
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.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.