java11-2 String面试题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
 
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 false true
      System.out.println(s3 == "hello" + "world");
因为这里的hello和world是字符串,先进行合并再和s3来判断的
 通过反编译看源码,得知这里已经做好了处理。
System.out.println(s3 == "helloworld");
System.out.println(s3.equals("helloworld"));

以上是关于java11-2 String面试题的主要内容,如果未能解决你的问题,请参考以下文章

Java工程师面试题,二级java刷题软件

Java进阶之光!2021必看-Java高级面试题总结

经验总结:Java高级工程师面试题-字节跳动,成功跳槽阿里!

前端面试题之手写promise

Java面试题和解答

JAVA面试集锦String相关的经典面试题