I have a piece of code for which i have to know how memory is allocated
public class Demo {
public void checkNullReference(){
ConsumerName name = null;
addReference(name);
System.out.println(name.getConsumerName());
}
public void addReference(ConsumerName name){
name = new ConsumerName();
name.setConsumerName("KRISHNA");
}
public static void main(String []args){
Demo demo = new Demo();
demo.checkNullReference();
}
}
The code is giving null pointer exception i have given a refrence of object to method and there i am allocating new object to it and setting name if i rewrite the method then every thing is working as expected.
public void checkNullReference(){
ConsumerName name = new ConsumerName();
addReference(name);
System.out.println(name.getConsumerName());
}
You cannot change a reference in a calling method from the called method. Thus, with this code:
namewill still benullafter the call toaddReference(name), regardless of whataddReferencedoes with its formal argument.You can redesign
addReferenceto return an instance ofConsumerName. While you’re at it, you can delete the argument, since it is ignored. The result could be: