Issue
public static void main(String[] args) {
int a = 1;
int b = a;
b = b - 1;
System.out.println(a);
System.out.println(b);
}
The current output is "1,0." However, I wanted "a" and "b" to point to the same object, and if "b" changes, "a" changes, as well. I am not sure how to make this happens.
Solution
As @Jeffrey Ram said, Java has no pointer data types, specifically in primitive types: int, byte, short, long, float, double, boolean, and char. But don't worries, still have some trick to do it, that is use object
types.
Not like primitive
type, object
type in java will point to the same address if you assign one object to other. So see my ex here:
class HelloWorld {
public static void main(String[] args) {
Pointer g = new Pointer();
g.i = 6;
System.out.println(g.i); // 6
Pointer b = g; // assign object g to b, this will make b point to g's address
b.i = 9;
System.out.println(b.i); // 9
System.out.println(g.i); // guess what value is this :) it's 9
}
}
class Pointer {
int i;
}
But remember, make sure you not declare b
like this:
Pointer b = new Pointer();
b.i = g.i;
this will not pass g
's address to b
, so now if b
is 9, g
still is 6.
Hope this will help your problem. Happy coding! ;)
Answered By - KiluSs
Answer Checked By - Senaida (JavaFixing Volunteer)