File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "NullPointerException" Watch "NullPointerException" New topic


subhasish nag
Ranch Hand

Joined: Apr 25, 2008
Posts: 101
public class SBTest

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


public class STest

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



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

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;
I agree. Here's the link:
subject: NullPointerException
It's not a secret anymore!