• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the difference between few string assigments and equality checks mentioned.  RSS feed

 
ajay mittal
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can anyone help me out to know the difference between the following statements:-

1. String str = null;
String str = "";

2. str.equals(null);
null.equals(str);

Waiting for your valuable replies.

Ajay

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
null is not the same thing as an empty string.

When you assign null to str, you're making str refer to no object at all.
When you assign "" (the empty string) to str, you're making it refer to a String object that has zero characters.

In str.equals(null); you call the equals() method on str, passing it null as the argument. The result will always be false.

The expression null.equals(str); does not compile. You could try this instead:

but that would give a NullPointerException, because that's what happens when you try to call a method on a variable that is null.
 
Paweł Baczyński
Bartender
Posts: 2076
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.
String str = null; - this assigns value null to the variable str of type String. The null means "no value".
String str = ""; - this assigns value "" to the variable str of type String. The "" means "empty String". That is a String with length equal to 0 and that contains no characters.
Those two are not the same.

2.
str.equals(null) - that checks if value of str variable equals null. This will always return false. If str really is null you'll get NullPointerException.
The correct way to check a variable against null is by evaluating: str == null.

null.equals(str) - this won't even compile.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!