my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes NullPointer exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "NullPointer exception" Watch "NullPointer exception" New topic
Author

NullPointer exception

Vishal Chugh
Ranch Hand

Joined: Oct 27, 2007
Posts: 177
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
Jun Wu
Greenhorn

Joined: Mar 20, 2008
Posts: 14
Hello vishal chugh ,your codes throw NullPointerException for :
public String getValue() {
return classC.getValue();
} // the classC = null
Vishal Chugh
Ranch Hand

Joined: Oct 27, 2007
Posts: 177
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

Joined: Oct 27, 2007
Posts: 177
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
 
jQuery in Action, 2nd edition
 
subject: NullPointer exception
 
Similar Threads
Why Exception in this code?
NullPointer Exception
Why runtime exception thrown is this code