Beingness a coffee developer, you must encounter numberless bugs and errors on daily basis. Whether you are a beginner or experienced software engineers, errors are inevitable only over time you lot can go experienced plenty to be able to correct them efficiently. 1 such very unremarkably occurring error is "Illegal commencement of expression Java mistake".

What is "illegal starting time of expression java fault"?

The illegal start of expression coffee fault is a dynamic fault which ways you lot would run into information technology at compile time with "javac" statement (Java compiler). This error is thrown when the compiler detects any statement that does not abide by the rules or syntax of the Coffee linguistic communication. There are numerous scenarios where you lot tin can get an illegal showtime of expression error. Missing a semicolon at the stop of The line or an omitting an opening or closing brackets are some of the nearly common reasons simply it tin can be hands stock-still with slight corrections and can salve you a lot of time in debugging.

Post-obit are some well-nigh common scenarios where you would confront an illegal start of expression Java error along with the method to prepare them,

Java Developer Jobs

ane. Use of Access Modifiers with local variables

Variables that are declared inside a method are chosen local variables. Their functionality is exactly like any other variable just they accept very limited scope simply inside the specific block that is why they cannot exist accessed from anywhere else in the lawmaking except the method in which they were declared.

Access modifier (public, private, or protected) tin exist used with a simple variable only it is not allowed to be used with local variables within the method as its accessibility is divers by its method scope.

See the code snippet below,

          i.	public class classA { two.	    public static void main(String args[]) 3.	    {         4.	       public int localVar = 5; 5.	    } half dozen.	}        

 Here the public access modifier is used with a local variable (localVar).

This is the output you will run into on the concluding screen:

            $javac classA.java   classA.coffee:4: error: illegal offset of expression        public int localVar = v;        ^ 1 fault          

It reports 1 mistake that only points at the wrong placement of admission modifier. The solution is to either movement the proclamation of the local variable outside the method (it volition not be a local variable after that) or simply donot use an access modifier with local variables.

2. Method Within of Another Method

Dissimilar some other programming languages, Java does not allows defining a method inside another method. Attempting to do that would throw the Illegal start of expression mistake.

Below is the demonstration of the code:

          1.	public class classA { 2.	    public static void master(Cord args[]) {         iii.	       int localVar = five; four.	       public void anotherMethod(){  5.	          Organization.out.println("information technology is a method inside a method."); 6.	       } 7.	    } 8.	}        

This would be the output of the code,

                      $javac classA.java   classA.coffee:5: error: illegal start of expression        public void anotherMethod()        ^ classA.java:v: error: illegal start of expression        public void anotherMethod()               ^ classA.java:5: error: ';' expected        public void anotherMethod()                                 ^ iii errors        

It is a restriction in Coffee and so you just have to avoid using a method inside a method to write a successfully running code. The best do would be to declare some other method outside the main method and telephone call information technology in the master as per your requirements.

3. Form Inside a Method Must Not Have Modifier

Java allows its developers to write a class inside a method, this is legal and hence would non raise whatever error at compilation fourth dimension. That class will be a local type, similar to local variables and the scope of that inner course volition likewise be restricted just inside the method. However, an inner form must not brainstorm with access modifiers, as modifiers are not to exist used inside the method.

In the code snippet below, the class "mammals" is defined inside the main method which is inside the class called animals. Using the public admission modifier with the "mammals" class will generate an illegal start of expression java mistake.

          1.	public class Animals { 2.	    public static final void master(String args[]){         three.	      public grade mammals { } iv.	    } v.	}        

 The output will be equally follows,

          $javac Animals.java   Animals.coffee:iv: error: illegal start of expression        public grade mammals { }        ^ i mistake        

This error tin be fixed but by non using the access modifier with the inner class or you can ascertain a form within a class merely outside of a method and instantiating that inner class inside the method.

Below is the corrected version of code besides,

          1.	course Animals { ii.	    3.	   // inside class iv.	   private class Mammals { five.	      public void print() { six.	         Arrangement.out.println("This is an inner class"); 7.	      } 8.	   } 9.	    10.	   // Accessing the inside class from the method within 11.	   void display_Inner() { 12.	      Mammals inside = new Mammals(); 13.	      within.print(); fourteen.	   } 15.	} 16.	public class My_class { 17.	  xviii.	   public static void main(Cord args[]) { nineteen.	      // Instantiating the outer class  20.	      Animals classA = new Animals(); 21.	      // Accessing the display_Inner() method. 22.	      classA.display_Inner(); 23.	   } 24.	}        

 At present you volition get the correct output,

          $javac Animals.java   $java -Xmx128M -Xms16M Animals   This is an inner form        

4.Nested Methods

Some recent programming languages, like Python, supports nested methods but Java does not permit to make a method inside some other method.  Yous will run into the illegal start of expression java error if you try to create nested methods.

Below mentioned is a modest code that attempts to declare a method called calSum inside the method called outputSum,

          1.	public class classA { 2.	    public void outputSum(int num1, int num2) { 3.	        System.out.println("Calculate Event:" + calSum(10, y)); 4.	        public int calSum ( int num1, int num2) { 5.	            return num1 + num2; half-dozen.	        } seven.	    } 8.	}        

 And hither is the output,

          $ javac classA.java NestedMethod.java:6: mistake: illegal start of expression         public int calSum ( int num1, int num2) {         ^ classA.java:half-dozen: error: ';' expected         public int calSum ( int num1, int num2) {                           ^ classA.java:6: error:  expected         public int calSum ( int num1, int num2) {                                    ^ NestedMethod.coffee:6: mistake: not a statement         public int calSum ( int num1, int num2) {                                            ^ NestedMethod.java:vi: fault: ';' expected         public calSum ( int num1, int num2) {                                          ^ v errors        

The Coffee compiler has reported five compilation errors. Other four unexpected errors are due to the root cause. In this code, the first "illegal start of expression" error is the root cause. It is very much possible that a single error can crusade multiple farther errors during compile fourth dimension. Same is the case here. We tin can easily solve all the errors by just avoiding the nesting of methods. The all-time practice, in this case, would be to move the calSum() method out of the outputSum() method and just call it in the method to get the results.

See the corrected code beneath,

          1.	public course classA { 2.	    public void outputSum(int num1, int num2) { iii.	        Arrangement.out.println("Calculation Consequence:" + calSum(x, y)); iv.	    } 5.	    public int calSum ( int num1, int num2) { half dozen.	        render x + y; seven.	    } 8.	}        

5. Missing out the Curly "{ }" Braces

Skipping a curly brace in whatsoever method can result in an illegal start of expression java error. According to the syntax of Java programming, every cake or course definition must start and finish with curly braces. If you skip any curly braces, the compiler will not be able to identify the starting or catastrophe betoken of a cake which will result in an error. Developers often make this error because there are multiple blocks and methods nested together which results in forgetting closing an opened curly subclass. IDEs usually prove to be helpful in this example by differentiating the brackets by assigning each pair a different colour and fifty-fifty identify if you have forgotten to shut a bracket but sometimes it nevertheless gets missed and consequence in an illegal commencement of expression java fault.

In the following code snippet, consider this class chosen Computer, a method called calSum perform addition of 2 numbers and stores the result in the variable total which is then printed on the screen. The code is fine but it is just missing a closing curly bracket for calSum method which will result in multiple errors.

          i.	public class Calculator{ 2.	  public static void calSum(int x, int y) { 3.	    int total = 0; 4.	    full = x + y; v.	    Organisation.out.println("Sum = " + total); 6.	  7.	  public static void primary(Cord args[]){ 8.	    int num1 = 3; 9.	    int num2 = 2; 10.	   calcSum(num1,num2); 11.	 } 12.	}        

Following errors will be thrown on screen,

          $javac Calculator.java Calculator.java:12: error: illegal commencement of expression public int calcSum(int x, int y) { ^  Calculator.java:12: error: ';' expected    Calculator.coffee:13: error: reached terminate of file while parsing }  ^ iii fault        

The root cause all these illegal starts of expression java error is just the missing closing subclass at calSum method.

While writing your code missing a single curly bracket can accept up a lot of time in debugging particularly if you are a beginner and then always lookout for it.

6. String or Grapheme Without Double Quotes "-"

Just like missing a curly bracket, initializing string variables without using double quotes is a common fault made past many beginner Java developers. They tend to forget the double quotes and later on get bombarded with multiple errors at the run fourth dimension including the illegal start of expression errors.

If you forget to enclose strings in the proper quotes, the Java compiler will consider them as variable names. It may issue in a "cannot find symbol" error if the "variable" is non declared just if yous miss the double-quotations around a string that is not a valid Coffee variable name, information technology will be reported as the illegal start of expression Coffee error.

The compiler read the String variable as a sequence of characters. The characters can be alphabets, numbers or special characters every symbol central on your keyboard tin be a part of a cord. The double quotes are used to keep them intact and when you miss a double quote, the compiler can not identify where this series of characters is ending, it considers another quotation anywhere later on in the lawmaking every bit closing quotes and all that code in between as a string causing the mistake.

Consider this code snippet beneath; the missing quotation marks effectually the values of the operator inside if conditions volition generate errors at the run time.

          1.	public class Operator{ two.	  public static void main(String args[]){ 3.	    int num1 = 10; iv.	    int num2 = 8; 5.	    int output = 0;  half-dozen.	    Scanner scan = new Scanner(System.in); seven.	    System.out.println("Enter the operation to perform(+OR)"); viii.	    String operator= scan.nextLine(); 9.	    if(operator == +) x.	  { 11.	     output = num1 + num2; 12.	  } xiii.	  else if(operator == -) xiv.	  { 15.	     output = num1 - num2; 16.	  } 17.	  else 18.	  { xix.	     System.out.prinln("Invalid Operator"); xx.	  } 21.	  System.out.prinln("Consequence = " + output);  22.	}        

String values must be e'er enclosed in double quotation marks to avoid the fault similar to what this lawmaking would return,

          $javac Operator.java   Operator.coffee:14: error: illegal start of expression if(operator == +)                 ^ Operator.coffee:19: error: illegal start of expression    if(operator == -)                    ^ 3 error        

Conclusion

In a nutshell, to fix an illegal beginning of expression error, look for mistakes earlier the line mentioned in the mistake message for missing brackets, curly braces or semicolons. Recheck the syntax likewise. Ever look for the root cause of the error and always recompile every time you set up a bug to check as information technology could be the root cause of all errors.

See Also: Java Feature Spotlight – Sealed Classes

Such run-time errors are designed to assist developers, if you take the required noesis of the syntax, the rules and restrictions in java programming and the practiced programming skills than you tin easily minimize the frequency of this error in your code and in example if it occurs you would be able to quickly remove it.

Practice you take a knack for fixing codes? And so we might have the perfect job role for yous. Our careers portal features openings for senior full-stack Java developers and more.