What is an object returned in parentheses?

4
    }

    return (carro);
}

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

    
asked by anonymous 11.06.2015 / 23:39

3 answers

4

In Java, a single element in parentheses is identical to the same element with no parentheses. Only when there are two or more elements does the parenthesis matter - either by improving readability (see MarcusVinicius response ) affecting the precedence (order of execution) of the operators (see Maicon's response ). Otherwise, the behavior will be the same, because by transforming the source code into bytecodes the same assembly code will be generated with or without the 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 #

    
12.06.2015 / 06:54
1
  

What is an object returned in 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 legibility can be improved by putting it in parentheses. Consider the following case:

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

It can be made clearer by writing:

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

But the value returned is the same.

    
12.06.2015 / 00:08
0

The parentheses in java serve to execute expressions separately. For example.

This:

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.

  

Does it have any behavior other than an unmasked object?

No, there may be a slight drop in performance.

Why java will try to execute an expression within the parentheses.

    
12.06.2015 / 01:21