Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null reference in java

Tags:

java

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());
}
like image 488
Abhij Avatar asked Dec 03 '25 11:12

Abhij


1 Answers

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;
}
like image 163
Ted Hopp Avatar answered Dec 06 '25 01:12

Ted Hopp