Last active
November 20, 2021 06:20
-
-
Save tomty89/f4b93a8403d4ed88412a3d664601334c to your computer and use it in GitHub Desktop.
Example to clarify re-assignment of references
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Huh { | |
public int huh; | |
public Huh() { | |
huh = 123; | |
} | |
} | |
public class Meh { | |
// Re-implement "toString()" for String | |
private static String refString(String str) { | |
return str.getClass().getName() + "@" + | |
Integer.toHexString(str.hashCode()); | |
} | |
public static void main(String[] args) { | |
// Assign the reference to "the 1st String" to str1 | |
String str1 = "the 1st String"; | |
// Assign the current value / reference of str1 to str2 | |
String str2 = str1; | |
System.out.println("[str1: " + refString(str1) + "] -> (\"" + str1 + "\")"); | |
System.out.println("[str2: " + refString(str2) + "] -> (\"" + str2 + "\")"); | |
/* | |
Assign the reference to "the 2nd String" to str1 | |
this changes NEITHER the value / reference of str2 | |
NOR the object it refers to | |
String objects in Java are *immutable*, which means | |
whenever you make "changes" to a String, you are | |
actually assigning the reference of a new instance | |
to it instead of making changes to the current instance. | |
It's the same story even when you are performing String | |
concatenation with +=, by the way. | |
*/ | |
str1 = "the 2nd String"; | |
System.out.println("[str1: " + refString(str1) + "] -> (\"" + str1 + "\")"); | |
System.out.println("[str2: " + refString(str2) + "] -> (\"" + str2 + "\")"); | |
System.out.println(); | |
/* | |
Another example with a simple class that has | |
a *mutable* field | |
*/ | |
Huh huh1 = new Huh(); | |
Huh huh2 = huh1; | |
System.out.println("[huh1: " + huh1 + "] -> (huh: " + huh1.huh + ")"); | |
System.out.println("[huh2: " + huh2 + "] -> (huh: " + huh2.huh + ")"); | |
/* | |
This changes the field of a single instance | |
that both huh1 and huh2 currently refers to | |
*/ | |
huh1.huh = 456; | |
System.out.println("[huh1: " + huh1 + "] -> (huh: " + huh1.huh + ")"); | |
System.out.println("[huh2: " + huh2 + "] -> (huh: " + huh2.huh + ")"); | |
/* | |
This creates a new instance and assign the | |
reference to it to huh1. It changes NEITHER | |
the value / reference of huh2 NOR the | |
instance (i.e. its field) it refers to | |
*/ | |
huh1 = new Huh(); | |
System.out.println("[huh1: " + huh1 + "] -> (huh: " + huh1.huh + ")"); | |
System.out.println("[huh2: " + huh2 + "] -> (huh: " + huh2.huh + ")"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: