[Python-Dev] Unicode experience

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Fri, 7 Jul 2000 22:53:37 +0200


> Really?  Does 3+"" really convert the 3 to a string in Java?

Yes. It is one of my favorite Java features...

If a binary + has one argument of type java.lang.String, then the
other object is coerced to string as well (unless the other operand is
also a string), using the following procedure:

If it is a primitive type, an instance of the appopriate helper is
created, in this case java.lang.Integer, so we only have
java.lang.Object specializations now (*).

Then, .toString() is invoked for the object, and the strings are
concatenated.

This allows to write things like

  System.out.println("Name:"+name" Age:"+age);

so they did not have to copy the printf(3C) family of function, nor to
introduce operator overloading for iostream-style output.

Teaching this stuff to students, it turns out that there are two major
sources of confusion:

a) System.out.println("abc"+3+3) prints "abc33", whereas
   System.out.println(3+3+"abc") prints "6abc", so the binary +
   is not commutative.

b) Both System.out.println("result "+myobj) and
   System.out.println(myobj) work, but for different reasons. In the
   first case, it works because of the magic binary '+'. In the second
   case, it works because println is overloaded for all types, i.e.
    println(int);
    println(double);
    ...
    println(Object); // invokes println(o.toString());
    println(String); // does the real work

Regards,
Martin

(*) Implementations don't have to create those temporaries; the usual
as-if rule applies.