Operation of variables by reference

Asked

Viewed 993 times

5

I know that variables by reference in java serve to provide a location in memory of a certain object. However, how does this mechanism work? It is equal to the C language, where the reference types store exactly the memory address of the one you want to locate?

  • 2

    Exact. Variables by reference only point to an address in memory. Roughly, they are aliases (shortcuts)

2 answers

3

When you create an Animal object for example, with the command new Animal(); the object of this class is being created at this time, but to manipulate the information of the "Animal" you need a reference variable that is precisely the variable that stores the memory address of the instantiated object. That’s why it’s usually done this way 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. A fact that sometimes confuses a little who is beginning to study java is to think that there is a passage of parameters by value and by reference, when in fact the passage 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 contains a memory address) but still what is being passed is only a copy of the variable’s content and not a reference to it. This site shows in a very didactic way how it happens http://www.javaranch.com/campfire/StoryPassBy.jsp

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 taking a look at my answer to the question Pass-by Object Reference Wrapper 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:

Variável apontando para objeto

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

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

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

In Java, on the other hand, variables that reference objects are only means to access such objects and cannot be used as generic references to memory positions, nor to modify these objects directly.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.