Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Invalid assignment" error from == operator

I was trying to write a simple method:

boolean validate(MyObject o)
{
  // propertyA && propertyB are not primitive types.
  return o.getPropertyA() == null && o.getPropertyB() == null;
}

And got a strange error on the == null part:

Syntax error on token ==. Invalid assignment operator.

Maybe my Java is rusty after a season in PLSQL. So I tried a simpler example:

Integer i = 4;
i == null;
// compile error: Syntax error on token ==. Invalid assignment operator.

Integer i2 = 4;
if (i == null); //No problem

How can this be?

I'm using jdk160_05.

To clarify: I'm not trying to assign anything, just do an && operation between two boolean values. I don't want to do this:

if (o.propertyA() == null && o.propertyB() == null) { return true; }
else { return false; }
like image 867
Tom Avatar asked Dec 03 '22 05:12

Tom


2 Answers

== is not an assignment operator, it's a boolean equality operator, see:

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.2

If you want to set i to null use the simple assignment operator =:

i = null;

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.1

If you want to check that i is null then you need to use the == operator

if (i == null)
like image 170
Jon Avatar answered Dec 04 '22 19:12

Jon


I don't think you are confusing assignment and equality comparison. I think your compiler is just giving you a confusing error message. This program:

Integer i = 4;
i ==null; 

should give an error something like this:

Program.java:8: not a statement
                 i ==null;

Your first program should compile correctly. Perhaps there is some invisible unicode character in the text that is confusing the compiler. Try deleting the entire function and typing it in again.

like image 31
Mark Byers Avatar answered Dec 04 '22 17:12

Mark Byers