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

后端 未结 10 767
挽巷
挽巷 2020-12-12 10:21

In Java, is there any difference between String.valueOf(Object) and Object.toString()? Is there a specific code convention for these?

10条回答
  •  我在风中等你
    2020-12-12 10:42

    The below shows the implementation for java.lang.String.valueOf as described in the source for jdk8u25. So as per my comment, there's no difference. It calls "Object.toString". For primitive types, it wraps it in its object form and calls "toString" on it.

    See below:

    /*
     * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
     * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     */
    
    
        public static String valueOf(Object obj) {
            return (obj == null) ? "null" : obj.toString();
        }
    
        public static String valueOf(char data[]) {
            return new String(data);
        }
    
        public static String valueOf(char data[], int offset, int count) {
            return new String(data, offset, count);
        }
    
        public static String copyValueOf(char data[], int offset, int count) {
            return new String(data, offset, count);
        }
    
        public static String copyValueOf(char data[]) {
            return new String(data);
        }
    
        public static String valueOf(boolean b) {
            return b ? "true" : "false";
        }
    
        public static String valueOf(char c) {
            char data[] = {c};
            return new String(data, true);
        }
    
        public static String valueOf(int i) {
            return Integer.toString(i);
        }
    
        public static String valueOf(long l) {
            return Long.toString(l);
        }
    
        public static String valueOf(float f) {
            return Float.toString(f);
        }
    
        public static String valueOf(double d) {
            return Double.toString(d);
        }
    

提交回复
热议问题