大家好,又见面了,我是你们的朋友全栈君。
例如:
public static void main(String[] args) { BigDecimal bnum1, bnum2; bnum1 = new BigDecimal(“10”); bnum2 = new BigDecimal(“20”); int res = bnum1.compareTo(bnum2); String str1 = “两个数相等”; String str2 = “第一个数更大”; String str3 = “第二个数更大”; if( res == 0 ) System.out.println( str1 ); else if( res == 1 ) System.out.println( str2 ); else if( res == -1 ) System.out.println( str3 ); } }
运行代码,得到以下结果: 第二个数更大
为什么比较返回值是0,-1和1呢? 我们去看看源代码!
根据源码中的三元运算符
可以发现:
情况1. 如果xs等于ys,则返回0。
情况2. 如果xs不等于ys,则会执行另外一个三元运算符((xs > ys) ? 1 : -1)
这时候就会比较 xs 和 ys:
xs > ys 返回 1,
xs < ys 返回 -1。
因此得到结论!
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159883.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有