0

Reading Java Headfirst found this example pls if someone can help me understand.

class Scratch {
    public static void main(String[] args)   {
        int x = 0;
        int y = 0;
        while ( x < 2 ) {
            y = y + x;
            System.out.print(x + "" + y + " ");
            x = x + 1;
        }
    }
}

I can't wrap my head around whats the function of quotes here in print statement the results vary a lot if you remove them.

The second one adds "Space" but the first somehow adds another integer?!

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
Mad Max
  • 3
  • 4
  • 5
    I think that the first set of quotes should also have a space to put a space between the x and y. However, even if it is just two quotes without a space it serves a purpose by making x + "" + y be a String rather than the sum of two integers. – NomadMaker May 24 '20 at 03:57
  • Holy moly. Goodness Gracious thx a lot I was about bash my head on the keyboard. I'm running the code. I just didn't spot the fact that without first quotes the function ads x+y instead of printing out as a string. Thank you good sir. I'can learn without clearing these things that bother me. – Mad Max May 24 '20 at 04:04

1 Answers1

1

This is a common Java idiom to convert a number to a string:

int x = 1;
System.out.println(x + "" + x); // prints 11

In Java the + operator is overloaded to mean either addition or string concatenation, depending on the operand types.

What happens here is that x + "" is interpreted as a string concatenation rather than an addition.

   x + "" -> 1 + "" -> "1"
   "1" + x -> "1" + 1 -> "11"

Now there are some people who say that x + "" should be written as String.valueOf(x). They say that the latter is more efficient. In reality, it depends on how good the JIT compiler is at optimizing string concatenation expressions, and that varies with the Java version.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks a lot) I was going crazy. Thinking that double quotes without a character in between refers to some value. – Mad Max May 24 '20 at 04:39