Académique Documents
Professionnel Documents
Culture Documents
Java Arrays
In this article, you will learn to work with arrays in Java. You will learn to declare, initialize and,
access array elements with the help of examples.
An array is a container that holds data (values) of one single type. For example, you can create an
array that can hold 100 values of int type.
Array is a fundamental construct in Java that allows you to store and access large number of
values conveniently.
dataType[] arrayName;
dataType can be a primitive data type like: int, char, Double, byte etc. or an object (will be
discussed in later chapters).
arrayName is an identifier.
Double[] data;
Good question! We haven't defined it yet. The next step is to allocate memory for array
elements.
data = new Double[10];
The length of data array is 10. Meaning, it can hold 10 elements (10 Double values in this case).
Note, once the length of the array is defined, it cannot be changed in the program.
int[] age;
It's possible to declare and allocate memory of an array in one statement. You can replace two
statements above with a single statement.
You can access elements of an array by using indices. Let's consider previous example.
If the length of an array is n, the last element will be arrayName[n-1]. Since the length of age
array is 5, the last element of the array is age[4] in the above example.
The default initial value of elements of an array is 0 for numeric types and false for boolean. We
can demonstrate this:
class ArrayExample {
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
There is a better way to access elements of an array by using looping construct (generally for
loop is used).
class ArrayExample {
public static void main(String[] args) {
System.out.println(age[i]);
In Java, you can initialize arrays during declaration or you can initialize (or change values) later in
the program as per your requirement.
The length of the array is determined by the number of values provided which is separated by
commas. In our example, the length of age array is 5.
Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5
You can easily access and alter array elements by using its numeric index. Let's take an example.
class ArrayExample {
age[2] = 14;
age[0] = 34;
Element at index 0: 34
Element at index 1: 0
Element at index 2: 14
Element at index 3: 0
Element at index 4: 0
The program below computes sum and average of values stored in an array of type int.
class SumAverage {
Double average;
sum += number;
Sum = 36
Average = 3.6
The for..each loop is used to access each elements of the array. Learn more on how for...each
loop works in Java.
To calculate the average, int values sum and arrayLength are converted into double since average
is double. This is type casting. Learn more on Java Type casting.
To get length of an array, length attribute is used. Here, numbers.length returns the length of
numbers array.
Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays. In Java, you can declare an
array of arrays known as multidimensional array. Here's an example to declare and initialize
multidimensional array.
{4.1, -1.1}
};
Before learning multidimensional array, visit Java array article to learn about one-dimensional
array.
In that chapter, you learned to create and use array of primitive data types (like: Double, int etc.),
String array, and array of objects. It's also possible to create an array of arrays known as
multidimensional array. For example,
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of type int.
2d arrays in Java
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not
1.
Here, personalInfo is a 3d array that can hold maximum of 24 (3*4*2) elements of type String.
If you know C/C++, you may feel like, multidimensional arrays in Java and C/C++ works in similar
way. Well, it doesn't. In Java, rows can vary in length.
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
As mentioned, each component of array a is an array in itself, and length of each rows is also
different.
class MultidimensionalArray {
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Since each component of a multidimensional array is also an array (a[0], a[1] and a[2] are also
arrays), you can use length attribute to find the length of each rows.
int[][] a = {
{7},
};
System.out.println(a[i][j]);
It's better to use for..each loop to iterate through arrays whenever possible. You can perform the
same task using for..each loop as:
class MultidimensionalArray {
int[][] a = {
{7},
};
System.out.println(data);
-2
-4
-5
You can initialize 3d array in similar way like a 2d array. Here's an example:
// test is a 3d array
int[][][] test = {
{
{1, -2, 3},
{2, 3, 4}
},
{1},
{2, 3}
};
class ThreeArray {
// test is a 3d array
int[][][] test = {
{2, 3, 4}
},
{2, 3}
};
System.out.println(item);
-2
-4
-5
6
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++
In this article, you will learn about different ways you can use to copy arrays (both one
dimensional and two-dimensional) in Java.
There are several techniques you can use to copy arrays in Java.
class CopyArray {
}
}
1, 2, 3, 4, 5, 6
Though this technique to copy arrays seem to work perfectly, there is a problem with it.
If you change elements of one array in the above example, corresponding elements of the other
array is also changed.
class AssignmentOperator {
numbers[0] = -1;
-1, 2, 3, 4, 5, 6
When the first element of numbers array is changed to -1, the first element of positiveNumbers
array also becomes -1. It's because both arrays refers to the same array object.
However, most often, we need deep copy rather than shallow copy. A deep copy copies the
values creating the new array object.
import java.util.Arrays;
class ArraysCopy {
destination[i] = source[i];
System.out.println(Arrays.toString(destination));
}
When you run the program, the output will be:
[1, 2, 3, 4, 5, 6]
Here, for loop is used to iterate through each element of source array. In each iteration,
corresponding element of source array is copied to destination array.
The source and destination array doesn't share the same reference (deep copy). Meaning, if
elements of one array (either source or destination) is changed, corresponding elements of
another array is unchanged.
The toString() method is used to convert array to string (for the purpose of output only).
There is a better way (than using loops) to copy arrays in Java by using arraycopy() and
copyOfRange() method.
The System class contains arraycopy() method that allows you to copy data from one array to
another.
The arraycopy() method is efficient as well as flexible. The method allows you to copy a specified
portion of the source array to the destination array.
Here,
import java.util.Arrays;
class ArraysCopy {
n3 = [0, 12, 4, 0, 0]
Additionally, you can use copyOfRange() method defined in java.util.Arrays class to copy arrays.
You do not need to create the destination array before this method is called. Visit this page to
learn more about copyOfRange() method.
import java.util.Arrays;
class ArraysCopy {
import java.util.Arrays;
class ArraysCopy {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
};
int[][] destination = new int[source.length][];
destination[i][j] = source[i][j];
System.out.println(Arrays.deepToString(destination));
You can see we've used Arrays' deepToString() method here. deepToString() provides better
representation of a multi-dimensional array as in a 2 dimensional array. Learn more about
deepToString().
You can replace the inner loop of the above code with System.arraycopy() or Arrays.copyOf()
array as in case of one-dimensional array.
Here's an example to do the same task with arraycopy() method.
import java.util.Arrays;
class AssignmentOperator {
int[][] source = {
{1, 2, 3, 4},
{5, 6},
};
System.out.println(Arrays.deepToString(destination));
}
}
==============================================================================
=======
In this program, you'll learn different techniques to print the elements of a given array in Java.
System.out.println(element);
In the above program, the for-each loop is used to iterate over the given array, array.
import java.util.Arrays;
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5]
In the above program, the for loop has been replaced by single line of code using
Arrays.toString() function.
As you can see, this gives a clean output without any extra lines of code.
import java.util.Arrays;
System.out.println(Arrays.deepToString(array));
In the above program, since each element in array contains another array, just using
Arrays.toString() prints the address of the elements (nested array).
To get the numbers from the inner array, we just another function Arrays.deepToString(). This
gets us the numbers 1, 2 and so on, we are looking for.
==============================================================================
=
In this program, you'll learn to convert an array to a set and vice versa in Java.
import java.util.*;
Set: [a, b, c]
In the above program, we've an array named array. To convert array to set, we first convert it to a
list using asList() as HashSet accepts list as a constructor.
import java.util.*;
In the above program, instead of converting array to list and then to a set, we use stream to
convert to set.
We first convert the array to stream using stream() method and use collect() method with toSet()
as parameter to convert the stream to a set.
import java.util.*;
set.add("a");
set.add("b");
set.add("c");
set.toArray(array);
System.out.println("Array: " + Arrays.toString(array));
Array: [a, b, c]
In the above program, we've a HashSet named set. To convert set into an array, we first create an
array of length equal to the size of the set and use toArray() method.
In this program, you'll learn different techniques to convert byte array to hexadecimal in Java.
System.out.print(st);
}
}
0A020F0B
In the above program, we have a byte array named bytes. To convert byte array to hex value, we
loop through each byte in the array and use String's format().
We use %02X to print two places (02) of Hexadecimal (X) value and store it in the string st.
This is relatively slower process for large byte array conversion. We can dramatically increase the
speed of execution using byte operations shown below.
}
public static void main(String[] args) {
String s = bytesToHex(bytes);
System.out.println(s);