Last Updated:

Example of using String in switch in Java

String in switch in Java

Often you have to write methods that take a string and, depending on the content of that line, execute certain pieces of code. Previously, to implement such a method, you had to use the if-else construct or come up with workarounds. However, with Java 7, programmers now have the opportunity to use a convenient switch statement with strings!

An example of using String on Switch.

The program below provides a simple example of how to use a string with a switch statement in Java. Also, for clarity, the same method is given, but using if-else.

Important points about using switch with strings in Java:

  • Using String in the switch statement makes the code more readable by replacing if-else reuse.
  • The switch statement is case sensitive.
  • Switch uses a method to compare the input value with existing values.String.equals()
  • Be sure to check the line passed to switch on , otherwise you can get .nullNullPointerException
  • According to the Java 7 switch line documentation, the Java compiler generates more efficient bytecode than for multiple if-elses.
  • Before using switch in your programs or projects at work, make sure that the project uses Java 7 and higher - otherwise an exception will be thrown.

An important point: to write less and more beautifully, if possible, use a ternary statement in Java instead of the de switch or if-else.