-9

Is there anything similar to C++ pointers in Java? If there is, I would like to know what it is. Could you give me some examples?

Bart
  • 19,692
  • 7
  • 68
  • 77
Sai Ye Yan Naing Aye
  • 6,622
  • 12
  • 47
  • 65

2 Answers2

7

Java's pointers (so called by the language specification, while I believe Java programmers mostly know them as "references") do not support pointer arithmetic.

And Java has no way to do pointer arithmetic.

If you want to do such low-level stuff in Java, one way is to use JNI (the Java Native Interface) to access code written in C or C++.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
3

The Java object model is different from that of C++:

  • In C++, for every type you can have a variable of that type. Additionally, for every non-reference type T there is a type T& and you can have variables of that type (but references are never objects).

  • In Java, types which are class types can never be the type of a variable. Objects of class type can only exist dynamically, and a variable that is declared as being of type T (where T is of class type) is always implicitly a tracked reference to an object. (Let us ignore primitive types for this discussion.)

In both languages, variables are scoped. However, in C++ you can take advantage of scoped lifetime because objects whose lifetime ends automatically call a destructor. In Java, the only variables are references, and their going out of scope does something very different: It informs the memory manager that the object which they were tracking now has one fewer reference; and if there are no based references left, the object becomes eligible for (non-deterministic) collection.

If you will, you can equate class-type variables in Java to pointers in C++:

// Java:
{
    Foo x = new Foo();
    x = new Foo();      // no assignment in Java!
}

// C++:
{
    Foo * px = new Foo;
    px = new Foo;       // ... leaks the previous object
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084