Java中String str=new String("a")和String str = "a"有什么区别?
Q:
String A="ABC";
String B=new String("ABC");
这两个值,A,B 是否相等,如果都往HashSet里面放,能放下吗?
答:(a)A==B 的判断为false;
(b)A.equals(B)为true ;因为值相等,所以都往HashSet里面放不下,只能放一个
问题:==与equals()的区别:
- ==:比较引用类型比较的是地址值是否相同
- equals:比较引用类型默认也是比较地址值是否相同,注意:String类重写了equals()方法,比较的是内容是否相同。
String A = "ABC";内存会去查找永久代(常量池) ,如果没有的话,在永久代中中开辟一块儿内存空间,把地址付给栈指针,如果已经有了"ABC"的内存,直接把地址赋给栈指针;
因此
String str1="aa";
Srting str2="aa";
String Str3="aa";
....
这样下去,str1==Str2==str3;会一直相等下去,(a) ==的判断, (b) equals()的判断;都相等,因为他们的地址都相等,因此只在常量池中有一份内存空间,地址全部相同;
而String str = new String("a");是根据"a"这个String对象再次构造一个String对象;在堆中从新new一块儿内存,把指针赋给栈,
将新构造出来的String对象的引用赋给str。 因此 只要是new String(),则,栈中的地址都是指向最新的new出来的堆中的地址,
(a)“”==“” 是判断地址的,当然不相同;
(b)至于equals,String类型重写了 equals()方法,判断值是否相等,明显相等,因此 equals 是相等的;
这是String 重写的equals:

* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}


public class StringDemo2 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
}
}
**运行结果:**
> false
> true

代码详解
- 首先,通过main()方法进栈。
- 然后再栈中定义一个对象s1,去堆中开辟一个内存空间,将内存空间的引用赋值给s1,“hello”是常量,然后去字符串常量池 查看是否有hello字符串对象,没有的话分配一个空间存放hello,并且将其空间地址存入堆中new出来的空间中。
- 在栈中定义一个对象s2,然后去字符串常量池中查看是否有”hello”字符串对象,有,直接把”hello”的地址赋值给s2.
- 即s1中存的是堆中分配的空间,堆中分配的空间中存的是字符串常量池中分配空间存放”hello”的空间的地址值。而s2中之间存的是字符串常量池中分配空间存放”hello”的空间的地址值。
- 由于s1与s2中存放的地址不同,所以输出false。因为,类String重写了equals()方法,它比较的是引用类型的 的值是否相等,所以输出true。即结果为false、true。
Demo1

public class StringDemo1 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);// false
System.out.println(s3.equals(s4));// true
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);// true
System.out.println(s5.equals(s6));// true
}
}


Demo1详解
s1~s6用equals()的比较不解释,都是比较的值,均为true。以下讲解==
- s1、s2:二者均为new出来的,各自在堆中分配有空间,并各自将内存地址赋值给s1、s2。空间地址不同,==比较为false。但是各自在堆中空间中保存的值均为在字符串常量池中的同一个对象的地址。根据Demo处的图即解释不难理解。
- s3、s4同上Demo出解释。
- s5、s6都是在常量池中取值,二者都指向常量池中同一对象,其地址值相同,所以结果为true。
Demo2

public class StringDemo4 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);// false
System.out.println(s3.equals((s1 + s2)));// true
System.out.println(s3 == "hello" + "world");//true
System.out.println(s3.equals("hello" + "world"));// true
}
}


