I have the following code for a class:
public class sqrt
{
public sqrt()
{
char start = 'H';
int second = 3110;
char third = 'w';
byte fourth = 0;
char fifth = 'r';
int sixth = 1;
char seventh = 'd';
float eighth = 2.0f;
boolean ninth = true;
String output = new String(start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);
System.out.println(output);
}
}
The required output is:
H3110 w0r1d 2.0 true
However, this outputs the following:
3182 w0r1d 2.0 true
I can only assume this is because it sees the numerical (ASCII) value of char 'H'
and adding it to int 3110
.
My question is:
Shouldn't new String()
convert each item within to a string and concatenate them?
If I change the output to:
String output = start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth +
" " + ninth;
It does the same thing, and adds the value of char
and int
together before concatenating the rest.
I know I can overcome this by adding a "" +
before start
, and I suppose that explains why it is seeing the ASCII value of char 'H'
(because it looks at the next value, sees it's an int, and goes from there?), but I'm confused as to why the new String()
isn't working as intended.
PS, I want to write better questions, and I know I am still a bit of a beginner here, so any advice in that regard would be appreciated as well. PMs are more than welcome, if anyone is willing to take the time to help.
PPS, If I figure out why this is, I will post the answer myself, but I am really trying to learn this, and I'm just very confused.