• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

why not nullpointer exception?  RSS feed

 
Ranch Hand
Posts: 689
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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

why?
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class returnNull{
static String myName="SCJP"; //line 2
public static void main(String args[]){
returnNull r1=new returnNull();
r1=null;
System.out.println(r1.myName);
}
}



I tried running the above code. I m getting the o/p as "SCJP" and not Null pointer exception. Could you explain me why???
 
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neelesh Bodas has already given the answer......
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Farmers know to never drive a tractor near a honey locust tree. But a tiny ad is okay:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!