java开篇之路:运算符
运算符
java语言支持如下运算符:
- 算数运算符:+,-,*,/,%,++,--
- 赋值运算符:=
- 关系运算符:>,<,>=,<=,==,!= instanceof
- 逻辑运算符:&&,||,!
- 位运算符:&,|,^,~,>>,<<,>>>(了解!即可)
- 条件运算符:?:
- 扩展赋值运算符:+=,-=,*=,/=
%是取余(模运算),a%b = a - (int)(a/b)*b;
package operation;
/**
* 运算符
*/
public class Demo1 {
public static void main(String[] args) {
int a=10;
int b=20;
int c=24;
int d=27;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b);
System.out.println(a%b);//10%20=10-(10/20)*20=10
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
}
package operation;
public class Demo2 {
public static void main(String[] args) {
long a=123123123L;
int b=123;
short c=100;
byte d=120;
System.out.println(a+b+c+d);//long参与运算的时候 结果类型为long
System.out.println(b+c+d);//long不参与运算的时候。运算结果的类型都为int
System.out.println(c+d);
}
}
package operation;
public class Demo3 {
public static void main(String[] args) {
int a=3;
int b=a++; //先赋值后自增
int c=++a; //先自增后赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println((a++)+(++b));
System.out.println((a--)+(b++));
System.out.println(a);
}
}
package operation;
/**
* 逻辑运算符
*/
public class Demo4 {
public static void main(String[] args) {
boolean x=true;
boolean y=false;
System.out.println(x&&y);//&&短路与 左右全为true则为true 左边为false结果直接为false右边不参与运算
System.out.println(x||y);//||短路或 有一方为真则为真 左边为true结果直接为true右边不参与运算
System.out.println(!(x&&y));//取反
}
}
位运算
package operation;
/**
* 位运算
*/
public class Demo5 {
public static void main(String[] args) {
/*
二进制
A= 0011 1100
B= 0001 1000
A&B 比较两者的每一位 都为1则为1 反之为0 0001 1000
A|B 比较两者的每一位 都为0则为0 反之为1 0011 1100
A^B 比较两者的每一位 每一位相同则为0 反之为1 0010 0100
~B 取反 1110 0111
2*8怎么算最快 2*2*2*2
<< 向左移 *2
>> 向右移 /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
*/
System.out.println(2<<3);
}
}
赋值运算符
package operation;
/**
* 赋值运算符
*/
public class Demo6 {
public static void main(String[] args) {
int x=10;
int y=20;
x+=y;// x=x+y;
x-=y;//x=x-y;
System.out.println(x);
//字符串连接符 先后顺序
System.out.println(""+x+y);
System.out.println(x+y+"");
}
}
三元运算符
package operation;
/**
* 三元运算符
*/
public class Demo7 {
public static void main(String[] args) {
//x ? y :z
//x为真则为y 假为z
int score=50;
String type= score>60?"及格":"不及格";
System.out.println(type);
}
}

浙公网安备 33010602011771号