Java String valueOf()

You can convert different data types into a string by using the valueOf() method in Java. On this page, we are going to share some examples of this method.

Method signature:

The valueOf() is an overloaded method, which accepts different types of data types as an input and returns the string representation.

The signature for a valueOf() method is as shown below.

public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

Method parameters and return type:

Return type: It returns a string representation of a given value.

Parameters: It takes a variable or an array of specific data types as a parameter.

Throws: It throws a NullPointerException.

Example 1:

We have converted a double number into a string and then we have concatenated it with another string.

Source code:

public class Example1 {

    public static void main(String args[]) {
        double num = 5.2123;
        String str = String.valueOf(num);
        System.out.println(str + 21.1);
    }
}

Output:

run:
5.212321.1
BUILD SUCCESSFUL (total time: 1 second)

Example 2:

We have initialized an integer variable and a char variable. We have converted both and data types into a string and combined those string values.

Source code:

public class Example2 {
    
    public static void main(String[] args) {
        
        int num1= 44;
        char num2 = 'a';
        String str = String.valueOf(num1) + String.valueOf(num2);
        System.out.println(str);
    }
}

Output:

run:
44a
BUILD SUCCESSFUL (total time: 1 second)

Example 3:

Here we have converted boolean to string by using the valueOf() method.

Source code:

public class Example3 {

    public static void main(String[] args) {
        boolean value = false;
        String str = String.valueOf(value);
        System.out.println(value);
    }
}

Output:

run:
false
BUILD SUCCESSFUL (total time: 0 seconds)

References:

Leave A Comment