How can I use pointers in Java?
Asked Answered
T

17

152

I know Java doesn't have pointers, but I heard that Java programs can be created with pointers and that this can be done by the few who are experts in Java. Is it true?

Trask answered 17/11, 2009 at 16:34 Comment(8)
The default "hashCode" for an Object is its pointer address.Lundberg
In Sun's implementation anyway.Mimas
can i use that pointer addressTrask
what do you mean "use?" you will "use" it every time you reference the object.Anus
No, as I said in my answer, you can't do anything with specific memory addresses in Java.Mimas
The default hashCode for a java object is NOT it's pointer address, re-read the contract for hashCode carefully and you'll notice that two distinct objects in memory can have the same hashCode value.Evensong
In 64-bit and 32-bit Java, the 32-bit hashCode is not the address. hashCodes are not guaranteed to be unique. The location of a object can be moved in memory as it moved between spaces and the memory is compacted, the hashCode however doesn't change.Gore
90% of what you could do with C++ pointers you can do with java refrences, the remaining 10% you can acieve by packaging a reference inside annother object (not that I've ever found it nessissary to do that)Consequently
T
285

All objects in Java are references and you can use them like pointers.

abstract class Animal
{...
}

class Lion extends Animal
{...
}

class Tiger extends Animal
{   
public Tiger() {...}
public void growl(){...}
}

Tiger first = null;
Tiger second = new Tiger();
Tiger third;

Dereferencing a null:

first.growl();  // ERROR, first is null.    
third.growl(); // ERROR, third has not been initialized.

Aliasing Problem:

third = new Tiger();
first = third;

Losing Cells:

second = third; // Possible ERROR. The old value of second is lost.    

You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.

first = second;
second = third; //OK

Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to.

The Java system will throw an exception (OutOfMemoryError) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion.

Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error.

Novices often make the following error.

Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed. 

What you probably meant to say was:

Tiger tony = null;
tony = third; // OK.

Improper Casting:

Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler. 

Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.

Pointers in C:

void main() {   
    int*    x;  // Allocate the pointers x and y
    int*    y;  // (but not the pointees)

    x = malloc(sizeof(int));    // Allocate an int pointee,
                                // and set x to point to it

    *x = 42;    // Dereference x to store 42 in its pointee

    *y = 13;    // CRASH -- y does not have a pointee yet

    y = x;      // Pointer assignment sets y to point to x's pointee

    *y = 13;    // Dereference y to store 13 in its (shared) pointee
}

Pointers in Java:

class IntObj {
    public int value;
}

public class Binky() {
    public static void main(String[] args) {
        IntObj  x;  // Allocate the pointers x and y
        IntObj  y;  // (but not the IntObj pointees)

        x = new IntObj();   // Allocate an IntObj pointee
                            // and set x to point to it

        x.value = 42;   // Dereference x to store 42 in its pointee

        y.value = 13;   // CRASH -- y does not have a pointee yet

        y = x;  // Pointer assignment sets y to point to x's pointee

        y.value = 13;   // Deference y to store 13 in its (shared) pointee
    }
} 

UPDATE: as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.

Thurmanthurmann answered 17/11, 2009 at 16:48 Comment(12)
Nice answer, but you failed to address one key difference: C has pointer arithmetics. (Fortunately) you can't do that in Java.Jaguar
I hate to down vote any answer, especially one that is popular, but Java does not have pointers and you simply can not use a reference like a pointer. There are certain things you can only do with real pointers - for example, you can get or set any byte in your process data space. You simply can't do that in Java. It's really bad that so many people here seem to not understand what a pointer really is, imho, and now I will get off my rant soap box and hope you forgive me for my little outburst.Cognomen
I think you mean Unfortunately. Why would you think it is good that java does not support pointer arithmetic?Include
@Include Because people seem to think it is too difficult to be used by the general populace, and can only be understood by coding ninjas writing compilers or device drivers.Cardigan
@Cognomen He says "You can use these like a pointer", while it's true that it's only a reference, the general behavior of the object is the same, and it addresses the question properly.Snaggletooth
@Snaggletooth You misquoted the question. Nowhere in the question does the OP use the word "like". Therefore I believe both this answer and your comment are misleading and I will stand by my comment, which is: Java simply has no pointers. You can use a reference in some ways that are similar to pointers, but no, Java has no pointers which is what this question asked.Cognomen
@Cognomen First line of answer "All objects in Java are references and you can use them like pointers.". This is the best answer that can be provided. If the only answer had been "No, java has no pointers." that answer would have been unhelpful. This answer instead states what you can do instead.Snaggletooth
@Cognomen I did 1 up your comment when I read it, as I think it's a good point that java doesn't have pointers, that may have been better represented in the answer, however, the answer does not state that there ARE pointers, only that objects are references, and other helpful information.Snaggletooth
It is true you can use references like pointers if you severely restrict how you use pointers, but then you're missing the point. (pun intended!) Thank you for 1-upping my comment though. A better and more clear answer would start with: "No, Java does not have pointers. But if you consider a restricted use of pointers which we can call references, than you can used a restricted subset of pointer functionality within Java."Cognomen
Could you elaborate on the aliasing problem?Richierichlad
I think the answer should be updated from "This is very rare and usually only results from run away recursion" to "This is very rare and usually only results from infinite loops or run away recursion" lolNorword
The inability to do maths on a Java pointer does not disqualify it from being called a pointer because it still "points to" an object.Hobby
J
67

As Java has no pointer data types, it is impossible to use pointers in Java. Even the few experts will not be able to use pointers in java.

See also the last point in: The Java Language Environment

Joel answered 17/11, 2009 at 16:36 Comment(7)
One of the few correct answers here hardly has any upvotes?Cognomen
Note that there exist 'pointer' objects that simulate pointerlike behavior. For many purposes this can be used the same way, memory level addressing not withstanding. Given the nature of the question I feel its odd that nobody else mentioned this.Sandpiper
This should be the answer at top. Because for beginners telling that "behind the scenes java have pointers" can lead to very confusing state. Even when Java is taught at starting level, it is taught that pointers are not secure that's why they are not used in Java. A programmer needs to be told what he/she can see and work on. Reference and pointers are actually very different.Aria
Not sure I entirely agree with the "2.2.3 No Enums" topic in the link. The data might be outdated, but Java does support enums.Idomeneus
@Idomeneus the document linked to is a white paper from 1996 describing the very first version of java. Enums are introduced in java version 1.5 (2004)Joel
@Joel derp... I didn't realize the document was dated. Thanks for clarifying :)Idomeneus
Java has pointers. Dog d = new Dog(); d.bark(); in Java is the same as Dog *d = new Dog(); d->bark(); in C++. The difference is that, in Java you can't take a reference to get a pointer to non-objects, and you can't deference object pointers. Also you can't convert to numbers and do maths on it. Accessing an object thru a null pointer will get a NullPointerException.Hobby
M
51

Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null, and the original object will still exist (pending garbage collection).

What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.

If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.

Mimas answered 17/11, 2009 at 16:39 Comment(5)
Java simply does not have pointers, plain and simple, and I can not for the life of me understand why so many answers here state incorrect information. This is StackOverlfow people! The definition of a pointer in computer science is (you can Google for this): "In computer science, a pointer is a programming language object, whose value refers to (or "points to") another value stored elsewhere in the computer memory using its address." A reference in Java is NOT a pointer. Java needs to run garbage collection and if you had a real pointer it would then be wrong!Cognomen
@Cognomen A pointer is a a piece of data containing a memory address. Java is two things, which people forget. It is a language and a platform. Much as one would not say that .NET is a language, we need to remember that saying 'Java doesn't have pointers' can be misleading because the platform does of course have and use pointers. Those pointers are not accessible to the programmer through the Java language, but they do exist in the runtime. References in the language exist on top of actual pointers in the runtime.Sandpiper
@Sandpiper It would appear that you are agreeing with me. I believe you said "Those pointers are not accessible to the programmer through the Java Language" which is consistent with my statement that "Java does not have pointers". References are semantically significantly different from pointers.Cognomen
@Cognomen this is true, but I think its important in these cases to distinguish between the platform and the language because I know that when I was first starting out a statement like yours would have confused me.Sandpiper
Yup, Java certainly has pointers behind the variables. It is just that developers dont have to deal with them because java is doing the magic for this behind the scenes. This means developers are not directly allowed to point a variable to a specific memmory adress, and deal with data offsets and stuff. It allows java to keep a clean memmory garbage collection, but since every variable is essentialy a pointer, it also takes some extra memmory to have all those auto generated pointer adresses, which in the more low level languages could have been avoided.Unpractical
S
12

There are pointers in Java, but you cannot manipulate them the way that you can in C++ or C. When you pass an object, you are passing a pointer to that object, but not in the same sense as in C++. That object cannot be dereferenced. If you set its values using its native accessors, it will change because Java knows its memory location through the pointer. But the pointer is immutable. When you attempt to set the pointer to a new location, you instead end up with a new local object with the same name as the other. The original object is unchanged. Here is a brief program to demonstrate the difference.

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone {

    public static void main(String[] args) throws java.lang.Exception {
        System.out.println("Expected # = 0 1 2 2 1");
        Cat c = new Cat();
        c.setClaws(0);
        System.out.println("Initial value is " + c.getClaws());
        // prints 0 obviously
        clawsAreOne(c);
        System.out.println("Accessor changes value to " + c.getClaws());
        // prints 1 because the value 'referenced' by the 'pointer' is changed using an accessor.
        makeNewCat(c);
        System.out.println("Final value is " + c.getClaws());
        // prints 1 because the pointer is not changed to 'kitten'; that would be a reference pass.
    }

    public static void clawsAreOne(Cat kitty) {
        kitty.setClaws(1);
    }

    public static void makeNewCat(Cat kitty) {
        Cat kitten = new Cat();
        kitten.setClaws(2);
        kitty = kitten;
        System.out.println("Value in makeNewCat scope of kitten " + kitten.getClaws());
        //Prints 2. the value pointed to by 'kitten' is 2
        System.out.println("Value in makeNewcat scope of kitty " + kitty.getClaws());
        //Prints 2. The local copy is being used within the scope of this method.
    }
}

class Cat {

    private int claws;

    public void setClaws(int i) {
        claws = i;
    }

    public int getClaws() {
        return claws;
    }
}

This can be run at Ideone.com.

Sandpiper answered 5/8, 2015 at 15:11 Comment(0)
P
11

Java does not have pointers like C has, but it does allow you to create new objects on the heap which are "referenced" by variables. The lack of pointers is to stop Java programs from referencing memory locations illegally, and also enables Garbage Collection to be automatically carried out by the Java Virtual Machine.

Piezoelectricity answered 17/11, 2009 at 16:39 Comment(0)
G
10

You can use addresses and pointers using the Unsafe class. However as the name suggests, these methods are UNSAFE and generally a bad idea. Incorrect usage can result in your JVM randomly dying (actually the same problem get using pointers incorrectly in C/C++)

While you may be used to pointers and think you need them (because you don't know how to code any other way), you will find that you don't and you will be better off for it.

Gore answered 6/12, 2009 at 9:20 Comment(11)
Pointers are extremely powerful and useful. There are many cases where not having pointers (Java) makes code much less efficient. Just because people suck at using pointers doesn't mean languages should exclude them. Should I not have a rifle because others (like the military) use them to kill people?Characteristic
There isn't much useful or powerful you can't do in Java as the language is. For everything else there is the Unsafe class which I find I need to use very rarely.Gore
Much of the code I have written over the last 40 years could never have been implemented in Java, because Java is lacking core, low level capabilities.Cognomen
@Cognomen which is why a large number of libraries use Unsafe and the idea of removing it has sparked so much debate in Java 9. The plan is to provide replacements, but they are not ready yet.Gore
This actually is the only correct answer. I was just about to write an answer pointing to baeldung.com/java-unsafe.Legit
@Legit about 5 years ago I wrote a library to wrap much of this functionality to make it safer. github.com/OpenHFT/Chronicle-BytesGore
@PeterLawrey thank you for the comment. I'll have a closer look at it.Legit
@Legit I suggest you also look at Chronicle Queue and Chronicle Map which use this library to store data in off heap and persisted shared memory.Gore
Stop marketing your software and just admit pointers in java would change the game. And , dare I say , make (most) of the library you have worked so hard on obsolete ? Don't worry though, "they" won't add pointers any time soon, because come on, just read some of the answers and comments ( lol... )Luo
@Luo Mentioning software in a comment 11 years after the original answer isn't marketing.Gore
@Luo In May it had 80K downloads, not too obsolete.Gore
B
7

Technically, all Java objects are pointers. All primitive types are values though. There is no way to take manual control of those pointers. Java just internally uses pass-by-reference.

Baleful answered 17/11, 2009 at 16:36 Comment(6)
Not even through JNI? No Java knowledge to speak of here, but I thought I'd heard you could get some low-level bit-grubbing done that way.Cochard
As far as my ~4 years of Java experience and looking for the answer myself says no, Java pointers are not externally accessible.Baleful
Thanks for response. I asked because, my lecturer told that at research level where java used in handheld devices,,they use pointer...that;s why I askedTrask
@unknown(google) if it's at the research level, depending upon what is being done, it may have been that they needed such functionality, so they violated the normal idioms and implemented them anyway. You can implement your own JVM if you so wish to have a superset (or subset, or mixture) of normal Java features, but such code may not run on other Java platforms.Anus
@san: Thanks for the answer. BTW I cannot vote..says that I need 15 reputationTrask
Technically, no Java objects are pointers. They are references. If they were pointers, and your garbage collection ran, your program would instantly crash.Cognomen
B
2

Not really, no.

Java doesn't have pointers. If you really wanted you could try to emulate them by building around something like reflection, but it would have all of the complexity of pointers with none of the benefits.

Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?

Baum answered 17/11, 2009 at 16:36 Comment(2)
I am curious to know that. Thanks for the answerTrask
Java does need pointers, and that is why Java added JNI - to get around the lack of "pointer-like" or lower level functions you simply can not do in Java, no matter what code you write.Cognomen
M
2

All objects in java are passed to functions by reference copy except primitives.

In effect, this means that you are sending a copy of the pointer to the original object rather than a copy of the object itself.

Please leave a comment if you want an example to understand this.

Mantelletta answered 17/11, 2009 at 16:39 Comment(3)
This is plain wrong. You can't write a swap function in Java which will swap two objects.Hobby
@MichaelTsang Where did he talk about swap?! There is nothing wrong with this answer. You're copying references, not objects. This implies that you cannot move the objects itself.Tearle
The ability to write a swap function is the litmus test of the existence of passing-by-reference in a programming language.Hobby
C
1

As others have said, the short answer is "No".

Sure, you could write JNI code that plays with Java pointers. Depending on what you're trying to accomplish, maybe that would get you somewhere and maybe it wouldn't.

You could always simulate pointes by creating an array and working with indexes into the array. Again, depending on what you're trying to accomplish, that might or might not be useful.

Circumstantiate answered 17/11, 2009 at 17:15 Comment(0)
L
1

from the book named Decompiling Android by Godfrey Nolan

Security dictates that pointers aren’t used in Java so hackers can’t break out of an application and into the operating system. No pointers means that something else----in this case, the JVM----has to take care of the allocating and freeing memory. Memory leaks should also become a thing of the past, or so the theory goes. Some applications written in C and C++ are notorious for leaking memory like a sieve because programmers don’t pay attention to freeing up unwanted memory at the appropriate time----not that anybody reading this would be guilty of such a sin. Garbage collection should also make programmers more productive, with less time spent on debugging memory problems.

Laurentia answered 3/4, 2014 at 12:56 Comment(1)
I might be a weird case, but I've had more memory leaks using Java than C or C++ because the garbage collector wasn't triggering. I seem to always end up need to explicitly call the garbage collector. Not that I haven't had other pointer related errors, but specifically for leaks I've had them more often with Java than without.Kriegspiel
S
1

Java reference types are not the same as C pointers as you can't have a pointer to a pointer in Java.

Strangle answered 12/7, 2015 at 0:15 Comment(0)
K
0

you can have pointers for literals as well. You have to implement them yourself. It is pretty basic for experts ;). Use an array of int/object/long/byte and voila you have the basics for implementing pointers. Now any int value can be a pointer to that array int[]. You can increment the pointer, you can decrement the pointer, you can multiply the pointer. You indeed have pointer arithmetics! That's the only way to implements 1000 int attributes classes and have a generic method that applies to all attributes. You can also use a byte[] array instead of an int[]

However I do wish Java would let you pass literal values by reference. Something along the lines

//(* telling you it is a pointer) public void myMethod(int* intValue);

Kibosh answered 27/1, 2010 at 3:19 Comment(0)
M
0

You can, but not completely. You can't directly access pointers but you can have lists with variables that point to the same location. I came across a way by accident a few years ago.

I'm not sure why but in Java when you set a list to equal another list, rather than copying all the information, a pointer to the original list is made. I'm not sure if it applies to all forms of lists, but it has for the ones I have tested so far. I believe arrayList also has the function clone(), to circumvent this, if you wanted a proper seperate list.

int[] example

public class Main {

    public static void main(String[] args){

        int[] alpha = new int[] {1,2,3};

        int[] beta = alpha;
        beta[0]=9;
        beta[1]=9;
        beta[2]=9;

        System.out.println("alpha: " + alpha[0] + ", " + alpha[1] + ", " + alpha[2]);
        System.out.println("-beta: " + beta[0] + ", " + beta[1] + ", " + beta[2]);
    }
}

arrayList example

import java.util.ArrayList;

public class Main {

    public static void main(String[] args){

        ArrayList<Integer> alpha = new ArrayList<>();
        alpha.add(1);
        alpha.add(2);
        alpha.add(3);

        ArrayList<Integer> beta = alpha;
        beta.add(4);
        beta.set(0, 5);

        System.out.println("alpha: " + alpha.toString());
        System.out.println("-beta: " + beta.toString());
    }
}
Mouthful answered 19/11, 2022 at 3:34 Comment(0)
K
0

If you want the feeling of pointers in Java, i made this small thingy right here: https://github.com/v22lel/C-Pointers-in-Java But keep in mind, that those pointers are only allocated on a virtual memory, so they dont use real ram and are way slower than normal java. This is just a little fun joke and shouldnt be used in project seriously.

Kermitkermy answered 21/4, 2023 at 4:17 Comment(0)
T
-1

All java objects are pointer because a variable which holds address is called pointer and object hold address.so object is pointer variable.

Tripura answered 11/7, 2013 at 9:54 Comment(1)
No, Java objects are not pointers. They are equivalent to references, which have a different set of capabilities and semantics.Cognomen
M
-5

java can easily has pointer by knowing that the array name is pointer to the the first index. this why when we pass array to function we don't write its square brackets. because array is reference


public class Main    
{
    public static void func ( int ptr1[] , int ptr2[] )
 {
      int temp;
      temp = ptr1[0];
      ptr1[0] = ptr2[0];
      ptr2[0] = temp;
      
 }
    
    public static void main(String[] args) {
        
        int x = 5;               int y = 8;
        
        // in c language
        //  int *p = &x;       int *q = &y;
        
        
        //  in Java
        int p[] = new int[1];
        int q[] = new int[1];
        
        p[0] = x;   // same as pointer
        q[0] = y;   // same as pointer
        
        func( p , q );  // passing address ( refrence )
        
        System.out.println( "  After Swap " );
        System.out.println( "x = "  + p[0] + "  " +  "y = " + q[0] );
        
    }
}


Microsporangium answered 23/2, 2022 at 9:17 Comment(1)
You are not showing pointers in Java, just because for arrays the syntax to pass them to a method does not include []. For C to understand you could have a look at https://mcmap.net/q/17439/-is-an-array-name-a-pointerApplejack

© 2022 - 2024 — McMap. All rights reserved.