aspose file tools*
The moose likes Beginning Java and the fly likes null pointer exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "null pointer exception" Watch "null pointer exception" New topic
Author

null pointer exception

priya rishi
Ranch Hand

Joined: Oct 26, 2008
Posts: 119
Without line 6 this code throws nullpointer exception.
but with it ,prints null.
How come? please explain

class nullDemo
{
static String s;
public static void main(String args[])
{
s = s + ""; //line 6
System.out.println(s);
String s1 = s.toLowerCase();
System.out.println(s1);
}
}


SCJP 5 , SCWCD 5
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

Every static or instance field gets an initial value. For numbers that's 0, for booleans false, and for objects null.

Since line 6 is the only assignment to static field s, without that line s will remain null. When you then try to call a method on it (line 8) - BOOM! NullPointerException.

Now on line 6 you assign something to s. You are using the old value of s for that though, so the result will be

Because of this concatenation, the null is converted to string literal "null" and then concatenated with the empty string - leading to the string "null".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

For details (and future reference), see JLS - 15.18.1 String Concatenation Operator +...
If an operand of type String is null, then the string "null" is used instead of that operand.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: null pointer exception