Java Puzzlers on local variable initialization


Intent of my blog

Some time back, i posted a blog on common interview questions on overriding.The blog was very popular on dzone so i decided to write some of the java puzzlers on local variable initialization.One thing which should be kept in mind is that Local variables should be initalized before they are used.Knowing this fact try to answer these questions.

Local Variable Initialization Puzzlers

Question1


public class Question1{
 public static void main(String[] args) {
 int x;
 int y = 10;
 if (y == 10) {
 x = y;
 }
 System.out.println("x is " + x);
 }
}

Question 2


class Question2{
 public static void main(String[] args) {
 int x;
 if(true){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Question 3


class Question3{
 public static void main(String[] args) {
 int x;
 final int y = 10;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);

 }
}

Question 4


class Question4{
 static int y = 10;

 public static void main(String[] args) {
 int x ;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Question 5


class Question5{
 static final int y = 10;

 public static void main(String[] args) {
 int x ;
 if(y == 10){
 x = 10;
 }
 System.out.println("x is " + x);
 }
}

Again, like the previous post, i am not posting the solutions because i dont want to take away the fun. So, play with these and have fun.

4 thoughts on “Java Puzzlers on local variable initialization”

  1. First and fourth examples won’t compile, since compiler will not know for sure that x is set. Others will compile and show what is expected since the test vars (y) are final (Questions 3 & 5), so the compiler knows for sure the result of the comparison. Question 2 will also compile since the test condition is always true, no variation involved there.

Leave a comment