Demo2详解
equals()比较方法不解释,比较值,均相等,均为true。
- s1与s2相加是先在字符串常量池中开一个空间,然后拼接,这个空间的地址就是s1与s2拼接后的地址。与s3的地址不同,所以输出为false。
- s3与”hello”+”world”作比较,”hello”+”world”先拼接成”helloworld”,然后再去字符串常量池中找是否有”helloworld”,有,所以和s3共用一个字符串对象,则为true。
总结
- String s = new String(“hello”)会创建2(1)个对象,String s = “hello”创建1(0)个对象。
注:当字符串常量池中有对象hello时括号内成立! - 字符串如果是变量相加,先开空间,在拼接。
- 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。
Java中String str=new String("a")和String str = "a"有什么区别?的更多相关文章
- java中数组有没有length()方法?string没有lenght()方法?
java中数组有没有length()方法,求数组的长度可以使用数组的length属性. int[] arr={1,2,3,4,5}; int length=arr.length;//求数组的长度 -- ...
- 【Java基础】2、Java中普通代码块,构造代码块,静态代码块区别及代码示例
Java中普通代码块,构造代码块,静态代码块区别及代码示例.Java中普通代码块,构造代码块,静态代码块区别及代码示例 执行顺序:静态代码块>静态方法(main方法)>构造代码块>构 ...
- JAVA中日期 yyyy-MM-dd HH:mm:ss和yyyy-MM-dd hh:mm:ss的区别
JAVA中日期 yyyy-MM-dd HH:mm:ss和yyyy-MM-dd hh:mm:ss的区别 : HH:24小时制 hh:12小时制 package time; import java.tex ...
- Java中List,ArrayList、Vector,map,HashTable,HashMap区别用法
Java中List,ArrayList.Vector,map,HashTable,HashMap区别用法 标签: vectorhashmaplistjavaiteratorinteger ArrayL ...
- Java中利用MessageFormat对象实现类似C# string.Format方法格式化
我们在写C#代码的时候常常会使用到string.Format("待格式化字符串{0},{1},....",参数1,参数2,...),来格式化字符串,特别是拼接字符的时候,这种方式使 ...
- Java中的类型转换(Integer、Long、String)
这段时间将项目中一个模块参照C++源代码,实现一个JAVA版.主要功能是将一些字段信息转换为String类型,传输后可以进行解析. Integer.Long转为String,Java本身提供了这种转换 ...
- 【Java面试题】18 java中数组有没有length()方法?string没有lenght()方法?下面这条语句一共创建了多少个对象:String s="a"+"b"+"c"+"d";
数组没有length()这个方法,有length的属性.String有有length()这个方法. int a[]; a.length;//返回a的长度 String s; s.length();// ...
- Java中常用的API(二)——String
在第一节中我们介绍了Object类的方法以及操作,那么这一节,我们将介绍一个新的类:String. String类是我们经常使用的类,应用十分广泛.同时,String类中封装了一系列的方法,非常常用, ...
- Java 中 常用API概述之 Math, Object, String,StringBuffer类,Arrays,Integer类
Math Math类包含执行基本数字运算的方法,如基本指数,对数,平方根和三角函数. 与StrictMath类的一些数字方法不同,Math类的StrictMath所有Math都没有定义为返回比特位相同 ...
- Java中的常用类:包装类、String、StringBuffer、StringBuilder、Math、System、Arrays、BigInteger、BigDecimal、Data、Calendar
一.包装类 √ 二.String类 ★ 三.StringBuffer和StringBuilder类 ★ 四.Math类 五.System类 六.Arrays类 七.BigInteger类和BigDec ...
随机推荐
- 强大的httpClientUtils
<!-- https://mvnrepository.com/artifact/com.arronlong/httpclientutil --> <dependency> &l ...
- 线程池 一 ThreadPoolExecutor
java.util.concurrent public class ThreadPoolExecutor extends AbstractExecutorService ThreadPoolExecu ...
- Servlet(Server Applet) 详解
Java编写的服务器端程序.其主要功能在于交互式地浏览和修改数据,生成动态Web内容. Servlet的工作模式 客户端发送请求至服务器 服务器启动并调用Servlet,Servlet根据客户端请求生 ...
- JavaWeb学习篇之----Servlet
今天来继续学习JavaWeb的相关知识,之前都是都介绍一些基本知识,从今天开始我们来说一下如何在服务器编写程序,这里就需要来介绍一下Servlet的相关知识了.Servlet就是一个能够运行在服务器端 ...
- hive的行列互转
行转列 多行转多列 数据表 row2col col1 col2 col3 a c 1 a d 2 a e 3 b c 4 b d 5 b e 6 现在要将其转化为: col1 c d e a 1 2 ...
- 原生js实现文件下载并设置请求头header
原生js实现文件下载并设置请求头header const token="自行定义";//如果有 /** * 向指定路径发送下载请求 * @param{String} url 请求路 ...
- (转)RSA加密解密及数字签名Java实现
转:http://my.oschina.net/jiangli0502/blog/171263?fromerr=hc4izFe2 RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rives ...
- hexo next主题深度优化(七),cdn加速。
文章目录 注: 正题: 免费cdn 收费cdn 个人博客:https://mmmmmm.me 源码:https://github.com/dataiyangu/dataiyangu.github.io ...
- subId、slotId、SubscriptionInfo和SubscriptionManager的解释及关系说明
1. subid和slotid(phoneid) slotid(phoneid)是指卡槽:双卡机器的卡槽1值为0,卡槽2值为1,依次类推. subid:SubscriptionId(Subscript ...
- Bootstrap3的响应式缩略图幻灯轮播效果设计
在线演示1 本地下载 HTML <div class="container"> <div class="col-md-12"> &l ...
