Consider the following program:
public class Main { public static void main(String[] args) { calculate(2);// w w w.ja va 2 s. co m } public static void calculate(int x) { String val; switch (x) { case 2: default: val = "def"; } System.out.println(val); } }
What will happen if you try to compile and run the program?
Select 2 options
Correct Options are : B D
When you try to access a local variable, the compiler makes sure that it is initialized in all the cases.
If it finds that there is a case in which it may not be initialized then it flags an error.
For example:
int i; if ( somecondition) i = 20; int k = i;
If some condition returns false, then i remains uninitialized hence the compiler flags an error.