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());
-
3If you're getting compile errors your code is, almost by definition, NOT syntactically correct.Jim Garrison– Jim Garrison2016年02月01日 07:59:19 +00:00Commented Feb 1, 2016 at 7:59
-
Thanks I feel stupid! Didn't really notice that my lambda expression was outside the Main code blockalcaideredb– alcaideredb2016年02月01日 08:00:50 +00:00Commented Feb 1, 2016 at 8:00
3 Answers 3
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
Konstantin Yovkov
63k9 gold badges107 silver badges152 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Mohammed Aouf Zouag
17.2k4 gold badges44 silver badges68 bronze badges
1 Comment
alcaideredb
Thanks! I didn't notice that! :)
runner.run(() -> System.out.println()); -- is outside main method. Put the code inside the main method and it will work perfectly fine.
lang-java