JAVA将 boolean 转换为 int。将 int转换为boolean

引用

编程语言的true、false和1、0之间的相互转化
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
发布了113 篇原创文章 · 获赞 105 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43124279/article/details/105417044
今日推荐