JAVA学习笔记-数据类型与运算符01
public class demotest0402{
public static void main(String[] args){
//byte 和byte运算;
byte a = 10;
byte b = 20;
byte c = (byte)(a + b);//如果写成 byte c = a + b,则编译会报错,因为a 和b 虽然是byte同类型,但是运算时,short,byte这种比四字节小的类型会先提升为4字节的int类型。结果c也就变成int类型,要用byte来接收,就得用强制类型转换。
System.out.println(c);
//int 和 long 运算:
int a1 = 10;
long b1 = 20;
//int c1 = a1 + b1;提示不兼容的类型,从int转换成long会有损失,int 和long运算时,提升int为long,long值赋给int,可能会有损失,显然错误。
//正确写法
long c1 = a1 + b1;
int c2 = (int)(a1 + b1);//强制转换;
System.out.println(c1);
System.out.println(c2);
//结论:1、不同类型的数据混合运算,范围小的会提升为范围大的;2、比四个字节小的数据会先提升为int类型,在继续运算(计算机的cpu通常以4个字节为单位从内存中提取数据)。
//int和string之间的转换:
//int转String:
int a2 = 10;
String str = a2 + " ";//方法1用“+”来与字符串进行拼接,结果统统都是字符串;
String str1 = String.valueOf(a2);// “.”调用;(注意valueOf的O是大写);
System.out.println(str);
System.out.println(str1);
//String转换为int
String str2 = "11";
int num = Integer.parseInt(str2);//同样parseInt的I是大写。
System.out.println(num);
//算数运算符
int a3 = 1;
int b3 = 2;
int c3 = a/b;
System.out.println(c3);//结果c3 = 0,int/int结果还是int;需用double;
double a301 = 1;
double b301 = 2;
double c301 = a301/b301;
System.out.println(c301);//c301 = 0.5;
int a4 = 2;
double b4 = 2.5;
//int c4 = a4 * b4;
//System.out.println(c4);//编译错误,从double转换成int可能会有损失;
double c401 = a4 * b4;
System.out.println(c401);//c401 = 5.0;
int a5 = 1;
double b5 = 1.4;
double c5 = a5 + b5;
System.out.println(c5);
//取余%不仅可以对int取余,也可对double取余;
System.out.println(11.5%2);
System.out.println(11%2);
//增量赋值运算符:+= -= *= /= %=
int a6 = 1;
a6 += 1;//等价于a6 = a6 + 1;对a6 + 1,再赋值给a6;
System.out.println(a6);
int a601 = 2;
int b601 = 5;
int c6 = b601 %= a601;//把 5 对 2取余的余数赋给c6;
System.out.println(c6);
//自增/自减运算符:
int a7 = 0;
a7 ++;
++ a7;
System.out.println(a7);//a7 = 2;+在前和在后都为自加1;
int a701 = 0;
int b7 = 0;
int b701 = 0;
b7 = a701 ++;
System.out.println("b7 = " + b7);//b7 = 0;
System.out.println("a701 = " + a701);//a701 = 1,b7取表达式的返回值时,+在后则取a701自 增之前的值,然后a701再自增;
b701 = ++ a701;
System.out.println("a701 = " + a701);//a701 = 2;
System.out.println("b701=" + b701);// b701 = 2,+在前a701 先自增,再把返回值赋给b701;
}
}