Search code examples
javastringstring-concatenationaddition

How does this equal 105 instead of 15?


public class Review {

public static void main(String[] args) {
    int x = 10, y = 5;
    System.out.println(" " + x + y); // string + x + y
  }

}

How does this equal 105 rather then 15? What makes it different from the below code?

public class Review {

public static void main(String[] args) {
    int x = 10, y = 5;
    System.out.println(x + y); //Only x + y
  }

}

Solution

  • " " + x + y means " " + x then + y

    so the first code that you write we can divide into 2 steps:
    1. " " + x => " " + 10 => "10"
    2. "10" + y => "10" + 5 => "105"

    But the second is just a number + number, so we get the number result.

    I'm not a native English speaker, and I'm learning, sorry about my bad English, And I hope this is helpful.