AG愛思即將回歸,貓神淪為替補,換回以前的首發陣容準備覺醒!
阿新 • • 發佈:2022-04-02
1 基本運算子
- 二元運算子:需要兩個數運算
- 一元運算子:一個運算元運算
1.1 基本運算子
算數運算子:+ - * / % ++ --
賦值運算子:=
關係運算符:> < >= <= == != instanceof
邏輯運算子:&& || !
1.1.1 基本運算
public class T { public static void main(String[] args) { int a = 10; int b = 20; int c = 22; System.out.println(a / (double) b); //%:取餘(java稱為模運算),如下 System.out.println(c % a);// 2 } }
1.1.1 不同資料型別運算
public class T { public static void main(String[] args) { Long a = 123456789L; int b = 123; short c = 128; byte d = 30; double e = 1.1; float f = 1.2f; System.out.println(a + b + c + d);//Long System.out.println(b + c);//Int System.out.println(c + d);//Int System.out.println(a+e);//long+double=double System.out.println(a+f);//long+float=float System.out.println(e+f);//float+double=double //兩個運算元或多個運算元有一個數型別為Long,結果型別為Long;如果沒Long,無論是否有int操作,結果都為Int } }
PS:最終運算資料結果為高容量的資料型別。
1.1.3 關係運算
關係運算的結果為布林值。【true false】
public class T {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a==b);//false
System.out.println(a!=b);//true
}
}
1.1.4 邏輯運算
結果為布林值,true,false。
public class T { public static void main(String[] args) { // 與(and) 或(or) 非(取反) boolean a = true; boolean b = false; System.out.println(a && b);//false,兩個變數均為真,結果為真 System.out.println(a || b);//true,兩個一個為真,結果為真 System.out.println(!(a && b));//true,取反 //短路運算 int c = 5; boolean d = (c < 4) && (c++ > 1); System.out.println(d);//flase System.out.println(c);//5 } }
1.2 位運算子
跟計算機操作相關的運算子
位運算子:& | ^ ~ >> << >>>
1.2.1 例項
public class T {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
---------------------位運算操作
A&B=0000 1100 //A,B 兩者都1,才為1
A|B=0011 1101 //有一個為1,則為1
A^B=0011 0001 //相同為0,不同為1
~A =1100 0011 //取反
*/
}
}
1.2.2 應用
如何最快得出 2*8 。
public class T {
public static void main(String[] args) {
/*
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
2*8=16 2*2*2*2
*/
System.out.println(2<<3);
}
}
PS:左移 * 2 ,右移 / 2
1.3 偷懶專用運算子
條件運算子:?:
擴充套件賦值運算子:+= -= *= /=
1.3.1 擴充套件賦值運算子&字串連線符
public class T {
public static void main(String[] args) {
int a = 10;
int b = 20;
a += b;//a=a+b
System.out.println(a);//30
//字串連線符 + String
int c = 10;
int d = 20;
System.out.println(c + d);//30
System.out.println("" + c + d);//1020;拼接
System.out.println(c + d + "");//30;先運算再拼接
}
}
1.3.2 條件運算子(三元運算子)
public class T {
public static void main(String[] args) {
// x ? y : z
//若 x=true,則結果為y,否則為z
int score = 30;
String type = score > 60 ? "合格" : "不合格";
System.out.println(type);
}
}
2 自增(減)運算子
自增,自減為一元運算子
public class T1 {
public static void main(String[] args) {
//++ -- 自增,自減 一元運算子
//++a 先自增再賦值
//a++ 先賦值再自增
int a = 3;
int b = a++;
int c = ++a;
System.out.println(a);//5
System.out.println(b);//3
System.out.println(c);//5
}
}
冪運算
使用數學工具類
public class T {
public static void main(String[] args) {
//冪運算 2^3 2*2*2 = 8 很多運算,會使用工具類來實現
double pow=Math.pow(3,2);
System.out.println(pow);
}
}