Accessing elements in an array
Creating Arrays in Java
Either one of the following two coding techniques will create an array that will hold 10 integers
// declares the array
int[] n;
// initializes the array
n = new int[10];
//declare and initialize in one line
int[] n= new int[10];
Either one of the following two coding techniques will create an array that will hold 10 Strings
String[] str;
str = new String[10];
String[] str= new String[10];
you can have an array of any data type, including an array of a class you create!
Assign Values in an Array
the following code will place ten random integers into the array from 0 to 99
for(int x=0;x<10;x++){
n[x]= (int)(Math.random()*100);
}
in this case the x is used as the index of the array and the counter for the for loop
Retrieve Values from an Array
the following code will add all the integers in the array together.
int sum = 0;
for(int x=0;x<10;x++){
sum = sum + n[x];
// System.out.println(x+": "+n[x]+": "+ sum);
}
To create a copy of an array, you must use the System.arrayCopy()method, find the details in the Java API