Is it possible to perform an assignment and comparison in if clauses in Java?

6

Is it possible to assign and at the same time perform a comparison in an if clause in Java?

For example:

String linha = leitor.readLine();
String saida = "";
if (linha = leitor.readLine()) {
    saida += "\n";
}

This does not seem to work.

How would I do it?

    
asked by anonymous 09.02.2014 / 22:46

2 answers

5

You do not show the condition you want to test on if , let's call it condicao :

if ((linha = leitor.readLine()) == condicao) {
    saida += "\n";
}

The above code will first assign the linha the value of readLine and then make the comparison with the condicao .

    
09.02.2014 / 22:53
7

It does not work directly because java does not allow automatic conversion to boolean. But you can do the following:

String linha = leitor.readLine();
String saida = "";
if ( (linha = leitor.readLine()) != null) {
    saida += "\n";
}

As in C and C ++, the assignment is an expression whose value is that of the variable that has just been assigned. In this case the type is String , which is not accepted within if . With the set of parentheses, we can isolate the value of the assignment and compare it with null to know if the operation occurred as expected.

    
09.02.2014 / 22:53