Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
How can I assign a certain case to execute the same code as another case in a java switch statement?

What I'm trying to do is allow a user to input different variations of a string(by that I mean, a user could enter either "Calculator", "Calc", "calculator", etc.), and still get the same code executed so I don't have to copy it into each case I want to do the same thing. i.e.

switch(input) {
    case "string1":
        statement 1;
        break;
    case "string2":
        statement 1;
        break;
    case "string3":
        statement 2;
        break;
    case "string4":
        statement 2;
        break;
    default:
        break;

Is there an easy way to do this, other than writing the same statement for each case?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

A comment gave me the term I was looking for, so I searched it up and found the answer myself. I now know that I can combine cases by putting the case label with just the colons above the next case, that has the statement to be run in both cases. i.e.

switch(input) {
    case "string1":
    case "string2":
        statement1;
        break;
    case "string3":
    case "string4":
        statement2;
        break;
    default:
        break;

This gives my desired output. Thank you, Dave Newton!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!