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

Asked

Viewed 982 times

6

It is 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";
}

That doesn’t seem to work.

As I would?

  • "It is possible to assign and at the same time perform a comparison in an if clause in Java?" Yes.

  • You would have forgotten only the second question @Spark =)

2 answers

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";
}

Just 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 its type is String, what is not accepted within a if. With the set of parentheses, we can isolate the value of the assignment and compare it with null to find out if the operation occurred as expected.

5


You don’t show what condition you want to test on if, let’s call it condicao:

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

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

Browser other questions tagged

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