运算符
加减乘除
package operator;
public class D01 {
public static void main(String[] args) {
int a =10;
int b =20;
int c =25;
int d =30;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println((double)a/b);//0.5
}
}
package operator;
public class D02 {
public static void main(String[] args) {
long a =12300000000L;
int b =123;
short c =10;
byte d =8;
System.out.println(a+b+c);//long
System.out.println(d+b+c);//int
System.out.println(d+c);//int
}
}
package operator;
public class D03 {
public static void main(String[] args) {
//关系运算符返回的结果:正确,错误/*布尔值*/
int a=10;
int b =20;
int c = 21;
System.out.println(a>b);//false
System.out.println(a<b);//true
System.out.println(a==b);//false
System.out.println(a!=b);//true
//取余,模运算
System.out.println(c%a);//c/a=21/10=2..............1 取余数1
}
}
++ -- 和幂运算
package operator;
public class D04 {
public static void main(String[] args) {
// ++ -- 自增 ,自减 一元运算符
int a=3;
//System.out.println(a);=3
int b =a++;//a++ a=a+1执行完这行代码后,先给b赋值,再自增
//System.out.println(a);=4
int c = ++a;//++a a=a+1执行完这行代码前,先自增,再给c赋值
System.out.println(a);//=5
System.out.println(b);
System.out.println(c);
//幂运算 2^3 2*2*2=8 工具Math 很多运算使用工具类来操作!
double pow =Math.pow(2,3);
System.out.println(pow);
}
}
与或非
package operator;
public class D05 {
public static void main(String[] args) {
//与(and)或(or)非(取反)
boolean a=true;
boolean b =false;
System.out.println("a && b:"+(a&&b));//逻辑运算,两个变量都为真,结果才为ture
System.out.println("a || b:"+(a||b));//逻辑运算,两个变量有一个为真,结果才为ture
System.out.println("!(a && b):"+!(a&&b));//如果是真,则变为假,如果是假则变为真
//短路运算
System.out.println("=========================================================");
int c=5;
boolean d=(c<4)&&(c++<4);
System.out.println(d);
System.out.println(c);
}
}
<<左移 >>右移
package operator;
public class D06 {
public static void main(String[] args) {
/**
* A=0011 1100
* B=0000 1101
* -----------------------------------------------
* A&B= 0000 1100都是1为1
* A|B= 0011 1101都是0为0
* A^B= 0011 0001相同为0,不同为1
* ~B= 1111 0010相反
*--------------------------------------------------
* <<左移 *2
* >>右移 /2
* */
System.out.println(2<<3);
System.out.println(2>>3);
}
}
字符串连接
package operator;
public class D07 {
public static void main(String[] args) {
int a=10;
int b =20;
a+=b;//a=a+b
//30
a-=b;//a=a-b
//10
System.out.println(a);
//字符串连接符 + ,String
System.out.println(""+a+b);
System.out.println(a+b+"");
}
}
?:
package operator;
public class D08 {
public static void main(String[] args) {
//x ? y : z
//如果x==true 则结果为y,否则结果为z
int age =18;
String type = age>=18?"成年":"未成年";
System.out.println(type);
}
}