Java Arrays: Key Concepts, Declarations, and Examples
Java Array Fundamentals
Array Size
Once an array is created, its size is fixed.
Declaring Integer Arrays
Which of the following are correct ways to declare an array of int
values?
int[] a;
int a[];
Incorrect Array Declarations
Which of the following are incorrect?
int[] a = new int(2);
int a = new int[2];
int a() = new int[2];
Array Indexing
If you declare an array double[] list = new double[5]
, the highest index in array list
is 4.
Array Length
How many elements are in array double[] list = new double[5]
? – 5
Analyzing Code Snippets
Random Number Generation
Analyze the following code:
(int)(Math.random() * 100)
Array Element Access
If you declare an array double[] list = {3.4, 2.0, 3.5, 5.5}
, list[1]
is 2.0.
Valid Array Statements
Which of the following statements are valid?
double d[] = new double[30];
int[] i = {3, 4, 3, 2};
Initializing Character Arrays
How can you initialize an array of two characters to ‘a’ and ‘b’?
char[] charArray = {'a', 'b'};
char[] charArray = new char[2]; charArray[0] = 'a'; charArray[1] = 'b';
Code Analysis with Double Array
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) {
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
Output: 1
Runtime Error Example
Analyze the following code:
public class Test {
public static void main(String[] args) {
int[] x = new int[5];
int i;
for (i = 0; i < x.length; i++)
x[i] = i;
System.out.println(x[i]);
}
}
The program has a runtime error because the last statement in the main method causes ArrayIndexOutOfBoundsException
.
Output Prediction
What is the output of the following code?
public class Test {
public static void main(String[] args) {
double[] x = {2.5, 3, 4};
for (double value: x)
System.out.print(value + " ");
}
}
The program displays 2.5 3.0 4.0
.
Array Manipulation
What is the output of the following code?
public class Test {
public static void main(String[] args) {
int list[] = {1, 2, 3, 4, 5, 6};
for (int i = 1; i < list.length; i++)
list[i] = list[i - 1];
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
}
}
Output: 1 1 1 1 1 1
Array Assignment
In the following code, what is the output for list2
?
public class Test {
public static void main(String[] args) {
int[] list1 = {1, 2, 3};
int[] list2 = {1, 2, 3};
list2 = list1;
list1[0] = 0; list1[1] = 1; list2[2] = 2;
for (int i = 0; i < list2.length; i++)
System.out.print(list2[i] + " ");
}
}
Output: 0 1 2
Final Arrays
Analyze the following code:
public class Test {
public static void main(String[] args) {
final int[] x = {1, 2, 3, 4};
int[] y = x;
x = new int[2];
for (int i = 0; i < y.length; i++)
System.out.print(y[i] + " ");
}
}
The program has a compile error on the statement x = new int[2]
, because x
is final and cannot be changed. The program displays 1 2 3 4
.