数据类型及转换
数据类型与变量
数据类型
基本数据类型
-
byte 字节型
-
short 短整型 包装类 Short
-
int 整型 包装类 Integer(Integer.MIN-VALUE~Integer.MAX-VALUE)
-
long 长整型 包装类 Long
-
float 单精度浮点型
-
double 双精度浮点型
-
char 字符型
-
boolean 布尔型 精确到第几位?
不管什么系统所占字节都不变
变量
变量必须赋初值否则编译会出错
ctrl+/ 行注释
ctrl+shift+/ 块儿注释
小数最好还是使用double吧,float是四个字节



类型转换
强制转换 (范围大转到范围小): 容易丢失数据,
强制类型不一定能成功,【不相干类型,比如Boolean到int】
不同的数据类型进行运算,数据类型小的会转为数据类型大的。
对于short、byte这种字节数小的数据类型会先转为四个字节再进行运算
public class Demo {
public static void main(String[] args) {
float a =3.14f;
System.out.println("======================");
int b =(int)a;
System.out.println(b);//结果为3,精度丢失
System.out.println("=====================");
byte c=1;
byte d=12;
//byte e=c+d;所有小于四个字节的数据在运算时会提升为四个字节。
int e=c+d;
System.out.println(e);
System.out.println("======================");
double f=12.341;
double g=12.142;
int h=(int)(f+g);//结果为24,精度丢失。
System.out.println(h);
String str="yes";
System.out.println(str);
System.out.println("====================");
String str2=" no";
System.out.println(str2);
System.out.println("==============");
String str3=str+str2;
System.out.println(str3);//输出结果位:yes no
// 字符串可以拼接
}
}
不同的前后顺序,输出不同的结果。
int i=3;
int j=78;
System.out.println("i + j ="+i+j);
System.out.println("========================");
System.out.println(i + j +"= i + j");
System.out.println("==========================");
System.out.println("i + j ="+ (i + j));
//输出结果33333333333333333333
i + j =378
========================
81= i + j
==========================
i + j =81
String类型的转换
String.valueOf()
public static void main1(String[] args) {
int num=10;
//方法一
String str00= num+"";
System.out.println("=======================");
System.out.println(str00);
//方法二
String str01= String.valueOf(num);
System.out.println(str01);
System.out.println("============================");
String str02= String.valueOf(5668);//通过String.valueOf()这个函数可以把任何类型的数据都转化成字符串。
System.out.println(str02);
}
Integer.parseInt(str)
public static void main(String[] args) {
//字符串转化为int
String str ="16";
int num =Integer.parseInt(str);
System.out.println(num-1);//运行结果 15
System.out.println("=================");
String str1 ="1.123";
double num1 =Double.parseDouble(str1);
System.out.println(num1+0.2);//运行结果1.323
}

浙公网安备 33010602011771号