apotalion
apotalion

Reputation: 33

Behavior of Lambda expression with multiple statements without curly brackets

public class A  {
    interface Interface{
        void print();
    }
    public static void main(String[] args) {
        Interface i=()->{System.out.println("1");System.out.println("2");System.out.println("3");System.out.println("4");};
        i.print();
    }
}
output:
1
2
3
4

when I remove the curly brackets like this:

public class A  {
    interface Interface{
        void print();
    }
    public static void main(String[] args) {
        Interface i=()->System.out.println("1");System.out.println("2");System.out.println("3");System.out.println("4");
        i.print();
    }
}
output:
2
3
4
1

I know we have to use curly brackets when we want to implement more than 1 statement. When we remove the curly brackets application is still compiling but my question is why second statement is executed first and first statement as last? I couldn't found any explanation about this.

Upvotes: 0

Views: 312

Answers (2)

Ramesh PVK
Ramesh PVK

Reputation: 15446

Here is your second code after formatting it properly:

public class A  {
   interface Interface{
     void print();
   }
   public static void main(String[] args) {
      Interface i=()->System.out.println("1");
      System.out.println("2");
      System.out.println("3");
      System.out.println("4");
      i.print();
   }
}

function i() is assigned to only System.out.println("1") since there is no braces.

So, before i.print(), the other statements are getting invoked i.e,

System.out.println("2");System.out.println("3");System.out.println("4");

and then i.print() invokes System.out.println("1")

Upvotes: 2

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

Interface i=()->System.out.println("1");System.out.println("2");System.out.println("3");System.out.println("4");
i.print();

Most of those expressions are not part of the lambda. Java does not treat newlines as significant, so this is equivalent to

Interface i=()->System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
i.print();

and now it's clearer what it's doing.

Upvotes: 5

Related Questions