Functioning of variables by reference

4

I know that the reference variables in java serve to provide a memory location for a certain object. However, how does this mechanism work? Is it the same as the C language, where referenced types store exactly the memory address you want to find?

    
asked by anonymous 07.12.2015 / 15:19

2 answers

3

If you want to get an idea of how references work during the creation of an object, and when you pass a reference by parameter, I suggest you take a look at my response to the question Passing by Wrapper object reference to method .

Basically, doing this:

Integer k = new Integer(1);

You declare a variable and assign a new instance to it. A possible representation would be:

We can say that k is a variable that references the object of type Integer whose internal value is 1 .

So far nothing other than a pointer in C referencing a structure in memory. However, the difference from Java is evident when you think about what you can do with that reference.

In C you are literally referencing memory and can even perform operations with the pointer, such as p++ to advance to the next position in memory. You can also access the bytes of this object by disregarding the content.

In Java, on the other hand, variables that reference objects are just means to access such objects and can not be used as generic references to memory locations, nor to modify those objects directly.

Basically, all a reference can do is access members, attributes and methods of the objects in question.

    
08.12.2015 / 02:05
3

When you create an object of type Animal for example, with the command new Animal(); the object of this class is being created at the moment, but to manipulate the information of "Animal" you need a reference variable that is just variable that stores the memory address of the instantiated object. This is why it is usually done Animal animal = new Animal(); where animal is a reference variable that stores the memory address of the object, but usually this reference variable is called an object. One fact that sometimes confuses people who are starting to study java is to think that there is a passage of parameters by value and by reference, when in fact the passing of parameters in java is always by value. This mistake is due to the fact that when an object is passed as a parameter, what is being passed is actually its reference variable (which has as its content a memory address) but still what is being passed is only a copy of the variable content and not a reference to it. This site shows in a very didactic way how this happens link

    
07.12.2015 / 21:25