How can I use pointers in Java?

Viewed 472272

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?

15 Answers

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);

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] );
        
    }
}


Related