Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Practice Question

 
Praveen Mathur
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Javaranchers:
Please try to predict the output of this question:
class A {
static A createA() {
return new A();
} // createA()
} // A

public class Tester {
public static void main(String[] parms) {
A aVar = null;
System.out.println(aVar.createA().hashCode());
} // main()
} // Tester
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It will print hashCode for an object of class A.
 
Ed B.
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it should throw a NullPointerException as the aVar is null. The createA method is static so it can be invoked like A.createA().
Adnan
 
Ed B.
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now that I tested the class, it does print out the hashcode. I am truly amazaed
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Barkat's right: there's no problem with the code, you don't have to have an instance of a class to call its static(class) methods. e.g., Math class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic