【JAVA】Java的boolean 和 int互相转换 ——Java的true、false和1、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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM