Home > Enterprise >  Is it possible to use Integers and Strings as cases in a switch case?
Is it possible to use Integers and Strings as cases in a switch case?

Time:07-03

I've done some looking around and haven't really found much direct info on this so I'd like to just ask it directly.

Is it possible to use integers and strings in a switch case? I know the switch is of one type (int, string, etc), but is there a way around it? For example:

int list;

switch(list)
{
     case 1: ...code...
             break;
     case 2: ...code...
             break;
     case XY: ...code...
             break;
}

I know this would throw an error of mismatched data. But is it possible to work around the error? Would something like Integer.toString() work to convert the int to a string? Just want to get some thoughts and information on the subject.

CodePudding user response:

What you are looking for is called pattern matching for switch statements. This is a feature that has been offered with Java 17 as you can see here. However, this feature is still in preview. With that in mind you could modify your code to look like so, and then enable preview features in order to make it work. An example would be:

public static void main(String... args) {
  var list = new ArrayList<>();
  list.add(1);
  list.add(2);
  list.add("test");
  for (var element : list) {
     var result = switch (element) {
     case Integer i -> i * 2;
     case String s -> String.format("This is a formatted string %s", s);
     default -> element;
     };
     System.out.println(result);
  }
}

And then enabled preview features when compiling.

CodePudding user response:

A way to do this that should work even on older versions of Java and doesn't require the use of preview features from the latest versions is to combine the use of instanceof and switch:


import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        var list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add("XY");
        list.add(3);
        list.add("test");
        for (var element : list) {
            if (element instanceof Integer) {
                Integer element2 = (Integer) element;
                switch (element2) {
                    case 1: System.out.println(1); break;
                    case 2: System.out.println(2); break;
                    default: System.out.println("Not 1 or 2"); 
                }
            }
            if (element instanceof String) {
                String element3 = (String) element;
                switch (element3) {
                    case "XY": System.out.println("XY"); break;
                    default: System.out.println("NOT XY");
                }
            }
        }
    }   
}

Output:

1

2

XY

Not 1 or 2

NOT XY

CodePudding user response:

Well this approach is not possible, it has to be same data type But you can to this

Try to convert the int to string then you will be fine.

int list;

  switch(list.toString()){
    case "1": ...code...
         break;
    case "2": ...code...
         break;
    case "XY": ...code...
         break;
    default: ....code...
          break;
  }

CodePudding user response:

You can use enum.

Pay attention to the following code example:

public enum MethodClick {
    Error,
    OnClick,
    OnDelete
}

  MethodClick methodClick;
    switch (methodClick){
        case Error:
            break;
        case OnClick:
            break;
        case OnDelete:
    }

CodePudding user response:

I think, it will work.

It depends on your jdk, because the switch statement has been "tuned" a few times. If you can "compare" a String in a switch statement, then this will work and the stage is yours.

I looked it up, you need at least jdk7. https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html

Convert the ints to String like this:

int x = 5; 
String intString = x   "" ;  //string concatenation or StringBuilder, your choice


  switch(intString){
    case "1": ...code...
         break;
    case "2": ...code...
         break;
    case "XY": ...code...
         break;
    default: ....code...
          break;
  }

Sorry for the many edits, I just hate my smartphone.

  • Related