[Bluej-discuss] concatenating an index value with a note ex 4.15
Michael Kölling
M.Kolling at kent.ac.uk
Thu Oct 5 10:13:25 BST 2006
On 4 Oct 2006, at 19:51, Sheryl wrote:
> Colleen
>
> I already tried that which didn't compile ie System.out.println
> (index + notes.get(index));
> It says that you can't use the + operator in this situation.
>
> However, when I added the string for the colon to make it display
> like the example in the book, it compiled. why is this?
Having any String in the expression with the plus sign changes
everything.
Your original expression was
index + notes.get(index)
The types if this are
int + Object
There is no 'plus' operation defined that takes an int and an Object
as an operand, so this does not work. BUT: Java defines a 'plus
operator with anything and a String. So if you write
int + String
or
String + Object
It all will work, since Java has a rule that says: If any of the
operands of a + operator is a String, then the other operand will be
converted to a String, and the '+' will be interpreted as String
concatenation.
Thus, once you write
index + ":" + notes.get(index)
All is fine. Java will evaluate this left to right, so first it looks at
index + ":"
which will result in something like "1:" (a String), and then it
evaluates
"1:" + notes.get(index)
which is fine again because the first operand is now a String.
Regards,
Michael
More information about the bluej-discuss
mailing list