0

I just started the "Head First Java" book. There is an exercise that is tripping me up due to the double quotes ("") with no space in the code below. I think I figured it out, but it doesn't look like the book explains it and I would like to make sure I am correct moving forward.

Is the purpose of the double quotes ("") in the code below to concatenate the two integers (x and y) and prevent the + operator from performing addition for the output? That's what it seems.

The OUTPUT for the code below is: 00 11 21 32 42.

I deleted the double quotes and the output gives me: 0 2 3 5 6.

class Test
{
    public static void main (String[] args) 
    {
       int x = 0;
       int y = 0;

       while ( x < 5)
       {
       y = x - y;
       System.out.print(x + "" + y + " ");
       x = x + 1;
       }
    }
}
biscuit
  • 353
  • 3
  • 10
  • 3
    Otherwise it will do `Integer` addition `1 + "" + 2` is `12` but `1 + 2` is `3` - A better was to convert an `int` to a String is to use `Integer.valueOf` method – Scary Wombat Oct 09 '19 at 05:35
  • The purpose is to force java to interpret + as string concatenation not integer addition. –  Oct 09 '19 at 05:35
  • Don't take downvotes personally -- this isn't Facebook or Reddit. Whoever voted you down is probably hoping you will search SO more diligently next time i order to avoid duplicate questions. Remember that SO isn't here just to answer questions for you, but rather, to create a resource to help many users going forward. In that context, duplicates only serve to add noise. And yes, it would have been better if the downvoter had explained the vote, but that's just how people are these days, not just on SO. – MarsAtomic Oct 09 '19 at 05:45
  • @ScaryWombat `Integer.valueOf(x)` returns an `Integer`. Did you meant `Integer.toString(x)`. Because you said `A better was to convert an int to a String ...`. – SubOptimal Oct 09 '19 at 05:50
  • @MarsAtomic I see that this question has been marked as "answered", but it technically hasn't. My question on the use of double quotes ("") with no space is a little different than double quotes surrounding an integer or character. The example (x + "" + y) is different than (x + "y") and thus a little more confusing if you didn't know the purpose and it was never been explained to you. Although the link to the answer explains the use of the double quotes and concatenation, it doesn't explain the use of double quotes with no space, integer, or character in between. – biscuit Oct 09 '19 at 05:59
  • @SubOptimal Yes, you are right, `toString` is what I told my hands to type - they are sooo disobedient – Scary Wombat Oct 09 '19 at 06:00
  • 1
    @biscuit - more than one way to skin a cat – Scary Wombat Oct 09 '19 at 06:01

2 Answers2

4

To answer your direct question: you are correct that the "" is there to turn the + into a concatenation, rather than addition. But I'll give a few more details as to what's going on here.

It's perhaps a little bad of the authors of the book to use this without explaining, since this appears to be a key thing in the exercise (even a brief footnote saying "this is just an easy way to convert to a String"); but it's one of those things most Java programmers wouldn't even think about needing to explain, so easy to miss; or, perhaps they did explain it earlier, and you just missed it, because of the throw-away nature of the explanation. No accusations; it's just what it is.


We're trying to evaluate the expression x + "" + y + " " in order to print it. Because + is left-associative, this is evaluated as

((x + "") + y) + " "

So, in terms of the effect of including "", the question is how the subexpression x + "" will be evaluated. If the "" had been omitted, it would be evaluated as

(x + y) + " "

There is no separate operator for "numeric addition" and "string concatenation" in Java: both use +. So, Java uses a simple rule to decide between the two:

If the type of either operand of a + operator is String, then the operation is string concatenation.

As such, x + "" is string concatenation, but x + y would be numeric addition.

If you look into the specifics of string concatenation:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

So this is saying that the int in int + String has to be converted to a string, in order to concatenate it with another string, which is pretty reasonable. And this string conversion is done using:

If T is byte, short, or int, then use new Integer(x).

...

the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments

("as if" is just wiggle room to say you don't actually have to invoke new Integer(x) - implementations could use Integer.toString(x), or some other method, instead).

Then, concatenation is defined as:

The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

Given that "" has no characters, it is trivially true that someString + "" will have the same characters as someString (*).

So, int + "" (or "" + int) is simply a syntactic trick to convert the int to a String. There is no other effect of doing this. It's just less verbose to write this than Integer.toString(x) or new Integer(x).toString().

It's also worth pointing out that it would work the same had it been "" + x + y + " ". But that's perhaps less clear to the human eye that the x and y won't be added.


(*) The slight detail here is that concatenation results in a new string (unless the two operands are constant expressions, in which case the concatenation is done at compile time), i.e. someString + "" != someString, even though (someString + "").equals(someString).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
3

Is the purpose of the double quotes ("") in the code below to concatenate the two integers (x and y) and prevent the + operator from performing addition for the output?

That's exactly what it is. The alternative would be something like

print(String.valueOf(x) + String.valueOf(y) + " ")

which is a lot less readable. The String type can be forced also in the beginning, as in "" + x + y + " ", just as long as we're dealing with Strings before we start to use the + operator.

Kayaman
  • 72,141
  • 5
  • 83
  • 121