0

Programming languages like C and C++ use pointers but Java does not use them for security reasons, then how does it keep record of dynamically allocated memory which in C is maintained using pointers?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • 8
    Java doesn't expose pointers. The internals of the JVM use them. – Jonathan Leffler Jul 23 '17 at 17:38
  • Java uses pointers or actually JVM uses it, most of the modern language doing the memory allocation internally. – Fady Saad Jul 23 '17 at 17:41
  • When you declare a variable of a class type and assign something to it, it will be a "reference", which essentially serves the same purpose as a pointer, except that your ability to use it is more limited: (1) you can't do arithmetic on it; (2) you can't make it point to a variable of a primitive type or an arbitrary area of memory. But it still works like a pointer, and you could think of it as a pointer if you want to. – ajb Jul 23 '17 at 17:50
  • Also, a reference might not contain the actual address; I think it contains an index into an object table where the address is stored. Doing this would allow objects to be moved to different locations (although I'm not sure if the JVM does this) and probably helps the memory manager in other ways. I don't know much about JVM internals, though. I'm sort of guessing. – ajb Jul 23 '17 at 17:52
  • Not exposing pointers to the user has nothing to do with security. – too honest for this site Jul 23 '17 at 18:12
  • Mainly see the second answer by Edwin Buck to the "duplicated" question. Beyond that: try doing some prior research yourself the next time. – GhostCat Jul 23 '17 at 18:46
  • @Olaf It has a great deal to do with security. Specifically, Java references are a type of *capability*, and one of their key attributes is that they can't be forged (i.e., manufactured to point to an arbitrary location). – chrylis -cautiouslyoptimistic- Jul 23 '17 at 19:08

1 Answers1

-1

Java does indeed have pointers. Let's say that you have a class A with an attribute x with setter and getter void set_x(int) and int get_x() and consider this code:

public static void foo(A a)
{
   a.setx(13);
}

public static void main()
{
    A a = new A();
    a.setx(12);
    foo(a);
    System.out.println(a.getx());
}

This will print 13 so that's indeed a pointer. However, you cannot declare a pointer and make it point as freely as you can in C. Nor can you do pointer arithmetics.

And there's lots of pointers inside the Java Virtual Machine, but they are not exposed to the programmer.

klutt
  • 30,332
  • 17
  • 55
  • 95