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:
public void checkNullReference(){
ConsumerName name = null;
addReference(name);
System.out.println(name.getConsumerName());
}
name will still be null after the call to addReference(name), regardless of what addReference does with its formal argument.
You can redesign addReference to return an instance of ConsumerName. While you're at it, you can delete the argument, since it is ignored. The result could be:
public void checkNullReference(){
ConsumerName name = addReference();
System.out.println(name.getConsumerName());
}
public ConsumerName addReference(){
ConsumerName name = new ConsumerName();
name.setConsumerName("KRISHNA");
return name;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With