Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding "null" in java

 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Please have a look at the following code snippet:


When we invoke the method isEmpty with null as argument, why does it not return boolean value "true" for s==null. Isn't null==null true?
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mansukhdeep Thind wrote:Isn't null==null true?

Let's test : System.out.println(null == null);

If you get exception in runtime. you have to analyze why you are getting that
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I followed your instruction. printing null==null does in fact return a Boolean true. Then why does throw null pointer exception? Or is it simply the act of passing a null to the method that spoils the show?
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just realized I am thinking on wrong lines. It is the bitwise OR operator that is causing harm. How does this "|" operator function. What s meant by bitwise OR?
 
Henry Wong
author
Marshal
Pie
Posts: 21362
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mansukhdeep Thind wrote:I just realized I am thinking on wrong lines. It is the bitwise OR operator that is causing harm. How does this "|" operator function. What s meant by bitwise OR?


As you figured out, a bitwise OR doesn't short circuit. It is used to OR all the bits of the two operands. From your code, the logical OR is what you need.

Henry
 
Mansukhdeep Thind
Ranch Hand
Posts: 1158
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So when the JVM tries to evaluate s.length, it hits a brick wall as String reference "s" is null(pointing to nothing). Hence, the stack explodes throwing a NullPointerException. Correct Henry?
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic