public class IntArray {
public static void main (String [] args) {
// creating a new array of length 5
int [] a = new int[5];
// printing out the contents of a (all 0s):
for (int i = 0; i < a.length; ++i) {
System.out.println("a[" + i + "] = " + a[i]);
}
// storing some data in the array:
for (int i = 0; i < a.length; ++i) {
a[i] = i * i;
}
// printing out the contents of a after the assignment:
System.out.println("a after the assignment:");
for (int i = 0; i < a.length; ++i) {
System.out.println("a[" + i + "] = " + a[i]);
}
// counting the number of elements in a which are < 10:
int count = 0;
for (int i = 0; i < a.length; ++i) {
if (a[i] < 10) count++;
}
System.out.println(count + " elements are less than 10");
// creating another array (of length 'count')
int [] b = new int[count];
// copy elements from a into b (note: b is shorter)
for (int i = 0; i < b.length; ++i) {
b[i] = a[i];
}
// print out b:
System.out.println("array b:");
for (int i = 0; i < b.length; ++i) {
System.out.println("b[" + i + "] = " + b[i]);
}
// change a:
for (int i = 0; i < a.length; ++i) {
a[i] = a[i] - i;
}
// print out a:
System.out.println("a after the change:");
for (int i = 0; i < a.length; ++i) {
System.out.println("a[" + i + "] = " + a[i]);
}
// print out b:
System.out.println("array b after a has changed:");
for (int i = 0; i < b.length; ++i) {
System.out.println("b[" + i + "] = " + b[i]);
}
}
}
This is an example from CSci 1211 course.