• Post Reply Bookmark Topic Watch Topic
  • New Topic

A simple question regarding String class  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Rajat
{
public static void main(String args[])
{
String a=null;
String b="rajat";
System.out.println(a+b);
System.out.println(a);
System.out.println(a.toString());
}
}
output of 1st system.oout.println statement comes to be nullrajat.
output of 2nd system.out.println statement comes to be null.
3rd system.out.println statement throws null pointer exception.
can you tell me why?

can you tell me why?
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

The reason for the 3rd call throwing an Exception is obvious: You are trying to invoke a method on a null reference.
If you try to print a null reference it prints the word "null", and the "+" concatenates the word "rajat" to form "nullrajat."
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!