This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization 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: 20894
76
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