目录

  • 引用
  • true、false和1、0转化原理
  • 一、Boolean转化为数字——false为 0,true为 1
  • 二、数字转化为Boolean——0 为 false; 非 0 为true
    • 方法一:
    • 方法二:三目语句

引用

其他文章:
【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之间的相互转化