Why can't we use pointers in Java?
This question already has an answer here:
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.
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.
It's good isn't it? You don't have pointers in the C programming sense, the Virtual Machine looks after all that. However, that's not to say you don'f have have similar capabilities. For example, variables for objects are references, when you pass a variable for an object you are passing a reference which is sort of a pointer. You might also use a variable to store the index of an item in an array, that again is a kind of pointer in a programmatical sense.
链接地址: http://www.djcxy.com/p/31658.html上一篇: 为什么地址零用于空指针?
下一篇: 为什么我们不能在Java中使用指针?