Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Medium
Question 21
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.*;
- class Employee {
- private String name;
- private double salary;
- public Employee(String name, double salary) {
- this.name = name;
- this.salary = salary;
- }
- public String getName() {
- return name;
- }
- public double getSalary() {
- return salary;
- }
- public void setSalary(double salary) {
- this.salary = salary;
- }
- public String toString() {
- return "{" + name + ", " + salary + "}";
- }
- }
- public class Test {
- public static void main(String[] args) {
- List<Employee> employees = Arrays.asList(new Employee("Jack", 10000), new Employee("Lucy", 12000));
- employees.forEach(e -> e.setSalary(e.getSalary() + (e.getSalary() * .2)));
- employees.forEach(System.out::println);
- }
- }
What will be the result of compiling and executing Test class?
-
A
{Jack, 12000}
{Lucy, 14400} -
B
{Jack, 10000}
{Lucy, 12000} -
C
{Jack, 10000.0}
{Lucy, 12000.0} -
D
{Jack, 12000.0}
{Lucy, 14400.0}
Reveal correct answer
Correct answer: D
Explanation
Iterator<T> interface has forEach(Consumer) method. As Consumer is a Functional Interface and it has 'void accept(T t)' method, hence a lambda expression for 1 parameter can be passed as argument to forEach(...) method.
'e -> e.setSalary(e.getSalary() + (e.getSalary() * .2))' => increments the salary of all the employees by 20%.
'System.out::println' => prints employee object on to the console.
As salary is of double type, so decimal point (.) is shown in the output.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
