- Java定义的数据类型
- 整数类型
- 浮点类型
- 字符类型:char
- 强制类型转换
- String字符串
整数类型
| 类型 | 占用存储空间 | 表数范围 |
|---|---|---|
| byte | 1字节=8bit位 | -128 ~ 127 |
| short | 2字节 | -215 ~ 215-1 |
| int | 4字节 | -231 ~ 231-1 (约21亿) |
| long | 8字节 | -263 ~ 263-1 |
Java的浮点型常量默认为double型,申明float型后面必须加“f”或“F”
| 类型 | 占用存储空间 | 表数范围 |
|---|---|---|
| 单精度float | 4字节 | -3.403E38 ~ 3.403E8 |
| 双精度double | 8字节 | -1.798E308 ~ 1.798E308 |
- char型数据用来表示通常意义上"字符"(2字节)
- Java中的所有字符都使用Unicode编码,故一个字符可以存储一个字母,一个汉字,或其他书面语的一个字符。
- 字符型变量的三种表现形式:
– 通常常量是用单引号(‘’)括起来的单个字符。例如:har c1 = 'a';har c2 = '中';har c3 = '9';
– Java中还允许使用转义字符’‘来将其后的字符转变为特殊字符类型常量。例如:har c3 = 'n';//'n'示换行符
– 直接使用 Unicode 值来表示字符型常量:’uXXXX’。其中,XXXX代码一个十六进制整数。如:u000a 表示 n。
– char类型是可以进行运算的。因为它们都对应有 Unicode 码
class VariableTest1 {
public static void main(String[] args) {
byte b1 = 127;
int i1 = 1234;
long l1 = 3411111111L;
System.out.println(l1);
System.out.println(b1);
System.out.println(i1);
char c5 = 'n';//换行符
c5 = 't'; //制表符
System.out.println("hello" + c5);
System.out.println("world");
char c6 = 'u0043';
System.out.println(c6);
}
}
| 转义字符 | 说明 |
|---|---|
| b | 退格符 |
| n | 换行符 |
| r | 回车符 |
| t | 制表符 |
只能取2个值之一:true、false
常常在条件判断、循环结构中使用
class VariableTest1 {
public static void main(String[] args) {
//布尔型:boolean
//① 只能取2个值之一:true、false
//② 常常在条件判断、循环结构中使用
Boolean bb1 = true;
System.out.println(bb1);
boolean rightorwrong = true;
if(rightorwrong){
System.out.println("数据为true你是1号的");
}else{
System.out.println("数据为false你是2号的");
}
}
}
强制类型转换
1.需要使用强转符:()
2.注意:强制类型转换,可能导致精度损失。
3.如果数值不声明数值类型,自动为int型
public class VariableTest2 {
public static void main(String[] args) {
double d1 = 12.9;
int i1 = (int) d1;//截断操作,把double转换为int类型,精度损失
System.out.println(i1);
long l1 = 123;
short s2 = (short)l1;//精度没有损失
System.out.println(s2);
int i2 = 128;
byte b = (byte)i2;//精度损失
System.out.println(b);
}
}
输出结果为:
12 123 -128String字符串
public class StringTest {
public static void main(String[] args) {
String s1 = "Hello World!";
System.out.println(s1);
String s2 = "a";
String s3 = "";
//char c = ''; //字符编译编译不通过
//**************
int number = 1001;
String number111 = "学号:";
String info = number111 + number; // +:连接运算
System.out.println(info);
}
}
String是字符串,char是字符



