Java 运算符
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);
}
}

浙公网安备 33010602011771号