java中String字符串解析

本文深入解析Java中String对象的创建方式,探讨使用new关键字、直接创建及字符串连接的区别,以及==与equals方法比较字符串的原理。同时,分析不同情况下字符串比较的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建String字符串的三种方式:

  • 使用new关键字创建String s1 = new String("abc");
  • 直接创建String s2 = "abc";
  • 使用字符串连接创建String s3 = "ab" + "c";

String字符串的特性:

  • 1、在创建的时候会在堆内存的String池中查看该字符串是否存在,如果不存在,则使用new关键字创建一个,如果存在,则无需重新创建。
  • 2、只有使用new关键字创建一定会在内存中重新创建一个对象

String字符串中两个字符串使用“==”与equals方法区别

  • 当两个字符串使用“==”进行比较时,比较的是两个字符串在内存中的地址
  • 当两个字符串使用equals方法比较时,比较的是两个字符串的值
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");

System.out.println((s1 == s2) + " and " + (s1.equals(s2)));
System.out.println((s1 == s3)  + " and " + (s1.equals(s3)));
System.out.println((s3 == s4) + " and " + (s3.equals(s4)));

//输出结果:
true and true
false and true
true and true

String字符串一些情况下的“==”比较

  • 1、当直接创建字符串时
String s1 = "abc";
String s2 = "abc";
System.out.println("The result: " + (s1 == s2));

//结果
The result: true
  • 当使用纯字符串串联创建字符串时
String s1 = "abc";
String s2 = "ab" + "c";
System.out.println("The result: " + (s1 == s2));

//结果
The result: true
  • 当使用编译期间可以确定结果的变量表达式创建字符串时
final String s1 = "c";
String s2 = "abc";
String s3 = "ab" + s1;
System.out.println("The result: " + (s2 == s3));

//结果
The result: true
  • 当只有在运行期间才能确定的值创建字符串时
String s1 = "c";
String s2 = "abc";
String s3 = "ab" + s1;
final String s4 = getString();
String s5 = "ab" + s4;
System.out.println("The result: " + (s2 == s3));
System.out.println("The result: " + (s2 == s5));

public String getString(){
   return "c";
}

//结果
The result: false
The result: false

以上代码中,s1不是final类型的,所以只有在代码运行时值才能确定,s4虽然定义成final类型的,但是其值是通过getString这个方法得来的,其值也只能在代码运行才能确定。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值