Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Objects having Null value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Objects having Null value" Watch "Objects having Null value" New topic

Objects having Null value

Atul Sawant
Ranch Hand

Joined: Jul 06, 2006
Posts: 304

Please see the following code: please let me know how variable i was been able to get called when actually object a1 had no reference in it i.e. it has null value.

class A1
static int i = 10;
static { System.out.println("A1 Loaded "); }
public class A
static { System.out.println("A Loaded "); }
public static void main(String[] args)
System.out.println(" A should have been loaded");
A1 a1 = null;
System.out.println(" A1 should not have been loaded");

When you run it you get the output:
A Loaded
A should have been loaded
A1 should not have been loaded
A1 Loaded

Any kind of help would be appreciated.

Mission SCWCD. Mission SCJP Complete: SCJP 1.4 - 91%
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
When resolving a1.i, only the reference type of a1 is important.
Vinayagar Karpagam
Ranch Hand

Joined: Apr 09, 2006
Posts: 72
a1.i is not throwing a NullPointerException because i is a static variable and while accessing a static variable through an instance, the reference need not be non-null.
Anuragk kushwaha
Ranch Hand

Joined: Aug 02, 2006
Posts: 51
Hi Atul...

No need to create a reference if you declared i as static
because it gets memory when the class is loaded.

Even you get the same output if you write

if you want to see NullPointerException the remove static keyword
from your very first statement....
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10031

Hi Guys,

It would be interesting to know, why A1 should not have been loaded runs before A1 Loaded.

I thought as soon as we say A1 a, the class A1 gets loaded in the memory. Am I wrong on this??Anyone to help me out??

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Greg L Tonn
Ranch Hand

Joined: Nov 27, 2006
Posts: 52
Originally posted by Jothi Shankar Kumar Sankararaj:
It would be interesting to know, why A1 should not have been loaded runs before A1 Loaded.

Jothi, A1 is not acctually "loaded" until the call to the static variable.

Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Yes, it is not loaded until you call a static variable (that is no compile time constant!) or if you make a new object of that class.

A1 a1 = null;
will not execute the static block.


all events occur in real time
I agree. Here's the link:
subject: Objects having Null value
jQuery in Action, 3rd edition