Switch statement with boolean is not working?
Asked Answered
C

11

20

Why is my compiler telling me:

Incompatible Types:

Required: Boolean

Found: Int

under case 0 & case 1


For instance:

    public void test(boolean isOn){
    switch (isOn){
        case 0:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 1:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }

}

Driver Class:

Club me = new Club();
me.test(true);
Corespondent answered 13/10, 2013 at 22:50 Comment(4)
Your switch and if are redundant.Unbodied
I know its just so I can at least see how it works, I'm only learning thisCorespondent
Boolean values - true, false, FILE_NOT_FOUND! In Java, a boolean can only have two values - true, and false. Your default case will never be reached (and most people would likely use an if statement). Now, Boolean (note the capital 'B') can be null (at which point "I don't know" makes sense), but you're not using that here...Lise
It's Java's 'feature' proving lazy compiler makes programmer write more in my view.Parachute
J
20

You are switching on boolean type, and your cases are using int types. But even though you change your cases to have boolean types, that wouldn't work. You cannot switch on boolean type. And that wouldn't make any sense as using an if-else would be easier anyways:

if (isOn) {
    System.out.println("its on");
} else {
    System.out.println("its off");
}

Note that there is no "I don't know!" case here. A boolean type can have either true or false value. This is another reason, why switch-case is not for boolean type. There is no default case.

You can also condense it to a single statement by using a conditional expression:

public void test(boolean isOn) {
    System.out.println(isOn ? "its on" : "its off");
}
Jadda answered 13/10, 2013 at 22:52 Comment(3)
I did the changes now under switch (isOn) its saying Found: Boolean, Required: Char, Byte, short or intCorespondent
@someone You can't switch on boolean type, but only int types, String, or enum types.Jadda
Switching on true is actually more useful that you make it seem. Go uses it all the time code.google.com/p/go-wiki/wiki/Switch#Missing_expressionMittiemittimus
A
8

¯\(ツ)

switch (Boolean.hashCode(isOn)) {
    case 1231 -> System.out.println("its on");
    case 1237 -> System.out.println("its off");
}
Angst answered 17/5, 2018 at 10:14 Comment(1)
Bit late to the party, but made me laugh :DPneumoencephalogram
R
5

Just convert the boolean to number of 1 and 0.

public void test(boolean isOn){
    int trueOrFalse;
    if(isOn == true){
      trueOrFalse = 1;
    }else{
      trueOrFalse = 0;
    }
    switch (trueOrFalse){
        case 1:
            if (isOn){
                System.out.println("its on");
            }
            break;
        case 0:
            if (!isOn){
                System.out.println("its off");
            }
            break;
        default:
            System.out.println("I don't know!");
    }
}
Renie answered 7/7, 2017 at 12:31 Comment(0)
A
4

switch (isOn): switching boolean and want to case with int e.g., case 0!

According to the JLS section 14.11: for a switch ( Expression ) SwitchBlock:

Expression can only be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type other wise a compile-time error occurs.

According to the specification followings are also must be true:

  1. Every case constant expression associated with a switch statement must be assignable to the type of the switch Expression.
  2. No two of the case constant expressions associated with a switch statement may have the same value.
  3. No switch label is null.
  4. At most one default label may be associated with the same switch statement

Hence, switch expression can't be float, double or boolean. TO answer the question why?: boolean true false are meaningful using with if-else, e.g., if(true) then do. Floating point numbers (float, double) are not a good candiadtes for switch as exact comparison is often broken by rounding errors. e.g. 0.11 - 0.1 == 0.01 is false.

Abortifacient answered 13/10, 2013 at 22:53 Comment(0)
C
3

In Java, Switch does NOT work with Boolean.

Accepted variable types are : char,byte,short,int,String,Character,Byte,Short,Integer,enum

Choiseul answered 17/11, 2017 at 10:29 Comment(0)
U
2

As the error clearly states, numbers are not booleans.

You want true and false.

Unbodied answered 13/10, 2013 at 22:51 Comment(0)
E
0

This is not C++ where 1 and 0 get implicitly converted to/from true and false. Switching on boolean is also a waste of time even if you could do it; just write a simple if/else statement, or use the ? : construct.

Expositor answered 14/10, 2013 at 3:0 Comment(0)
G
0

In Java switch works only with integer literals and those which could be possibly promoted to integer literals such as char.

Moreover in Java boolean type has only two values either true or false. This is unlike the situation in C/C++ where true is any value not equals to zero and false is zero.

Moreover your code is a bit redundant

Guay answered 27/1, 2019 at 13:18 Comment(1)
As previously stated: Accepted variable types are : char,byte,short,int,String,Character,Byte,Short,Integer,enum. One can not switch off of Boolean or boolean, as how would one define a default case of neither True or False?Grenoble
S
0

You can not use boolean on switch statements. it is no point to use switch when the statement is true or false. it is easy to use if-else.

Spondaic answered 4/11, 2020 at 23:51 Comment(0)
F
0

Imho switch with boolean would make sense if you could use expressions for case checks instead of if else trees or continues in a loop (maybe I'm wrong that it's a benefit), e.g.:

class Testomatoe
{
    private final String country;
    private final String sort;
    private final int pricePerKiloEUCent;
    
    public Testomtoe
    (   final String country,
        final String sort,
        final int pricePerKiloEUCent
    )
    {
        this.country = country;
        this.sort = sort;
        this.pricePerKiloEUCent = pricePerKiloEUCent;
    }
    
    //get...
}


List<Testomataoe> offers = ...
String country;
String sort
int price;

for( Testomatoe tom : offers )
{
    country = tom.getCountry();
    sort = tom.getSort();
    price = tom.getPricePerKiloEUCent();
    
    switch( true )
    {
        case price < 100:
            addToQueryQuality( tom );
            break;

        case isUrgent( sort ) && price < 300:
            adddToPriOrder( tom );
            break;

        case !country.equals( "Somewheria" ) && price <= 200:
            addToOrder( tom );
            break;

        case country.equals( "Island" ) && sort.equals( "BlueFrost" ) && price < 600:
            addToAcceptable( tom );
            break;
        ...
    }
}
Frecklefaced answered 18/2, 2022 at 9:8 Comment(0)
C
0

Switch case does not support to use Boolean ,long,float,double. It supports only primitive data types such as char,int,byte ,short and non primitive String data types....

Claycomb answered 5/6, 2023 at 10:2 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Peplum

© 2022 - 2024 — McMap. All rights reserved.