Error not a statement java

How to resolve compilation error "Error: not a statement" accompanied by "Error: ';' expected" or "Error: ')' expected " in Java.

If you are getting the following error(s) at compilation time –

which may be accompanied by –

Error: ';' expected 
OR
Error: ')' expected

Then there are two possible reasons for these compiler errors to happen –
Possible Reason 1: Applicable in case of Java 8 lambda expressions – When trying to assign a Java 8 Lambda ExpressionRead Lambda Expressions Tutorial to a Functional Interface
Click to Read Detailed Article on Functional Interfaces instance like this –

import java.util.function.Function;
public class ErrorExample{
  public static void main(String args[]){
    Function func= Integer i -> i.toString();
    func.apply(10);
  }  
}

The lambda assignment statement above will give the compilation errors – Error: not a statement along with Error: ‘;’ expected
Solution: Enclose the statement Integer i in parenthesis/circular brackets. This is because when specifying the type of an argument in lambda expressions it is mandatory to add parenthesis around the arguments.

The correct assignment statement without the compilation errors would then be
Function func= (Integer i) -> i.toString();

Possible Reason 2: Applicable to Java Code in General – Compiler expected a statement in that line but instead got something different. Lets see couple of examples to understand the scenarios in which this error could occur –
Example 1:
Incorrect: if (i == 1) "one";
The above statement will give a “Error: not a statement” compilation error because its actually not a proper statement. The corrected statement is –
Corrected: if(i==1) System.out.println("one");

Example 2:
Incorrect: System.out.println("The "+"value of ";+i+" is "+i+" and j is"+j);//i.j being integers
The above statement will give “Error: not a statement” along with “Error: ‘)’ expected” compilation errors because of the incorrectly added extra semicolon(;) after “value of ” in the above statement. If we remove this extra semicolon then the compiler errors are removed.
Corrected: System.out.println("The "+"value of "+i+" is "+i+" and j is"+j);

Digiprove sealCopyright © 2014-2022 JavaBrahman.com, all rights reserved.

public class Hello
{
   public static void main(String args[])
   {
     int i = 1;
     for(i; ;i++ )
     {
        System.out.println(i);
     }      
}

}

I would like to understand why above code is giving error as:

not a statement for(i ; ; i++)

dbush's user avatar

dbush

199k21 gold badges210 silver badges262 bronze badges

asked Feb 18, 2015 at 15:31

Indrajeet's user avatar

3

Because the raw i in the first position of your for is not a statement. You can declare and initialize variables in a for loop in Java. So, I think you wanted something like

// int i = 1;
for(int i = 1; ;i++ )
{
    System.out.println(i);
}      

If you need to access i after your loop you could also use

int i;
for(i = 1; ; i++)
{
    System.out.println(i);
}      

Or even

int i = 1;
for(; ; i++)
{
    System.out.println(i);
}      

This is covered by JLS-14.4. The for Statement which says (in part)

A for statement is executed by first executing the ForInit code:

If the ForInit code is a list of statement expressions (§14.8), the expressions are evaluated in sequence from left to right; their values, if any, are discarded.

Community's user avatar

answered Feb 18, 2015 at 15:37

Elliott Frisch's user avatar

Elliott FrischElliott Frisch

195k20 gold badges156 silver badges246 bronze badges

The lone i at the start of the for statement doesn’t make any sense — it’s not a statement. Typically the variable of the for loop is initialized in the for statement as such:

for(int i = 1;; i++) {
    System.out.println(i);
}

This will loop forever though, as there is no test to break out of the for loop.

answered Feb 18, 2015 at 15:42

Mathias R's user avatar

Change your for loop to:

 for(; ;i++ )

It will loop infinitely printing i. Your i is not of boolean type which you could have place in condition of for loop and for loop has format like:

for (init statement; condition; post looping)

So in your init statement you just had i which is not a valid statement and hence you get error from compiler.

answered Feb 18, 2015 at 15:34

SMA's user avatar

SMASMA

35.9k8 gold badges47 silver badges73 bronze badges

Being a java developer, you must encounter numberless bugs and errors on daily basis. Whether you are a beginner or experienced software engineers, errors are inevitable but over time you can get experienced enough to be able to correct them efficiently. One such very commonly occurring error is “Illegal start of expression Java error”.

The illegal start of expression java error is a dynamic error which means you would encounter it 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 Java language. There are numerous scenarios where you can get an illegal start of expression error. Missing a semicolon at the end of The line or an omitting an opening or closing brackets are some of the most common reasons but it can be easily fixed with slight corrections and can save you a lot of time in debugging.

Following are some most common scenarios where you would face an illegal start of expression Java error along with the method to fix them,

new java job roles

1. Use of Access Modifiers with local variables

Variables that are declared inside a method are called local variables. Their functionality is exactly like any other variable but they have very limited scope just within the specific block that is why they cannot be accessed from anywhere else in the code except the method in which they were declared.

Access modifier (public, private, or protected) can be used with a simple variable but it is not allowed to be used with local variables inside the method as its accessibility is defined by its method scope.

See the code snippet below,

1.	public class classA {
2.	    public static void main(String args[])
3.	    {        
4.	       public int localVar = 5;
5.	    }
6.	}

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

This is the output you will see on the terminal screen:

$javac classA.java
 
classA.java:4: error: illegal start of expression
       public int localVar = 5;
       ^
1 error

It reports 1 error that simply points at the wrong placement of access modifier. The solution is to either move the declaration of the local variable outside the method (it will not be a local variable after that) or simply donot use an access modifier with local variables.

2. Method Inside of Another Method

Unlike 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 error.

Below is the demonstration of the code:

1.	public class classA {
2.	    public static void main(String args[]) {        
3.	       int localVar = 5;
4.	       public void anotherMethod(){ 
5.	          System.out.println("it is a method inside a method.");
6.	       }
7.	    }
8.	}

This would be the output of the code,

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

It is a restriction in Java so you just have to avoid using a method inside a method to write a successfully running code. The best practice would be to declare another method outside the main method and call it in the main as per your requirements.

3. Class Inside a Method Must Not Have Modifier

Java allows its developers to write a class within a method, this is legal and hence would not raise any error at compilation time. That class will be a local type, similar to local variables and the scope of that inner class will also be restricted just within the method. However, an inner class must not begin with access modifiers, as modifiers are not to be 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 access modifier with the “mammals” class will generate an illegal start of expression java error.

1.	public class Animals {
2.	    public static final void main(String args[]){        
3.	      public class mammals { }
4.	    }
5.	}

 The output will be as follows,

$javac Animals.java
 
Animals.java:4: error: illegal start of expression
       public class mammals { }
       ^
1 error

This error can be fixed just by not using the access modifier with the inner class or you can define a class inside a class but outside of a method and instantiating that inner class inside the method.

Below is the corrected version of code as well,

1.	class Animals {
2.	   
3.	   // inside class
4.	   private class Mammals {
5.	      public void print() {
6.	         System.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.	      inside.print();
14.	   }
15.	}
16.	public class My_class {
17.	 
18.	   public static void main(String args[]) {
19.	      // Instantiating the outer class 
20.	      Animals classA = new Animals();
21.	      // Accessing the display_Inner() method.
22.	      classA.display_Inner();
23.	   }
24.	}

 Now you will get the correct output,

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

4.Nested Methods

Some recent programming languages, like Python, supports nested methods but Java does not allow to make a method inside another method.  You will encounter the illegal start of expression java error if you try to create nested methods.

Below mentioned is a small 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 Result:" + calSum(x, y));
4.	        public int calSum ( int num1, int num2) {
5.	            return num1 + num2;
6.	        }
7.	    }
8.	}

 And here is the output,

$ javac classA.java
NestedMethod.java:6: error: illegal start of expression
        public int calSum ( int num1, int num2) {
        ^
classA.java:6: error: ';' expected
        public int calSum ( int num1, int num2) {
                          ^
classA.java:6: error:  expected
        public int calSum ( int num1, int num2) {
                                   ^
NestedMethod.java:6: error: not a statement
        public int calSum ( int num1, int num2) {
                                           ^
NestedMethod.java:6: error: ';' expected
        public calSum ( int num1, int num2) {
                                         ^
5 errors

The Java compiler has reported five compilation errors. Other 4 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 cause multiple further errors during compile time. Same is the case here. We can easily solve all the errors by just avoiding the nesting of methods. The best 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 below,

1.	public class classA {
2.	    public void outputSum(int num1, int num2) {
3.	        System.out.println("Calculation Result:" + calSum(x, y));
4.	    }
5.	    public int calSum ( int num1, int num2) {
6.	        return x + y;
7.	    }
8.	}

5. Missing out the Curly “{ }“ Braces

Skipping a curly brace in any method can result in an illegal start of expression java error. According to the syntax of Java programming, every block or class definition must start and end with curly braces. If you skip any curly braces, the compiler will not be able to identify the starting or ending point of a block which will result in an error. Developers often make this mistake because there are multiple blocks and methods nested together which results in forgetting closing an opened curly bracket. IDEs usually prove to be helpful in this case by differentiating the brackets by assigning each pair a different colour and even identify if you have forgotten to close a bracket but sometimes it still gets missed and result in an illegal start of expression java error.

In the following code snippet, consider this class called Calculator, a method called calSum perform addition of two 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.

1.	public class Calculator{
2.	  public static void calSum(int x, int y) {
3.	    int total = 0;
4.	    total = x + y;
5.	    System.out.println("Sum = " + total);
6.	 
7.	  public static void main(String 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 start of expression public int calcSum(int x, int y) { ^ 
Calculator.java:12: error: ';' expected 
 
Calculator.java:13: error: reached end of file while parsing
}
 ^
3 error

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

While writing your code missing a single curly bracket can take up a lot of time in debugging especially if you are a beginner so always lookout for it.

6. String or Character Without Double Quotes “-”

Just like missing a curly bracket, initializing string variables without using double quotes is a common mistake made by many beginner Java developers. They tend to forget the double quotes and later get bombarded with multiple errors at the run time 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 result in a “cannot find symbol” error if the “variable” is not declared but if you miss the double-quotations around a string that is not a valid Java variable name, it will be reported as the illegal start of expression Java error.

The compiler read the String variable as a sequence of characters. The characters can be alphabets, numbers or special characters every symbol key on your keyboard can be a part of a string. 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 in the code as closing quotes and all that code in between as a string causing the error.

Consider this code snippet below; the missing quotation marks around the values of the operator within if conditions will generate errors at the run time.

1.	public class Operator{
2.	  public static void main(String args[]){
3.	    int num1 = 10;
4.	    int num2 = 8;
5.	    int output = 0; 
6.	    Scanner scan = new Scanner(System.in);
7.	    System.out.println("Enter the operation to perform(+OR)");
8.	    String operator= scan.nextLine();
9.	    if(operator == +)
10.	  {
11.	     output = num1 + num2;
12.	  }
13.	  else if(operator == -)
14.	  {
15.	     output = num1 - num2;
16.	  }
17.	  else
18.	  {
19.	     System.out.prinln("Invalid Operator");
20.	  }
21.	  System.out.prinln("Result = " + output); 
22.	}

String values must be always enclosed in double quotation marks to avoid the error similar to what this code would return, 

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

Conclusion

In a nutshell, to fix an illegal start of expression error, look for mistakes before the line mentioned in the error message for missing brackets, curly braces or semicolons. Recheck the syntax as well. Always look for the root cause of the error and always recompile every time you fix a bug to check as it 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 have the required knowledge of the syntax, the rules and restrictions in java programming and the good programming skills than you can easily minimize the frequency of this error in your code and in case if it occurs you would be able to quickly remove it.

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

new Java jobs

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

When you compile code in java, and you have an error, it show you the error. One of the errors is «not a statement».


IO.java

String firstName = console.readLine ("What is your first name?") ;
String lastName = console.readLine ("What is your last name?");
  console.printf = ("First name %s"); firstName;
//The console.printf part has the error on it.

3 Answers

Shadd Anderson June 14, 2016 1:34am

When forming a printf statement, the format is («sentence with placeholders«,objects to replace placeholders);

In other words, instead of closing the parentheses and separating «firstName» with a semicolon, simply place a comma after the quotes, then put firstName, and then close the parentheses.

console.printf("First name: %s",firstName);

Jason Anders

MOD

Hey Christina,

There are a few things wrong with the printf line:

  • console.printf is a method and cannot have an equal sign. As you have it, it’s trying to assign the string as a variable to the method, which can’t be done.

  • The firstName variable needs to be inside of the parenthesis in order for it to be attached to the placeholder.

  • You have a semi-colon where a comma should be.

Below is the correct line of code for you to review. I hope it makes sense. :)

console.printf("First name: %s", firstName);

Keep Coding! :dizzy:

Philip Gales June 14, 2016 1:38am

line 3 you used firstName;. This not a statement even though it is well-dressed. Below is the code you need for the challenge, make sure you understand line 3 as I have fixed it. I assume you placed the firstName outside of the last closing parenthesis because it told you (when you use console.printf = (); it will not let you use the formatted %s properly and will show random errors).

String firstName = console.readLine ("What is your first name?") ;
String lastName = console.readLine ("What is your last name?");
console.printf("First name: %s", firstName); 
console.printf("Last name: %s", lastName); 

A «compile-time» error is one which prevents your code from compiling. This page describes 14 of the most common errors you will encounter. Compile-time errors are divided into three categories:

  1. Lexical: These generally occur when you include disallowed characters in your code (e.g. int #people = 10;).
  2. Syntactical: These occur when your code is «out of order» (e.g. for (int i=0; i++; i<10)).
  3. Semantic: These occur when the meaning of your code is unclear (e.g. two variables with the same name).

Note that the exact wording of these errors may vary, depending on which development environment you are using.

Errors described on this page (click to jump to that error):

  1. Cannot return a value from a method of type void
  2. ‘Class’ or ‘interface’ expected
  3. Class should be delcared abstract; it does not define…
  4. Else without if
  5. Expected: ;, {, }, (, or )
  6. Identifier expected / Illegal character
  7. Incompatible types / Inconvertible types (cannot cast)
  8. Method does not return a value / Missing return statement
  9. Method not found
  10. Not a statement
  11. Return type required
  12. Unreachable statement
  13. Variable already defined
  14. Variable not declared

Cannot return a value from a method of type void

When a method is declared as having a return type of void, it cannot contain any return statements which return a value (it can, however, contain a return statement by itself, which will simply end the execution of the method). This problem is usually caused by accidentally making a method be of type void when it shouldn’t be or by accidentally including a return statement where there shouldn’t be one.

Example 1: Incorrect Code Example 1: Fixed Code

This method has a return type of void and so it may not return any values.

We change the return type of this method in order to fix the problem.

01  public void getName()
02  {   return this.name;
03  }
01  public String getName()
02  {   return this.name;
03  }


‘Class’ or ‘interface’ expected

This error will most likely be caused when you omit the keyword class or interface, as seen in the example below.

Example 1: Incorrect Code Example 1: Fixed Code

Here, we do not have either keyword present.

We add in class or interface, depending on our intentions within the program.

01  public Test
02  {
03      public void someMethod()
04      {   System.out.println("Hello, world!");
05      }
06  }
01  public class Test
02  {
03      public void someMethod()
04      {   System.out.println("Hello, world!");
05      }
06  }

— OR —

01  public interface Test
02  {
03      public void someMethod();
04  }

Class should be delcared abstract; it does not define…

This error arises when implementing an interface. Recall that when you say implements SomeInterface for a certain class, you guarantee that you have written all of the methods specified within that interface. If you are missing at least one of the methods which is listed in the interface, Java will not let your code compile.

As an example, consider an interface TestInterface which looks like:

public interface TestInterface
{
  public int methodOne();
  public String methodTwo(String z);
  public boolean methodThree();
}

Using TestInterface, consider the following example.

Example 1: Incorrect Code Example 1: Fixed Code

We receive an error message in this case because we implement TestInterface but do not include methodThree().

To allow this program to compile, we add in a «stub» for the required method. This is the quick way around the problem: in most cases, you will want to actually write a method body for this method so that it does what it was intended to do.

01  public class Test implements TestInterface
02  {
03      private int y = 700;
04  
05      public int methodOne()
06      {   int x = this.y - 1;
07          return x;
08      }
09  
10      public String methodTwo(String z)
11      {   String label = "Val: " + z;
12          return label;
13      }
14  }
01  public class Test implements TestInterface
02  {
03      private int y = 700;
04  
05      public int methodOne()
06      {   int x = this.y - 1;
07          return x;
08      }
09  
10      public String methodTwo(String z)
11      {   String label = "Val: " + z;
12          return label;
13      }
14
15      public boolean methodThree()
16      {   return false;
17      }
18  }

Note that when you are implementing methods in the interface, the method signatures must match exactly. That is, if the interface expects that you implement a method public String longer(String a, String b), then you must write a method with exactly the same name, exactly the same return type, and exactly the same parameters (in this case, two Strings).


Else without if

This error occurs when you have an else or else if clause without an if clause above it. This is most likely because you have accidentally forgotten/added extra { or } braces, or you have placed an else clause in the wrong place, as illustrated in the example below. The key idea is that every else clause needs to have an associated if clause which occurs before it.

Example 1: Incorrect Code Example 1: Fixed Code

Here, we have accidentally placed the else clause within the if clause.

We place the else clause after the if clause, which correctly associates them.

01  String text = "abaaba";
02    
03  if (text.length() >= 6)
04  {   text += text;    
05  else
06  {   text += text.substring(3);
07  }
08  }
01  String text = "abaaba";
02    
03  if (text.length() >= 6)
04  {   text += text;
05      
06  }
07  else
08  {   text += text.substring(3);
09  }

Expected: ;, {, }, (, or )

Java is very specific about use of characters such as semicolons, brackets, or braces. Forgetting a semicolon is the simplest of these errors, and is fixed by placing a semicolon at the end of the line which causes the error. Brackets can be more complicated, because you may have to read through several nested if statements or loops in order to make sure that all brackets «match up» with each other properly. This is one of the reasons why indenting your code properly is a good idea.

Example 1: Incorrect Code Example 1: Fixed Code

Here, lines 6, 7, and 10 will give us compile-time errors because we have forgot to include brackets, a semicolon, and a close-brace respectively.

We add these in to fix the problems.

01  public class Test
02  { 
03      public void getName()
04      {   int k = 10;  
05    
06          if k == 10
07          { k++
08          }
09      }
10
01  public class Test
02  { 
03      public void getName()
04      {   int k = 10;  
05    
06          if (k == 10)
07          { k++;
08          }
09      }
10  }

Identifier expected / Illegal character

An identifier is another term for a variable. In Java, every variable name must begin with a letter/underscore and can then have any combination of letters, numbers, and underscores. The example below illustrates two cases you may run into.

Example 1: Incorrect Code Example 1: Fixed Code

The variable name 10Names is not allowed because it begins with a number. The variable name wtPer#ofPeople is not allowed bacause it contains a pound sign.

To fix this, we change these to valid variable names.

01  private String[] 10Names;
02  private int wtPer#ofPeople;
01  private String[] tenNames;
02  private int wtPerNumberOfPeople;


Incompatible types / Inconvertible types (cannot cast)

In a Java assignment statement, the type of the variable on the left hand side must be the same as the type of the variable on the right hand side (or it needs to be able to be cast first in order to make it work). The example below would give three ‘incompatible types’ error messages.

Example 1: Incorrect Code Example 1: Fixed Code

Lines 5, 6, and 7 all give us errors. This is because an int cannot be assigned to a String, a boolean cannot be assigned to an int, and a String cannot be assigned to a boolean, respectively.

We change these three statements so that the primitive type / Object type is the same on both sides of the assignment (=) sign.

01  String theAge = "Twenty-two";
02  int x = 22;
03  boolean b = false;
04    
05  theAge = x;
06  x = b;
07  b = theAge;
01  String theAge = "Twenty-two";
02  int x = 22;
03  boolean b = false;
04    
05  theAge = "Thirty-three";
06  x = 33;
07  b = true;

Note that one common exception to this rule is that an int value can be assigned to a char value and vice-versa (this is because every character is actually represented as an integer ASCII value).

This error may also occur when trying to pass a value of one type into a method which expects another. An example of this is below.

Example 2: Incorrect Code Example 2: Fixed Code

Here, we try to pass a String as an actual parameter into a method which has an int as its formal parameter (these two types are incompatible).

To fix this, we change the type of the variable which is being passed. Alternately, we could have also changed the type of the actual parameter to be a String and then re-coded the method calcNewAge accordingly.

01  String theAge = "Twenty-two";
02  int result = calcNewAge(theAge);
03  
04  public int calcNewAge(int theAge)
05  {   return theAge / 2 + 7;
06  }
01  int theAge = 22;
02  int result = calcNewAge(theAge);
03  
04  public int calcNewAge(int theAge)
05  {   return theAge / 2 + 7;
06  }

You may also get a similar error if you are attempting to cast incorrectly. Recall that a primitive type may not be cast to an object or vice-versa. When casting between two objects, recall that object «A» may be cast to be of the same type as object «B» only if B’s class extends A’s class. As an example, consider a class Cat which extends the class Animal.

Example 3: Incorrect Code Example 3: Fixed Code

Here, lines 2 and 3 are incorrect attempts at casting because neither Animal nor String are subclasses of Cat.

Line 2 is a correct cast because Cat is a subclass of Animal (a Cat is an Animal, but an Animal is not necessarily a Cat).

01  Cat c = new Cat("Sparky", "black");
02  Animal a = (Animal) c;
03  String theCat = (String) c;
01  Animal a = new Animal("Sparky");
02  Cat c = (Cat) a;

Method does not return a value / Missing return statement

In Java, every method which does not have a return type of void must have at least one return statement.

Example 1: Incorrect Code Example 1: Fixed Code

The return type of this method is String, so Java expects that we have a return statement which returns a value with this type. As written, this method does not return anything.

Instead of printing these values to the screen, we return them.

01  public String getFortune()
02  {   if (this.age >= 19)
03      {   System.out.println("Good times ahead");
04      } 
05      else
06      {   System.out.println("Hailstorms unavoidable");
07      }
08  }
01  public String getFortune()
02  {   if (this.age >= 19)
03      {   return "Good times ahead";
04      } 
05      else
06      {   return "Hailstorms unavoidable";
07      }
08  }

This compile-time error can have a very subtle point which is often overlooked. If the return type of a method is not void, Java needs to ensure that the method will return a value in every possible case. That is, if all of your return statements are nested within if statements, Java will disallow the compilation process to continue because there is a chance that no return statement will be reached. The example below illustrates this.

Example 2: Incorrect Code Example 2: Fixed Code

In this example, we get a compile-time error because Java sees a possibility of this method not returning a value (if this.age is 99, for example).

To fix this, we ensure that the method will return a value in all possible cases by adding an else clause.

01  public String chatMethod()
02  {   if (this.age <= 18)
03      {   return "MSN";
04      } 
05      else if (this.age > 19 && this.age <= 30)
06      {   return "ICQ";
07      }
08  }

01  public String chatMethod()
02  {   if (this.age <= 18)
03      {   return "MSN";
04      } 
05      else if (this.age > 19 && this.age <= 30)
06      {   return "ICQ";
07      }
08      else
09      {   return "BBS";
10      }
11  }

Note that an easy way to «fix» this error is to simply add a meaningless return statement at the end of the method, such as return -1; or return null;. This often leads to problems elsewhere, such as causing the method to return unintended values.


Method not found

In Java, recall that a method’s signature consists of the method’s name and the types of its actual parameters. For example, the method public void move(int howFar) has the signature move(int). When a method call is made, a method with a signature exactly matching that of the method call must exist (e.g. the method name, the number of parameters, and the types of all parameters must match exactly). This error is illustrated below.

Example 1: Incorrect Code Example 1: Fixed Code

Line 3 calls a method which has signature larger(String, String). However, the method at line 5 has signature larger(int, int). These two signatures do not match (e.g. there exists no method with signature larger(String, String)), so an error is produced.

To fix this, we can modify the larger so that it has a matching signature to our method call. Alternately, we could have left the current method alone and written another (overloaded) method with the appropriate signature.

01  String first = "CN Tower";
02  String second = "Calgary Tower";
03  String res = this.larger(first, second);
04  
05  public int larger(int a, int b)
06  {   if (a > b)
07      {   return a;
08      } else
09      {   return b;
10      }
11  }
01  String first = "CN Tower";
02  String second = "Calgary Tower";
03  String res = this.larger(first, second);
04  
05  public String larger(String a, String b)
06  {   if (a.length() > b.length())
07      {   return a;
08      } else
09      {   return b;
10      }
11  }

Also note that this error may occur if you do not have the correct import statements at the top of your class.


Not a statement

Each line of Java code must have some sort of meaningful purpose. The compile-time error «not a statement» is usually the result of typing only part of a statement, leaving it incomplete and meaningless. One example of how this may occur (there are many) is seen below. In general, asking yourself «what was I trying to do with this line of code?» is sufficient to fix the problem.

Example 1: Incorrect Code Example 1: Fixed Code

Line 5 will cause the error in this case, as the line grades[1]; is completely meaningless by itself, as it does not give any instruction to the compiler.

We change this line to be a valid, meaningful statement («set the value of x to be the value of the array grades at element 1″). This is just one possible way of fixing the problem (it depends on how you intend things to work).

01  int grades[] = new int[2];
02  int x;
03  grades[0] = 96;
04  grades[1] = 93;
05  grades[1];
06  System.out.println(x);

01  int grades[] = new int[2];
02  int x;
03  grades[0] = 96;
04  grades[1] = 93;
05  x = grades[1];
06  System.out.println(x);

Return type required

For each method, Java requires a return type (e.g. String, int, boolean). Note that void is also considered to be a «return type» even though a method with a void return type does not return a value.

Example 1: Incorrect Code Example 1: Fixed Code

An error is caused because the theAnswer() method does not have a declared return type.

Two possible solutions to this problem are suggested (each would depend on the context of how the method is to be actually used in your program).

01  private theAnswer()
02  {   System.out.println("42");
03  }
01  private void theAnswer()
02  {   System.out.println("42");
03  }

— OR —

01  private int theAnswer()
02  {   return 42;
03  }

Unreachable statement

This error usually occurs if you have a statement placed directly after a return statement. Since Java executes code line-by-line (unless a method call is made), and since a return statement causes the execution of the program to break out of that method and return to the caller, then anything placed directly after a return statement will never be reached.

Example 1: Incorrect Code Example 1: Fixed Code

Line 4 is directly after a return statement, so it cannot be reached because the method will end at line 3.

We switch lines 3 and 4 to ensure that nothing is after the return statement.

01  public String oneMoreA(String orig)
02  {   String newStr = orig + "A";
03      return newStr;
04      this.counter++;
05  }
01  public String oneMoreA(String orig)
02  {   String newStr = orig + "A";
03      this.counter++;

04      return newStr;
05  }

You (may) also get this error if you place a statement outside of a method, which could be the result of { and } braces not being matched up properly.


Variable already defined

This compile-time error is typically caused by a programmer attempting to declare a variable twice. Recall that a statment such as int temp; declares the variable named temp to be of type int. Once this declaration has been made, Java can refer to this variable by its name (e.g. temp = 15;) but does not let the programmer declare it a second time by including the variable type before the name, as seen in the example below.

Example 1: Incorrect Code Example 1: Fixed Code

Here, we have declared the variable temperature twice: once at line 3 and then again at line 6.

We have fixed the problem by only declaring the variable once (at line 3) and we refer only to the variable’s name on line 6.

01  int a = 7;
02  int b = 12;
03  int temperature = Math.max(a, b);
04    
05  if (temperature > 10)
06  {   int temperature = 0;
07  }
01  int a = 7;
02  int b = 12;
03  int temperature = Math.max(a, b);
04    
05  if (temperature > 10)
06  {   temperature = 0;
07  }

You may also get this error if you have tried to declare two variables of different types using the same variable name (in Java, every variable must have a unique name). The example below illustrates this using two variables of type int and String.

Example 2: Incorrect Code Example 2: Fixed Code

Here we are trying to declare two variables using the same variable name of temperature. This is not allowed, regardless of the types of the variables.

We fix the problem by ensuring that each variable has a unique name.

01  int temperature = 22;
02  String temperature = "Hot Outside";
01  int temperature = 22;
02  String tempDescription = "Hot Outside";

The only time where repetition of variable names or declarations are allowed is if the two variables are in different scopes. Recall that the scope of a variable is determined by the set of braces, { and }, in which it is enclosed. This is illustrated in the two examples below.

Example 3: Correct Code Example 4: Correct Code

This is allowed because the delarations on lines 4 and 7 are being done within different scopes. One is within the scope of the if statement, and the other is within the scope of the else if statement.

Similarly, this is also allowed because temp is declared in two different methods and will therefore be done within different scopes.

01  int temp = 22;
02
03  if (temp >= 20)
04  {   String desc = "Hot";
05  }
06  else if (temp >= 10 && temp < 20 )
07  {   String desc = "Nice";
08  }

01  public void cold()
02  {   int temp = -27;
03  }
04
05  public void hot()
06  {   int temp = 27;
07  }

Variable not declared

This error occurs when a variable is not declared within the same (or an «outer») scope in which it is used. Recall that the scope of a variable declaration is determined by its location with { and } braces. The example below illustrates a simple case of this error. To fix this problem, make sure that the variable is declared either in the same scope in which it is being used, or it being delcared in an «outer» scope.

Example 1: Incorrect Code Example 1: Fixed Code

The variable balance is declared within the scope of the first if statement, so line 9 will cause an error.

To fix the problem, we declare balance in the scope of the entire method so that it can be referred to in all places within the method.

01  boolean newAcct = true;
02  double deposit = 17.29;
03    
04  if (newAcct == true)
05  {   double balance = 100.0;
06  }
07    
08  if (deposit > 0)
09  {   balance += deposit;
10  }
01  boolean newAcct = true;
02  double deposit = 17.29;
03  double balance = 0;

04    
05  if (newAcct == true)
06  {   balance = 100.0;
07  }
08    
09  if (deposit > 0)
10  {   balance += deposit;
11  }

Return to Main Page

Created by Terry Anderson (tanderso at uwaterloo dot ca) for use by ISG, Spring 2005

Error when running the following code:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
/**
 * Determination of score levels
 * Use the nesting of conditional operators to complete this question: students with an >=90 academic score are represented by A, those between 60-89 are represented by B, and those below 60 are represented by C.
 * (a>b)?a:b This is a basic example of a conditional operator
*/

class ClassifyGrade
{
	public static void main(String[] args)
	{
		System.out.println("Please enter the score for a particular student.");
		Scanner aInt = new Scanner(System.in);
		int score = aInt.nextInt();			// This way we have a score to experiment with
		String grade = classify(score);
		System.out.println(grade);
	}
	public static String classify(int n)
	{
		n>=90?(grade = "A"):(n>=60?(grade = "B"):(grade = "C"));
		return grade;
	
	}
}

Error:

Main.java:26: error: not a statement
		n>=90?(grade = "A"):(n>=60?(grade = "B"):(grade = "C"));
		     ^
1 error

The reason for the mistake is:
Java ternary operator?: different from C++
In Java, N> = 90?(grade = “A”):(n> = 60?(grade = “B”):(grade = “C”)); This is just an expression, not a statement,
There are specific requirements for expressions in JAVA. Namely: expression E;
To form an expression statement, the expression E must only be :
1) assignment expression,
2) autoincrement ++ expression,
3) autodecrement — expression,
4) method call expression,
5)new expression (object creation expression)
The following statement is easier to understand:
Conditional statement?[expression 1] : [expression 2] where expression 1 is executed if the conditional statement is true, otherwise expression 2 is executed. Expression 1 or expression 2 should have a return value, which means that expression 1 or expression 2 can be some value, such as the integer 123. In my code, grade = “B” is an assignment statement that cannot return any value.

Correct code:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
/**
 * Determination of score levels
 * Use the nesting of conditional operators to complete this question: students with an >=90 academic score are represented by A, those between 60-89 are represented by B, and those below 60 are represented by C.
 * (a>b)?a:b This is a basic example of a conditional operator
*/

class ClassifyGrade
{
	public static void main(String[] args)
	{
		System.out.println("Please enter the score for a particular student.");
		Scanner aInt = new Scanner(System.in);
		int score = aInt.nextInt();			//This way we have a score to experiment with
		String grade = classify(score);
		System.out.println(grade);
	}
	public static String classify(int n)
	{
		String grade = n>=90?"A":(n>=60?"B":"C");
		return grade;
	}
}

See the reference post:
Why can’t the ternary operator stand alone as a sentence, but a method that returns a value can stand alone as a sentence?

Read More:

Автор оригинала: Kai Yuan.

1. Обзор

“Незаконное начало выражения”-это распространенная ошибка, с которой мы можем столкнуться во время компиляции.

В этом уроке мы рассмотрим примеры, иллюстрирующие основные причины этой ошибки и способы ее устранения.

2. Отсутствующие Фигурные Скобки

Отсутствие фигурных скобок может привести к ошибке “незаконное начало выражения”. Давайте сначала рассмотрим пример:

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Если мы скомпилируем вышеуказанный класс:

$ javac MissingCurlyBraces.java
MissingCurlyBraces.java:7: error: illegal start of expression
        public int calcSum(int x, int y) {
        ^
MissingCurlyBraces.java:7: error: ';' expected
        public int calcSum(int x, int y) {
   .....

Отсутствие закрывающей фигурной скобки print Sum() является основной причиной проблемы.

Решение проблемы простое — добавление закрывающей фигурной скобки в метод printSum() :

package com.baeldung;

public class MissingCurlyBraces {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum(int x, int y) {
        return x + y;
    }
}

Прежде чем перейти к следующему разделу, давайте рассмотрим ошибку компилятора.

Компилятор сообщает, что 7-я строка вызывает ошибку “незаконное начало выражения”. На самом деле, мы знаем, что первопричина проблемы находится в 6-й строке. Из этого примера мы узнаем, что иногда ошибки компилятора не указывают на строку с основной причиной , и нам нужно будет исправить синтаксис в предыдущей строке.

3. Модификатор Доступа Внутри Метода

В Java мы можем объявлять локальные переменные только внутри метода или конструктора . Мы не можем использовать модификатор доступа для локальных переменных внутри метода, поскольку их доступность определяется областью действия метода.

Если мы нарушим правило и у нас будут модификаторы доступа внутри метода, возникнет ошибка “незаконное начало выражения”.

Давайте посмотрим на это в действии:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        private int sum = x + y; 
        System.out.println("Calculation Result:" + sum);
    }
}

Если мы попытаемся скомпилировать приведенный выше код, мы увидим ошибку компиляции:

$ javac AccessModifierInMethod.java 
AccessModifierInMethod.java:5: error: illegal start of expression
        private int sum = x + y;
        ^
1 error

Удаление модификатора private access легко решает проблему:

package com.baeldung;

public class AccessModifierInMethod {
    public void printSum(int x, int y) {
        int sum = x + y;
        System.out.println("Calculation Result:" + sum);
    }
}

4. Вложенные методы

Некоторые языки программирования, такие как Python, поддерживают вложенные методы. Но, Java не поддерживает метод внутри другого метода.

Мы столкнемся с ошибкой компилятора “незаконное начало выражения”, если создадим вложенные методы:

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
        public int calcSum ( int x, int y) {
            return x + y;
        }
    }
}

Давайте скомпилируем приведенный выше исходный файл и посмотрим, что сообщает компилятор Java:

$ javac NestedMethod.java
NestedMethod.java:6: error: illegal start of expression
        public int calcSum ( int x, int y) {
        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                          ^
NestedMethod.java:6: error:  expected
        public int calcSum ( int x, int y) {
                                   ^
NestedMethod.java:6: error: not a statement
        public int calcSum ( int x, int y) {
                                        ^
NestedMethod.java:6: error: ';' expected
        public int calcSum ( int x, int y) {
                                         ^
5 errors

Компилятор Java сообщает о пяти ошибках компиляции. В некоторых случаях одна ошибка может привести к нескольким дальнейшим ошибкам во время компиляции.

Выявление первопричины имеет важное значение для того, чтобы мы могли решить эту проблему. В этом примере первопричиной является первая ошибка “незаконное начало выражения”.

Мы можем быстро решить эту проблему, переместив метод calcSum() из метода print Sum() :

package com.baeldung;

public class NestedMethod {
    public void printSum(int x, int y) {
        System.out.println("Calculation Result:" + calcSum(x, y));
    }
    public int calcSum ( int x, int y) {
        return x + y;
    }
}

5. символ или строка Без кавычек

Мы знаем, что String литералы должны быть заключены в двойные кавычки, в то время как char значения должны быть заключены в одинарные кавычки.

Если мы забудем заключить их в соответствующие кавычки, компилятор Java будет рассматривать их как имена переменных .

Мы можем увидеть ошибку “не удается найти символ”, если “переменная” не объявлена.

Однако если мы забудем дважды заключить в кавычки Строку , которая не является допустимым именем переменной Java , компилятор Java сообщит об ошибке “незаконное начало выражения” .

Давайте посмотрим на это на примере:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals(+)) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

Мы забыли процитировать строку |//+ внутри вызова метода equals , и + , очевидно, не является допустимым именем переменной Java.

Теперь давайте попробуем его скомпилировать:

$ javac ForgetQuoting.java 
ForgetQuoting.java:5: error: illegal start of expression
        if (operation.equals(+)) {
                              ^
1 error

Решение проблемы простое — обертывание String литералов в двойные кавычки:

package com.baeldung;

public class ForgetQuoting {
    public int calcSumOnly(int x, int y, String operation) {
        if (operation.equals("+")) {
            return x + y;
        }
        throw new UnsupportedOperationException("operation is not supported:" + operation);
    }
}

6. Заключение

В этой короткой статье мы рассказали о пяти различных сценариях, которые приведут к ошибке “незаконное начало выражения”.

В большинстве случаев при разработке приложений Java мы будем использовать среду IDE, которая предупреждает нас об обнаружении ошибок. Эти замечательные функции IDE могут значительно защитить нас от этой ошибки.

Тем не менее, мы все еще можем время от времени сталкиваться с этой ошибкой. Поэтому хорошее понимание ошибки поможет нам быстро найти и исправить ошибку.

Понравилась статья? Поделить с друзьями:
  • Error no forward proxy ports configured squid ubuntu
  • Error nonetype object is not iterable симс 4
  • Error no domain set
  • Error nonetype object has no attribute getvalidatorstatus
  • Error object reference not set to an instance of an object veeam