Java String valueOf()

The valueOf() method returns the string representation of the argument passed.

Example


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


Example 2: Convert char and char array to String

In Java, you can also use the + operator to concatenate two strings. For example,


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


Example 4: Convert Object to String

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.