The + operator is overloaded to concatenate strings. When + is used with one String operand and one non-String operand, the non-String operand will be sent the toString() message:
Integer i = new Integer(7); System.out.println("i = " + i); System.out.println(2 + 3 + " = 1 + 4."); System.out.println("Other numbers are " + 5 + " and " + 2.1);
What's tricky about the last two lines in the above code snippet? (They're tricky in different ways.)
First: Addition is left-associative, so in the next-to-last line, 2 + 3 gets evaluated first. So the overloaded operator + is resolved to the addition operation on integers, not the concatenation operation on strings.
Second: You can't send messages to primitive types! So, you can't just say 5.toString(). Therefore, when you try to concatenate a string with a value of primitive type, Java will implicitly create a new instance of the appropriate wrapper classes so that it can send the toString() message to it. So the last line above translates to:
System.out.println("Other numbers are " + new Integer(5).toString() + " and " + new Float(2.1));
Arrays are a special kind of object with syntactic support (and weird typechecking rules, but let's leave that till next week). Arrays of both primitives and objects are supported:
int[] intArr = new int[10]; Foo[] fooArr = new Foo[10]; for (int i = 0; i < fooArr.length; i++) fooArr[i] = new Foo();
The important thing to remember is that, despite the syntax, Java arrays don't actually behave that much like C arrays: