public class MyClassTest {
private static MyClass m;
public static void main(String[] args) {
m.initMe(getint());
}
public static int getint() {
m = new MyClass();
return (int) Math.random()*100;
}
}
class MyClass{
int i;
void initMe(int i) {
this.i = i;
System.out.println(this.i);
}
}
This code snippet gives NullPointerException
, causing initMe()
is invoked before getint
is invoked. What would be the root cause of this problem? Is JAVA pass-by-value so reference updation is not affected.
Give me the proper reason behind it.
As specified in
Now you see to identiry which method is to be called involves type identification. As java supports method overriding hence you can have different types implementing same method. So before resolving the method arguments instance type is identified which in your case turns out to be null and results in NPE.
Hope it helps.
main is the first method called, initialize m, before calling initMe of MyClass. Like
See,
m.initMe(getint());
invokes initMe() on m, but you have not initialized m as this is the first line of main method, som = null
, hence exception.m.initMe(getint());
When
m.initMe()
is called,m
is still uninitialized. It gets initialized in thegetint()
only. Therefore, you need to initialized yourm
before you could use it call a method using it.or else you can initialize it just before calling
initMe()
as well in themain()
method.Without instantiating
MyClass
, you have invoked its methodinitMe
. So, since the object is not instantiated, you are getting this exception Change this to:A compiler could generate what you have in mind
m
would be initialized)But the Java specifications describe several steps that are necessary before evaluating the parameters. The JVM has to be able to identify the type of the object (the runtime type) before knowing how to handle the parameters.
This is the bytecode which is generated
As you can see the first step is to load
m
on the stack. It will load null. Thengetint
is invoked, it will setm
but the value used byinvokevirtual
will be the one already loaded on the JVM stack.First you have to initialize the 'm'
Java does manipulate objects by reference and all object variables are references. Java doesn't pass method arguments by reference but by value.