Trying to understand Java print

3

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?

    
asked by anonymous 14.10.2018 / 13:06

2 answers

3

Because + occurs soon after a string , " " , then the object there is of type string . Operators are overloaded (in Java this is half a gambiarra, but still it is), so in each type of data, the operator can execute a different thing. You can not define your own overloads, but the so-called primitive types in Java 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.

In this case Java decided that it would be poor typing and auto-coercion for string because the initial expression was string . Then " " + 7 gives " 7" , then " 7" + 2 gives " 72" and finally " 72" + " " gives " 72 " .

So it's this, overloading partial weak typing have made Java give this result that looks weird, but it does make some sense, even though it's a questionable rule.

    
14.10.2018 / 13:12
0

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

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

        System.out.print(" " + (7 + 2) + " ");
    }
}
    
15.10.2018 / 05:58