wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes explain the answer 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 "explain the answer " Watch "explain the answer " New topic
Author

explain the answer

ganesh subbiah
Ranch Hand

Joined: Nov 18, 2004
Posts: 39
hi all,

This question is taken Valentin's Mock Exam . can any one explain the answer .Is this under Java cert objective?


public class Question24
{
public static void main(String[] args)
{
Question24 q24 = null;
int i = q24.throwDice(); //line 1
int j = getDice().throwDice(); //line 2
System.out.println("Result: "+i+","+j);
}
private static int throwDice(){
return 1+(int)(Math.random()*6);
}
private static Question24 getDice(){
return null;
}
}
A. Compilation error.
B. The code compiles but throws a NullPointerException at line 1 when run.
C. The code compiles but throws a NullPointerException at line 2 when run.
D. The program will always print Result: x,y, where x and y are two numbers between 1 and 6.
E. The code compiles fine.
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830
public class Question24
{
public static void main(String[] args)
{
Question24 q24 = null;
int i = q24.throwDice(); //line 1
int j = getDice().throwDice(); //line 2
System.out.println("Result: "+i+","+j);
}
private static int throwDice(){
return 1+(int)(Math.random()*6);
}
private static Question24 getDice(){
return null;
}
}


I think answer 2 is correct .
q24 is reference that is pointing to null ( has no object ) & when we call anything from null reference it throws NullPointerException .
Rajasekar Elango
Ranch Hand

Joined: Sep 13, 2004
Posts: 105
Hi,

The answer D & E is correct and the program complies and runs perferctly.

The reason for not getting a NullPointerException is the method throwDice() method is static.

Because static method invocations are done based on reference type and doesn't cares about value of reference variable (even it could be null).

If you make throwDice() method as non-static try to call getDice().throwDice() method you would get null pointer exception.

check out this

JLS

for more explanation

- Raja.


SCJP 1.4
ganesh subbiah
Ranch Hand

Joined: Nov 18, 2004
Posts: 39
hi,

Thanx for the answer i know it is d & e ..But i need someone who can
simplify this concept of Target Reference and Static Methods ...with an easy explanaion
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: explain the answer
 
Similar Threads
Null References
Mock Exam
null doubt
calling a method()
Null Reference