Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are my bitwise operations not working with `int`s in Java?

Tags:

java

I just got the following compiler error:

./package/path/FrameScreenPosition.java:80: incompatible types
found   : int
required: boolean
    if (frame.getExtendedState() & Frame.MAXIMIZED_BOTH) {
                                 ^

An 'extended state' is a bitwise mask of various different states such as maximized or iconified, and I'm trying to test whether the frame is maximized. The following short example produces a similar error:

public class BitTest
{
  public static void main(String[] args)
  {
    int a = 1;
    int c = 3;

    if (a & c) {
      System.out.println("This is right.");
    }
  }
}

Everything I've seen suggests that the bitwise operator & isn't restricted to boolean variables in Java, so why am I getting an error message?

like image 602
John Gowers Avatar asked Jun 05 '26 03:06

John Gowers


1 Answers

The expression inside if must explicitly be a boolean (that is, boolean or Boolean -- see JLS §14.9 for further details):

if ((a & c) != 0) {

Also note that the second set of parenthesis are required here since != has a higher precedence than &.

like image 59
arshajii Avatar answered Jun 06 '26 17:06

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!