Not a statement java ошибка что значит

I am new to java programming. I tried hello world program, but I got an error «not a statement«. Whereas when I copy, paste the hello world program from the internet, my program compiled. This is the program I used. What is meant by «not a statement«, please explain why I got this error and what is meant by it and what should I look for when I get this error in the future. Thanks!

public class hello
{
    public static void main(String args[]) {    
        System.out.println(“hello world”);
    }
}

My errors:-

hello.java:8: error: illegal character: '\u201c'
       System.out.println(“hello world”);
                          ^
hello.java:8: error: ';' expected
       System.out.println(“hello world”);
                           ^
hello.java:8: error: illegal character: '\u201d'
       System.out.println(“hello world”);
                                         ^
hello.java:8: error: not a statement
       System.out.println(“hello world”);
                                 ^
4 errors

Shar1er80's user avatar

Shar1er80

9,0012 gold badges20 silver badges29 bronze badges

asked Jul 6, 2018 at 15:38

Goku's user avatar

3

You code cannot contain smart quotes like your used in your «Hello World». I replaced your smart/fancy quotes with the correct kind.

public class hello
{
    public static void main(String args[]) {    
        System.out.println("hello world");
    }
}

answered Jul 6, 2018 at 15:47

Matthew S.'s user avatar

Matthew S.Matthew S.

3211 gold badge9 silver badges22 bronze badges

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

207k23 gold badges220 silver badges275 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

198k20 gold badges159 silver badges250 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

36.4k8 gold badges49 silver badges73 bronze badges

Java — Compiler Error «Error: not a statement»

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);

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

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

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); 

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

Понравилась статья? Поделить с друзьями:
  • Nosuchelementexception selenium вывод ошибки
  • Novel2002 ошибки богов
  • Nordac 500e ошибки
  • Novex стиральная машина коды ошибок
  • Normacs ошибка 1067