Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

java.lang.NullPointerException

  Asked By: Loretta    Date: Jan 10    Category: Java    Views: 881
  

I am facing a simple problem..if i run this simple code in my main
function..i am getting a java.lang.NullPointerException

String s = null;

if ( s!= null || s.length()> 0)
System.out.println("s != null || s.length() > 0");

but if i change it to

if ( s== null || s.length()> 0)
System.out.println("s != null || s.length() > 0");

then i am getting the output..
can anybody plz explain..why itz not wrking in first case??

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Walborgd Fischer     Answered On: Jan 10

the efforts by u all ..help me to draw following conclusion..

String s="";
case1:

if (s==null || s.length()> 0 )
System.out.println("s==null || s.length()> 0 ");

here first conditon(s==null) is not met..second is also not met(||
s.length()> 0 )
as we cant assume String S="" and String =null; the same case...

Case2:
if (s==null || s.length()< 0 )
System.out.println("s==null || s.length()< 0 ");

here first condition is not met..as well as second also lead to false..

Case 3:

if (s==""|| s.length()< 0 )
System.out.println("s==""|| s.length()< 0 ");

here first condition is met..s=="" leads to true..so second condition is
nt chkd at all..

now if String=null;

if (s==""|| s.length()> 0 )
System.out.println("s==null || s.length()> 0 ");

now there will be NPE...for second condition..and first condition is not
met..

so wat i conclude is that
i) we can't calculate the length of a string which is set to null...and if its
not set to null..then the length is equal to the number of 16-bit Unicode
characters in the string..otherwise its zero(String s="";).
ii)we can't assume String s=null and String S="";..the same case..

 
Answer #2    Answered By: Bradley Evans     Answered On: Jan 10

The problem  is that for conditional statements (like if, else etc.) in
java/C++, it does "Short-circuiting". i.e. This means that the expression will
be evaluated only until the truth or falsehood of the entire expression can be
unambiguously determined.

In ur case when, s = null;

a. if (s== null  || s.length()> 0),
Here s==null is TRUE, so s.length() is not evaluated.

b. if ( s!= null || s.length()> 0),
Here s!=null, this means the conditional statement can be true
if s.lenght()>0. But the time it evaluates s.lenght(), it finds
s is null and throws NPE.

 
Didn't find what you were looking for? Find more on java.lang.NullPointerException Or get search suggestion and latest updates.




Tagged: