一篇代码教你如何区分String的"=="和"equals()"

我们都知道String 类型存的是地址,用 "==" 进行判断的话,如果地址不一样,即使两个数的值是一样的,输出的结果也为false 。所以我们通常使用equals方法进行比较。

但是我的这一行代码却发现了一个"bug",我定义了s3和s4 两个变量,进行 "==" 比较的时候结果竟然为true?

ini 复制代码
String s3 = "hello";
String s4 = "hello";

System.out.println(s3 == s4);//结果为true
System.out.println(s3.equals(s4));//结果也为true

给大家看一下正常情况 (s1-s2)

ini 复制代码
String s1 = new String("hey");
String s2 = new String("hey");

System.out.println(s1 == s2);//结果为false
System.out.println(s1.equals(s2));//结果为true

对比一下。

大家看图上,想必能明显看到这两个结果也稍显不同。从图上来了解:s3和s4

该类型属于常量串直接赋值,它使用了*==*比较地址,两者的区别就在于:

s1和s2是new String赋值

常量串直接赋值导致地址直接进入了常量池中

new String赋值并没有进入常量池,两者对比起来应该是这样

所以才出现了System.out.println(s3 == s4);结果也为true的情况。

相关推荐
zhoxier2 小时前
elementui el-select 获取value和label 以及 对象的方法
javascript·vue.js·elementui
是小狐狸呀2 小时前
elementUI-表单-下拉框数据选中后,视图不更新
前端·javascript·elementui
Nejosi_念旧4 小时前
git报错解决:ssh: connect to host github.com port 22: Connection refused
git·ssh·github
IT码农-爱吃辣条6 小时前
Three.js 初级教程大全
开发语言·javascript·three.js
烛阴6 小时前
告别繁琐的类型注解:TypeScript 类型推断完全指南
前端·javascript·typescript
gnip6 小时前
工程项目中.env 文件原理
前端·javascript
JohnYan7 小时前
工作笔记 - CentOS7环境运行Bun应用
javascript·后端·容器
xixingzhe28 小时前
多人同时导出 Excel 导致内存溢出
服务器·设计
东风西巷9 小时前
Rubick:基于Electron的开源桌面效率工具箱
前端·javascript·electron·软件需求
大千AI助手9 小时前
GitHub Copilot:AI编程助手的架构演进与真实世界影响
人工智能·深度学习·大模型·github·copilot·ai编程·codex