Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Objects having Null value

 
Atul Sawant
Ranch Hand
Posts: 304
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

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");
System.out.println(a1.i);
}
}

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

Any kind of help would be appreciated.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When resolving a1.i, only the reference type of a1 is important.
 
Vinayagar Karpagam
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??
 
Greg L Tonn
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

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


Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic