What is the result?

Given:

1. public static void parse(String str) {
2. try {
3. float f = Float.parseFloat(str);
4. } catch (NumberFormatException nfe) {
5. f = 0;
6. } finally {
7. System.out.println(f);
8. }
9. }
10. public static void main(String[] args) {
11. parse(“invalid”);
12. }

What is the result?

Given:

1. public static void parse(String str) {
2. try {
3. float f = Float.parseFloat(str);
4. } catch (NumberFormatException nfe) {
5. f = 0;
6. } finally {
7. System.out.println(f);
8. }
9. }
10. public static void main(String[] args) {
11. parse(“invalid”);
12. }

What is the result?

A.
0.0

B.
Compilation fails.

C.
A ParseException is thrown by the parse method at runtime.

D.
A NumberFormatException is thrown by the parse method at runtime.

Explanation:
Main.java:5: cannot find symbol
symbol : variable f
location: class Test
f = 0;
^
Main.java:7: cannot find symbol
symbol : variable f
location: class Test
System.out.println(f);
^
2 errors

f variable is being declared inside try block. Because of it, cannot be used neither inside catch nor finally blocks.



Leave a Reply 0

Your email address will not be published. Required fields are marked *