Trying to understand the Java print

Asked

Viewed 214 times

4

Watch the code right below;

public class Dois {

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

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

    }

}

The score is 72, but I thought the result was supposed to be 7 + 2 that would make 9.

Why did he print 72? Is he following some rule?

2 answers

4


Because the + occurs shortly after a string, the " ", then the object there is of the type string. Operators are overloaded (in Java this is kind of a gambiarra, but still it is), so in each type of data, the operator can run something different. You cannot set your own overloads, but the so-called Java primitives already have one ready. The + when he finds a string is a concatenation operation, so it gathers all the texts and does no sums.

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

So that’s it, overload plus partial weak typing have made Java give this result that looks weird, but makes some sense, even if it’s a questionable rule.

0

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.