Trying to understand Java print

Look at the code below;

public class Dois {

    public static void main(String[] args) {
        int a = 3;
        int b = 4;

        System.out.print(" " + 7 + 2 + " ");

    }

}

The result is 72, but I thought it was for the result to be 7 + 2 that would give 9.

Why did he print 72? Is he following any rules?

Author: Maniero, 2018-10-14

2 answers

Because + occurs right after a string, the " ", then the object there is of type string. Operators are overloaded (in Java this is kind of a gambiarra, but still it is), so on each type of data, the operator can perform a different thing. You can't set your own overloads, but the types called Java primitives already have one ready. The + when it finds a string is a concatenation operation, so it joins all the texts and does not make sums.

To join, in this case, Java resolved that it would be weak typing and do an automatic coercion for string because the initial expression was string. Then " " + 7 Gives " 7", then " 7" + 2 gives " 72" and finally " 72" + " " gives " 72 ".

So that's it, overhead plus partial weak typing made Java give this result that sounds weird, but makes some sense, even if it's a questionable rule.

 4
Author: Maniero, 2020-08-11 14:00:05

Just put parentheses around the operation and java will perform the operation instead of cancatenating them.

public class testes {
    public static void main(String[] args){
        int a = 3;
        int b = 4;

        System.out.print(" " + (7 + 2) + " ");
    }
}
 0
Author: Fábio Furtado, 2018-10-15 03:58:17