MRP
class B {
static int v;
public B(int i) {
System.out.format("Constructor called with value %d\n", i);
v=i;
}
}
public class A {
static B[] c;
A(){
c=new B[5];
c[1]=new B(1);
for (int i=0; i<3; i++) {
System.out.format("c[%d] is %d\n", i, c[i].v);
}
c[2]=new B(2);
for (int i=0; i<3; i++) {
System.out.format("c[%d] is %d\n", i, c[i].v);
}
}
public static void main(String[] args) {
new A();
}
}
Output is:
Constructor called with value 1
c[0] is 1
c[1] is 1
c[2] is 1
Constructor called with value 2
c[0] is 2
c[1] is 2
c[2] is 2
Would expect exception to be raised by reference to unassigned array elements e.g. c[0]. Array values are also incorrectly changed by previous assignment. c[0] is never assigned a value but takes on the values 1 and 2 in the output above.
public class A {
static String[] c;
A(){
c=new String[5];
c[0]=new String("alpha");
for (int i=0; i<3; i++) {
System.out.format("c[%d] is %s\n", i, c[i]);
}
c[1]=new String("beta");
for (int i=0; i<3; i++) {
System.out.format("c[%d] is %s\n", i, c[i]);
}
}
public static void main(String[] args) {
new A();
}
}
Output for the above is:
c[0] is alpha
c[1] is null
c[2] is null
c[0] is alpha
c[1] is beta
c[2] is null
Different behavior is seen for String object in the above example.