Search code examples
javaif-statementoperators

operator '&&'cannot be applied to 'int', 'int'


@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode = 1 && resultCode = RESULT_OK && data!=null){
        imagePath = data.getData();
        getImageinImageView();
    }
}`

I don't understand why it gives me this error.

I'm trying to make a profile picture changer and when the picture is selected, it shows the new profile picture.


Solution

  • Your code is a good example why it is "dangerous" to do equality comparisons:

    requestCode = 1 && resultCode = RESULT_OK && data!=null

    This could be split up in

    • requestCode = 1
    • and
    • resultCode = RESULT_OK
    • and
    • data != null

    Of the three comparisons probably only the last gets evaluated as you intended. The first two are actually assignements that assign a value on the right side of the = to the variable on the left side. But even an assignement is evaluated to something and that something is the value that's assigned to the left side, so requestCode = 1 not only assigns the int value 1 to requestCode but also evaluates to 1 in total.

    Then the int results of the comparisons are combined via the && operator, but that does only work on boolean values, and that is where the error comes from.

    You probably wanted to write requestCode == 1 && resultCode == RESULT_OK && data != null.

    (N.B.: in C it's even worse, because there you can combine ints with the && operator, and the whole statement would not be thrown back by the compiler. There you should always write the constant first, like 1 == requestCode because even if you forget on of the =, the compiler cannot assign a value to the constant on the left side, while the comparison doesn't care about the order of the operands.)