I just need to add the numbers, right?

What is the output of the following code?

1
2
3
4
5
public class Challenge {
    public static void main(String[] args) {
        System.out.print(10 + 20 + "30" + 40 + 50) ;
    }
}

303090 1020304050 30304050 The code will not run. 10203090

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Jaydee Lucero
Aug 17, 2017

In Java, the addition operator "+" operates from left to right .

  • When applied to two numbers, they will be added arithmetically.
  • When applied to two strings, they will be concatenated .
  • When applied to a number and a string, the number will be "converted" to a string, and then be concatenated to the (other) string.

For this problem, this becomes 10 + 20 + "30" + 40 + 50 = 30 + "30" + 40 + 50 (arithmetical addition) = "3030" + 40 + 50 (integer-string concatenation) = "303040" + 50 (integer-string concatenation) = "30304050" (integer-string concatenation) \begin{aligned} 10 + 20 + \text{"30"} + 40 + 50 &= 30 + \text{"30"} + 40 + 50\text{ (arithmetical addition)} \\ &= \text{"3030"} + 40 + 50\text{ (integer-string concatenation)} \\ &= \text{"303040"} + 50\text{ (integer-string concatenation)} \\ &= \boxed{\text{"30304050"}}\text{ (integer-string concatenation)} \end{aligned}

Thanks.I am learning java and I didnot knew that integers will be converted to string for concatenation in some case

Saksham Jain - 3 years, 6 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...