java11-2 String面试题
2024-09-27 22:36:26
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 public class StringDemo3 {
2 public static void main(String[] args) {
3 String s1 = new String("hello");
4 String s2 = new String("hello");
5 System.out.println(s1 == s2);
6 System.out.println(s1.equals(s2));
7
8 String s3 = new String("hello");
9 String s4 = "hello";
10 System.out.println(s3 == s4);
11 System.out.println(s3.equals(s4));
12
13 String s5 = "hello";
14 String s6 = "hello";
15 System.out.println(s5 == s6);
16 System.out.println(s5.equals(s6));
17 }
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
package cn.itcast_02;
/*
* 看程序写结果
* 字符串如果是变量相加,先开空间,在拼接。
* 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
*/
public class StringDemo4 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);
System.out.println(s3.equals((s1 + s2))); System.out.println(s3 == "hello" + "world"); System.out.println(s3.equals("hello" + "world")); }
}
答案: false true true true
System.out.println(s3 == "hello" + "world");
因为这里的hello和world是字符串,先进行合并再和s3来判断的
通过反编译看源码,得知这里已经做好了处理。
System.out.println(s3 == "helloworld");
System.out.println(s3.equals("helloworld"));
最新文章
- day7_subprocess模块和面向对象,反射
- 用java 代码下载Samba服务器上的文件到本地目录以及上传本地文件到Samba服务器
- JAVA &; JSON详解
- HashMap原理详解
- memcache中的add和set方法区别
- 梯度下降之随机梯度下降 -minibatch 与并行化方法
- schema 对象的简单介绍
- Responder Pro new version could analyze Win10 memory dump
- linux开发调试工具---GDB的使用
- 标签传播算法(Label Propagation Algorithm, LPA)初探
- ASP.NET Core中使用Unity5
- CPU与IRP的一些相关函数
- java FTPClient 上传文件 0kb 问题
- 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V2 -- 本地方法调用 整合 Spring
- ArcMap等值面
- PHP 调试工具Xdebug安装配置
- Ambari Rest api 使用
- transition过渡效果
- Session not active, could not store state 的解决方法
- 2、Android自己的下拉刷新SwipeRefreshLayout--样式2