Forums Register Login

NullPointerException

+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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;
Everyone is a villain in someone else's story. Especially this devious tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 696 times.
Similar Threads
Why does this give compilation error ?
confuse about StringBuffer insert method
How to Compare StringBuffer object with String Object
about 'equals'method
Passing null to Obj,String args methods
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 19, 2024 00:24:31.