- 算术运算符
- 关系运算符
- 位运算符
- 逻辑运算符
- 赋值运算符
- 其他运算符
一、算术运算符
- +
- -
- *
- /
- %
- ++
- --
a++(--): 先运算,在自增(减)
++(--)a: 现自增(减),再运算
二、关系运算符
- ==
- !=
- <
- >
- <=
- >=
三、位运算符
- 关于原码,反码,补码
- 正数的原码、反码、补码都一样;
- 负数的反码 = 原码的符号位不变,其他位取反;
- 负数的补码 = 反码+1;
- 0的原码、反码、补码都是0;
- 计算机以补码进行运算;
- 取反不同于反码;
- 位运算符对数二进制数运算
- Java没有无符号数
假设a=60(0011 1100) b=13(0000 1101)
/*
* 十进制转成二进制
* String s = Integer.toBinaryString(n) ;
* 十进制转成十六进制的数
* String s = Integer.toHexString(n);
*/
public abstract class Test
{
public static void main(String[] args)
{
int a=60,b=13;
System.out.println(Integer.toBinaryString(a&b));
System.out.println(Integer.toBinaryString(a|b));
System.out.println(Integer.toBinaryString(a^b));
System.out.println(Integer.toBinaryString(~a));
System.out.println(~a);
System.out.println(Integer.toBinaryString(a<<2));
System.out.println(Integer.toBinaryString(a>>2));
System.out.println(Integer.toBinaryString(a>>>2));
}
}
运行结果:
1100
111101
110001
11111111111111111111111111000011
-61
11110000
1111
1111
特别的对于~运算:
例如,~2 = -3
对2的原码取反:11111111 11111111 11111111 11111101 (取反后结果的补码,也就是-3的补码。我们需要从补码推出原码,才能得到-3)
转换成反码: 11111111 11111111 11111111 11111100 (补码减1)
转换成码: 10000000 00000000 00000000 00000011 =-3 (符号为不变,其他位取反)
四、逻辑运算符
- &&
- ||
- !
public abstract class Test
{
public static void main(String[] args)
{
int a=60,b=13;
boolean c=true;
boolean d=false;
System.out.println("c||d= "+(c||d));
System.out.println("c&&d= "+(c&&d));
System.out.println("!c= "+(!c));
System.out.println("!d= "+(!d));
System.out.println("a<1&&b>13= "+(a<1&&b>12));
System.out.println("a<1||b>13= "+(a<1||b>12));
}
}
运行结果:
五、赋值运算符
- =
- +=
- -=
- *=
- /=
- %=
- <<=
- >>=
- ^=
- &=
- |=
六、其他运算符
6.1 条件运算符(?:)
条件?正确值:错误值
public abstract class Test
{
public static void main(String[] args)
{
int a=60,b=13;
b=(a==60)?60:0;
System.out.println(b);
b=(a!=60)?60:0;
System.out.println(b);
}
}
运行结果:
60
0
6.2 instanceof运算符
- 该运算符用于操作对象实例,检查该对象是否是一个特定类型(类类型或接口类型)。
- instanceof运算符使用格式如下:
( Object reference variable ) instanceof (class/interface type)
- 如果运算符左侧变量所指的对象,是操作符右侧类或接口(class/interface)的一个对象,那么结果为真。
public class Test
{
public static void main(String[] args)
{
Test a=new Test ();
System.out.println(a instanceof Test);
}
}
输出为:true
- 如果被比较的对象兼容于右侧类型,该运算符仍然返回true。
class Test1
{
}
public class Test extends Test1
{
public static void main(String[] args)
{
Test a=new Test();
System.out.println(a instanceof Test);
}
}
输出为: true