I've been learning java and wanted to know if it's possible to construct objects that are inside an array using foreach loop. Using for-loop it's very easy:
public class Bottle {
double waterAmount;
Bottle(){
waterAmount = 1.0;
}
public static void main(String[] args) {
Bottle[] bottles = new Bottle[3];
//foreach
for (Bottle bottle : bottles) {
bottle = new Bottle();
System.out.println(bottle.waterAmount);
}
//for
for (int i = 0; i<bottles.length;i++){
bottles[i] = new Bottle();
System.out.println(bottles[i].waterAmount);
}
System.out.println("index 1: " + bottles[1].waterAmount);
}
}
When I'm running this program using for loop I get:
1.0
1.0
1.0
index 1: 1.0
which is ok because the array of bottles has been constructed properly. When I execute it using only foreach there is the output:
1.0
1.0
1.0
Exception in thread "main" java.lang.NullPointerException
at Bottle.main(Bottle.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
So as much as I understand the bottle inside foreach constructs every bottle object but then it's not asigning those new bottles to the every index of an array so that's why I cannot refer to bottles[1].waterAmount.