The valueOf()
method returns the string representation of the argument passed.
Example
class Main {
public static void main(String[] args) {
double interest = 923.234d;
// convert double to string
System.out.println(String.valueOf(interest));
}
}
// Output: 923.234
Syntax of valueOf()
The syntax of the String valueOf()
method for different data types is:
String.valueOf(boolean b)
String.valueOf(char c)
String.valueOf(char[] data)
String.valueOf(double d)
String.valueOf(float f)
String.valueOf(int b)
String.valueOf(long l)
String.valueOf(Object o)
Here, valueOf()
is a static method. We call the valueof()
method using the class name like this: String.valueOf(b);
valueOf() Parameters
The valueOf()
method takes a single parameter.
- data that is to be converted to a string
valueOf() Return Value
- returns the string representation of the argument passed
Example: Java String valueOf() for Numbers
class Main {
public static void main(String[] args) {
int a = 5;
long l = -2343834L;
float f = 23.4f;
double d = 923.234d;
// convert numbers to strings
System.out.println(String.valueOf(a)); // "5"
System.out.println(String.valueOf(l)); // "-2343834"
System.out.println(String.valueOf(f)); // "23.4"
System.out.println(String.valueOf(d)); // "923.234"
}
}
Example 2: Convert char and char array to String
In Java, you can also use the +
operator to concatenate two strings. For example,
class Main {
public static void main(String[] args) {
char c = 'J';
char ch[] = {'J', 'a', 'v', 'a'};
// convert char to string
System.out.println(String.valueOf(c)); // "J"
// convert char array to string
System.out.println(String.valueOf(ch)); // "Java"
}
}
Convert subarray of the char Array to String
You can also convert a subarray of a character array to string. For this, we use this syntax.
valueOf(char[] data, int offset, int length)
Here,
- data - the character array
- offset - initial offset of the subarray
- count - the length of the subarray
Example 3: Subarray of a char Array to String
class Main {
public static void main(String[] args) {
char ch[] = {'p', 'r', 'o', 'g', 'r', 'a', 'm'};
int offset = 2;
int length = 4;
String result;
// subarray {'o', 'g', 'r', 'm'} is converted to string
result = String.valueOf(ch, offset, length);
System.out.println(result); // "ogrm"
}
}
Example 4: Convert Object to String
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<String>();
languages.add("Java");
languages.add("Python");
languages.add("Kotlin");
String result;
// Output: "[Java, Python, Kotlin]"
result = String.valueOf(languages);
System.out.println(result);
}
}
Here, an ArrayList object, languages, is converted to a string.
In Java, there is another method named copyValueOf()
which is equivalent to the valueOf()
method.
Note: You can also use the object.toString()
method to convert an object to a string. To learn more, visit: Java Object toString() method.