Is it possible to use pointers in Java?

11

In language C we can use ponteiros as follows:

int *ponteiro, teste;

ponteiro = &teste;

And in Java is there any alternative?

    
asked by anonymous 13.04.2015 / 22:42

3 answers

9

There is no possibility of using raw pointers in Java. Even references have only implicit use through instantiated objects.

It is possible to simulate them through an array of bytes, but just to demonstrate how it would work, this would hardly have a practical use, and yet it does not mean that the language has pointers, only that its semantics can be emulated with other constructs.

This is not to say that the code does not use internal pointers but since they are not exposed in any way to the programmer, they can not be considered as existing in the language.

They are rare cases they are useful - essentially performance, but it really is a shame not to have them in those cases.

Pointers X References .

    
13.04.2015 / 22:45
6

Everything in Java that is not primitive is an object, objects are referenced by reference variables, in a very similar way to C ++ pointers.

That is, what you know as a pointer in C ++ is known as a reference in Java.

The differences do not stop at the name, the biggest difference is that in Java you do not work directly with the memory address, allocation and clearing of allocated memory. In Java you have new , but you do not have delete . This is not to say that the memory allocated when creating a new object will never be released, this work is performed by the Garbage Collector, which from time to time clears memory objects that no longer have a valid reference to them.

Answering your question: You can not have a pointer in the same way as in C ++, but you can have a reference variable that is likely to meet your needs. Java has been architected differently than C ++, it is more level-high, so if you need to work with access directly to memory then Java will not be your choice.

An example of creating and instantiating an object in Java:

Object obj = new Object();
    
13.04.2015 / 22:54
0

You can create a pointer in an object. For example:

Object A = new Object(); //New trata de reservar memória o suficiente para o objeto e criar automaticamente uma referência a ele. 
A.setValue("valor qualquer");
Object B = A;//Aqui o B aponta para o endereço de memória de A
System.out.printf(B.getValue.toString());
//Resultado impresso: valor qualquer

A.setValue("outro valor");
System.out.printf(B.getValue.toString());
//Resultado impresso: outro valor

B.setValue("valor posto por B");
System.out.printf(B.getValue.toString());
//Resultado impresso: valor posto por B
    
16.11.2018 / 07:18