• 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic