• Post Reply Bookmark Topic Watch Topic
  • New Topic

can we access null.[member]  RSS feed

 
Kumaran brk Rajakumar
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This program executes successfully and prints 42..

public class Foo {
static int fubar = 42;

Foo getFoo() {
return null;
}

public static void main(String args[]) {
Foo foo = new Foo();
System.out.println(foo.getFoo().fubar);
}
}

Can anyone tell funda behind this.
Thanks..
 
Andrew Nomos
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key point is not that the method getFoo() returns null but that it returns an instance of class Foo and since fubar is a static member it can be accessed.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

The previous poster is correct, but I just wanted to clarify that the return value of getFoo() is not used at runtime. The compiler emits code to access the variable "x" based solely on the class type; that code doesn't refer to any object of type Foo.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words, getFoo() actually never gets executed in your code!
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
With other words, getFoo() actually never gets executed in your code!


No, actually, it does; but the return value is ignored. You could see this by putting a "println" into the getFoo() method.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ernest Friedman-Hill:


No, actually, it does; but the return value is ignored. You could see this by putting a "println" into the getFoo() method.


You are right, of course. Silly me... :roll:

Thanks for the correction!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!