What is the BooleanUtils.toStringOnOff() method in Java?
The toStringOnOff static method of the BooleanUtils class in Java converts a boolean to either string on or string off.
Import BooleanUtils
BooleanUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
Syntax
The prototype of the toStringOnOff() method is as follows:
public static String toStringOnOff(Boolean bool);
Parameters
The toStringOnOff() method takes a Boolean object as a parameter.
Return value
This method returns one of the following:
"on": If the argument isBoolean.TRUE"off": If the argument isBoolean.FALSEnull: If the argument isnull
The illustration below shows the possible return cases:
BooleanUtils.toStringOnOff
Case | Result |
BooleanUtils.toStringOnOff(Boolean.TRUE) | "on" |
BooleanUtils.toStringOnOff(Boolean.FALSE) | "off" |
BooleanUtils.toStringOnOff(null) | null |
Code
The code below shows how to use the toStringOnOff() method:
import org.apache.commons.lang3.BooleanUtils;class ToStringOnOffExample {public static void main( String args[] ) {System.out.println("BooleanUtils.toStringOnOff(Boolean.TRUE) => " + BooleanUtils.toStringOnOff(Boolean.TRUE)); // "on"System.out.println("BooleanUtils.toStringOnOff(Boolean.FALSE) => " + BooleanUtils.toStringOnOff(Boolean.FALSE)); // "off"System.out.println("BooleanUtils.toStringOnOff(null) => " + BooleanUtils.toStringOnOff(null)); // null}}
Explanation
In the code above:
- Line 1: We import the
BooleanUtilsclass.
import org.apache.commons.lang3.BooleanUtils;
-
Lines 5 to 8: We use the
toStringOnOff()method to get the “on” or “off” string based on the passed argument. -
Below is the output.
BooleanUtils.toStringOnOff(Boolean.TRUE); // "on"
BooleanUtils.toStringOnOff(Boolean.FALSE); //"off"
BooleanUtils.toStringOnOff(null); //null