运算符问题
算术运算符
加减乘除模(取余)运算与幂运算
package operator;
public class Demo01 {
public static void main(String[] args) {
//二元运算符
//ctrl+d 复制当前行至下一行
int a = 10;
int b = 20;
int c = 25;
int d = 35;
System.out.println(a+b); //30
System.out.println(a-b); //-10
System.out.println(a*b); //200
System.out.println(a/b); //0 注意结果为小数时只会保留整数部分
System.out.println(d%c); //10
System.out.println(a/(double)b); //0.5
//幂运算
//2^3 = 2*2*2 = 8 java中很多运算需要借助一些工具类
double pow = Math.pow(2,3); //2^3
double pow1 = Math.pow(3,2); //3^2
System.out.println(pow); //8.0
System.out.println(pow1); //9.0
}
}
package operator;
public class Demo02 {
public static void main(String[] args) {
long a = 1231231312131L;
int b = 200;
short c = 1000;
byte d = 8;
System.out.println(a+b+c+d); //long 1231231313339
System.out.println(b+c+d); //int 1208
System.out.println(c+d); //int 1008
//System.out.println((String) (c+d));
//Inconvertible types; cannot cast 'int' to 'java.lang.String'
//整数型当有long时为long,否则结果为int类型,不管有没有int类型
}
}
自减自增运算
package operator;
public class Demo04 {
public static void main(String[] args) {
//自增,自减运算符 ++ --
int a = 10;
int b = a++;
//a++先附值后自增
int c = ++a;
//++a先自增后附值
System.out.println(a); //12
System.out.println(b); //10
System.out.println(c); //12
}
}
关系运算符
大于小于等于不等于
package operator;
public class Demo03 {
public static void main(String[] args) {
//关系运算符 布尔 true false
int a = 10;
int b = 20;
System.out.println(a>b); //false
System.out.println(a<b); //true
System.out.println(a==b); //false
System.out.println(a!=b); //true
}
}
逻辑运算符
与或非以及短路运算
package operator;
public class Demo05 {
public static void main(String[] args) {
//逻辑运算符 与 或 非
boolean flag = true;
boolean flag1 = false;
System.out.println(flag1 && flag); //false 逻辑与运算 两个都为真才为真
System.out.println(flag || flag1); //true 逻辑或运算 有一个为真就为真
System.out.println(!(flag1 && flag)); //true 逻辑非运算 真的为假,假的为真
//短路运算,逻辑与运算当左边为假时不再执行右边
int a = 5;
boolean b = (a<4) && (a++<4);
System.out.println(b); //false
System.out.println(a); //5 a = 5,所以右侧a++没有执行
}
}
位运算
位运算是极快的运算方式
package operator;
public class Demo06 {
public static void main(String[] args) {
/*
位运算
A=0011 1100
B=0000 1100
A&B = 0000 1100 与
A|B = 0011 1100 或
A^B = 0011 0000 异或
~A = 1100 0011 取反
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
<<,>> 左移右移运算即乘2,除2运算
2*8 = 16 = 2*2*2*2 = 2 << 3
极快运算
*/
System.out.println(2<<3); //16
}
}
拓展赋值运算符
package operator;
public class Demo07 {
public static void main(String[] args) {
//+= -= *= /=
int a = 10;
int b = 20;
a += b;
System.out.println(a); //30 a = a+b
a -= b;
System.out.println(a); //10 a = a-b
}
}
条件运算符
package operator;
public class Demo08 {
public static void main(String[] args) {
//三元运算符
//x?y:z 如果x为true,则返回y,否则返回z
int score = 80;
int score1 = 50;
String result = score < 60 ? "不及格" : "及格";
String result1 = score1 < 60 ? "不及格" : "及格";
System.out.println(result); //及格
System.out.println(result1);//不及格
}
//优先级问题 多使用括号()
}
详情请去观看【狂神说Java】Java零基础学习视频通俗易懂