Bruce Eckel's Thinking in Java Contents | Prev | Next

12: Passing and returning objects

By this time you should be reasonably comfortable with the idea that when you’re “passing” an object, you’re actually passing a handle.

In many programming languages, if not all of them, you can use that language’s “regular” way to pass objects around and most of the time everything works fine. But it always seems that there comes a point at which you must do something irregular and suddenly things get a bit more complicated (or in the case of C++, quite complicated). Java is no exception, and it’s important that you understand exactly what’s happening with them as you pass them around and assign to them. This chapter will provide that insight.

Another way to pose the question of this chapter, if you’re coming from a programming language so equipped, is “Does Java have pointers?” Some have claimed that pointers are hard and dangerous and therefore bad, and since Java is all goodness and light and will lift your earthly programming burdens, it cannot possibly contain such things. However, it’s more accurate to say that Java has pointers; indeed, every object identifier in Java (except for primitives) is one of these pointers, but their use is restricted and guarded not only by the compiler but by the run-time system. Or to put in another way, Java has pointers, but no pointer arithmetic. These are what I’ve been calling “handles,” and you can think of them as “safety pointers,” not unlike the safety scissors of elementary school- they aren’t sharp so you cannot hurt yourself without great effort, but they can sometimes be slow and tedious.

Contents | Prev | Next