Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in Java

C++ supports pointers whereas Java does not. But when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers.” So we can say Java supports Restricted pointers?

like image 977
Nikunj Patel Avatar asked Sep 20 '11 06:09

Nikunj Patel


People also ask

What is the difference between Java pointers and C++ pointers?

In this article, we will take a look at the comparison of Java Pointers (References ) with C++ Pointers. Java has four types of references which are strong, weak, soft, and phantom references. In C++, you can use references and java pointer.

Why are Java references pointers?

Java references are not pointer. They contain some kind of pointer data or something because that comes from the nature of today computer architecture but this is totally up to the JVM implementation what it stores in a reference value and how it accesses the object it refers to.

Is an array a pointer in Java?

No, Java objects are not pointers. They are equivalent to references, which have a different set of capabilities and semantics. java can easily has pointer by knowing that the array name is pointer to the the first index. this why when we pass array to function we don't write its square brackets. because array is reference

How do you pass a function pointer in Java?

Java does not provide function pointers in the same way C/C++ does. Instead of passing a function pointer f, you create an object with an instance method f and pass the object instead.


1 Answers

The terminology is quite fuzzy here.

Java supports what it calls "references". References act a lot like pointers in C/C++-like languages. They don't act the same way "references" work in those languages.

The major differences between a pointer in C and a reference in Java are:

  • You can't do pointer arithmetic in Java (i.e. you can't "add" or "subtract" from a Java reference, you can only dereferencere it or compare it with another one).
  • You can't cast it to an incompatible type: Java is strongly type-safe, you can't "re-interpret" the bytes in memory as some other object.

For some uses of pointers this has no real effect (for example linked lists work pretty much the same in both languages), for others the difference is quite major (arrays in C are just fancy pointer arithmetic, in Java they work quite differently).

So in a way Java references could be called "restricted pointers".

Wikipedia defines a pointer as

... a programming language data type whose value refers directly to (or "points to") another value

Emphasis mine. According to this strict definition, Java doesn't have pointers.

The more general reference is the superclass of pointers, but also contrains more abstract things like file handles or even URLs.

like image 93
Joachim Sauer Avatar answered Oct 01 '22 09:10

Joachim Sauer