Given:
What is the result?
Given:
What is the result?
The code attempts to convert the string 'a' to an integer using Integer.parseInt, which throws a NumberFormatException since 'a' is not a valid integer. This exception is caught, and an empty Optional is returned. When the main method calls convert("a").get(), it attempts to retrieve the value from this empty Optional, which results in a NoSuchElementException being thrown at runtime.
Since Integer.parseInt("a") will throw NumberFormatException. Empty Optional will be returned. and if we try to get() from Empty Optional it results into NoSuchElementException. So, correct answer is A
.get() : If a value is present, returns the value, otherwise throws NoSuchElementException.
public static void main(String[] args) { System.out.println("Ans:" + convert("a").get()); } private static Optional<Integer> convert(String s){ try{ return Optional.of(Integer.parseInt(s)); }catch (Exception e){ return Optional.empty(); } } A is correct
Tested: A.
Answer: A
A is correct
NoSuchElementException at runtime