This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes NullPointerException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "NullPointerException" Watch "NullPointerException" New topic
Author

NullPointerException

subhasish nag
Ranch Hand

Joined: Apr 25, 2008
Posts: 101
code#SBTest.java
----------------
public class SBTest
{

static StringBuffer s;
public static void main(String[] args)
{
StringBuffer result=new StringBuffer();
result.append(s);

System.out.println(result);


}
}
code#STest.java
public class STest
{

static String s;
public static void main(String[] args)
{
String result=new String();
result.concat(s);

System.out.println(result);



}
}


Here the Ist one comiles fine and output null. But 2nd code gives NullPointerException. Pl explain the reason why it is ok for StringBuffer but not ok for String.


Thanks,<br />Subhasish
ankit kumar
Ranch Hand

Joined: Apr 28, 2008
Posts: 108
in the second code you are using String . it will return a new string and you are adding a null in that thats why it is giving you a NullPointerException.


Cleared SCJP 1.5 | Cleared SCWCD 5.0
SCDJWS 6 in progress.....
Jiang zhixiao
Greenhorn

Joined: Jul 01, 2008
Posts: 13
for StringBuffer
public StringBuffer append(StringBuffer sb)
if sb is null, the StringBuffer object will return four character "null";

let's see String:
public String concat(String str)
if str's length is 0;method concat return the object itself,else,it will creat a new String object ,as we know parameter "null" can't be added into class String 's constructor;
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: NullPointerException
 
Similar Threads
Passing null to Obj,String args methods
confuse about StringBuffer insert method
How to Compare StringBuffer object with String Object
about 'equals'method
Why does this give compilation error ?