What is the difference between a pointer and a reference variable in Java?

后端 未结 9 1630
南笙
南笙 2020-11-28 15:42

My Java book explains that to use objects, we can assign them to reference variables. How is that different from a pointer to an object? Does Java have pointers?

T

9条回答
  •  悲哀的现实
    2020-11-28 16:20

    Cat x = new Cat();
    

    This line creates a Cat object in memory and stores a reference to it in x.

    x now contains a reference to the Cat object, but if you were to do:

    x = x + 1;
    

    This would not give the next memory address like in C, but would give a compiler error. Java doesn't allow control to the reference or memory location.

提交回复
热议问题