What is an object returned in parentheses?

Asked

Viewed 821 times

4

    }

    return (carro);
}

Does it have any behavior other than the object without parentheses? I was in doubt, apparently the code works normally.

  • @mgibsonbr why not answer? Just this snippet of your comment is already better than any answer I could give.

  • 1

    Who voted to close: He’s just wondering if return foo; is different from return (foo); , whether using (or not) parentheses influences something. :)

3 answers

5

In Java, a single element in parentheses is identical to the same element without any parentheses. Only when there are two or more elements does the parenthesis matter - be it improving readability (see reply from Marcusvinicius) is affecting the precedence (order of execution) of operators (see maicon’s response). Otherwise, the behavior will be identical, as by transforming the source code into bytecodes the same mounting code will be generated with or without parentheses:

Semparenteses.java

public int teste() {
    int carro = 42;
    return carro;
}

Semparenteses.class

public int teste();
  Code:
     0: bipush        42
     2: istore_1      
     3: iload_1       
     4: ireturn       

Comparenteses.java

public int teste() {
    int carro = 42;
    return (carro);
}

Comparenteses.class

public int teste();
  Code:
     0: bipush        42
     2: istore_1      
     3: iload_1       
     4: ireturn       

Other languages could have a different behavior (in Lisp the parenthesis would create a new list, in Python the empty parenthesis, with two or more elements or with a comma after carro would create a tuple, etc), but in Java there is no special meaning of it apart from establishing the order of evaluation of the expressions involved.

1

What is an object returned between parentheses?

The answer to your question is simple: the object itself!

There is no difference in the value or behavior of an object placed in parentheses in this way.

There are some cases where readability can be improved by placing yourself in parentheses. Consider the following case:

return umaCondicao && umValor > 0 || outroValor == 1;

It may be clearer if written:

return (umaCondicao && umValor > 0) || (outroValor == 1);

But the value returned is the same.

0

Java parentheses are used to execute expressions separately. For example.

That:

return 5 + 5 * 2;

And different from that:

return (5 + 5) * 2;

In the first case it will return 15 in the second it will return 20.

It has some different behavior than the object without parentheses?

No, but there might be a little performance drop.

Why java will try to execute an expression within parentheses.

Browser other questions tagged

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