How to use String.valueOf() method in Java

The String.valueOf() method in Java transforms various forms of data into a string representation. It is an overloaded method that can handle multiple input types such as:

  • bool
  • char
  • char[]
  • int
  • long
  • float
  • double

Syntax

Here’s how you can use the String.valueOf() function:

String.valueOf(int i)

It takes one of the parameters from the list above and converts the given input into a string.

Code example

Following is a code example that uses all data types.

class string_coversion {
public static void main( String args[] ) {
int integer_num = 10;
char character = 'c';
char[] character_array= {'E', 'd', 'u', 'c', 'a', 't', 'i', 'v', 'e'};
float float_num = 10.986f;
double double_num = 10.987654623;
long long_num = 17237826381273L;
boolean condition = true;
System.out.println("After converting the data types values are:");
System.out.println("The integer value: " + String.valueOf(integer_num));
System.out.println("The character value: " + String.valueOf(character));
System.out.println("The character array value: " + String.valueOf(character_array));
System.out.println("The float value: " + String.valueOf(float_num));
System.out.println("The double value: " + String.valueOf(double_num));
System.out.println("The long value: " + String.valueOf(long_num));
System.out.println("The condition value: " + String.valueOf(condition));
}
}

Explanation

  • Line 3: It initializes an integer variable named integer_num with a value of 10.
  • Line 4: It initializes a character variable named character with the value ‘c’.
  • Line 5: It initializes a character array variable named character_array with the values ‘E’, ‘d’, ‘u’, ‘c’, ‘a’, ‘t’, ‘i’, ‘v’, ‘e’.
  • Line 6: It initializes a float variable named float_num with the value 10.986f. The ‘f’ suffix indicates that it is a float value.
  • Line 7: It initializes a double variable named double_num with the value ‘10.987654623’.
  • Line 8: It initializes a long variable named long_num with the value ‘17237826381273L’. The L suffix denotes a long value.
  • Line 9: It initializes a boolean variable named condition with the value true.
  • Lines 12–18: It converts the different variables into string using String.valueOf() method, and prints the result.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved