-3

So I was just trying to experiment with ArrayList and I came to this problem:

Why do Java say 'ArrayList already is declared' when I do this:

ArrayList<Integer> myList = new ArrayList<>();
ArrayList<Integer> myList = new ArrayList<>();

But Java won't say the list is already declared when I do this (and compiles with no error):

for(int i=0; i<5; i++){
   ArrayList<Integer> myList = new ArrayList<>();
 }
3
  • because you have two variables with the same name. in the second one you just have one, all the times, even if the loop is infinite Commented Feb 22, 2019 at 10:27
  • The braces describe the scope of your variable. In the loop, the variable myList goes out of scope at the end of each turn through the loop. Commented Feb 22, 2019 at 10:28
  • 1
    Also you have unwanted () in your variable declarations. Commented Feb 22, 2019 at 10:28

2 Answers 2

0

1. However, you CANNOT create same name variables within same scope in java.

2. About declaring same variable inside loop. This is called variable shadowing:

variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables)

Scope of Variables In Java

public class Test
{
    // All variables defined directly inside a class 
    // are member variables
    int a;
    private String b;

    void method1() {
         // Local variable (Method level scope)
         int x;
    }
    int method2() {....}
    char c;
}

In your case,

after each loop, the scope is destroyed, and the variable is gone. In the next loop, a new scope is created, and the variable can be declared again in that scope.

With this:

for(int i=0; i<5; i++){
    ArrayList<Integer> myList = new ArrayList<>();
}

A new block is created on every iteration. And there is only 1 variable named myList in each block.

Refer here

Sign up to request clarification or add additional context in comments.

Comments

0

In the first case, you define two variables having the same name in the same scope.

In the loop case, the scope of the myList variable is only inside the loop. That means each time you enter in the loop the variable is initiated and then destroyed at the end of the loop.

Have a look to : https://www.geeksforgeeks.org/variable-scope-in-java/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.