【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
大家好,我是[爱做梦的子浩](https://blog.csdn.net/weixin_43124279),我是东北大学大数据实验班大三的小菜鸡,非常向往优秀,羡慕优秀的人,已拿两个暑假offer,欢迎大家找我进行交流😂😂😂 这是我的博客地址:[子浩的博客https://blog.csdn.net/weixin_43124279] —— 版权声明:本文为CSDN博主「爱做梦的子浩」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
 
https://www.cnblogs.com/DreamingFishZIHao/p/12983007.html
posted @ 2021-07-11 13:23  a318013800  阅读(1443)  评论(0)    收藏  举报