×
☰ See All Chapters

String.valueOf() method in Java

valueOf() method is a static method available in String class. valueOf() method takes one argument and returns the string representation of the argument. There are several overloaded static methods valueOf() methods each takes arguments of different types. Below is the list of available valueOf() methods.

  1. public static String valueOf(boolean b) 

  2. public static String valueOf(char c) 

  3. public static String valueOf(char[] data) 

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

  5. public static String valueOf(double d) 

  6. public static String valueOf(float f) 

  7. public static String valueOf(int i) 

  8. public static String valueOf(long l) 

  9. public static String valueOf(Object obj) 

String.valueOf()example

package com.java4coding;

 

class A {

        void meth() {

                System.out.println("Class A");

        }

}

 

public class Demo {

        public static void main(String args[]) {

                A a = new A();

                System.out.println(String.valueOf(a));

                StringBuffer s = new StringBuffer("Manu Manjunatha");

                String s1 = String.valueOf(s);

                System.out.println(s1);

                long l = 100L;

                System.out.println(String.valueOf(l));

        }

}

Output:

com.java4coding.A@3f3afe78

Manu Manjunatha

100

String.valueOf() vs. Object.toString()

String.valueOf()

Object.toString()

String.valueOf() returns string representation of value of any data type. Works with primitive data type too.

Object.toString() returns string representation of value of object type. Works with only objects cannot be used for primitive data type.

This is null safe.

String.valueOf(null) returns string “null”

This is not null safe.

Object.toString(), here if Object is null (null.toString()) gives NullPointerException.

 


All Chapters
Author