Search code examples
javabooleanswitch-statementcompiler-errors

Java Switch Incompatible Types Boolean Int


I have the following class:

public class NewGameContract {

  public boolean HomeNewGame = false;
  public boolean AwayNewGame = false;

  public boolean GameContract() {
    if (HomeNewGame && AwayNewGame){
        return true;
    } else {
        return false;
    }
  }
}

When I try to use it like so:

if (networkConnection) {
  connect4GameModel.newGameContract.HomeNewGame = true;
  boolean status = connect4GameModel.newGameContract.GameContract();

  switch (status) {
    case true: break;
    case false: break;
  }
  
  return;
}

I am getting the error:

incompatible types found: boolean required: int on the following
`switch (status)` code.

What am I doing wrong?


Solution

  • You can't switch on a boolean (which only have 2 values anyway):

    The Java Language Specification clearly specifies what type of expression can be switch-ed on.

    JLS 14.11 The switch statement

    SwitchStatement:
        switch ( Expression ) SwitchBlock
    

    The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type, or a compile-time error occurs.

    It is a lot more readable and concise to simply use an if statement to distinguish the two cases of boolean.