Pages

Apr 12, 2015

int is not an object in Java

Type int in Java is not an object. So when we assign a previously created int variable to another newly created int variable, they are not sharing the same memory (they are mutually independent).
int nu1 = 13;
int nu2 = nu1;
nu2 = 12;
//now nu1 is still 13, and nu2 is 12
view raw int.java hosted with ❤ by GitHub

Unlike type int, String is an object in Java. When we assign a previously created string assigned to another newly created string, they share the same object.
PS. String is not mutable.
String str1 = "Hello World";
String str2 = str1;
str2.replace("H", "X");//replace is an accessor, not a mutator
System.out.println(str2);
//print "Hello World"
System.out.println(str1);
//print "Hello World"
String str3 = str1.replace("H", "X");
System.out.println(str3);
//print "Xello World"
view raw string.java hosted with ❤ by GitHub

No comments:

Post a Comment