Reputation:
I am really new to Java. I have a question regarding the numbers. I was given a task of printing 2 numbers side by side.
For example, if there are 2 numbers: a = 5
, b = 9
, I should print both of them side by side. So the output would look 59
.
In python, we can do:
print(a,b)
Even though it adds a space, I can remove that later.
But in Java. when I do System.out.println(a,b)
, I get:
error: no suitable method found for println(int,int)
System.out.println(a,b);
^
So after scratching my head for a little bit, I came up with System.out.println(a+''+b)
And then it gives:
error: empty character literal
System.out.println(a+''+b);
^
So, looking at the error, it looked like ''
is invalid. So I did ' '
And the result I got was:
46
Why did I get an error? When I do:
System.out.println(a+""+b);
It prints what I want: 59
Here is my code (working):
public class Main
{
public static void main(String[] args) {
int a=5;
int b=6;
System.out.println(a+""+b);
}
}
I just want to know why does this above work while doing ' '
doesn't. It is related to the data type?
Upvotes: 0
Views: 187
Reputation: 51
for ''
it represents a char value, so it recognizes as ASCII value(32).that's why it gives you a different output (5 + 32 + 9)
. By using ""
, int
will auto-cast into a string
example :
1+2+""+4 =34
Upvotes: 0
Reputation: 20185
' '
is a char
. It will be autocasted to an int
(the ASCII code of blank
is used, it has the value 32
). Then the addition is executed (5 + 32 + 9
, which will evaluate to 46
). That explain why we see the 46
being printed out.
Replacing ' '
with ""
will force the int
-values being autocasted to String
s, which will then work as expected.
Another possible solution woudl be to use System.out.printf("%d%d%n", a, b);
.
Upvotes: 1
Reputation: 28414
The single quote ' '
is a space character, and printing 5 + ' ' + 9
results in adding the integers with its ASCII value which is 32 (5 + 32 + 9 = 46).
You can either use ""
or printf
:
System.out.printf("%d%d", 5, 9);
Upvotes: 1