JAVA基础语法03
运算符
![yunsuanfu]()
- %是取除数的余,java的等于是==,!=是不等于的意思,&&与,||或,!非
二元运算符
public class demo01 {
public static void main(String[] args) {
// 二元运算符
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b); //结果本应该为0.5但是int向下取整为0了,这里需要强转为double
}
}
public class Demo02 {
public static void main(String[] args) {
long a = 123456789;
int b = 123;
short c = 10;
byte d = 8;
System.out.println(a+b+c+d); //有long时,所有类型变成long
System.out.println(b+c+d); //没有long时,所有非int类型转为int类型
System.out.println((c+d)); //运算结果的数据类型为参与运算的变量中最高优先级的数据类型
//类型转换:byte、short、char用运算符运算后自动转型为int类型
}
}
关系运算符
public class Demo03 {
public static void main(String[] args) {
//关系运算符返回的结果 : 正确,错误 布尔值
int a = 10;
int b = 20;
int c = 22;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
//取余,模运算
System.out.println(c%a);
}
}
一元运算符 自增自减
public class Demo04 {
public static void main(String[] args) {
//++ -- 自增,自减 一元运算符
int a = 3;
int b = a++; //执行完这一代码后,先给b赋值,再自增
//a++ a = a + 1
int c = ++a; //执行完这行代码前,先自增,再赋值
//输出值 a=5 b=3 c=5
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2^3 很多运算会使用一些工具类来操作
double pow = Math.pow(2,3);
System.out.println(pow);
}
}