Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817
Moderator: admin
codemonkey
Posts: 2 Joined: Fri Jul 08, 2016 4:11 am
Contact:
Post
by codemonkey » Fri Jul 08, 2016 4:38 am
Hello,
I've compiled and run the code given in the question and got a result other then in the answer. Can you please tell me what I did wrong?
Answer applied by enthuware is:
UNKNOWN
PASS
Real result:
FAIL
PASS
My code:
Code: Select all
package tests;
import java.util.Optional;
public class Test2 {
public static void main(String[] args) {
Optional<String> g1 = getGrade(50);
Optional<String> g2 = getGrade(55);
System.out.println(g1.orElse("UNKNOWN"));
if (g2.isPresent()) {
g2.ifPresent(x -> System.out.println(x));
} else {
System.out.println(g2.orElse("EMPTY"));
}
}
static Optional<String> getGrade(int marks) {
Optional<String> grade = Optional.empty();
if (marks > 50) {
grade = Optional.of("PASS");
} else {
grade = Optional.of("FAIL");
}
return grade;
}
}
Sorry if I post this question in any incorrect way and do moderate it.
admin
Site Admin
Posts: 10384 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Fri Jul 08, 2016 9:05 pm
The given answer is correct. Please try exactly the same code as given in the question.
codemonkey
Posts: 2 Joined: Fri Jul 08, 2016 4:11 am
Contact:
Post
by codemonkey » Sat Jul 09, 2016 2:27 am
Admin, you are right. I found my mistake. Typed
instead of
wich changed an output. I apologize.
Sieusc
Posts: 21 Joined: Mon Mar 02, 2020 3:38 am
Contact:
Post
by Sieusc » Wed May 19, 2021 1:25 pm
How come this does not result in a compilation error?
admin
Site Admin
Posts: 10384 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Wed May 19, 2021 11:34 pm
Why do you expect it to result in a compilation error?
of(T ) is a static method in Optional class and grade is a variable of type Optional. Although not a preferred way to invoke a static method, you can invoke a static method using a reference.
Users browsing this forum: No registered users and 20 guests