Win a copy of Head First Android this week in the Android forum!
  • 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

NullPointer exception

 
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


I had read that NullPointerException is thrown when we try to call some method on reference variable which is not pointing to any object(or pointing to null)


But :

Why the below one is throwing NullPOinter exception , when i am trying to run it , it compiles fine.
public class ClassA {
public void methodA() {
ClassB classB = new ClassB();
classB.getValue();
}
public static void main(String args[])
{
ClassA a = new ClassA();
a.methodA();

}


}
class ClassB {
public ClassC classC;

public String getValue() {
return classC.getValue();
}
}

class ClassC {
public String value;

public String getValue() {
value = "ClassB";
return value;
}
}


Please throw some light on it...

Thanks
Vishal
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello vishal chugh ,your codes throw NullPointerException for :
public String getValue() {
return classC.getValue();
} // the classC = null
 
Vishal Chugh
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much Anmy!!!
Great noticing power

How i missed it :roll: ?

Yeah here it is calling getValue() on ClassB without creating its object while this was not the case with getValue() call of ClassA and ClassB

Thanku
Vishal Chugh
 
Vishal Chugh
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much Anmy!!!
Great noticing power

How i missed it :roll: ?

Yeah here it is calling getValue() on ClassC without creating its object while this was not the case with getValue() call of ClassA and ClassB

Thanku
Vishal Chugh
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic