[Solved] Java orphaned case

In this post, I will be sharing how to solve java orphaned case error in Java. This error is rare and mostly occurs when there is a code syntax mistake in the switch statement in the program. It is a compile-time error. As always, first, we will produce the java orphaned case error before moving on to the solution.

Read Also: [Solved] Error: Reached end of file while parsing

[Fixed] Java Orphaned Case

Example 1: Producing the error by capitalizing the switch statement


We can easily produce this error by capitalizing the switch statement as shown below:

public class JavaOrphanedCase {
    public static void main(String args[]) {
      int i = 0;
      
Switch(i)
{ case 0: System.out.println("Alive is Awesome"); break; } } }


Output:
JavaOrphanedCase.java:4: error: ';' expected
              Switch(i)
                              ^
JavaOrphanedCase.java:6: error: orphaned case
                       case 0:
                       ^
2 errors

Explanation:

The error is because of capitalizing the first letter of the switch statement.

Solution:

In Java, we need to write a switch statement in lowercase to get rid of the error orphaned case as shown below:

public class JavaOrphanedCase {
    public static void main(String args[]) {
      int i = 0;
      
switch(i)
{ case 0: System.out.println("Alive is Awesome"); break; } } }

Output:
Alive is Awesome


Example 2: Producing the error by having cases out of the switch statement

We can easily produce this error by having the cases out of the switch statement as shown below:

public class JavaOrphanedCase2 {
    public static void main(String args[]) {
      int i = 1;
      switch(i) 
      {
          case 1:
            System.out.println("Be in present");
            break;      
}
case 2: System.out.println("Alive is Awesome"); break; } }


Output:
JavaOrphanedCase2.java:10: error: orphaned case
             case 2:
             ^
1 error


Explanation:

The cause of this error is by having cases out of the switch statement.

Solution:

In Java, we need to include cases inside the switch statement to get rid of the error orphaned case as shown below:

public class JavaOrphanedCase2 {
    public static void main(String args[]) {
      int i = 1;
      switch(i) 
      {
          case 1:
            System.out.println("Be in present");
            break;
      
          case 2:
            System.out.println("Alive is Awesome");
            break;
      
}
} }

Output:
Be in present


That's all for today, please mention in the comments in case you are still facing the compilation error orphaned case in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry