Java Program to Convert boolean variables into String
What is a boolean Variable in Java ?
In Java, a boolean variable is a variable that can hold one of two possible values: true or false. Boolean variables are commonly used in control structures (such as if statements) to make decisions based on the value of the variable.
What is String in Java ?
- In Java, a string is an object that represents a sequence of characters. The String class in Java is used to create and manipulate strings. A string can be created by enclosing characters in double quotes, for example:
- Java strings are immutable, which means that once a string is created, its value cannot be changed. However, methods such as concatenation, substring, and replace can be used to create new strings with modified values. The String class also provides methods for comparing strings, searching for substrings, and more.
Ways to Convert boolean variables into String :
- Convert boolean to string using valueOf()
- Convert boolean to String using toString()
Example 1 : Convert boolean to string using valueOf()
public class Main { public static void main(String[] args) { boolean myBoolean = true; String myString = String.valueOf(myBoolean); System.out.println(myString); } }
Output :
true
Explanation :
In this example, a boolean variable myBoolean is declared and initialized to true. The String.valueOf(myBoolean) method is called and the boolean variable is passed as an argument. The method returns the string representation of the boolean value (i.e. "true") which is then assigned to the variable myString. The value of myString is then printed out using the System.out.println() method.
Example 2 : Convert boolean to String using toString()
public class Main { public static void main(String[] args) { boolean myBoolean = true; String booleanAsString = Boolean.toString(myBoolean); System.out.println(booleanAsString); // Output: "true" } }
Output :
true
Explanation :
In this example, we first define a boolean variable myBoolean and set it to true. Then, we use the toString() method from the Boolean class to convert myBoolean to a String. The toString() method takes a single boolean parameter and returns the corresponding String representation of the boolean value. In this case, the output will be "true".
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment