Anton Anton Anton Anton - 2 months ago 19
Java Question

Array output structure

Why the output of this code is

island = Fiji
island = Cozumel
island = Bermuda
island = Azores


Why the output starts from Fiji island , instead of "Bermuda"? Bermuda have 0 element in array . Can you please point me why my output have such specific order.

public class TestArrays {
public static void main (String[] args){
int y = 0;
int[] index = new int [4];
index[0] = 1;
index[1] = 3;
index[2] = 0;
index[3] = 2;


String[] islands = new String[4];
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";

int ref;
while ( y < 4){
ref = index[y];
System.out.print("island = ");
System.out.println(islands[ref]);
y = y + 1;

}

}

Answer

Your index is ordered as {1, 3, 0, 2}

int[] index = new int [4];
index[0] = 1;
index[1] = 3;
index[2] = 0;
index[3] = 2;

So it will print islands[1], islands[3], islands[0], islands[2]

String[] islands = new String[4];
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";

Fiji, Cozumel, Bermuda, Azores