2

A little confused about object reference in Java. As I understand it, when I say:

Obj objA = new Obj();
Obj objB = objA;

I'm assigning objB a reference to objA. So if I change either I'll change the other. This is in fact how it works with Arrays. Say I pass Boolean[] a = {false, false} to the following method:

Boolean[] test(Boolean[] a){
    Boolean[] b = a; //Array object = Array object
    b[0] = true;
    System.out.println("In method:");
    for(int i=0;i<a.length;i++){
        System.out.printf("%d ", a[i]?1:0);
    }
    System.out.println();
    return a;
}

On return, a[0] is now true. But say instead I pass the same thing to:

Boolean[] test2(Boolean[] a){
    Boolean[] b = new Boolean[2];
    b[0] = a[0];  //Boolean obj = Boolean obj
    b[0] = true;
    System.out.println("In method:");
    for(int i=0;i<a.length;i++){
        System.out.printf("%d ", a[i]?1:0);
    }
    System.out.println();
    return a;
}

If I return a now, a[0] will still be false. (It works the same if I say b = new Boolean(true);) But what's the difference? In both cases I said Object = Object. Why does the reference work in the first but not in the second? Furthermore, is there a way to get the same functionality where one cell refers to another the way one array refers to another?

jimboweb
  • 4,362
  • 3
  • 22
  • 45
  • I believe primitives like Boolean and Ints are not by reference. You are essentially assigning `b[0]=false;` There's a good SO question on it in JavaScript that I'm trying to find that explains it clearly. – Script Kitty Feb 19 '17 at 03:47
  • https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html – PM 77-1 Feb 19 '17 at 03:52
  • 2
    Nothing to do with primitives (and `Boolean` isn’t one). You’re overwriting a reference rather than modifying the object referenced. – Ry- Feb 19 '17 at 03:53
  • A "reference" in Java is actually a pointer, and does not correspond to what is called a "reference" in other languages like C++. – Lew Bloch Feb 19 '17 at 04:03
  • Thank you for your comment Ryan but can you please tell me what this is a duplicate of? Because I spent about 10 minutes putting different versions of this question in the search box. – jimboweb Feb 19 '17 at 04:04
  • @jimboweb: The duplicate is linked at the top of the question. – Ry- Feb 19 '17 at 04:19
  • "I'm assigning objB a reference to objA." Not exactly. _Both_ of these are now references to some _other_ object living on the heap somewhere. You can change the contents of that object and it'll be reflected in both places, but you can also make `objB` point to something new and `objA` won't change at all. – Louis Wasserman Feb 19 '17 at 05:20

0 Answers0