/**
- 测试算数运算符
- @author 老窦
*/
public class TestOperator01 {
public static void main(String[] args) {
/*
byte a = 1;
int b = 2;
long b2 = 3;
//byte c = a+b; //不能将byte和int的值进行运算
//int c2 =b+b2; //不能将long和int的值进行运算
float f1 = 3.14F;
float d = b+b2; //此处用double就报错
//float d2 = f1+6.2; //报错
System.out.println(-9%5);
*/
/*
//测试自增和自减
int a = 3;
int b = a++; //执行完后,b=3。先给b赋值,再自增。
System.out.println("a="+a+"\nb="+b);
a = 3;
b = ++a; //a先自增,再给b赋值
System.out.println("a="+a+"\nb="+b);
*/
int a=3;
int b=4;
a+=b;//相当于a=a+b
System.out.println("a="+a+"\nb="+b);
a=3; //重新令a=3
a*=b+3;
System.out.println("a="+a+"\nb="+b);
}
}
/**
- 关系运算符
- @author 老窦
*/
public class TestOperator02 {
public static void main(String[] args) {
int a = 3;
System.out.println(a==3);
System.out.println(a!=3);
System.out.println(a<5);
//char也可以转为数字的比较
char b = 'a';
char b2 = 'c';
System.out.println((int)b);
System.out.println(0+b);
System.out.println(0+b2);
System.out.println(b<b2);
}
}
/**
- 逻辑运算符
- @author 老窦
*/
public class TestOperator03 {
public static void main(String[] args) {
boolean b1 = true;
boolean b2 = false;
System.out.println(b1&b2); //'与'的关系
System.out.println(b1|b2); //'或'的关系
System.out.println(b1^b2); //'异或'的关系
System.out.println(!b2); //'非'的关系
//短路
//int c = 3/0;
boolean b3 = 1>2&&2<(3/0); //短路与,第一个操作数的值为false,则不需要再计算后面的操作数
System.out.println(b3);
}
}
/**
- 位运算符
- @author 老窦
*/
public class TestOperator04 {
public static void main(String[] args) {
int a = 3;
int b = 4;
System.out.println(a&b);
System.out.println(a|b);
System.out.println(a^b);
System.out.println(~a);
//移位
int c = 3<<2;
System.out.println(c);
System.out.println(12>>1);
}
}
/**
- 字符串运算符
- @author 老窦
*/
public class TestOperator05 {
public static void main(String[] args) {
String a = "3";
int b = 4;
int c = 5;
char d = 'a';
System.out.println(a+b+c); //字符串'3'先和'4'连在一起为'34',再跟'5'连在一起构成'345'
System.out.println(b+c+a); //数字4+5=9然后'9'跟字符串'3'连在一起构成'93'
System.out.println(d+4); //这是字符的表示'a'代表97,这里显示为97+4=101
}
}
/**
- 条件运算符(三目运算符)
- @author 老窦
*/
public class TestOperator06 {
public static void main(String[] args) {
int score = 80;
int x = -100;
//方法一
String type = score<60?"不及格":"及格";
System.out.println(type);
//方法二
if(score<60) {
System.out.println("不及格");
} else {
System.out.println("及格");
}
System.out.println(x>0?1:(x == 0?0 :-1)); /* (x ? y : z)
x 为 boolean 类型表达式,先计算 x 的值,
若为true,则整个运算的结果为表达式 y 的值,
否则整个运算结果为表达式 z 的值。
*/
}
}