Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pRINTING AN OBJECT WITH NULL REFERENCE

 
Porchelvi Vendhan
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
When the following code is executed:
public class Test{
static String s1;
static Integer i1;

public static void main (String args [])
{
System.out.println(s1);
System.out.println(i1);
}
}
null
null
gets printed instead of throwing a NullPointerException.
Can someone please explain why?
Thanks
Porchelvi
 
leena rane
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class Test{
static String s1;
static Integer i1;
public static void main (String args [])
{
System.out.println(s1);
System.out.println(i1);
}
}

Since s1 and i1 are member variables they are automatically initialised to default value(null)
It is as good as writing
static String s1=null;
static Integer i1=null;
But if u have something like this:
public class Test{
public static void main (String args [])
{
static String s1;
static Integer i1;
System.out.println(s1);
System.out.println(i1);
}
}
It will not compile,because now they are in a method body they will not be initialized to default value(null)
Hope it helps
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Porchelvi,
I'm going to move this over to Certification Study as the question is not related to a mock exam error.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
marilyn murphy
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>When the following code is executed:

>null
>null
>gets printed instead of throwing a NullPointerException.
>Can someone please explain why?

The System.out.println( obj ) method changes the obj to a String by calling
String.valueOf( obj );
Since, as Leena explained, the objects are initialized to null, "If the argument is null then the string "null" is printed" (API)
[This message has been edited by marilyn murphy (edited September 22, 2001).]
 
Marilyn de Queiroz
Sheriff
Posts: 9066
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since there is another discussion of this same question in another thread, I am closing this one.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic