About Question enthuware.ocpjp.v8.2.1784 :

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

Moderator: admin

Post Reply
tylrdr
Posts: 6
Joined: Sun Sep 01, 2019 9:33 am
Contact:

About Question enthuware.ocpjp.v8.2.1784 :

Post by tylrdr »

Code: Select all

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Common {

    public static void main(String[] args) {

        List<Integer> values = Arrays.asList(2, 4, 6, 9);
        Predicate<Integer> check = (Integer i) -> {
            System.out.println("Checking");
            return i == 4;
        };
        Predicate<Integer> even = (Integer i) -> i % 2 == 0; //Compiles
//        Predicate even =  i -> ((Integer)i) % 2 == 0; //Compiles
//        Predicate even = (Object i) -> ((Integer)i) % 2 == 0; //Compiles

//        Predicate even = (Integer i) -> i % 2 == 0; //Doesn't compile: expected Object but found Integer
//        Predicate even = (Integer i) -> ((Integer)i) % 2 == 0; //Doesn't compile: expected Object but found Integer
//        Predicate even = (Object i) -> ((Object)i) % 2 == 0; //Doesn't compile: Operator '%' can't be applied to java.lang.Object
//        Predicate even = (Object i) -> i % 2 == 0; //Doesn't compile: Operator '%' can't be applied to java.lang.Object


        values.stream().filter(check).filter(even).count(); //Checking Checking Checking Checking
    }
}
I tested a bit and found these examples. Could someone please explain if there is some rules that is useful to remember for this to make sense please?
1) Why does Java expect Object to be the type of lambda variable? Why can't Java figure out the type by itself like it does here:
Predicate even = i -> ((Integer)i) % 2 == 0; //Compiles
2) Why in Java operator '%' can't be applied to java.lang.Object?

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

Re: About Question enthuware.ocpjp.v8.2.1784 :

Post by admin »

>Why does Java expect Object to be the type of lambda variable?
Java doesn't expect Object to be the type of lambda variable. Type of the lambda depends on the type of function parameter that you are trying to implement. Please do through short article to understand: https://enthuware.com/lambda-for-ocajp

> Why in Java operator '%' can't be applied to java.lang.Object?
Well, you know what % does, right? It divides one number by another and return the remainder. It is a mathematical operation. How will you divide an object?

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests