简体   繁体   中英

weird thing about String.intern in Java

I am learning Java basic concept recently, when I tried some code samples about String.intern there was a weird thing happened. Code below:

Snippet 1(normal):

String str1 = new String("0") + new String("0");
str1.intern();
String str2 = "00";
assertTrue(str1 == str2); // pass
assertTrue(str1.equals(str2)); // pass

Snippet 2(weird):

String str1 = new String("1") + new String("1");
str1.intern();
String str2 = "11";
assertTrue(str1 == str2); // fail; what happened???
assertTrue(str1.equals(str2)); // pass

Snippet 3(normal):

String str1 = new String("2") + new String("2");
str1.intern();
String str2 = "22";
assertTrue(str1 == str2); // pass
assertTrue(str1.equals(str2)); // pass

So, I don't understand what happened about new String("1") , it's really really confused, I need your help, Thanks a lot!

Any string which is already in the string literal pool will already have an object and will not be added when you call str1.intern() as it is already there.

On starting, the JVM creates thousands of objects and has many objects already in the String literal pool by the time main() is called.

Which strings are already in the pool depends on what code was run before your code.

System.out.println("Strings already in the literal pool");
for (char ch = ' '; ch < 127; ch++) {
    String s = Character.toString(ch);
    System.out.println(s + " " + (s != s.intern()));
}

prints

Strings already in the literal pool
  true
! false
" true
# false
$ false
% true
& true
' true
( false
) false
* true
+ false
, true
- true
. true
/ true
0 false
1 false
2 false
3 false
4 false
5 false
6 false
7 false
8 false
9 false
: true
; false
< true
= false
> false
? false
@ true
A false
B false
C false
D false
E false
F false
G false
H false
I true
J false
K false
L false
M false
N false
O false
P false
Q false
R false
S false
T false
U true
V false
W false
X false
Y false
Z true
[ true
\ false
] true
^ false
_ true
` false
a false
b false
c false
d false
e false
f false
g false
h false
i false
j false
k false
l false
m false
n false
o false
p false
q false
r false
s false
t false
u false
v false
w false
x false
y false
z false
{ false
| true
} false
~ false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM