About Question enthuware.ocpjp.v11.2.3076 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
menelaus
Posts: 4
Joined: Sun Dec 20, 2020 7:49 am
Contact:

About Question enthuware.ocpjp.v11.2.3076 :

Post by menelaus »

Hi,
I know that a consumer does not return something. So it is normal for this code not to compile.

Code: Select all

Consumer<Book> c = b->b.getId()+":"+b.getTitle();
On the other hand this code compiles. Even it is returning a value.

Code: Select all

Consumer<Book> c = b->b.getId();
What is the difference between these two codes?

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v11.2.3076 :

Post by admin »

For this you need to understand two things:
1. The difference between a statement and an expression. b.getId()+":"+b.getTitle(); is a valid expression but not a valid statement.
and b.getId(); is a valid expression as well as a valid statement. (Check out section 6.1.2 of https://amzn.to/2PucBeT for details.)

2. You can check the validity of a lambda expression by converting it into an anonymous class (the compiler does not actually do this but it is a valid approach). Like this:

Code: Select all

Consumer<Book> c = new Consumer<Book>(){
     public void consume(Book b){
      b.getId()+":"+b.getTitle(); //code from lambda body goes here
     }
  };

and 

Consumer<Book> c = new Consumer<Book>(){
     public void consume(Book b){
      b.getId(); //code from lambda body goes here
     }
  };
You can now easily see why the first one will not compile even though both expression return a value and which can be ignored by the JVM. A method body must be composed of valid statements (which may or may not be valid expressions) but b.getId()+":"+b.getTitle(); is not a valid statement.
If you like our products and services, please help us by posting your review here.

menelaus
Posts: 4
Joined: Sun Dec 20, 2020 7:49 am
Contact:

Re: About Question enthuware.ocpjp.v11.2.3076 :

Post by menelaus »

Thanks

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 219 guests