[Solved] Syntax error on token "else", delete this token

In this post, I will be sharing how to fix syntax error on token "else", delete this token error in Java. It is a compile-time error. It is a syntax based error and mostly troubles Java beginners.

Read Also: [Fixed] Syntax error on token ",", { expected after this token

As always, first, we will produce the syntax error on token "else", delete this token error before moving on to the solution. Let's dive deep into the topic:

Note: This compiler error can be produced only in the Eclipse IDE.

[Fixed] Syntax error on token "else", delete this token

1. Producing the error using ; (semi-colon)


We can easily produce this error in the Eclipse IDE by having ;(semi-colon) after the if condition as shown below in the example:

public class SyntaxError 
{	
	public static void main(String args[])
	{
if("two".equals("two"));
{ System.out.println("inside if statement"); } else { System.out.println("inside else statement"); } } }

Output:
Syntax error on token "else", delete this token

1.2. Explanation:


The cause of this error is due to ; (semi-colon) present after the if condition.

1.3. Solution:


The above compilation error can be resolved by removing the ; (semi-colon) at the end of the if condition as shown below in the code:

public class SyntaxError 
{	
	public static void main(String args[])
	{
if("two".equals("two"))
{ System.out.println("inside if statement"); } else { System.out.println("inside else statement"); } } }


Output:
inside if statement


2. Producing the error using else


We can easily produce this error in the Eclipse IDE by having more than one else blocks for the corresponding if block as shown below in the example:

public class SyntaxError2 
{	
	public static void main(String args[])
	{
		if ("1".equals("1")){
		   System.out.println("You entered 1");
		}else{
		   System.out.println("You did not enter 1");
		}else{	        
                   System.out.println("Restart again");		
		}	
	}
}

Output:
Syntax error on token "else", delete this token 2


2.2. Explanation:


The cause of this error is due to more than one else block present after the if block. There should be one else block for the corresponding if block.

2.3. Solution:


The above compilation error can be resolved by combining the statements of all else blocks into one else block as shown below in the code:

public class SyntaxError2 
{	
	public static void main(String args[])
	{
		if ("1".equals("1")){
			System.out.println("You entered 1");
		}else{
			System.out.println("You did not enter 1");
			System.out.println("Restart again");		
		}	
	}
}


Output:
You entered 1


That's all for today. Please mention in the comments if you have any questions related to the syntax error on token "else", delete this token error 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