• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

NullPointerException

 
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;
 
Bras cause cancer. And tiny ads:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic