从头认识java-2.4 逻辑运算符
2015-10-26 00:00
423 查看
这一章节我们来讨论一些逻辑运算符。
逻辑运算符:||、&&、!
注意点:
(1)使用逻辑运算符,其实就是运算符两侧的表达式先算出布尔值,然后再进行比较
输出:
false
test1
test2
false
上面的代码我给出两个等价的代码,这样大家会更加清楚中间的执行过程。
从输出结果可以看出,运算符两侧的表达式先运算,然后再计算两个布尔值的对比。
(2)短路现象。
我们把上面的代码改一下,把b和c 的值对换。
输出:
false
test1
false
从输出看到,test2没有被执行,因为test1返回false,那么注定了整个表达式test1&&test2返回肯定是false,无论test2执行与否,这个时候jvm进行优化,test2不再执行。
总结:这一章节我们主要讲述了逻辑运算符的注意点。
这一章节就到这里,谢谢。
-----------------------------------
目录
版权声明:本文为博主原创文章,未经博主允许不得转载。
逻辑运算符:||、&&、!
注意点:
(1)使用逻辑运算符,其实就是运算符两侧的表达式先算出布尔值,然后再进行比较
package com.ray.ch01; public class Test { public static void main(String[] args) { int b = 3, c = 2; System.out.println((b > c) && (c > b)); System.out.println(test1(b, c) && test2(b, c)); } private static boolean test1(int b, int c) { System.out.println("test1"); return b > c; } private static boolean test2(int b, int c) { System.out.println("test2"); return b < c; } }
输出:
false
test1
test2
false
上面的代码我给出两个等价的代码,这样大家会更加清楚中间的执行过程。
从输出结果可以看出,运算符两侧的表达式先运算,然后再计算两个布尔值的对比。
(2)短路现象。
我们把上面的代码改一下,把b和c 的值对换。
package com.ray.ch01; public class Test { public static void main(String[] args) { int b = 2, c = 3; System.out.println((b > c) && (c > b)); System.out.println(test1(b, c) && test2(b, c)); } private static boolean test1(int b, int c) { System.out.println("test1"); return b > c; } private static boolean test2(int b, int c) { System.out.println("test2"); return b < c; } }
输出:
false
test1
false
从输出看到,test2没有被执行,因为test1返回false,那么注定了整个表达式test1&&test2返回肯定是false,无论test2执行与否,这个时候jvm进行优化,test2不再执行。
总结:这一章节我们主要讲述了逻辑运算符的注意点。
这一章节就到这里,谢谢。
-----------------------------------
目录
版权声明:本文为博主原创文章,未经博主允许不得转载。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统