AlphaCodingSkills

Java - Booleans


Advertisements

Previous Page Next Page

There are many instances in the programming, where a user need a data type which represents True and False values. For this, Java has a boolean data type, which takes either True or False values.

Boolean Values

A boolean variable is declared with boolean keyword and can only take boolean values: True or False values. In the below example, a boolean variable called MyBoolVal is declared to accept only boolean values.

public class MyClass {
  public static void main(String[] args) {
  boolean MyBoolVal = true;
  System.out.println(MyBoolVal); 

  MyBoolVal = false;
  System.out.println(MyBoolVal);   
}
}

Output

true

false

Boolean Expressions

A boolean expression in Java is an expression which returns boolean values: True or False values. In the below example, comparison operator is used in the boolean expression which returns true when left operand is greater than right operand else returns false.

public class MyClass {
  public static void main(String[] args) {
  int x = 10;
  int y = 25;
  System.out.println(x > y); 
}
}

Output

false

A logical operator can be used to combine two or more conditions to make complex boolean expression like && operator is used to combine conditions which returns true if all conditions are true else returns false. Please see the below example.

public class MyClass {
  public static void main(String[] args) {
  int x = 10;
  System.out.println(x > 0 && x < 25); 
}
}

Output

true

Previous Page Next Page