Java doesn’t use pointers?? Then what does it use??

Palak
3 min readJan 5, 2021

--

wait! what java doesn’t have pointers???

YES!! you heard it right!!!

Pointers are a concept of C++/C, java doesn’t have pointers. Now the question arises how does java work??

Java has references instead of pointers. But what is the need to introduce the concept of reference?

Disadvantages of using pointers -

  1. Memory access by the pointer is fundamentally unsafe. As if the pointers are available then a hacker can easily reach the main memory and can harm the application.
  2. Pointers causes a memory leak. Allocating and deallocating the pointers causes the formation of the array, quickly and immediately freeing the memory when no longer required. However, it can cause a memory leak when you were assigning a value to a pointer, WITHOUT freeing the previous memory. Garbage collection is your responsibility.
Meme

The difference between pointers and references

on the surface, both pointers, and references look similar. But they are not.

A pointer is a variable that stores the address of another variable.

A reference is a variable that refers to another variable.

int i = 3;
int *ptr = &i;
int &ref = i;

In the above code in the first line, we had declared the variable and then define the pointer and reference pointing to it.

To declare the pointer u must use * (in c++) where is reference does not have any constrain.

One of the major differences that the pointer can be reassigned whereas the reference can not be reassigned. What does that mean lets see an example-

The above code is written in c++. As u can see first we assign the value to pointer and reference and then on changing the value of pointer or variable a, the reference does not change. This allows us to say that reassigning the reference ie the address of the variable does not change.

Now extending the above code —

// changing the pointer ie pointing to bap = &b;cout<<" address of ap: "<<ap<<endl;cout<<" value of ap: "<<*ap<<endl;

Yes, U guess right now the reference will also change. Let's understand this by an example. Suppose a person as a variable on changing your room your home address won’t change ie. changing the value of variable won’t change the reference. but on changing the house your address will be changed similarly on changing the variable your pointer address ie reference will be changed.

Concluding as far, we have learned the need for reference instead of pointers. the basic difference between pointers and reference and some important points to remeber.

Thanks for reading.

--

--