0

I'm trying out the following code and compiling it using JDK 1.8.0_66. My code seems to be syntactically correct, did I miss something?

interface Executable {
 void execute();
}
class Runner {
 public void run(Executable e) {
 System.out.println("Executing code block!");
 e.execute();
 }
}
public class HelloWorld {
 public static void main(String[] args) {
 Runner runner = new Runner();
 runner.run(new Executable() {
 public void execute() {
 System.out.println("IN ANONYMOUS CLASS EXECUTE");
 }
 });
 }
 runner.run(() -> System.out.println());
}

throws the following compile error:

App.java:25: error: <identifier> expected
 runner.run(() -> System.out.println());
 ^
App.java:25: error: illegal start of type
 runner.run(() -> System.out.println());
 ^
App.java:25: error: ';' expected
 runner.run(() -> System.out.println());
asked Feb 1, 2016 at 7:55
2
  • 3
    If you're getting compile errors your code is, almost by definition, NOT syntactically correct. Commented Feb 1, 2016 at 7:59
  • Thanks I feel stupid! Didn't really notice that my lambda expression was outside the Main code block Commented Feb 1, 2016 at 8:00

3 Answers 3

4

Your statement is outside the block, where the runnner variable is defined. Should be something like:

public static void main(String[] args) {
 Runner runner = new Runner();
 runner.run(new Executable() {
 public void execute() {
 System.out.println("IN ANONYMOUS CLASS EXECUTE");
 }
 });
 runner.run(() -> System.out.println());
}
answered Feb 1, 2016 at 7:57
Sign up to request clarification or add additional context in comments.

Comments

3

That line of code needs to be inside a code block. So you need to move it into the body of the main method:

Change

} // end of main
runner.run(() -> System.out.println());

to

 runner.run(() -> System.out.println());
} // end of main
answered Feb 1, 2016 at 7:57

1 Comment

Thanks! I didn't notice that! :)
0

runner.run(() -> System.out.println()); -- is outside main method. Put the code inside the main method and it will work perfectly fine.

answered Jan 23, 2017 at 17:07

2 Comments

This answer is already expressed and realized in the main post's comments
Thanks. But i didn't notice that. Rating down is not good attitude.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.