【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