首页 > 编程语言 > 详细

【JAVA】Java的boolean 和 int互相转换 ——Java的true、false和1、0之间的相互转化

时间:2021-07-11 14:12:38      阅读:20      评论:0      收藏:0      [点我收藏+]

引用

其他文章:
【C++演示】编程语言的true、false和1、0之间的相互转化
【C++】C++ true和false代码演示

true、false和1、0转化原理

Boolean转化为数字
false为 0,true为 1
数字转化为Boolean
0 为 false; 非 0 为true

java本身不支持直接强转

一、Boolean转化为数字——false为 0,true为 1

唯一方法:三目语句

 int myInt = myBoolean ? 1 : 0;

示例代码:

 boolean myBoolean = true;
 int myInt = myBoolean ? 1 : 0;
 System.out.println(myInt); //输出1
 myBoolean = false;
 myInt = myBoolean ? 1 : 0;
 System.out.println(myInt);  //输出0

二、数字转化为Boolean——0 为 false; 非 0 为true

方法一:

 boolean myBoolean = myInt != 0;

示例代码:

 int myInt= 2;
 boolean myBoolean = myInt!= 0;
 System.out.println(myBoolean); //输出为true
 myInt= 0;
 myBoolean = myInt!= 0;
 System.out.println(myBoolean); //输出为false

方法二:三目语句

 int a = 1; //带转化int整数
 boolean result = (a==0)?false:true; //转化语句

示例代码:

 int myInt = 2; //被转化int整数
 boolean myBoolean = (myInt == 0) ? false : true; //转化语句
 System.out.println(myBoolean); //输出为true
 myInt = 0; //被转化int整数
 myBoolean = (myInt == 0) ? false : true; //转化语句
 System.out.println(myBoolean); //输出为true

【JAVA】Java的boolean 和 int互相转换 ——Java的true、false和1、0之间的相互转化

原文:https://www.cnblogs.com/pengmn/p/14998436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!