Declaring List before for loop in java

Below program gives output : 4 4 4 4 4

package HelloWorld;
import java.util.List;
import com.google.common.collect.Lists;
public class HelloWorld {
        public static void main(String args[]) {
                List<Product> productList = Lists.newArrayList();
                **Product product = new Product();**
                for (int i = 0; i < 5; i++) {                   
                        product.setId("id:" + i);
                        productList.add(product);
                }
                // Printing values
                for (int i = 0; i < productList.size(); i++) {
                        System.out.println(productList.get(i).getId());         
                }
        }
}

This is because Product is declared outside the loop.
But see another program :

package HelloWorld;
import java.util.List;
import com.google.common.collect.Lists;
public class HelloWorld {
    public static void main(String args[]) {
        **List<String> list = Lists.newArrayList();**
        for(int i=0;i<5;i++){           
            list.add(""+i);
        }       
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));        
        }
    }
}

This gives output : 0 1 2 3 4

May i know why is it printing 0 1 2 3 4 even if the list is declared out side the for loop? I expected it to print 4 4 4 4 4

product is defined outside the for loop, so each time you are doing product.setId(“id:” + i); you are overriding the id of the same instance and adding it again to the list. Create the product instance inside the loop

List<Product> productList = Lists.newArrayList();
for (int i = 0; i < 5; i++) {
    Product product = new Product();               
    product.setId("id:" + i);
    productList.add(product);
}

In your first example, you only instantiate one Productobject and add that 4 times to your list. However, each time – just before you add it, you overwrite the Id value with the current value of i. Ultimately that will become 4.

In your second example you add a new String object in every pass through of the loop and thus don’t overwrite the already set value.