Read Also: [Fixed] Unclosed String Literal Error
As always, first, we will produce the syntax error on token ",", { expected after 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 ",", { expected after this token
1. Producing the error
We can easily produce this error in the Eclipse IDE by writing code or executable statements outside the method as shown below:import java.util.*; public class SyntaxError { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++) { System.out.println(str); } }
Output:
2. Explanation:
The cause of this error is due to the code or executable statements not present inside the method. You can not directly write the code in a class in Java. Only variables declaration/initialization are allowed outside the method.3. Solution:
The above compilation error can be resolved by moving the code inside a method. In simple words, you can't call a class you have to call a method that is declared inside a class. We can easily avoid this error by using one of the solutions given below:Solution 1: Using public static void main() method
We have moved the code inside the public static void main() method as shown below in the code:
import java.util.*; public class SyntaxError { public static void main(String args[]) { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } }
Solution 2: Using any method
We can move the executable code inside any method, for example, the printString() method as shown below in the code:
import java.util.*; public class SyntaxError { public static void printString() { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } public static void main(String args[]) { printString(); } }
Solution 3: Using block
Any executable code inside {} without any method name is called a block. We can move the executable code inside the block also as shown below:
import java.util.*; public class SyntaxError { // Using block { String str = "Alive is Awesome"; Random rand = new Random(); for (int i = 0; i < 3; i++){ System.out.println(str); } } public static void main(String args[]) { new SyntaxError(); } }
That's all for today. Please mention in the comments in case you have any questions related to the syntax error on token ",", { expected after this token error in Java.