Java Boolean toValue() Method
The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true else it returns false.
Syntax
- public static Boolean valueOf(String s)
- public static Boolean valueOf(boolean b)
Parameters
The parameters ‘b’ and‘s’ represents a Boolean and a String value.
Return Value
The valueOf() method returns a Boolean instance representing b or s.
Example 1
public class JavaBooleanValueOfMethodExample1 { public static void main(String[] args) { Boolean b1 = true; // will return a boolean instance corresponding to Boolean b1 Boolean b2 = Boolean.valueOf(b1); System.out.println("value returned = "+b2); Boolean b3 = Boolean.valueOf(false); System.out.println("value returned = "+b3); } }
Output
value returned = true value returned = false
Example 2
import java.util.Scanner; public class JavaBooleanValueOfMethodExample2 { public static void main(String[] args) { Boolean b1 = true; Scanner scanner = new Scanner(System.in); System.out.println("Enter two numbers: "); System.out.print("a = ");int a=scanner.nextInt(); System.out.print("b = ");int b=scanner.nextInt(); if(a<=0 || b<=0 || a==b){ b1=false; } Boolean b2=Boolean.valueOf(b1); if(b2){ a=b-a; b=b-a; a=a+b; System.out.println(" After swapping value : "); System.out.println("a : "+a); System.out.println("b : "+b); } else{ System.out.println("Number not in the range. Please try with different numbers."); } } }
Output
Enter two numbers: a = 0 b = -19 Number not in the range. Please try with different numbers.
Example 3
public class JavaBooleanValueOfMethodExample3{ public static void main(String[] args) { //return a boolean value representing the string String str1="true"; Boolean b1 =Boolean.valueOf(str1); System.out.println("Boolean value: "+b1); // for any value of str other than true it will return false String str2="abc"; Boolean b2 =Boolean.valueOf(str2); System.out.println("Boolean value: "+b2); } }
Output
Boolean value: true Boolean value: false
Example 4
public class JavaBooleanValueOfMethodExample4{ public static void main(String[] args) { //for null value it will return an exception Boolean b1=null; Boolean b2= Boolean.valueOf(b1); System.out.println(b2); } }
Output
Exception in thread "main" java.lang.NullPointerException at com.interf.JavaBooleanValueOfMethodExample4.main(JavaBooleanValueOfMethod Example4.java:8)