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);
		 System.out.println(str);
	}

}

class Data{
	private int id;
	public Data(int i) {
		this.id = i;
	}
	@Override
	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);
System.out.println(str1);

Output: abc

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


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

Output: bc

String.valueOf(boolean b)


boolean flag = true;
String str3 = String.valueOf(flag);
System.out.println(str3);

Output: true

String.valueOf(char c)


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

Output: A

String.valueOf(int i)


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

Output: 65

String.valueOf(long l)


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

Output: 12345

String.valueOf(float f)


float f = 123.45f;
String str7 = String.valueOf(f);
System.out.println(str7);

Output: 123.45

String.valueOf(double d)


double d = 123.45d;
String str8 = String.valueOf(d);
System.out.println(str8);

Output: 123.45

That’s all for String valueOf() example.

You can download the complete code from my GitHub Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages