字符串类型
概念:
- String类型是引用数据类型,也叫字符串类型。虽然使用方式和基本数据类型很像,但本质更接近类。
- 代码中String类型常量使用
""
包裹,如"a"
、"abc"
。""
之间可以为空。
运算:
- String相关的运算有8种,包含boolean
- String类型进行运算时一定要将String类型的值放在前两位。
- String类型的运算只有连接运算,使用
+
连接,也因此String类型不能和其它类型相互转换。
public class StringTest{
public static void main(String[] args){
String s1 = "Hello";
String s2 = ""; // 可以为空
String s3 = s1 + " World"; // 字符串连接
System.out.println(s1);
System.out.println(s3);
// 和基本数据类型的运算
int a = 10;
String s4 = s1 + a; // 字符串连接
System.out.println(s4);
String s5 = a + "Hello";
System.out.println(s5);
boolean b = true;
// String s6 = a + b + s1; // 必须前两位中有一个是字符串,才能进行字符串连接
String s6 = a + s1 + b ;
}
}