Java String valueOf() Examples

Filed Under: Java

Java String valueOf() method is used to create the String representation from different types of inputs.

String valueOf() method is overloaded and accept following types of arguments:

  1. int
  2. long
  3. float
  4. double
  5. char
  6. char array
  7. boolean
  8. Object

Java String valueOf() Method Signature

Below image shows the valueOf() overloaded methods, they all are public and static and returns String.

Java String valueOf examples

If we pass null argument, then it will throw NullPointerException.

Java String valueOf() Examples

Let’s look at some code snippets for String valueOf() methods usage.

String.valueOf(Object obj)

public class JavaStringValueOfExamples {

	public static void main(String[] args) {
		 Data obj = new Data(10);
		 String str = String.valueOf(obj);


class Data{
	private int id;
	public Data(int i) { = i;
	public String toString() {
		return "Data{id:"+id+"}";

Output: Data{id:10}

Note that toString() method is used to create the String representation of the Object.

String.valueOf(char[] data)

char[] chars = {'a', 'b', 'c'};
String str1 = String.valueOf(chars);

Output: abc

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

char[] chars = {'a', 'b', 'c'};
String str2 = String.valueOf(chars,1,2);

Output: bc

String.valueOf(boolean b)

boolean flag = true;
String str3 = String.valueOf(flag);

Output: true

String.valueOf(char c)

char c = 65; // same as char c = 'A'
String str4 = String.valueOf(c);

Output: A

String.valueOf(int i)

int i = 'A'; // same as int i = 65
String str5 = String.valueOf(i);

Output: 65

String.valueOf(long l)

long l = 12345L;
String str6 = String.valueOf(l);

Output: 12345

String.valueOf(float f)

float f = 123.45f;
String str7 = String.valueOf(f);

Output: 123.45

String.valueOf(double d)

double d = 123.45d;
String str8 = String.valueOf(d);

Output: 123.45

That’s all for String valueOf() example.

You can download the complete code from my GitHub Repository.
Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors