Java: the sum of two integers prints as a concatenation of two

Consider this code:

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

When I run this code, I get 1711 output. Can anyone tell me how to get 1711?

+5
source share
10 answers

Right 17 .

013 is an octal constant equal to 11 in decimal form.

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

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

I think you want:

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

or

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

What will be the best result.

+11
source

There are two problems here: the octal literal and the evaluation order.

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

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

Look at the following diagram ( sc is a concatenation of strings, aa is an arithmetic addition):

 ("x+y = " + x)+y | | (1) sc | | sc (2) "x+y = " + (x+y) | | | aa (1) | sc (2) 

In both diagrams (1) occurs before (2) .

Without parentheses, the compiler evaluates from left to right (according to priority rules).

  "x+y = " + x+y | | (1) | | (2) 
+8
source

You are concatenating strings in the final print as you add a string. Since "x+y = " is the string, when you add x to it, it gives you "17" , making "x+y = 17" .

013 is in octal, therefore treated as a decimal value, you get 11. When you combine this, you get "x+y = 17" + "11" or 1711

+2
source
 "x+y = " + x+y 

equally

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

which is equal

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

which is equal

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

013 is octal = 11 in decimal value

+2
source

Numbers prefixed with 0: octal . 13 Octal - 11 decimal places.

The x + y call treats both parameters as strings, so you concatenate the strings "17" and "11".

0
source

013 is ocatal ... convert it to decimal and you get 11. Look here for an explanation of the octal system.

0
source

This is the string concatenation of decimal 17 and octal 13 (equivalent to decimal 11).

0
source

It seems to interpret y as an octal notation (which evaluates to 11). In addition, you concatenate the x and y string representations in System.out.printLn.

0
source

I will simply add to Reed's explanation that 013 is interpreted as octal 13, which is decimal 11.

0
source

all 0 mentioned make the number octal.
I just want to add that 0x makes it hex

0
source

Source: https://habr.com/ru/post/1303869/


All Articles