In Java, converting a boolean value to its equivalent String representation can be done using the Boolean.toString() method or by concatenating with an empty string. Let's explore both methods with examples.
1. Using Boolean.toString() Method
The Boolean.toString(boolean b) method is a simple and direct way to convert a boolean value to its String representation.
Example:
public class BooleanToStringExample {
public static void main(String[] args) {
boolean boolValue = true;
String stringValue = Boolean.toString(boolValue);
System.out.println("Boolean Value: " + boolValue);
System.out.println("String Value: " + stringValue);
}
}
Output:
Boolean Value: true
String Value: true
2. Concatenation with an Empty String
As with other primitive types, you can also convert a boolean to a String by concatenating it with an empty string.
Example:
public class BooleanToStringExample {
public static void main(String[] args) {
boolean boolValue = false;
String stringValue = "" + boolValue;
System.out.println("Boolean Value: " + boolValue);
System.out.println("String Value: " + stringValue);
}
}
Output:
Boolean Value: false
String Value: false
Conclusion
Converting a boolean to a String in Java is a straightforward task, and you have multiple methods available to do it. Whether you use Boolean.toString() or concatenation with an empty string, you will obtain a String representation of the original boolean value.
Related String Conversion Examples
- Java Convert Integer to String Example
- Java Convert Float to String Example
- Java Convert Double to String Example
- Java Convert Short to String Example
- Java Convert Long to String Example
- Java Convert Character to String Example
- Java Convert Byte to String Example
- Java Convert Boolean to String Example
- Java Convert String To Short Example
- Java Convert String To Long Example
- Java Convert String To Integer Example
- Java Convert String To Float Example
- Java Convert String To Double Example
- Java Convert String To Byte Example
- Java Convert String To Boolean Example
Comments
Post a Comment
Leave Comment