06 - 算术、逻辑、位运算符以及优先级
2017-09-24 本文已影响43人
flowerflower
由于这些跟我们小时候学的加减乘除基本上一致,在这里主要说一下自增或自减,在这里主要谈论一下自增问题,自减同理而得知。
1.算术运算符
image.png- Demo1
public class TypeConvert {
public static void main(String[] args){
// System.out.println(100/0); //报错:ArithmeticException: / by zero
// System.out.println(100.0/0); //Infinity 正无穷大
// System.out.println(0.0/0.0); //NaN 不是一个实数
/**
* ++前置情况:
* ++a: 表示a变量自身先加1,再运算
*
* ++后置情况
* a++:表示a变量自身先加1,把递增1之前的原始值拿去做运算
*
* */
int a1 = 5;
int b1 = ++ a1;
System.out.println("a1 = " + a1+" " + "b1 = "+b1); //a1 = 6 b1 = 6
System.out.println("=======================");
int a2 = 5;
int b2 = a2 ++;
System.out.println("a2 = " + a2+" " + "b2 = "+b2); //a2 = 6 b2 = 5
System.out.println("=======================");
int i = 10;
i++;
System.out.println("i = " + i); //11
++i;
System.out.println("i = " + i); //12
int x = ++i;
System.out.println("i = " + i); //13
System.out.println("x = " + x); //13
int y = i++;
System.out.println("i = " + i); //14
System.out.println("y = " + y); //13
int m = 50;
int n = 30;
//两数求最大值/最小值
int max = m>=n?m:n;
System.out.println(max); //50
//判断是奇数还是偶数
int number = 10;
String result = number % 2 == 0 ?"偶数":"奇数";
System.out.println(result); //偶数
}
}
image.png
- Demo2:一共请求totalCount条数据,要求每一页最多10条数据
public class TypeConvert1 {
public static void main(String[] args){
int totalCount = 65;
int pageSize = 10; //每一页最多10条数据
//总页数
int totalPage = totalCount % pageSize ==0 ? totalCount/pageSize:totalCount/pageSize+1;
System.out.println(totalPage); //7
int currentPage = 2;
//上一页
int prevPage = currentPage -1>=1?currentPage-1:1;
System.out.println(prevPage); //7
}
}
2.逻辑运算符
image.pngpublic class logicOperation {
public static void main(String[] args) {
System.out.println("=======================");
/**
* &和&&的区别:
* &(位与):如果A表达式是false,也会判断B表达式,再返回false
* &&(短路与):如果A表达式是false,则不再判断B表达式,直接返回false
* 效率:短路与效率高
*
* 或同理
* |和||的区别:
* |(或):如果A表达式为true,也会执行B表达式,无论B表达式结果为什么,都会返回true
* ||(短路或):只要A表达式为true,立刻返回true,不再执行B表达式
* */
System.out.println(true & true); //true
System.out.println(true & false);//false
System.out.println(false & true); //false
System.out.println(false & false);//false
System.out.println("=======================");
System.out.println(true && true);//true
System.out.println(true && false);//false
System.out.println(false && true);//false
System.out.println(false && false);//false
}
}
3.运算符的操作优先级
image.png4.Demo:交换2个变量的值
- 方式一:利用第三方变量
int a = 10;
int b = 20;
int temp = a; //把a的值赋给临时变量temp
a = b;//把b的值存储到a中
b = temp;
System.out.println("a = "+a +" "+"b = "+b); //a = 20 b = 10
- 方式二:不利用第三方变量
int a = 10;
int b = 20;
a = b+a;// 30
b = a -b; //30 -20
a = a -b; // 30 - 10
System.out.println("a = "+a +" "+"b = "+b);//a = 20 b = 10