文档首页> 常见问题> java中boolean怎么用

java中boolean怎么用

发布时间:2023-11-20 02:30       

在Java中,boolean是一种基本数据类型,它只有两个可能的值:true和false。boolean类型经常用于条件测试,比如进行比较或者检查某个条件是否满足。

下面是一些示例,展示了如何在Java中使用boolean类型:

声明boolean变量:

boolean isTrue;

赋值为true或false:

isTrue = true;

或者

isTrue = false;

在if语句中使用boolean表达式:

if (isTrue) {  
    System.out.println("The statement is true.");  
} else {  
    System.out.println("The statement is false.");  
}

在while语句中使用boolean表达式:

boolean running = true;  
while (running) {  
    // do something  
    if (someCondition) {  
        running = false;  
    }  
}

布尔逻辑操作(&&、||、!):

boolean a = true;  
boolean b = false;  
  
// 使用&& (AND) 操作符  
if (a && b) {  
    System.out.println("Both a and b are true.");  
} else {  
    System.out.println("At least one of a or b is false.");  
}  
  
// 使用|| (OR) 操作符  
if (a || b) {  
    System.out.println("At least one of a or b is true.");  
} else {  
    System.out.println("Both a and b are false.");  
}  
  
// 使用! (NOT) 操作符  
if (!a) {  
    System.out.println("a is false.");  
} else {  
    System.out.println("a is true.");  
}