11
運算符
算術(shù)運算符: ,-,*,/,%, ,--
賦值運算符:=
關(guān)系運算符:>,<,==,<=,>=,!=instanceof
邏輯運算符:&&,||,!
位運算符:&,|,^,~,>>,<<,>>>(了解?。?
條件運算符:?:
拓展賦值運算符: =,-=,*=,/=
算術(shù)運算符
public class Demo01 {
public static void main(String[] args) {
//二元運算符 小技巧:Ctrl D 復(fù)制當前行到下一行
int a = 10;
int b = 20;
int c = 30;
int d = 35;
System.out.println(a b);
System.out.println(a%b);//取余 這里相除余數(shù)是10,故輸出10
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b);//注意這里有小數(shù),記得轉(zhuǎn)換
}
}
不同類型相加,有l(wèi)ong類型就輸出long類型,沒有則輸出int類型
總之比int高的類型存在就輸出高的類型,沒有就輸出int
public class Demo02 {
public static void main(String[] args) {
int a = 123;
long b = 11233333333L;
byte c = 11;
short d =222;
System.out.println(a b c d);//long
System.out.println(a c d);//int
System.out.println( c d);//int
}
}
,--
public class Demo04 {
public static void main(String[] args) {
//自增 ,自減 ,--
//一元運算符
int a = 10;
int b = a ;
// 先給b賦值,再讓a 1
int c = a;
//先給a 1,再讓c賦值
System.out.println(a);
System.out.println(b);
System.out.println(c);
//很多數(shù)學(xué)運算都使用Math工具
double d =Math.pow(2,3);//冪運算
System.out.println(d);
}
}
關(guān)系運算符
public class Demo03 {
public static void main(String[] args) {
//關(guān)系運算符返回的結(jié)果:正確 or 錯誤, 布爾值
//if
int a = 10;
int b = 20;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
}
邏輯運算符
public class Demo05 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println(a&&b);//&& 與,都是真則為真
System.out.println(a||b);//|| 或,有真則為真
System.out.println(!b);//! 取反,真變假,假變真
//短路運算:與運算中,監(jiān)測到假就停止運算
int c = 5;
boolean d = (c <4)&&(c<4);
System.out.println(c);
System.out.println(d);//此時c已經(jīng)自增,結(jié)果輸出6
//調(diào)換順序
int e = 5;
boolean f = (e<4)&&(e <4);
System.out.println(e);
System.out.println(f);
//此時輸出5,說明短路了
}
}
位運算符
public class Demo06 {
public static void main(String[] args) {
/*
位運算,底層代碼,二進制
A = 1000 0111
B = 1100 0010
---------------------
A&B=1000 0010
A|B=1100 0111
A^B=0100 0101
!B=0011 1101
2*8 怎么樣運算快 =2*2*2*2
二進制數(shù)字
1左移一位代表*2
1右移一位代表/2
這樣算效率極高
<< >> 左移 右移
*/
System.out.println(2<<3);//輸出16
}
}
拓展賦值運算符
偷懶用的
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a =b;//a=a b
System.out.println(a);
a-=b;//a=a-b
System.out.println(a);
//字符串連接符 String
System.out.println(a b "");//輸出30,意為ab相加
System.out.println("" a b);//輸出1020,意為字符串連接
}
}
三元運算符
public class Demo08 {
public static void main(String[] args) {
//三元運算符 x ? y:z
//x=true,輸出y,否則,輸出z
int score = 80;
String ef =score>60?"及格":"不及格";
System.out.println(ef);
}
}
學(xué)習(xí)自狂神說Java
來源:https://www./content-4-855901.html
|