Boolean In Java

In the first sample in TryBoolean.java, you will learn how to define a boolean variable and how to set its value.

Save following content in a .java file called TryBoolean.java that is equivalent to your class name TryBoolean.

public class TryBoolean {
   public static void main(String[] args) {
      boolean tryMe1 = false;
      System.out.print("tryMe1 value: ");
      System.out.println(tryMe1);
      boolean tryMe2 = true;
      System.out.print("tryMe2 value: ");
      System.out.println(tryMe2);
   }
 }

Using javac command compile your .java file

$ javac TryBoolean.java

And using java command run it. You will see two printed phrases there which shows two values for two boolean variables tryMe1 and tryMe2. The value of tryMe1 is false and the value of tryMe2 is true.

$ java TryBoolean
tryMe1 value: false
tryMe2 value: true

After defining your class in the above sample with public class TryBoolean, like all other executable java classes you can find main method.
In the first line of main() function block, I defined a boolean variable simply by having boolean type at the beginning of the line. The variable name tryMe1 comes right after that. You can assign your variable value using equal sign =. I set tryMe1 to false.

boolean tryMe1 = false;

In the next lines I printed a prompt before printing the value of tryMe1 in the console using System.out.print and I printed the value of tryMe1 which is false using System.out.println that move the cursor to the line after as well. Click here to learn more about printing in console.

System.out.print("tryMe1 value: ");
System.out.println(tryMe1);

As you see in the next three lines, I tried to declare a variable called tryMe2 and I set its value to true.

boolean tryMe2 = true;
System.out.print("tryMe2 value: ");
System.out.println(tryMe2);

Leave a Reply