一、字符类型
1. Java在内存中用Unicode表示字符。
Unicode与ASCII区别:
编码 | 大小 | 支持语言 |
ASCII | 1个字节 | 英文 |
Unicode | 2个字节(生僻字4个) | all |
UTF-8 | 英文字母1个字节,汉字3个字节,生僻字4-6个字节 | all |
2. Unicode常用编码表
Unicode的编码是十六进制,用编码来给char赋值前需用转义字符“\u”+Unicode编码来表示。
- 0000:NUL;
- 0030-0039:0-9;
- 0041-0049-004F:大写字母(A-O);
- 0050-0059-005A:大写字母(P-Z);
- 0061-0069-006F:小写字母(a-o);
- 0070-0079-007A:小写字母(p-z)。
举例:
public class TestCharString {
public static void main(String[] args){
char c1 = 'A';
char c2 = '中';
int n1 = 'A';
int n2 = '中'; //'中'的Unicode编码为4e2d(十六进制)=20013(十进制)
char c3 = '\u0041'; //‘A’的Unicode编码
char c4 = '\u4e2d'; //'中'的Unicode编码
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println(n1);
System.out.println(n2);
}
}
输出:
二、字符串类型
1.
- 字符串类型String是引用类型(与char不同!);
- 表示:用双引号“”表示一个字符串,一个字符串可存储0到∞个字符;
- 转义:
举例:
public class TestCharCal {
public static void main(String[] args){
String s = "ABC\n\u4e2d\u6587"; //ABC、换行、中、文
System.out.print(s);
}
}
输出:
2. 字符串连接
(1)字符串可直接使用“+”进行连接。如果string+其他类型,会将其他类型先自动转换为字符串再连接。
举例:
public class TestCharCal {
public static void main(String[] args){
String s1 = "Hello";
String s2 = "World";
String st = s1+" "+s2+"!"; //字符串连接
System.out.println(st);
//string+其他类型
int age = 30;
String st2 = "age is "+age;
System.out.print(st2);
}
}
输出:
3. 多行字符串
可以用“ """(换行)XXX'""" ”表示多行字符串(string blocks)。举例:
public class TestCharCal {
public static void main(String[] args){
String mStr = """ //此处需换行开始
SELECT * FROM
users
WHERE id > 100
ORDER BY name DESC
""";
System.out.println(mStr);
}
}
输出:
4.字符(串)的重新赋值问题
字符(串)的重新赋值,只是重新对指向该变量的值进行更新,并不是对原字符(串)进行了重新赋值。
举例:
public class TestCharCal {
public static void main(String[] args){
String s3 = "Hello";
String t = s3;
s3 = "World";
System.out.println("s3为"+s3);
System.out.println("t为"+t);
}
}
输出:
5. 巧用“""”进行数据类型转换
可以用“ ""+int类型 ”,直接将int类型转换为字符型。
举例:
public class TestCharCal {
public static void main(String[] args){
//将a、b、c连接成一个字符串输出
int a = 72;
int b = 105;
int c = 65281;
String stest = ""+a+b+c;
System.out.print(stest);
}
}
输出:
★ 注意null和""的区别:
- null表示空值,不指向任何对象,不占内存空间,输出显示“null”;
- ""是一个有效的字符串对象,占内存空间,输出不显示。