[Bluej-discuss] concatenating an index value with a note ex 4.15

Ian Barland ibarland at radford.edu
Thu Oct 5 02:45:05 BST 2006


Hi Sheryl --

> 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?
> 
This is Java being so helpful it¹s become confusing.  (It¹s nothing about
BlueJ.)

When Java sees ³+², it checks:
* Are there numbers on each side of the ³+²?  If so, do addition.
* Are there strings on each side of the ³+²?  If so, do
string-concatenation.
* If there is a string on one side of the ³+² and something else on the
other side, then be helpful and automatically convert that something-else
into a String (usually by seeing an object, and calling that object¹s
toString method). 
* Otherwise, Java can¹t tell what the ³+² is supposed to mean, so ³+ cannot
be used in this context².
It¹s that third option which introduces confusion.  When you added the `+
³:²¹ to your expression, you bumped it from the fourth situation into the
third situation.

I try to mention to my students rather early on that when Java sees
   ³Catch ³ + 22
there is an invisible conversion which occurs, calling a function which
takes the int 22 and returns a String.
In fact, Java re-writes(*) that short statement behind-the-scenes as
   ³Catch ³.concat( (new Integer(22)).toString() )
which is more complicated in one sense, but simpler in the sense that it
shows that everything reduces to calling methods, without any magical ³+² or
hidden conversions.  Some students ignore this digression, but for some it
helps.

(*) Yes, I realize my translation is a bit of a lie; there is a static
Integer.toString(int) method.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.bluej.org/pipermail/bluej-discuss/attachments/20061005/e29d60ae/attachment.html


More information about the bluej-discuss mailing list