目录
前言
String 类在 Java 开发中特别常用,不管是 Java 开发者还是 Android 开发者在面试时或多或少都会碰到这方面的面试题。这整理下经常会碰到的关于 String 类的一些面试题,附有详解。
1. equals 和 == 考题一
String str1 = "java";
String str2 = "java";
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
解析:
true
true
== 比较的是地址值,而这里的 java
都会存在于方法区的常量池中,所以二者是同一地址。而 String 类重写了 Object 类的 equals() 方法,其源码注释如下:
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
大意之:只要目标字符串不是 null
,那么当二者是相同字符序列时,返回结果为 true
.
2. new String(“java”) 创建对象问题
// 下面这句代码创建了几个对象
String string = new String("java");
解析:
两个
结合 String(字符串) 方法源码注释和内存图来说明:
/**
* Initializes a newly created {@code String} object so that it represents
* the same sequence of characters as the argument; in other words, the
* newly created string is a copy of the argument string. Unless an
* explicit copy of {@code original} is needed, use of this constructor is
* unnecessary since Strings are immutable.
*
* @param original
* A {@code String}
*/
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
大意之:此构造方法所创建的对象乃是参数的副本。而参数本身是存在于内存中的方法区中的常量池,而对象存在于堆中,所以这是两个对象。内存图如下:
3. equals() 与 == 考题二
String string = new String("java");
String string2 = "java";
System.out.println(string == string2);
System.out.println(string.equals(string2));
解析:
false
true
根据第二题可知,这里的 string 实例创建在堆内存中,而执行 String string2 = "java"
时,是在常量池创建常量 java,所以二者的地址是不同的,故为false
。而 equals()
比较的是字符序列是否相同,所以结果为true.
4. equals() 与 == 考题三
String string = "j" + "a" + "v" + "a";
String string2 = "java";
System.out.println(string == string2);
System.out.println(string.equals(string2));
解析:
true
true
Java 中有常量优化机制。当执行 String string2 = "java";
时,常量池中已经有 java
存在了。
5. 字符串拼接与不拼接进行 equals() 和 == 比较
String str1 = "java";
String str2 = "javac";
String str3 = str1 + "c";
System.out.println(str2 == str3);
System.out.println(str2.equals(str3));
解析:
false
true
Java 中的字符串拼接(连接符+)是通过 StringBuffer 或者 append 方式,这样的方式是创建对象,然后在利用 toString()
转换为 String 类型字符串。具体内存图如下: