0

First program:

class Demo  {
   public static void main(String args[])  {
      Object obj ;
      while(true)  {
         obj = new Object();
      }
   }
}

2nd program:

class Demo  {
   public static void main(String args[])  {
      Object obj = null;
      while(true)  {
         obj = new Object();
      }
   }
}

question : is there any difference in terms of scope of obj in the two programs where obj is assigned value in the loop(in first program) and obj is assigned null value initially (in second program).

aliteralmind
  • 19,847
  • 17
  • 77
  • 108
Anonymous
  • 67
  • 6

1 Answers1

1

In both cases, the scope of obj is till the end of the main method. Both programs will run infinitely because of the while(true) condition.

In the first case however, an attempt to use obj outside the loop will cause compilation error since its not initialized (Assuming the while loop terminates at some point)

public static void main(String []args){
        Object obj;
        while(args != null)  {
             obj = new Object();
        }
       System.out.println(obj); //compilation error
}
Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
  • wrong.. there will be no compilation error.. – Anonymous Jul 17 '14 at 03:24
  • 1
    why don't you try it and check for yourself: http://ideone.com/xa2Hng – Nikhil Talreja Jul 17 '14 at 03:25
  • @nihal using `obj` outside loop will result in the compilation error because of `unreachable code` in your post. In Nikhils example that's because of `uninitialized local variable`. compiler checks if a local variable is initialized through every possible path before reaching to the statement where its being used. – Shailesh Aswal Jul 17 '14 at 03:46
  • ok.. but i was asking about the scope lifetime of uninitialized local variable.... – Anonymous Jul 17 '14 at 04:08
  • see this -> http://stackoverflow.com/questions/24737477/in-the-given-program-the-garbage-collector-is-running-before-the-object-is-deref/24738830#24738830 – Anonymous Jul 17 '14 at 04:09