What is the difference between using Object.toString() and String.valueOf()?

Asked

Viewed 5,013 times

20

I was doing some tests and I realized that using one or the other, the result turns out to be the same. I made this code to exemplify:

public class ParseToStringTest {

    public static void main(String[] args) {
        new ParseToStringTest().parseTest();
    }

    public void parseTest() {

        SomeObj o = new SomeObj();
        System.out.println(o.toString());
        System.out.println(String.valueOf(o));

    }

    class SomeObj {}
}

Rotating in the ideone, the result I got was:

Ideone$SomeObj@677327b6
Ideone$SomeObj@677327b6

That is, the result was identical.

There would be some difference between using String#valueOf() or Object#toString() to display a String-shaped object representation?

  • https://books.google.com/books?id=CsGtipt1wsQC&pg=PA330&lpg=PA330&dq=diferen%C3%A7a+entre+usar+Object.toString()+e+String.valueOf()? &source=bl&ots=ow7LMsxLf7&Sig=puZzLbqAuaKAguO3dzstM0dZGY&hl=en-Br&sa=X&ved=0ahUKEwjX_IGxrZXUAhVKOZAKHWFXA38Q6AEITTAG#v=onepage&q=difference%C3%A7a%20entre%20usar%20Object.toString()%20e%20String.valueOf()%3F&f=false

  • 2

    The .toString() NPE spear, String.valueOf() nay

  • 1

    Also the String.valueOf() check for nulls, so it may have some overhead in the application

3 answers

17

Oracle documentation

if the argument is null, then a string Equal to "null"; otherwise, the value of obj.toString() is returned.

Translation:

If the argument is null, then we have a string equal to "null"; Case otherwise, the value of obj.toString() is returned.

Translated into code would:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

In the case of a Object#toString, if the instance is null one Nullpointerexception will be released. There should be no difference except for an additional method invocation, ie are practically the same thing.

  • 1

    One is NPE proof, the other is not: https://answall.com/questions/208388/qual-a-diff%C3%a7a-between-use-Object-tostring-e-string-valueof#comment426202_208388

  • 1

    @Jeffersonquesado you say Nullpointer? Think you should add?

  • 1

    Mania: NullPointerException alias NPE by initials. I think you should put this in the difference between the two ways of transforming object into string

  • 1

    After all, being protected against exception I believe is a real difference

13

Almost none. There is an additional indirect String.valueOf, which is checking whether the parameter is null or not.

Paraphrasing the documentation of String.valueOf:

The method will check whether the object is null and, if it is, is returned to string "null", otherwise the call will be made from .toString() of the object.

In code, the valueOf is, basically:

public static String valueOf(Object obj) {
    return obj == null ? "null" : obj.toString();
}

There are still classes that implement a version static of toString() (as the Integer or Arrays, for example), this primarily serves to enable these classes to work on an alternative version of the object representation such as string, allowing additional parameters or a custom implementation independent of .toString() original.

This is very clear in class Integer, where there is a Overload that it is possible to define which basis the number will be shown.

Integer number = 15;

System.out.println(Integer.toString(number, 10)); // 15   (decimal, base 10)
System.out.println(Integer.toString(number, 2));  // 1111 (binário, base 2)
System.out.println(Integer.toString(number, 16)); // f    (hexadecimal, base 16)

See this example working on repl.it.

So, it’s best to use String.valueOf when the object may be null, in other cases, the .toString().

12


In the documentation says that "if the argument is null is returned null, otherwise the value returns .toString". According to this tragic, the String.valueOf(Object) prints null as long as the Object.toString() can generate a Nullpointerexception.

Another important detail is that the valueOf is a static method, already the toString is an instance method and can only be called in a reference type. However, the valueOf perhaps, I say perhaps, be more flexible in relation to toString(). See the basic types of static method valueOf, which may be invoked:

String   valueOf(boolean b) 
String   valueOf(char c) 
String   valueOf(char[] data) 
String   valueOf(char[] data, int offset, int count) 
String   valueOf(double d) 
String   valueOf(float f) 
String   valueOf(int i) 
String   valueOf(long l) 
String   valueOf(Object obj) 

As regards the toString(), you will always need to call your specific class. See an example:

Integer.toString(int i)   // inteiros
Float.toString(float f);  // flutuantes

See these examples:

Example 1:

public String doIt(float number) {

  return String.valueOf(number);
}

Example 2:

public String doIt(float number) {

  return Float.toString(number);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.