Java String valueOf() Method (original) (raw)

Last Updated : 02 Dec, 2024

The **valueOf()**method of the String class in Java helps to convert various data types like integers, floats, booleans, and objects into their string representations. It makes it simple to work with string manipulation, logging, and displaying data efficiently.

**Example:

To **convert a number into text for easy display or use in-text operations, we can use the **valueOf() method.

Java `

// Java program to demonstrate // working of valueOf() method public class ValueOf {

public static void main(String[] args) {
  
    int n = 21;     // Declare an integer
    String s = String.valueOf(n);       // Convert integer to string
    System.out.println("String representation: " + s); 
}

}

`

Output

String representation: 21

**Explanation: The number 21 is converted to the string "21" for easier use in text-related tasks.

Table of Content

**Syntax of valueOf() Method

The syntax of **valueOf() method for different kind of inputs are:

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(boolean b)

public static String valueOf(char c)

public static String valueOf(char[] data)

public static String valueOf(char[] data, int offset, int count)

public static String valueOf(Object obj)

**Return Type: It returns a String that represents the input data. If the input is null, it returns the text "null".

Other Examples of String valueOf() Method

1. Convert Boolean to String Using valueOf()

**Example:

Java `

public class ValueOf {

public static void main(String[] args) {
  
    boolean b = true;      // Boolean variable
    String s = String.valueOf(b);      // Convert boolean to string
    System.out.println("" + s); 
}

}

`

**Explanation: In the above example, the boolean true becomes the string "true" for display or text use.

2. Convert Object to String Using valueOf()

**Example:

Java `

public class ValueOf {

public static void main(String[] args) {
  
    Object o = null;      // Null object
    String s = String.valueOf(o);      // Convert object to string
    System.out.println("" + s); 
}

}

`

**Explanation: In the above example, the method converts the null object into the text "null" without errors.

3. Convert Part of a Char Array to String Using valueOf()

**Example:

Java `

public class ValueOf {

public static void main(String[] args) {
  
    // Character array
    char[] ch = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' };  
    String s = String.valueOf(ch, 0, 5);      // Convert first 5 characters to string
    System.out.println("" + s); 
}

}

`

**Explanation: In the above example, the first five characters ('H', 'e', 'l', 'l', 'o') are converted into the string "Hello".