Search code examples
javalambda

Lambda expression in java not working


I'm tryig to make a lambda expresion for an ActionListener, but it's giving me an IllegalStart of expression, what i'm trying to run so far looks like this:

    JFrame frame = new JFrame();
    JButton boton = new JButton("Lambda Button");
    boton.addActionListener(event -> System.out.println("Hello World!"));
    frame.add(boton);

    frame.setVisible(true);

On the other hand, when i use this code instead:

JFrame frame = new JFrame();
    JButton boton = new JButton("Lambda Button");
    boton.addActionListener( new ActionListener() {
                                public void actionPerformed(ActionEvent e)
                                {
                                    System.out.println("Hello World!");
                                }
                                }   );
    frame.add(boton);
    frame.setVisible(true);

It works perfectly fine,

Initially i tought the issue could be the version of java i'm running, but i just updated and keeps doing the same, when i do a java -version i gives me the following:

java -version java version "1.8.0_45" Java(TM) SE Runtime Environment (build 1.8.0_45-b14) Java HotSpot(TM) Client VM (build 25.45-b02, mixed mode)

So, as far as i know it have a version compatible with lambda expression but not succed on making them work, any ideas or suggestion of what could he happening ?

EDIT: When i try to compile i get this:

Prueba.java:57: error: illegal start of expression
            boton.addActionListener(event -> System.out.println("Hello World !"));
                                           ^1 error

EDIT2: I'm not using any IDE, im compiling from the command line


Solution

  • Edit

    As per your comments, you are not using any IDE and your javac version is 1.7. You need to compile with java 8, else the lambda won't be recognized.


    I will keep this part in my answer as it may solve the problem for someone else, even if this was not the solution in this case.

    Your lambda is perfectly fine. The error is probably due to a wrong compiler compliance level setting.

    If you use eclipse, refer to this post for how to change the compiler compliance level :

    How to change JDK version for an Eclipse project

    If you use Netbeans, remember (this is something many people forget) that you have to set both the source and libraries target to 8 if you want it to function properly.


    Source enter image description here


    Libraries

    enter image description here

    Calling java -version from the command-line does not mean that the proper library is set in the IDE, so you have to verify this.

    If you use any other IDE then google "How to change jdk version on YourIDE".