Identifier expected java ошибка

Learn how to fix the java error: identifier expected to get a better understanding of this error and being able to avoid in the future

Posted by Marta on November 21, 2021 Viewed 91034 times

Card image cap

In this article you will learn how to fix the java error: identifier expected to get a better understanding of this error and being able to avoid in the future.

This error is a very common compilation error that beginners frequently face when learning Java. I will explain what is the meaning of this error and how to fix it.

What’s the meaning of Identifier Expected error?

The identifier expected error is a compilation error, which means the code doesn’t comply with the syntax rules of the Java language. For instance, one of the rules is that there should be a semicolon at the end of every statement. Missing the semicolon will cause a compilation error.

The identifier expected error is also a compilation error that indicates that you wrote a block of code somewhere where java doesn’t expect it.

Here is an example of piece of code that presents this error:

public class Example {
	System.out.println("Hello");
}

If you try to compile this class, using the javac command in the terminal, you will see the following error:

Output:

Example.java:5: error: <identifier> expected
    System.out.println("Hello");
                      ^
Example.java:5: error: illegal start of type
    System.out.println("Hello");
                       ^

This error is slightly confusing because it seems to suggest there is something wrong with line 2. However what it really means is that this code is not in the correct place.

How to Fix it

We have seen what the error actually means, however how could I fix it? The error appears because I added some code in the wrong place, so what’s the correct place to right code? Java expects the code always inside a method. Therefore, all necessary to fix this problem is adding a class method and place the code inside. See this in action below:

public class Example {

    public void print() {
        System.out.println("Hello");
    }
}

The code above will compile without any issue.

Another example

Here is another example that will return the identifier expected error:

public class Example {

    public void print() {
        System.out.println("Hello");
    }

    Example e = new Example();
    e.print(); // Here is the error
}

Output:

Example.java:10: error: <identifier> expected
    e.print();
           ^

As before, this compilation error means that there is a piece of code: e.print() that is not inside a class method. You might be wondering, why line 7 ( Example e = new Example(); ) is not considered a compilation error? Variable declarations are allowed outside a method, because they will be considered class fields and their scope will be the whole class.

Here is a possible way to fix the code above:

public class Example {

    public void print() {
        System.out.println("Hello");
    }

    Example e = new Example();

    public void method2(){
        e.print();
    }
}

The fix is simply placing the code inside a method.

Conclusion

To summarise, this article covers how to fix the identifier expected java error. This compilation error will occur when you write code outside a class method. In java, this is not allow, all code should be placed inside a class method.

In case you want to explore java further, I will recommend the official documentation

Hope you enjoy the tutorial and you learn what to do when you find the identifier expected error. Thanks for reading and supporting this blog.

Happy coding!

More Interesting Articles

How to shuffle a string in java

How to open a web browser in python

Runnable vs Callable – Find out the differences

What is a mutator method in Java?

What’s the issue here?

class UserInput {
  public void name() {
    System.out.println("This is a test.");
  }
}

public class MyClass {
  UserInput input = new UserInput();
  input.name();
}

This complains:

<identifier> expected
   input.name();

asked May 11, 2012 at 22:52

randombits's user avatar

randombitsrandombits

46.2k74 gold badges249 silver badges426 bronze badges

3

Put your code in a method.

Try this:

public class MyClass {
    public static void main(String[] args) {
        UserInput input = new UserInput();
        input.name();
    }
}

Then «run» the class from your IDE

answered May 11, 2012 at 22:55

Bohemian's user avatar

You can’t call methods outside a method. Code like this cannot float around in the class.

You need something like:

public class MyClass {

  UserInput input = new UserInput();

  public void foo() {
      input.name();
  }
}

or inside a constructor:

public class MyClass {

  UserInput input = new UserInput();

  public MyClass() {
      input.name();
  }
}

answered May 11, 2012 at 22:54

Tudor's user avatar

TudorTudor

61.2k12 gold badges99 silver badges142 bronze badges

input.name() needs to be inside a function; classes contain declarations, not random code.

answered May 11, 2012 at 22:54

geekosaur's user avatar

geekosaurgeekosaur

58.1k11 gold badges120 silver badges112 bronze badges

Try it like this instead, move your myclass items inside a main method:

    class UserInput {
      public void name() {
        System.out.println("This is a test.");
      }
    }

    public class MyClass {

        public static void main( String args[] )
        {
            UserInput input = new UserInput();
            input.name();
        }

    }

answered May 11, 2012 at 22:56

Jonathan Payne's user avatar

I saw this error with code that WAS in a method; However, it was in a try-with-resources block.

The following code is illegal:

    try (testResource r = getTestResource(); 
         System.out.println("Hello!"); 
         resource2 = getResource2(r)) { ...

The print statement is what makes this illegal. The 2 lines before and after the print statement are part of the resource initialization section, so they are fine. But no other code can be inside of those parentheses. Read more about «try-with-resources» here: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

answered Sep 22, 2021 at 22:12

Eliezer Miron's user avatar

  1. Understanding <identifier> expected Error in Java
  2. Example 1: When Parameters in a Method Are Missing Data Type or Name
  3. Example 2: When the Expression Statements Are Misplaced
  4. Example 3: When Declaration Statements Are Misplaced
  5. Conclusion

Identifier Expected Error in Java

In this article, we will learn about Java’s <identifier> expected error.

Understanding <identifier> expected Error in Java

The <identifier> expected is the most common Java compile-time error faced by novice programmers. This error occurs when a method parameter does not have a data type or name declared or when an expression statement is written outside a method, a constructor, or an initialization block.

In Java, an identifier is a sequence of one or more characters where the 1st character must be a letter or $ or _, and the subsequent characters can be letters, digits, $ or _.

These identifiers are used to name a variable, a method, a class, a package, an interface, etc.

When the Java code is compiled initial phase involves lexical analysis of the program. Here the program is categorized into tokens, and all the tokens, including identifiers, are verified against a set of grammar rules.

And whenever as per grammar rules, an identifier is expected, but it’s not present, and something else is found in its place compiler raises the <identifier> expected error. Angle brackets here signify a reference to the token objects.

Let’s look at some examples to understand it better now.

Example 1: When Parameters in a Method Are Missing Data Type or Name

Parameters inside a method must have data followed by the variable name, which is an identifier; missing either of those will inevitably raise the <identifier> expected error.

  1. Data of the parameter is missing

    public class Demo
    {
        public static int square(x)
        {
            return x*x;
        }
    
        public static void main(String[] args)
        {
    
            System.out.println(square(10));
    
        }
    }
    

    Output:

    square.java:9: error: <identifier> expected
    public static int square(x) {
            	        	  ^
    1 error
    

    If we observe the error above, we see that variable x is missing the data type. If we give the data type for it, it will work properly.

    public class Demo
    {
    
            public static int square( int x)
            {
                return x*x;
            }
    
            public static void main(String[] args)
            {
    
                System.out.println(square(10));
    
            }
    }
    

    Output:

  2. The parameter’s data type is the identifier; the variable name is missing here.

    public class Demo
    {
    
        public static int square(int)
        {
            return x*x;
        }
    
        public static void main(String[] args)
        {
    
            System.out.println(square(10));
    
        }
    }
    

    Output:

    square.java:9: error: <identifier> expected
    public static int square(int) {
            	        	   ^
    1 error
    

    If we observe the error above, we can clearly see that we specified the data type but didn’t attach any variable name.

    public class Demo
    {
    
            public static int square( int x)
            {
            	return x*x;
            }
    
            public static void main(String[] args)
            {
    
            	System.out.println(square(10));
    
            }
    }
    

    Output:

Example 2: When the Expression Statements Are Misplaced

The compiler raises an error when an expression statement is written outside a method, a constructor or an initialization block <identifier> expected.

Example code:

public class Demo
{
    private String name;
    name = "Naruto";
    System.out.println(name);
}

Output:

Demo.java:9: error: <identifier> expected
  name = "Naruto";
      ^
Demo.java:10: error: <identifier> expected
  System.out.println(name);
                    ^
Demo.java:10: error: <identifier> expected
  System.out.println(name);
                        ^
3 errors

If we observe the error above, the error occurs because the statements are not enclosed within a function or a constructor. Let’s write these statements inside a method named print.

public class Demo {

    private String name;

    public void print()
    {
        name = "Naruto";
        System.out.println(name);
    }

    public static void main(String[] args) {

        Demo obj = new Demo();
        obj.print();

    }
}

Output:

Example 3: When Declaration Statements Are Misplaced

This is rare but not unheard of when working with try-with-resources statements. All these statements require that any closable resource be declared immediately after the try keyword.

If the resource variable is declared outside the try-with-resources statement, then the <identifier> expected error might be raised by the compiler (as compiler to compiler, this may vary).

Example code: Here, the closable resource is BufferedReader.

import  java.io.*;


public class Demo
{

        public static void main(String[] args) {
        StringBuilder obj = new StringBuilder();
        BufferedReader br = null;

        try (br = new BufferedReader(new InputStreamReader(System.in))){
            String lines = "";
            while (!(lines = br.readLine()).isBlank()) {
                obj.append(lines);
            }
        } catch(Exception e){
            e.printStackTrace();
        }


    }

}

Output:

Demo.java:13: error: <identifier> expected
        try (br = new BufferedReader(new InputStreamReader(System.in))) {
              ^
1 error

The error will be resolved if we declare the BufferedReader obj inside the try block.

import  java.io.*;


public class Demo
{

    public static void main(String[] args) {
        StringBuilder obj = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){

            String lines = "";
            while (!(lines = br.readLine()).isBlank()) {
                obj.append(lines);
            }
        } catch(Exception e){
            e.printStackTrace();
        }


    }

}

Conclusion

In this article, we learned about why the <identifier> expected error had been raised by the compiler and how it’s the most common compile-time error faced by newbies. We also looked at different examples analyzing the cases when this error was raised.

About Identifier Expected Error In Java

The “identifier expected” error in Java is, perhaps, a sensitive error which occurs in Java programming. This is also one of the most common errors that usually gets encountered by beginners who are still at the stage of learning the Java programming language and using it for creating applications, websites, etc.

Java Error Identifier Expected

Basically, an identifier in Java programming is one that recognises every syntax, characters, etc. Thus, in simple words, it means that the task of recognising any data in the code that is input by the programmer is done by the identifier. It checks for the code format as well as non-format characters at the compilation and/or execution phases and warns the programmer of incorrect entries in the code.

The reason why the identifier expected error occurs in Java and how you can resolve this is provided in this blog.

Why Does It Occur?

The identifier expected error in Java usually occurs when the programmer accidentally makes a mistake with the following:

  • Spelling

  • Keywords

  • Characters

  • Opening and closing curly braces “{}”

  • Variables

  • Declaring methods and/or classes

  • Upper-case and lower-case letters

  • Quoted text

Thus, due to such unintentional mistakes, however minor it may be, can eventually produce unwanted errors in your Java program. Therefore, because of this reason, you end up getting the identifier expected error in Java on your computer screen.

Error: <identifier> expected



(Description of error occurred is identified here)

The error message given above is similar to the one which usually occurs on the computer screens of the programmers who tend to input incorrect pieces of Java code, even though he or she is using an integrated development environment (IDE) such as Java Eclipse, Maven, NetBeans, etc.

Sometimes, it may also happen that when using a Java IDE for practising programming on your computer system, a single mistake or incorrect code can lead to errors. This could occur either during the compilation stage, or at the execution phase.

How To Fix Identifier Expected Error Java

If you are getting the identifier expected error in Java when compiling and/or executing your code and need quick tips to fix the error, we have the solution for you.

In order to prevent or fix the identifier expected error in Java, make sure you do the following checks:

  • Declare methods and classes accurately

  • Place messages appropriately inside double quotes

  • Extra or missing characters in the Java code

  • Every open curly bracket must have a closing curly bracket too

  • Use upper-case and lower-case letters properly (Java is a case-sensitive programming language)

  • Type spellings correctly

  • Assign variables correctly

  • Use keywords that exist in the Java language

These are the main suggestions that can help you deal with the identifier expected error in Java.

Get Support At Codexoxo – Contact Experts At

The solutions given above will help you resolve the “identifier expected” error in Java easily and quickly. Apart from the solutions given above, if you are still experiencing problems, or are getting other errors and issues with regards to Java programming, you can contact us to avail assistance from our Java experts at Codexoxo. Our support centre can be reached by dialling the toll-free phone number <enter-phone-number> round the clock.

Speak with our team of Java professionals today and get help immediately to resolve any issues and errors which you encounter in Java. Our experts can assist and guide you with tasks such as Java programming, developing websites and applications for desktop as well as mobile platform and much more.

I’am glad to see peaple learning Java, and i’am happy to see peaople helping the juniors.
When i see your code, my first advise is to get a good IDE like Eclipse, IntelliJ or Netbeans, it will help you to see quickly the compilation errors.

My second advise is to get a look to the dev norms, as a junior i think is the first methodology you have to study to have a comprehensive and maintainable code.

for example please avoid adding several blank lines between the method signature and the first statment.
I barely touched your code to get it works.
I hope you will enjoy Java.

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        intro(input);
        time(input);
    }

    public static void intro(Scanner input) {
        System.out.println("Welcome");
        System.out.println("What is your name");

        String name = input.nextLine();
        System.out.println("Nice to meet you, " + name + " where are you travelling to?");
        String dest = input.nextLine();
        System.out.println("Great! " + dest + " sounds like a great trip");
    }

    public static void time(Scanner input) {
        int hours, minutes;
        float perd, perdc, change;

        System.out.println("How many days are you going to spend travelling?");

        int days = input.nextInt();

        hours = days * 24;
        minutes = hours * 60;

        System.out.println("How much money in USD are you going to spend?");

        Float money = input.nextFloat();
        perd = money / days;

        System.out.println("What is the three letter currency symbol of your destination?");

        String curr = input.nextLine();

        System.out.println("How many " + curr + " are there in 1USD?");

        Float ex = input.nextFloat();
        change = money * ex;
        perdc = perd * ex;

        System.out.println("If you are travelling for " + days + " that is the same as " + hours + " or " + minutes + " minutes");
        System.out.println("If you are going to spend " + money + " $USD that means per day you can spend upto $" + perd + " USD");
        System.out.println("Your total budget in " + ex + " is " + change + ex + " ,which per day is  " + perdc + curr);
    }

Понравилась статья? Поделить с друзьями:
  • Ident error uninitiate golden media
  • Ident error uninitiate 8120 причина
  • Idea java compilation failed internal java compiler error
  • Iar fatal error pe1696 cannot open source file
  • Idea createprocess error 206 имя файла или его расширение имеет слишком большую длину