C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part 1: We create an array of 5 int elements. When created, the ints all have values of 0.
Part 2: We assign 3 elements into the newly-created int array. The first index in an array is zero.
Part 3: We use length in for-loops as the upper boundary. Every array has a length, even if it has zero elements.
ForArray LengthJava program that uses array
public class Program {
public static void main(String[] args) {
// Part 1: create int array.
int[] array = new int[5];
// Part 2: assign first three elements.
array[0] = 1;
array[1] = 10;
array[2] = 100;
// Part 3: loop over elements.
for (int i = 0; i < array.length; i++) {
// Get value.
int value = array[i];
// Print value.
System.out.println(value);
}
}
}
Output
1
10
100
0
0
Tip: For-each loop syntax is often applied to arrays. This reduces syntax complexity—no index variable is used.
Java program that uses char array, loop
public class Program {
public static void main(String[] args) {
// Create an array of four chars.
char[] values = new char[4];
values[0] = 'j';
values[1] = 'a';
values[2] = 'v';
values[3] = 'a';
// Loop over array with for-loop.
for (char value : values) {
System.out.println(value);
}
}
}
Output
j
a
v
a
Syntax: Here we see the syntax for an int array and a String array. Each array in this example has three elements.
Java program that initializes arrays
public class Program {
public static void main(String[] args) {
// Two input arrays.
int[] array1 = {1, 3, 5};
String[] array2 = {"frog", "toad", "squirrel"};
// Array lengths.
System.out.println(array1.length);
System.out.println(array2.length);
// First elements in each array.
System.out.println(array1[0]);
System.out.println(array2[0]);
}
}
Output
3
3
1
frog
Java program that loops over array in reverse
public class Program {
public static void main(String[] args) {
boolean[] values = { false, true, true, true };
// Loop over array elements in reverse order.
for (int i = values.length - 1; i >= 0; i--) {
System.out.println(values[i]);
}
}
}
Output
true
true
true
false
Java program that creates empty arrays
public class Program {
public static void main(String[] args) {
// Two empty arrays.
int[] array1 = {};
int[] array2 = new int[0];
// Each has zero length.
System.out.println(array1.length);
System.out.println(array2.length);
}
}
Output
0
0
Here: We try to access the length of the array, but the pointer is null. So we get an exception and the program ends.
Java program that shows NullPointerException
public class Program {
public static void main(String[] args) {
int[] values = null;
int size = values.length;
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at Program.main(Program.java:5)
Ascending: The Arrays.sort method by default uses an ascending sort, meaning elements are ordered from low to high.
ParallelSort: For large arrays, the parallelSort method can enhance performance (on systems with multiple processor cores).
Sort: parallelSortJava program that sorts array
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] array = { 100, 20, 0, 200 };
// Call Arrays.sort on the int array.
Arrays.sort(array);
for (int elem : array) {
System.out.println(elem);
}
}
}
Output
0
20
100
200
Java program that uses Arrays.fill
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] values = new int[10];
// Fill array with this number.
Arrays.fill(values, 5);
for (int value : values) {
System.out.print(value);
System.out.print(' ');
}
}
}
Output
5 5 5 5 5 5 5 5 5 5
Resize: This is essentially a resize method. An array's length is not dynamic. Resizing can only be done when copying.
Java program that uses Arrays.copyOf
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] values = { 10, 20, 30, 40 };
// Copy and display first 3 elements.
int[] copy = Arrays.copyOf(values, 3);
for (int value : copy) {
System.out.println(value);
}
System.out.println();
// Copy five elements.
int[] copy2 = Arrays.copyOf(values, 5);
for (int value : copy2) {
System.out.println(value);
}
}
}
Output
10
20
30
10
20
30
40
0
Argument 1: This is the array we are trying to take a copy from. Here we use an int array with several integers in it.
Argument 2: The second argument to copyOfRange is the start index—the element at this index will be copied.
Argument 3: The third argument we pass to Arrays.copyOfRange is the last index int. This value is exclusive (not included).
Java program that uses Arrays.copyOfRange
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] values = { 0, 10, 20, 30, 40, 50 };
// Copy elements from index 2 to 5 (2, 3, 4).
int[] result = Arrays.copyOfRange(values, 2, 5);
for (int value : result) {
System.out.println(value);
}
}
}
Output
20
30
40
And: We readjust the sentinel value without modifying the rest of the array. This is a fast way to change the conceptual length.
With sentinels: We can optimize program store use buffers and arrays. This makes programs faster.
Java program that tests for sentinel
public class Program {
static void scan(int[] buffer) {
for (int i = 0; i < buffer.length; i++) {
// Terminate loop when sentinel element is detected.
if (buffer[i] == -1) {
break;
}
System.out.println(buffer[i]);
}
System.out.println();
}
public static void main(String[] args) {
// The sentinel element is the sixth one.
int[] buffer = { 10, 20, 30, 25, 35, -1, 50, 55 };
scan(buffer);
// Make the third element the sentinel.
buffer[2] = -1;
scan(buffer);
}
}
Output
10
20
30
25
35
10
20
Java program that uses Arrays.toString
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] values = { 505, 100, 605 };
// Call Arrays.toString to display the elements.
System.out.println(Arrays.toString(values));
}
}
Output
[505, 100, 605]
Note: The second loop uses an offset value, equal to values.length to assign into the merged array.
Combine ArraysJava program that merges two arrays
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
int[] values = { 10, 20, 30 };
int[] values2 = { 100, 200, 300 };
// Merge the two arrays with for-loops.
int[] merge = new int[values.length + values2.length];
for (int i = 0; i < values.length; i++) {
merge[i] = values[i];
}
for (int i = 0; i < values2.length; i++) {
merge[i + values.length] = values2[i];
}
// Display the merged array.
System.out.println(Arrays.toString(merge));
}
}
Output
[10, 20, 30, 100, 200, 300]
Version 1: Here we sum a 100-element array of integers. We use a for-loop to iterate over each element.
Version 2: In this version of the code we sum the elements in an ArrayList. We try to measure the overhead here.
ArrayListResult: We find accessing all elements in a loop is faster with an array. The lower-level code has a benefit in speed.
Java program that times array, ArrayList
public class Program {
public static void main(String[] args) {
// ... Create array.
int[] array = new int[100];
array[0] = 1;
// ... Create ArrayList.
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
for (int i = 1; i < 100; i++) {
list.add(0);
}
long t1 = System.currentTimeMillis();
// Version 1: sum all elements in an array.
for (int i = 0; i < 1000000; i++) {
int sum = 0;
for (int v = 0; v < array.length; v++) {
sum += array[v];
}
if (sum != 1) {
System.out.println(false);
}
}
long t2 = System.currentTimeMillis();
// Version 2: sum all elements in an ArrayList.
for (int i = 0; i < 1000000; i++) {
int sum = 0;
for (int v = 0; v < list.size(); v++) {
sum += list.get(v);
}
if (sum != 1) {
System.out.println(false);
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
38 ms, int[], array[i]
91 ms, ArrayList, list.get(i)
Version 1: This loop reads the values of 100 elements in an array. The elements are packed together.
Version 2: This loop instead loads 100 elements, but they are spaced 100 elements apart each.
Result: The loop that accesses the elements that are packed tight together is faster. The programs has no other important differences.
Java program that shows locality of reference
public class Program {
public static void main(String[] args) {
// Create an array and fill it with values.
int[] values = new int[1000000];
for (int i = 0; i < values.length; i++) {
values[i] = i;
}
long t1 = System.currentTimeMillis();
// Version 1: sum 100 elements that are packed together.
for (int i = 0; i < 1000000; i++) {
int sum = 0;
for (int x = 0; x < 100; x++) {
sum += values[x];
}
if (sum == 0) {
System.out.println(false);
}
}
long t2 = System.currentTimeMillis();
// Version 2: sum 100 elements spaced apart by 100 slots each.
for (int i = 0; i < 1000000; i++) {
int sum = 0;
for (int x = 0; x < 10000; x += 100) {
sum += values[x];
}
if (sum == 0) {
System.out.println(false);
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
35 ms, access 100 packed elements (more locality)
61 ms, access 100 sparse elements