wood burning stoves 2.0*
The moose likes Mock Exam Errata and the fly likes pRINTING AN OBJECT WITH NULL REFERENCE Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "pRINTING AN OBJECT WITH NULL REFERENCE" Watch "pRINTING AN OBJECT WITH NULL REFERENCE" New topic
Author

pRINTING AN OBJECT WITH NULL REFERENCE

Porchelvi Vendhan
Greenhorn

Joined: Sep 08, 2001
Posts: 21
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

Joined: Aug 13, 2001
Posts: 280

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

Joined: Aug 30, 2000
Posts: 3141
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


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: pRINTING AN OBJECT WITH NULL REFERENCE
 
Similar Threads
pRINTING AN OBJECT WITH NULL REFERENCE
null exception!
Strings
Immutable classes in java
Null String Concat