一、数据类型
1、基本数据类型
在java中,默认的数字类型是int型,初始化long类型时,应当为 long 变量 = 1L(大小写l都可以)
int num = 1
定义了一个int型
long num = 1
num还是int型,因为存在类型自动转换,数字默认是int
long num = 1L
定义一个long型
char ch = 97
与 ch = 'a’相同
1.1、数据类型所占空间
byte(字节)——1字节
short(短整型)——2字节
int(整型)——4字节
long(长整型)——8字节
boolean(布尔型)——1bit
float(单精度浮点数)——4字节
double(双精度浮点数)——8字节
char(字符)——2字节
1.2、包装类
java中的包装类提供了将原始数据类型转换为对象,以及将对象转换为原始数据类型的机制
java.lang
包的八个类在java中称为包装类。八个包装类的列表如下:
基本类型 | 包装类 |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
package Demo;
/**
* @className:Data_Type;
* @time:2022-03-18-0:15;
* @author:Lee Ye;
* @description:这是一个java示例;
*/
public class Data_Type {
public static void main(String[] args)
{
byte byte_max = Byte.MAX_VALUE;
byte byte_min = Byte.MIN_VALUE;
System.out.println("byte 的最大值为:" + byte_max);
System.out.println("byte 的最小值为:" + byte_min);
System.out.println("byte的大小为:" + Byte.SIZE);
System.out.println("byte的类型为:" + Byte.TYPE);
}
}
1.3、布尔型
只存在两个值,非零数为真
boolean a = true;
boolean b = false;
二、数据类型转换
区别下下面这个结果
int a = 30, b = 7;
float g, h;
g = a / b; //4.0
h = (float) a / b;//4.285714
System.out.println(g);
System.out.println(h);
三、基本数据类型的默认值
成员变量有默认值,而局部变量没有,程序会随机给一个值
byte——(byte)0
short——(short)0
int——0
long——0L
float——0.0F
double——0.0D
char——’’ 或’/u0000’
boolean——false
四、练习
第一题、包装类的使用
题目:打印int类型中最小值到最大值是否为偶数
package Demo;
/**
* @className:Data_Type;
* @time:2022-03-18-0:15;
* @author:Lee Ye;
* @description:这是一个java示例;
*/
public class Data_Type {
public static void main(String[] args)
{
for(int i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++)
{
if (i % 2 == 0)
System.out.println(i + " 是偶数");
else
continue;
}
}
}
第二题、拼接符号的使用
-
作为加号,当与字符在一起时,会做加法,而不是拼接
-
作为
字符串
的连接符
int x = 1;
int y = 2;
System.out.println(x + y);
System.out.println(x + y + 'k');//110
System.out.println(x + y + "k");//3k
System.out.println(x + 'A' + y);//68
System.out.println(x + "A" + y);//1A2