| Author |
Doubt regarding "null" in java
|
Mansukhdeep Thind
Ranch Hand
Joined: Jul 27, 2010
Posts: 1142
|
|
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?
|
~ Mansukh
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
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
Joined: Jul 27, 2010
Posts: 1142
|
|
|
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
Joined: Jul 27, 2010
Posts: 1142
|
|
|
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
Sheriff
Joined: Sep 28, 2004
Posts: 16686
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Mansukhdeep Thind
Ranch Hand
Joined: Jul 27, 2010
Posts: 1142
|
|
|
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?
|
 |
 |
|
|
subject: Doubt regarding "null" in java
|
|
|