• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Good one from Whizlabs  RSS feed

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I came across this question in Whizlabs software. Can anybody explain me why the output is SCJP twice? The code is below:
class Myclass2 {
static String myName="SCJP";
Myclass2 getMyclass() {
System.out.println(myName);
return null;
}
public static void main(String args[]) {

System.out.println(new Myclass2().getMyclass().myName);
}
}
Latha
 
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First System.out.println is executed inside getMyclass() method and this method returns null but that doesn't matter since String myName is static. So the second System.out.println will still be able to find myName because the return type of the method is declared as Myclass2.
Basically you can say that "this type of null is Myclass2".
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the print statement. That method prints out the content of the myName static variable. It also returns a (null) MyClass2 reference.
The second SCJP output is generated from the second part of the print statement. Because getMyClass() returns null the JVM sees this part of the print statement as . Note that the null is a reference to a MyClass2 and that the myName member is static and you don't need an instance of the MyClass2 class to access the static member (remember with static members all you really need is the class)....the JVM is seeing the equivalent of . It's almost as if the JVM is saying: "ok, I have a MyClass2 reference...is the myName member static? Yes it is so I'll allow the access and not even bother to check to see if the MyClass2 reference is to a valid object."
I think this is another example of where you have a question designed to test your understanding of the language and what is allowed as opposed to an example of good code....
[ March 27, 2004: Message edited by: Richard Quist ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!