2017-10-08 114 views
0
String a = "x"; 
String b = a + "y"; 
String c = "xy"; 
System.out.println(b==c); 

为什么要打印false实习生如何在Concat的情况下工作

根据我的理解,“xy”(这是一个+“y”)将被实现,并且当变量c被创建时,编译器将检查字符串常量池中是否存在字面值“xy”,如果存在,那么它将分配相同的引用到c。

注意:我不是要求equals()vs ==操作符。

+0

' “XY”'被拘留,但结果'A +”因为'a'不是最终结果,所以y“'不是,也不是实际使用的”xy“结果。 –

+1

可能的重复[比较字符串与在Java中声明为最终的==](https://stackoverflow.com/questions/19418427/comparing-strings-with-which-are-declared-final-in-java) – Ravi

+0

此外其他答案:也尽量避免依赖它。如果代码被重用,它很脆弱。 – eckes

回答

0

原因"xy"被分配到c被直接添加到字符串池(由intern使用)是因为该值在编译时已知。

a+"y"在编译时不知道,但仅在运行时才知道。因为intern是一项昂贵的操作,除非开发人员明确地对其进行编码,否则通常不会这样做。

+0

Thanks for the reply.Ok,所以变量b将出现在堆栈中,因为c将引用字符串常量池? –

+0

从技术上讲,'b'将引用堆中的字符串,否则是。 –

1

如果通过连接两个字符串文本形成一个字符串,它也将被实现。

String a = "x"; 
String b = a + "y"; // a is not a string literal, so no interning 
------------------------------------------------------------------------------------------ 
String b = "x" + "y"; // on the other hand, "x" is a string literal 
String c = "xy"; 

System.out.println(b == c); // true 

这里是字符串常见的例子在Java中

class Test { 
    public static void main(String[] args) { 
     String hello = "Hello", lo = "lo"; 

     System.out.print((hello == "Hello") + " "); 
     System.out.print((Other.hello == hello) + " "); 
     System.out.print((other.Other.hello == hello) + " "); 
     System.out.print((hello == ("Hel"+"lo")) + " "); 
     System.out.print((hello == ("Hel"+lo)) + " "); 
     System.out.println(hello == ("Hel"+lo).intern()); 
    } 
} 

class Other { static String hello = "Hello"; } 

实习,接着它的输出

true 
true 
true 
true 
false 
true 
相关问题