How to Use Boolean in Java
- 1). Create a boolean variable in your Java project. Use the following code to create a primitive type boolean and assign it a value:
boolean isTooSmall = false;
Boolean values can only be either true or false; no other value is possible. Always name your boolean variables with meaningful names as in the example, which could be used to determine whether another value or variable falls within some required range. - 2). Assign the result of a test to your variable. Use the following sample code to carry out a test on another variable, assigning a value to the boolean variable depending on the result of this test:
String someText = "Here is a bit of text";
if(someText.length()<40) isTooSmall = true;
System.out.println("Too Small? " + isTooSmall);
This example simply tests whether the String length is less than 40 characters, assigning a true value to the boolean variable if it is. Save your file, compile and run your program to test it. You should see a message written to the standard output console indicating whether the String is "too small" or not. - 3). Return a boolean result from a method. Java methods often return boolean values. Use the following sample code to create a new method in your program:
public boolean isBelowMinimum(String testText) {
if(testText.length()<40) return true;
else return false;
}
The passed String is tested and a boolean result returned. In this case a boolean value is returned, however it would also be possible to provide the same functionality using a variable as follows:
public boolean isBelowMinimum(String testText) {
boolean tooSmall = false;
if(testText.length()<40) tooSmall = true;
return tooSmall;
} - 4). Call the boolean method in your program. Elsewhere in your code, you can call the "isBelowMinimum" method as follows after the line in which you created your String and boolean "isTooSmall" variable:
isTooSmall = isBelowMinimum(someText);
System.out.println("Too Small? " + isTooSmall);
Test the code using both possible implementations of the "isBelowMinimum" method and experiment by changing the String and number values. - 5). Use Boolean objects in your class. You can optionally use the Boolean class Java provides instead of using primitive types and values. The corresponding method implementation could be:
public Boolean isBelowMinimum(String testText) {
Boolean tooSmall = Boolean.valueOf(false);
if(testText.length()<40) tooSmall = Boolean.valueOf(true);
return tooSmall;
}
The function call could be amended as follows:
Boolean isTooSmall = isBelowMinimum(someText);
System.out.println("Too Small? " + isTooSmall.booleanValue());