Java Stream How to - Capture effective final variable








Question

We would like to know how to capture effective final variable.

Answer

/*from  w w  w.ja v  a2 s .  c  o m*/
import javax.swing.JButton;

public class Main {

  public static void main(String[] args) throws Exception {

  }

  public void capturingVariable() {
    String name = getUserName();
    JButton button = new JButton();
    button.addActionListener(event -> System.out.println("hi " + name));
  }

  public void capturingVariableError() {
    // fails to compile
    String name = getUserName();
    name = "asdf";
    JButton button = new JButton();
    // button.addActionListener(event -> System.out.println("hi " + name));
  }

  private String getUserName() {
    return "Test";
  }

}