Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: sum of two integers being printed as concatenation of the two

Tags:

java

Consider this code:

int x = 17;
int y = 013;
System.out.println("x+y = " + x + y);

When I run this code I get the output 1711. Can anybody tell me how do I get 1711?

like image 327
giri Avatar asked Mar 12 '10 00:03

giri


Video Answer


2 Answers

The 17 is there directly.

013 is an octal constant equal to 11 in decimal.

013 = 1*8 + 3*1 = 8 + 3 = 11

When added together after a string, they are concatenated as strings, not added as numbers.

I think what you want is:

int x = 17;
int y = 013;
int z = x + y;

System.out.println("x+y = " + z);

or

System.out.println("x+y = " + (x + y));

Which will be a better result.

like image 52
Carl Norum Avatar answered Nov 03 '22 01:11

Carl Norum


There are two issues here: octal literal, and order of evaluation.

int y = 013 is equivalent to int y = 11, because 13 in base 8 is 11 in base 10.

For order of evaluation, the + operator is evaluated left to right, so "x+y = " + x+y is equivalent to ("x+y = " + x)+y, not "x+y = " + (x+y). Whitespaces are insignificant in Java.

Look at the following diagram (s.c. is string concatenation, a.a. is arithmetic addition):

("x+y = " + x)+y
          |   |
     (1) s.c  |
              |
             s.c. (2)


"x+y = " + (x+y)
         |   |
         |  a.a. (1)
         |
        s.c. (2)

In both diagrams, (1) happens before (2).

Without the parantheses, the compiler evaluates left-to-right (according to precedence rules).

 "x+y = " + x+y
          |  |
         (1) |
             |
            (2)
like image 36
polygenelubricants Avatar answered Nov 03 '22 00:11

polygenelubricants