• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointer exception

 
Vishal Chugh
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • 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
 
Jun Wu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic