+ 1

Explain the output please

char[]chr = ("197").toCharArray(); int x1=Integer.parseInt(""+chr[1]); System.out.println(""+x1+chr[1]); Why 99 and not 18 as output? (ofc x1 and chr[1] is getting added)

1st Nov 2019, 3:00 PM
Ajit Kumar
Ajit Kumar - avatar
7 Respuestas
+ 4
"" + x1 + chr[1] Here the + operator acts as string concatenation operator rather than arithmetic add operator. This is because you have an empty string before <x1>. When a + operator is placed between a string and a number the number is automatically converted to string, then the two will be concatenated. "" + x1 + chr[1] An empty string is concatenated with '9' => "9" "9" + chr[1] Here chr[1] will concatenated into the string to the left ("9"). Then we have a final result as "99".
1st Nov 2019, 3:48 PM
Ipang
+ 3
<x1> is an int, while <chr[1]> is a char (an element of a char array).
1st Nov 2019, 3:55 PM
Ipang
+ 3
You're welcome, But is your doubt clear now? it's more important to understand. I'm not leaving you yet until it's all clear.
1st Nov 2019, 3:58 PM
Ipang
+ 1
Ipang so, typeof x1 and chr[1], both are string or number ?
1st Nov 2019, 3:52 PM
Ajit Kumar
Ajit Kumar - avatar
+ 1
Ipang got it, thanks
1st Nov 2019, 3:56 PM
Ajit Kumar
Ajit Kumar - avatar
+ 1
Ipang this is what i got; Equivalent to javascript, it is console.log(""+9+"9"); so the output is 99 where 9 is for x1 and "9" is for chr[1] Correct?
1st Nov 2019, 4:06 PM
Ajit Kumar
Ajit Kumar - avatar
+ 1
Noise Of Silence That's absolutely right! you got it correctly 👍
1st Nov 2019, 4:09 PM
Ipang