This week's book giveaway is in the JDBC forum.
We're giving away four copies of Make it so: Java DB Connections & Transactions and have Marcho Behler on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why not nullpointer exception? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why not nullpointer exception?" Watch "why not nullpointer exception?" New topic

why not nullpointer exception?

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689

hi here getMyClass is returning null but it is not throwing nullpointer exception ?


SCJP 1.4
Neelesh Bodas
Ranch Hand

Joined: Jul 20, 2006
Posts: 107
because myName is a static member of the class. The fact that java allows you to reference a static member using the instance of the class is simply a syntactic sugar, it doesnot use the instance reference to retrive the value of the member
[ August 23, 2006: Message edited by: Neelesh Bodas ]
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643

Check code above
Run above code as it is and see output
Remove static keyword at line 2 and run above code and see output
Kaush Kane
Ranch Hand

Joined: May 22, 2006
Posts: 37
public class returnNull{
static String myName="SCJP"; //line 2
public static void main(String args[]){
returnNull r1=new returnNull();

I tried running the above code. I m getting the o/p as "SCJP" and not Null pointer exception. Could you explain me why???
Jon Lee
Ranch Hand

Joined: Mar 04, 2005
Posts: 134
Neelesh Bodas has already given the answer......

SCJP 5.0 - 98% (2007)<br />SCWCD 1.4 - 97% (2007)
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643

As we know static variables or static methods can be executed by class
name also so The compiler replaces line System.out.println(r1.myName);
as System.out.println(returnNull.myName); this is why there is no null
point exception.
Check the code above
I agree. Here's the link:
subject: why not nullpointer exception?
It's not a secret anymore!