String 不属于基础类型,而是一个对象,继承自 Object 对象。
首先,Java 中仅有 8 种基础类型,如下:
boolean
char
byte
short
int
float
long
double
基础类型不是对象,如果要使用对象,必须使用它们对应的包装对象。
其次,String 是 Java API 提供的一个类,完整包名为 java.lang.String。它的源代码如下:
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { //省略代码 }
验证 String 类继承自 Object 类,代码如下:
public class Demo { public static void main(String[] args) { String str = "hello world"; if(str instanceof Object) { System.out.println("str is the object"); } else { System.out.println("str not an object"); } // 调用继承自 Object 类的 hashCode() 方法 System.out.println("hashCode=" + str.hashCode()); } }
运行示例,输出结果如下:
str is the object hashCode=1794106052