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

191
Views
How to have a switch case scenario using String as condition?

I have a String that I need to get the last digit from and use switch cases according to that character.

String securityNumber= "4561";
String lastDigit = securityNumber.substring(securityNumber.length()-1);

switch (lastDigit) {
    case "0": System.out.println("0");
        break;
    case "1": System.out.println("1");
        break;
    case "2": System.out.println("2");
        break;
    case "3": System.out.println("3");
        break;
    case "4": System.out.println("4");
        break;
    default: System.out.println("def");
}

I am getting the "def" as a result but should be "1".

What am I doing wrong? How can I have a case scenario for each of the digits from an input of String "securityNumber"?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need a break at the end of each case, otherwise the switch case will fall through and execute all the succeeding cases after the first one it matches. When I run it, it prints:

1 2 3 4 def

To fix this, here is the code:

String securityNumber = "4561";
String lastDigit = securityNumber.substring(securityNumber.length()-1);
switch (lastDigit) {
    case "0": System.out.println("0");
              break;
    case "1": System.out.println("1");
              break;
    case "2": System.out.println("2");
              break;
    case "3": System.out.println("3");
              break;
    case "4": System.out.println("4");
              break;
    default: System.out.println("def");
}

You also forgot a ; at the end of the declaration for securityNumber, so it might have not compiled.

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!