Meaningless Drivel is fun!*
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

Manju Devarla
Ranch Hand

Joined: Dec 14, 2006
Posts: 85
Why below given prg throws Nullpointer exception


[HENRY: Added Code Tags. Formatted Code.]
[ December 20, 2006: Message edited by: Henry Wong ]
ramya ray
Ranch Hand

Joined: Aug 11, 2006
Posts: 101
I think, because you are calling method on null reference of Test .
pengfei cao
Greenhorn

Joined: Dec 18, 2006
Posts: 4
class ClassA
{
public void methodA()
{
ClassB classB = new ClassB();
classB.getValue();
//System.out.println(" ClassA's methodA()!");
}
}
class ClassB
{
public Test classC=new Test();
public String getValue()
{
//System.out.println("ClassB's getValue() !");
return classC.getValue();

}
}
public class Test
{
public String value="ss";
public String getValue()
{
value = "ClassB";
// System.out.println("Test's getValue()!");
return value;

}
public static void main(String s[])
{
ClassA a = new ClassA();
a.methodA();
// System.out.println("main mothods()!");
}
}

Look at "public Test classC=new Test(); ",if I write this, there is no errors! Compilation successfully! So I think, the object classC must be instantiate. This is my own standpoint!
Geetha Arthanari
Greenhorn

Joined: Nov 24, 2006
Posts: 25
class ClassB { public Test classC; public String getValue() { return classC.getValue(); }}

In the above ClassB,ur statement is:
public Test classC;-------Here classC contains only null value.
Then only NullPointerException is occurring.

so
for avoid this,
we have two options:
1. we need to use statement like this,
Test classC=new Test();-----Now classC having details of Test class.
or
2. we've to change the class Test like this.

public class Test
{
public static String value="ss";
public static String getValue()
{
value = "ClassB";
return value;
}
public static void main(String s[])
{
ClassA a = new ClassA();
a.methodA();
}
}

Because static methods and static variables are class level variables.
Nicholas Cheung
Ranch Hand

Joined: Nov 07, 2003
Posts: 4982
Always keep in mind, for any non-primitive objects, default value will NOT be given, and you must NEW it before use.

Nick


SCJP 1.2, OCP 9i DBA, SCWCD 1.3, SCJP 1.4 (SAI), SCJD 1.4, SCWCD 1.4 (Beta), ICED (IBM 287, IBM 484, IBM 486), SCMAD 1.0 (Beta), SCBCD 1.3, ICSD (IBM 288), ICDBA (IBM 700, IBM 701), SCDJWS, ICSD (IBM 348), OCP 10g DBA (Beta), SCJP 5.0 (Beta), SCJA 1.0 (Beta), MCP(70-270), SCBCD 5.0 (Beta), SCJP 6.0, SCEA for JEE5 (in progress)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: NullPointer Exception