Why forcing a null string to a string "null"

When reading this question, I recalled a bug in a program that I wrote when I first studied Java, which made me permanently find and essentially reduce the following behavior:

String s1 = "This was a triumph";
String n1 = null;
System.out.println(s1 + n); // prints "This was a triumphnull"

Some other noteworthy examples (and perplexing counter examples) of similar behavior:

// "nullThis was a triumph", coercion happens commutatively
System.out.println(n1 + s1);

// as per above question, println explicitly converts null Strings to "null"
System.out.println(n1);

// similar result
System.out.println(String.valueOf(n1));

// NullPointerException (!!); null not silently converted to "null"
// note that this is the kind of thing I expected to occur for the other examples
// when I wrote the buggy code in the first place
System.out.println(n1.toString());

Although I assume that I technically understand this behavior, I definitely do not understand it, so my question is:

  • From a language design perspective, why does java convert a null string to a null string in many cases?
  • Why doesn't he do this in cases where ... it is not?

EDIT

, , , null -, . :

Integer i1 = 42;
Integer n2 = null;
// Both produce NullPointerExceptions:
Integer.valueOf(n2);
System.out.println(i1 + n2);

, NullPointerException - , , / "" .

+4
2

. null ; . null NullPointerException. , , 3.toString(), , .

, , null "null" , . , null; , , x == null? "null" : x.toString(). , System.out.println(3), 3.toString() .


autoboxing, , .

( 7 -) , int, Integer.valueOf . Integer.valueOf ; "null" null , 0 .

+3

1. , , String StringBuffer JDK1.0 (. http://docs.oracle.com/javase/6/docs/api/java/lang/String.html ..), 21 1996 - +. J2SE 5.0 ( 30 2004 .), JDK 1.5, StringBuilder ( , - + StringBuffer), ( ) , . (., , https://codegolf.stackexchange.com/questions/28786/write-a-program-that-makes-2-2-5 - Java- Integer / )

String.java

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

Objects.java

public static String toString(Object o) {
    return String.valueOf(o);
}

PrintStream.java

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
} 

StringBuilder.java

public StringBuilder append(Object obj) {
    return append(String.valueOf(obj));
}

... (Java src.zip, JDK v8)

Java, toString, (.. String.valueOf(), "null" String). , concat + , ( StringBuilder.append(Object o)).

2. #toString() - NPEx, .

3. (, , 3) , , .

System.out.println( ((String)null).toString() );

(, ),

System.out.println( ((String)null).valueOf((String)null).toString() ); // works?! why!?

:

.

+2

Source: https://habr.com/ru/post/1547280/


All Articles