2

This code doesn't work:

public class Test
{
    public static void main(String[] args)
    {
       int i=3;
       int i=4;
       System.out.println(i);   
    } 
}

Then why does this code work?

public class Test
{
    public static void main(String[] args)
    {
       for(int a=0;a<9;a++)
       {
           int b=a+1;
           System.out.println(b);
       }
    }
}

Aren't we re-declaring b again and again?

3
  • That is because, of scope of a variable, Commented Oct 23, 2014 at 6:00
  • When you iterate through the loop, there is a variable named b already. So, aren't we just declaring another b? Commented Oct 23, 2014 at 6:05
  • Look at my comment below, I have given a elaborated explanation for you. Commented Oct 23, 2014 at 6:06

6 Answers 6

5

Each iteration of the loop has its own scope, so the declarations of previous iterations are no longer in scope in the current iteration.

It's equivalent to writing :

   {
       int b=1;
       System.out.println(b);
   }
   {
       int b=2;
       System.out.println(b);
   }
   {
       int b=3;
       System.out.println(b);
   }
   ....
Sign up to request clarification or add additional context in comments.

1 Comment

@TheLostMind think about life span of local variable.
1

Your first example would work with a block

int i=3; 
{
  int i=4;
  System.out.println(i);
}

This creates a new 'i' that shadows the first 'i' within the block's lexical scope.

1 Comment

It works, but I don't think, that this clearly explains the loop related part of OP's question.
1

lifetime of int b is only till the iteration of the for loop, so everytime you iterate each it get new value with declaration .

In the first ex,

   int i=3;
   int i=4;

you are intialising i two times, rather it could be

 int i=3;
 i=4;

so the value of i will be 4 , remember int i makes it a variable and its value can be re-assigned with in its declaration block

Comments

1

In

    public class Test { 
     public static void main(String[] args) { 
          int i=3; 
          int i=4; 
          System.out.println(i);
    } 

You are declaring same variable name twice. And In

     public class Test {
       public static void main(String[] args) { 
          for(int a=0;a<9;a++) { 
             int b=a+1; 
             System.out.println(b); 
          }
      } 
    }

Here b is local variable inside for loop and you are declaring it in the start of loop. And there is no duplicate name inside this loop.

Comments

0

the local variables with loop scope are given memory location as it is initialized and the memory location is destroyed as soon as it goes out of scope,so as there is no previous record of 'b' b can be declared once again.But this is not the case to variable 'a' with main scope because your declaring a again in the main where there is already a record of variable 'a' so you cannot duplicate it.

Comments

0

That is because of scope of a variable,

Case1:

public class Test
{
 public static void main(String[] args)
 {
  int i=3;
  int i=4;
  System.out.println(i);   
 }
}

In here you have a variable i defined in the same scope twice.

Case2:

public class Test
{
 public static void main(String[] args)
 {
   for(int a=0;a<9;a++)
   {
       int b=a+1;
       System.out.println(b);
   }
 }
}

In here there will be only one b instance at a time, the moment the loop ends the variable is destroyed and recreated for the next iteration. So you will not get the error that you are looking for.

I suggest you to go through scope of variables in JAVA.

Note: I would not suggest this way of programming, as resource is getting wasted for creating the same variable again and again. all you do is reset it within the loop.


Update

public class Test1 {
public static void main(String[] args) {

    Person p1=new Person();
    System.out.println("Person Object p1 before for loop "+p1);

    for(int i=0;i<5;i++){
        Person p2=new Person();
        System.out.println("Person object "+i+" "+p2);
    }

    System.out.println("Person Object p1 after for loop "+p1);

}
}

Dummy class Person

class Person{ }

Output

Person Object p1 before for loop com.project.CVS.Person@fd13b5
Person object 0 com.project.CVS.Person@118f375
Person object 1 com.project.CVS.Person@117a8bd
Person object 2 com.project.CVS.Person@471e30
Person object 3 com.project.CVS.Person@10ef90c
Person object 4 com.project.CVS.Person@a32b
Person Object p1 after for loop com.project.CVS.Person@fd13b5

Here I have created a dummy class called Person and I have declared and initialized a Person object within a loop. Now, When I print out the person object, it gives out the hash code.

Now on analyzing the output one can clearly see that new object is getting created during every iteration, as the hash code values are not matching. If your application is really not needing such implementation then, you must and should avoid it. I hope i have cleared your doubt.

7 Comments

Thanks! I know that this practice is discouraged. I didn't know that a variable is destroyed when the scope ends. Thanks!!!
There is no resource waste. The variable is allocated once, and it is reused during the loop. In general, all local variables are created when the method is entered, and nothing you can do within the method can create new variables during execution. Also, this practice is actually encouraged, you should always limit the variable scope to the smallest possible.
by resource waste, I meant time thought its negligible for such a small application, consider some enterprise application where you need to create many objects.
@Joni what internally happens is similar to what explained by Eran in above comments. here the variable is being created again and again. I am sure you know that the value of b cannot be accessed outside the loop.
@Joni please have a look at my updated comment. You will be able to see that new variables are getting created WITHIN THE LOOP. such practices must be avoided at all cost. Else why do we need implement design patterns like, singleton, Factory etc.? (Ans: because it returns only one instance of the class. No matter how many times you instantiate it.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.