Day02
类型转换
int i = 128;
byte b = (byte)i;//内存溢出
//强制类型转换 (类型)变量名 高-低
double b = i;
//自动转换 低 - 高
注意点:
-
不能对布尔值进行转换
-
不能把对象类型转换为不相干的类型
-
在把高容量转换到低容量的时候,强制转换
-
转换的时候可能存在溢出,或者精度问题
例如:
System.out.println((int)23.7); //输出为23
char c = 'a';
int d = c + 1;
System.out.println(d); //98
System.out.println((char)d); //b
public class Demo06{
public static void main(String[] args){
//操作比较大的时候,注意溢出问题
//JDK新特性,数字之间可以用先划线分割
int money = 10_0000_0000;
int years = 20;
int total = money * years;
System.out.println(total); //-1474836480,计算的时候溢出了
long total2 = money * years; //默认是int,还算之前已经出问题了
long total3 = money * ((long)years); //先把一个数转换为龙
System.out.println(total3); //2000000000 结果正确
}
}
变量
变量:
就是可以变化的量
public class Demo07;{
public static void main(String[] args){
int a = 1;
int b = 2;
int c = 3;
String name = "zhang";
char x = 'z';
double pi = 3.14;
}
}
变量作用域
1.局部变量 2.实例变量 3.类变量
public class Demo08{
//类变量 static 从属于类
static double salary = 2500;
//实例变量
String name; //null
int age; //0
//实例变量 从属于对象,如果不自行初始化,就是这个类型的默认值
//布尔值:默认是false
//除了基本类型,其余的都是null
public static void main(String[args]){
int i = 10; //局部变量:必须声明初始化值
System.out.println(i);
}
public void add(){
System.out.println(i); //i只在上面的方法中有用
}
}
常量
初始化之后不能再改变值,不会变动的值
public class Demo09{
static final PI = 3.14; //final代表常量 修饰符,不存在先后顺序
public static void main(String[] args){
System.out.println(PI);
}
}
命名规范![]()
运算符
public class Demo01{
public static void main(String[]args){
int a = 10;//Ctrl + D 当前行到下一行
int b = 20;
int c = 25;
int a = 25;
System.out.println(a + b); //30
System.out.println(a - b); //-10
System.out.println(a * b); //200
System.out.println(a /(double)b); //0.5
}
}
public class Demo02{
public static void main(String[]args){
long a = 123123123123L;
int b = 123;
short c = 10;
byte d = 8
System.out.println(a+b+c+d); //long
System.out.println(ab+c+d); //int
System.out.println(c+d); //int
//有一个Long 结果就是long 没有long 都默认int类型 如果有double 结果就是double*---------------------2w
}
}
浙公网安备 33010602011771号