I need to print 'H3110 w0r1d 2.0 true' as output. Below is the code written and getting output as '3182 w0r1d 2.0 true'.
public class HelloWorld {
public static void main (String[] args){
char c1= 'H';
int num1 = 3110;
char c2='w';
byte b=0;
char c3='r';
int y=1;
char c4='d';
float f = 2.0f;
boolean bool= true;
String s = c1+num1 + " " + c2+b+c3+y+c4 + " " + f + " " + bool;
System.out.println(s);
}
}
Query: If I concatenate H
and 3110
, it is printing as 3182
. Why so?
char
is being promoted toint
before the addition, basically. If you use a string instead (string c1 = "H";
) it'll be fine.char + int
, thechar
gets converted toint
first (its corresponding Unicode value (for beginners, the index in the ASCII table in this case)) and then it is a regularint + int
addition.