• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointerException

 
subhasish nag
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
ankit kumar
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jiang zhixiao
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic