'Java: Identifier expected

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


Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

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

Solution 4:[4]

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

    }

Solution 5:[5]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bohemian
Solution 2 Tudor
Solution 3 geekosaur
Solution 4 Jonathan Payne
Solution 5 Eliezer Miron