java11-2 String面试题

package cn.itcast_02;

/*
* String s = new String(“hello”)和String s = “hello”;的区别?
* 有。前者会创建2个对象,后者创建1个对象。
*
* ==:比较引用类型比较的是地址值是否相同
* equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。
*/

public class StringDemo2 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";

System.out.println(s1 == s2);
System.out.println(s1.equals(s2)); 
}
}

答案: false true


package cn.itcast_02;
/*
* 看程序写结果
*/

 1  1 public class StringDemo3 {
 2  2 public static void main(String[] args) {
 3  3 String s1 = new String("hello");
 4  4 String s2 = new String("hello");
 5  5 System.out.println(s1 == s2);
 6  6 System.out.println(s1.equals(s2));
 7  7 
 8  8 String s3 = new String("hello");
 9  9 String s4 = "hello";
10 10 System.out.println(s3 == s4);
11 11 System.out.println(s3.equals(s4));
12 12 
13 13 String s5 = "hello";
14 14 String s6 = "hello";
15 15 System.out.println(s5 == s6);
16 16 System.out.println(s5.equals(s6));
17 17 }
18 18 }
答案:false true false true true true
解析:
  String s5 = "hello";
  String s6 = "hello";
  System.out.println(s5 == s6); true
因为之前的字符串赋值时,已经在方法区中创建了"hello",设它地址值为0x001,而s5、s6的时候,它会先在方法区中搜索是否存在"hello",存在的话,它直接调用到s6中,地址值也是0x001.
所以 s5 == s6 的结果为 true
 
23 package cn.itcast_02;
24 /*
25 * 看程序写结果
26 * 字符串如果是变量相加,先开空间,在拼接。
27 * 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
28 */
29 public class StringDemo4 {
30 public static void main(String[] args) {
31 String s1 = "hello";
32 String s2 = "world";
33 String s3 = "helloworld";
34 System.out.println(s3 == s1 + s2);
35 System.out.println(s3.equals((s1 + s2)));
36 
37 System.out.println(s3 == "hello" + "world");
38 
39 System.out.println(s3.equals("hello" + "world"));
40 
41 
42 }
43 }

  答案: false true true true
      System.out.println(s3 == "hello" + "world");
因为这里的hello和world是字符串,先进行合并再和s3来判断的
 通过反编译看源码,得知这里已经做好了处理。
System.out.println(s3 == "helloworld");
System.out.println(s3.equals("helloworld"));

何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5871081.html