Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we use pointers in Java? [duplicate]

Tags:

java

Why we are not using the pointer here?

Which concept is used instead of pointer in Java?

like image 430
BoomirajP Avatar asked Aug 03 '11 09:08

BoomirajP


2 Answers

Why can't we use pointers in Java?

Because the language designers chose not to include pointers in the language.

Why we are not using the pointer here.

Because the designers of Java thought it was a tricky-to-use and error prone construct.

Which concept is used instead of pointer in Java?

References (which are quite similar to pointers if you disregard from pointer arithmetic).

Keep in mind that all objects you create, you create on the heap (using the new keyword). This fact, together with the fact that there is no "dereference operator" (* in C/C++) means that there's no way to get hold of an object! Since you can't get hold of an object, there's no way you can store an object in a variable. Therefor all variables (except the ones holding primitive types) are of reference-type.

like image 106
aioobe Avatar answered Oct 13 '22 17:10

aioobe


It was a language design decision.

From the sun white paper The Java Language Environment:

Most studies agree that pointers are one of the primary features that enable programmers to inject bugs into their code. Given that structures are gone, and arrays and strings are objects, the need for pointers to these constructs goes away. Thus, Java has no pointer data types. Any task that would require arrays, structures, and pointers in C can be more easily and reliably performed by declaring objects and arrays of objects. Instead of complex pointer manipulation on array pointers, you access arrays by their arithmetic indices. The Java run-time system checks all array indexing to ensure indices are within the bounds of the array.

You no longer have dangling pointers and trashing of memory because of incorrect pointers, because there are no pointers in Java.

like image 30
Nivas Avatar answered Oct 13 '22 15:10

Nivas