java如何判定abc与abcd相似,“abc”之间的差异+“de”和“abc” Java中的+ de(de =" de")?...

I run the following code and get the results shown in the comments. I know the differences between == and .equals(). What I don't understand is why my code in the second line has different results from the code in the third line.

String de = "de";

// String abcde = "abc" + "de"; // abcde == "abcde" reture true

String abcde = "abc" + de; // abcde == "abcde" reture false;

System.out.println();

System.out.println(abcde=="abcde");

System.out.println(de=="de");

In trying to debug this I used the javap -c command and got the following output 'code' for the first string concatenation:

Code:

0: ldc #9; //String de

2: astore_1

3: new #10; //class java/lang/StringBuilder

6: dup

7: invokespecial #11; //Method java/lang/StringBuilder."":()V

10: ldc #4; //String abc

12: invokevirtual #12; //Method java/lang/StringBuilder.append:(Ljava/lang

String;)Ljava/lang/StringBuilder;

15: aload_1

16: invokevirtual #12; //Method java/lang/StringBuilder.append:(Ljava/lang

String;)Ljava/lang/StringBuilder;

19: invokevirtual #13; //Method java/lang/StringBuilder.toString:()Ljava/l

ng/String;

22: astore_2

23: getstatic #14; //Field java/lang/System.out:Ljava/io/PrintStream;

26: invokevirtual #15; //Method java/io/PrintStream.println:()V

29: getstatic #14; //Field java/lang/System.out:Ljava/io/PrintStream;

32: aload_2

33: ldc #16; //String abcde

35: if_acmpne 42

38: iconst_1

39: goto 43

42: iconst_0

43: invokevirtual #17; //Method java/io/PrintStream.println:(Z)V

46: getstatic #14; //Field java/lang/System.out:Ljava/io/PrintStream;

49: aload_1

50: ldc #9; //String de

52: if_acmpne 59

55: iconst_1

56: goto 60

59: iconst_0

60: invokevirtual #17; //Method java/io/PrintStream.println:(Z)V

63: return

And the output for the second string concatenation:

ZgoPB.png

I am not so familiar with this 'code' and can't see any reason why these differences exists. So could anyone explain why those differences happen?

Related post

解决方案

The "problem" is simply that the compiler is too smart for you. When it sees "abc" + "de" it immediately concatenates that into the literal "abcde". But when it sees "abc" + de it's not allowed (per Java rules) to "optimize" that to a literal but must instead implement the + function, creating a new String object.

String literals are always handled as interned Strings, so == will work on them.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值