boolean Exercises

Declare a boolean

Create a boolean variable called isOnline and assign it the value true. Print its value.

Show answer:
boolean isOnline = true;
System.out.println(isOnline);

true or false

boolean hasAccess = false;
hasAccess = true;
System.out.println(hasAccess);

What will be printed?

Show answer:

true // the old value is replaced

Find and fix the error

boolean isReady = "true";
Show answer:
boolean isReady = true; // booleans don't take Strings

Primitive or wrapper

Which one is a primitive and which one is a wrapper class?

boolean a = true;
Boolean b = Boolean.FALSE;
Show answer:
boolean a = true;      // primitive
Boolean b = Boolean.FALSE; // wrapper class

Convert primitive to wrapper

Write code to convert this primitive boolean into a Boolean object:

boolean isLoggedIn = true;
Show answer:

boolean isLoggedIn = true;
Boolean obj = Boolean.valueOf(isLoggedIn);

Convert String to primitive boolean

Convert this to String to Boolean – String s = “TRUE”

Show answer:
String s = "TRUE";
boolean result = Boolean.parseBoolean(s);
System.out.println(result); // prints true

Convert Boolean to String

Convert this Boolean to String – Boolean b = true

Show answer:
boolean isAvailable = true;
String s = Boolean.toString(isAvailable); // returns "true"

Compare booleans

What is the result of this comparison?

System.out.println(Boolean.compare(true, true));
Show answer:
0; // equal values return 0

Compare wrapper objects

What is printed?

Boolean b1 = true;
Boolean b2 = false;

System.out.println(b1.compareTo(b2));
Show answer:
1 // returns 1 if the first value is greater than the second

Reasoning challenge

What will be printed?

String s = "yes";
boolean value = Boolean.parseBoolean(s);
System.out.println(value);
Show answer:
false; // any value other than "true" returns false

Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories