Skip to content
Advertisement

Why do I get a different sum and errors for addition in Java

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?

Advertisement

Answer

' ' 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 Strings, which will then work as expected.

Another possible solution woudl be to use System.out.printf("%d%d%n", a, b);.

Ideone Demo

Advertisement