Pages

Sunday, May 19, 2019

Java Fix to Syntax error on token “;”, { expected after this token

1. Overview


In this tutorial, We'll learn how to fix "Syntax error on token “;”, { expected after this token" compile time error in Java.

This is very common error while writing java programs for beginners.



Syntax error on token “;”, { expected after this token


We'll explore how to solve these kind of compile time errors now.


2. Example


Let create a example program that creates an compile time error "Syntax error on token “;”, { expected after this token".

public class CompileTImeTokenError {

 String[] plaintext = new String[26];
 for(int i = 0; i < 26 ; i++)
 {
  System.out.println(" Welcome to Java-w3schools blog");
 }
}

Just try to compile this program then it produces the compile time error what we are looking for.

3. Solution


All lines of code in the program must and should be inside a method. We need to move all the logic to either a method or public static void main() method.

Remember that all code we write in java must be inside a method or a block.

We can avoid this error using any one of the following solutions.

3.1 public static void main


public static void main(String[] args) {
 String[] plaintext = new String[26];
 for (int i = 0; i < 26; i++) {
  System.out.println("Welcome to Java-w3schools blog");
 }
}

3.2 Any Method


public boolean print() {
 String[] plaintext = new String[26];
 for (int i = 0; i < 26; i++) {
  System.out.println("Welcome to Java-w3schools blog");
 }
 return true;
}

3.3 Block


Any code that is inside of "{ }" braces without any method name is Block.

{
 String[] plaintext = new String[26];
 for (int i = 0; i < 26; i++) {
  System.out.println("Welcome to Java-w3schools blog");
 }
}


4. Conclusion


In this tutorial, We've seen the common error in java "Syntax error on token “;”, { expected after this token".

Further in this article, We have seen 3 solutions to fix this error such as moving the code inside main method, any method or block.

All code snippets are shown in this post are available on GitHub.

No comments:

Post a Comment

Please do not add any spam links in the comments section.