Java convert boolean to string: In the previous article we have discussed Java Program to Convert Object to String
In this article we will see how to convert a Boolean to string.
Program to Convert Boolean to String
Before going into the actual program, let’s see the examples of both the types.
Example-1: Boolean type boolean a = true; boolean b = false;
Example-2: String type String a = "BtechGeeks"; String b = "B";
Let’s see different ways to do it.
Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.
Method 1 : Java Program to Convert Boolean to String Using valueOf() method
Boolean can be converted to string by using valueOf()
, let’s see how it works.
String.valueOf()
is a method which will simply typecast below-given parameter to strings always. It is an inbuilt method of String class in java.
Approach :
- Take a Boolean value and store it in a
boolean
variableinput1
- Then pass that
input1
variable as parameter toString.valueOf( )
method which will convert the Boolean to string value and return it . - Store that string value in a variable output.
- Display the result.
Program :
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a boolean through scanner class System.out.println("Enter a Boolean Value : "); boolean input1=sc.nextBoolean(); // converting to string String output = String.valueOf(input1); System.out.println("Converted String is : "+output); } }
Output : Enter a Boolean Value : true Converted String is : true
Method 2 : Java Program to Convert Boolean to String Using toString() method
Boolean can be converted to string by using toString()
, let’s see how it actually works..
Approach :
- Take a Boolean value and store it in a boolean variable
input1
. - Then pass that input1 variable as parameter to
Boolean.toString( )
method which will convert the Boolean to string value and return it . - Store that string value in a variable
output
. - Display the result .
Program :
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a boolean value through scanner class System.out.print ("Enter a Boolean Value : "); boolean input1=sc.nextBoolean(); // converting to string String output = Boolean.toString(input1); System.out.println("Converted String is : "+output); } }
Output : Enter a Boolean Value : false Converted String is : false
Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output
Related Java Program: