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"));

最新文章

  1. day7_subprocess模块和面向对象,反射
  2. 用java 代码下载Samba服务器上的文件到本地目录以及上传本地文件到Samba服务器
  3. JAVA & JSON详解
  4. HashMap原理详解
  5. memcache中的add和set方法区别
  6. 梯度下降之随机梯度下降 -minibatch 与并行化方法
  7. schema 对象的简单介绍
  8. Responder Pro new version could analyze Win10 memory dump
  9. linux开发调试工具---GDB的使用
  10. 标签传播算法(Label Propagation Algorithm, LPA)初探
  11. ASP.NET Core中使用Unity5
  12. CPU与IRP的一些相关函数
  13. java FTPClient 上传文件 0kb 问题
  14. 网络编程 -- RPC实现原理 -- RPC -- 迭代版本V2 -- 本地方法调用 整合 Spring
  15. ArcMap等值面
  16. PHP 调试工具Xdebug安装配置
  17. Ambari Rest api 使用
  18. transition过渡效果
  19. Session not active, could not store state 的解决方法
  20. 2、Android自己的下拉刷新SwipeRefreshLayout--样式2

热门文章

  1. [Tool] 透过PowerPoint Online在部落格文章里内嵌简报
  2. c# Sqlite帮助类
  3. 关于ol有序裂变和ul无序列表前面的列表项标记的位置
  4. Android 开关按钮切换,类似于iphone 效果,view实现
  5. C语言接口与实现实例
  6. JAVA基础学习day18--常用工具类
  7. Spring(三)Bean继续入门
  8. IOS杂笔- 7(类方法load与initialize的区别 浅析)
  9. android 进程/线程管理(二)----关于线程的迷思
  10. php多线程pthreads的安装与使用