Vous êtes sur la page 1sur 31

JAVA ARRAY

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.

How to declare an array?

Here's how you can declare an array in Java:

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.

Let's take the above example again.

Double[] data;

Here, data is an array that can hold values of type Double.

But, how many elements can array this hold?

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.

Let's take another example:

int[] age;

age = new int[5];

Here, age array can hold 5 values of type int.

It's possible to declare and allocate memory of an array in one statement. You can replace two
statements above with a single statement.

int[] age = new int[5];

Java Array Index

You can access elements of an array by using indices. Let's consider previous example.

int[] age = new int[5];

Java array index

The first element of array is age[0], second is age[1] and so on.

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 {

public static void main(String[] args) {

int[] age = new int[5];

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]);

When you run the program, the output will be:

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) {

int[] age = new int[5];

for (int i = 0; i < 5; ++i) {

System.out.println(age[i]);

How to initialize arrays in Java?

In Java, you can initialize arrays during declaration or you can initialize (or change values) later in
the program as per your requirement.

Initialize an Array During Declaration

Here's how you can initialize an array during declaration.

int[] age = {12, 4, 5, 2, 5};

This statement creates an array and initializes it during declaration.

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.

Java arrays with elements

Let's write a simple program to print elements of this array.


class ArrayExample {

public static void main(String[] args) {

int[] age = {12, 4, 5, 2, 5};

for (int i = 0; i < 5; ++i) {

System.out.println("Element at index " + i +": " + age[i]);

When you run the program, the output will be:

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

How to access array elements?

You can easily access and alter array elements by using its numeric index. Let's take an example.

class ArrayExample {

public static void main(String[] args) {

int[] age = new int[5];


// insert 14 to third element

age[2] = 14;

// insert 34 to first element

age[0] = 34;

for (int i = 0; i < 5; ++i) {

System.out.println("Element at index " + i +": " + age[i]);

When you run the program, the output will be:

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

Example: Java arrays

The program below computes sum and average of values stored in an array of type int.

class SumAverage {

public static void main(String[] args) {

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};


int sum = 0;

Double average;

for (int number: numbers) {

sum += number;

int arrayLength = numbers.length;

// Change sum and arrayLength to double as average is in double

average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);

System.out.println("Average = " + average);

When you run the program, the output will be:

Sum = 36

Average = 3.6

Couple of things here.

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.

Double[][] matrix = {{1.2, 4.3, 4.0},

{4.1, -1.1}

};

Here, matrix is a 2-dimensional array. Visit this page to learn in


detail about multidimensional array in Java.

Java Multidimensional Arrays

In Java, you can declare an array of arrays known as multidimensional array.

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,

int[][] a = new int[3][4];

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.

Similarly, you can declare a three-dimensional (3d) array. For example,

String[][][] personalInfo = new String[3][4][2];

Here, personalInfo is a 3d array that can hold maximum of 24 (3*4*2) elements of type String.

In Java, components of a multidimensional array are also arrays.

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.

You will see the difference during initialization.

How to initialize a 2d array in Java?

Here's an example to initialize a 2d array in Java.

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.

2d array example in Java with variable length


Let's write a program to prove it.

class MultidimensionalArray {

public static void main(String[] args) {

int[][] a = {

{1, 2, 3},

{4, 5, 6, 9},

{7},

};

System.out.println("Length of row 1: " + a[0].length);

System.out.println("Length of row 2: " + a[1].length);

System.out.println("Length of row 3: " + a[2].length);

When you run the program, the output will be:

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.

Example: Print all elements of 2d array Using Loop


class MultidimensionalArray {

public static void main(String[] args) {

int[][] a = {

{1, -2, 3},

{-4, -5, 6, 9},

{7},

};

for (int i = 0; i < a.length; ++i) {

for(int j = 0; j < a[i].length; ++j) {

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 {

public static void main(String[] args) {

int[][] a = {

{1, -2, 3},

{-4, -5, 6, 9},

{7},
};

for (int[] innerArray: a) {

for(int data: innerArray) {

System.out.println(data);

When you run the program, the output will be:

-2

-4

-5

How to initialize a 3d array in Java?

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}

},

{-4, -5, 6, 9},

{1},

{2, 3}

};

Basically, 3d array is an array of 2d arrays.

Similar like 2d arrays, rows of 3d arrays can vary in length.

Example: Program to print elements of 3d array using loop

class ThreeArray {

public static void main(String[] args) {

// test is a 3d array

int[][][] test = {

{1, -2, 3},

{2, 3, 4}

},

{-4, -5, 6, 9},


{1},

{2, 3}

};

// for..each loop to iterate through elements of 3d array

for (int[][] array2D: test) {

for (int[] array1D: array2D) {

for(int item: array1D) {

System.out.println(item);

When you run the program, the output will be:

-2

-4

-5
6

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++

Java Copy Arrays

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.

1. Copying Arrays Using Assignment Operator

Let's take an example,

class CopyArray {

public static void main(String[] args) {

int [] numbers = {1, 2, 3, 4, 5, 6};

int [] positiveNumbers = numbers; // copying arrays

for (int number: positiveNumbers) {

System.out.print(number + ", ");

}
}

When you run the program, the output will be:

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 {

public static void main(String[] args) {

int [] numbers = {1, 2, 3, 4, 5, 6};

int [] positiveNumbers = numbers; // copying arrays

numbers[0] = -1;

for (int number: positiveNumbers) {

System.out.print(number + ", ");

When you run the program, the output will be:

-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.

This is called shallow copy.

However, most often, we need deep copy rather than shallow copy. A deep copy copies the
values creating the new array object.

2. Using Looping Construct to Copy Arrays

Let's take an example:

import java.util.Arrays;

class ArraysCopy {

public static void main(String[] args) {

int [] source = {1, 2, 3, 4, 5, 6};

int [] destination = new int[6];

for (int i = 0; i < source.length; ++i) {

destination[i] = source[i];

// converting array to string

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.

3. Copying Arrays Using arraycopy() 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.

public static void arraycopy(Object src, int srcPos,

Object dest, int destPos, int length)

Here,

src - array you want to copy

srcPos - starting position (index) in the src array


dest - elements of src array will be copied to this array

destPos - starting position (index) in the dest array

length - number of elements to copy

Let's take an example:

// To use Arrays.toString() method

import java.util.Arrays;

class ArraysCopy {

public static void main(String[] args) {

int[] n1 = {2, 3, 12, 4, 12, -2};

int[] n3 = new int[5];

// Creating n2 array of having length of n1 array

int[] n2 = new int[n1.length];

// copying entire n1 array to n2

System.arraycopy(n1, 0, n2, 0, n1.length);

System.out.println("n2 = " + Arrays.toString(n2));

// copying elements from index 2 on n1 array

// copying element to index 1 of n3 array

// 2 elements will be copied

System.arraycopy(n1, 2, n3, 1, 2);


System.out.println("n3 = " + Arrays.toString(n3));

When you run the program, the output will be:

n2 = [2, 3, 12, 4, 12, -2]

n3 = [0, 12, 4, 0, 0]

Note, the default initial value of elements of an int type array is 0.

4. Copying Arrays Using copyOfRange() method

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.

Here's how you can do it.

// To use toString() and copyOfRange() method

import java.util.Arrays;

class ArraysCopy {

public static void main(String[] args) {

int[] source = {2, 3, 12, 4, 12, -2};

// copying entire source array to destination

int[] destination1 = Arrays.copyOfRange(source, 0, source.length);


System.out.println("destination1 = " + Arrays.toString(destination1));

// copying from index 2 to 5 (5 is not included)

int[] destination2 = Arrays.copyOfRange(source, 2, 5);

System.out.println("destination2 = " + Arrays.toString(destination2));

When you run the program, the output will be:

destination1 = [2, 3, 12, 4, 12, -2]

destination2 = [12, 4, 12]

5. Copying 2d Arrays Using Loop

Here's an example to copy irregular 2d arrays using loop:

import java.util.Arrays;

class ArraysCopy {

public static void main(String[] args) {

int[][] source = {

{1, 2, 3, 4},

{5, 6},

{0, 2, 42, -4, 5}

};
int[][] destination = new int[source.length][];

for (int i = 0; i < destination.length; ++i) {

// allocating space for each row of destination array

destination[i] = new int[source[i].length];

for (int j = 0; j < destination[i].length; ++j) {

destination[i][j] = source[i][j];

// displaying destination array

System.out.println(Arrays.deepToString(destination));

When you run the program, the output will be:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

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 {

public static void main(String[] args) {

int[][] source = {

{1, 2, 3, 4},

{5, 6},

{0, 2, 42, -4, 5}

};

int[][] destination = new int[source.length][];

for (int i = 0; i < source.length; ++i) {

// allocating space for each row of destination array

destination[i] = new int[source[i].length];

System.arraycopy(source[i], 0, destination[i], 0, destination[i].length);

// displaying destination array

System.out.println(Arrays.deepToString(destination));

}
}

==============================================================================
=======

Java Program to Print an Array

In this program, you'll learn different techniques to print the elements of a given array in Java.

Example 1: Print an Array using For loop

public class Array {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5};

for (int element: array) {

System.out.println(element);

When you run the program, the output will be:

In the above program, the for-each loop is used to iterate over the given array, array.

It accesses each element in the array and prints using println().


Example 2: Print an Array using standard library Arrays

import java.util.Arrays;

public class Array {

public static void main(String[] args) {

int[] array = {1, 2, 3, 4, 5};

System.out.println(Arrays.toString(array));

When you run the program, the output will be:

[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.

Example 3: Print a Multi-dimenstional Array

import java.util.Arrays;

public class Array {


public static void main(String[] args) {

int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}};

System.out.println(Arrays.deepToString(array));

When you run the program, the output will be:

[[1, 2], [3, 4], [5, 6, 7]]

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.

This function works for 3-dimensional arrays as well.

==============================================================================
=

Java Program to Convert Array to Set (HashSet) and Vice-Versa

In this program, you'll learn to convert an array to a set and vice versa in Java.

Example 1: Convert Array to Set

import java.util.*;

public class ArraySet {

public static void main(String[] args) {


String[] array = {"a", "b", "c"};

Set<String> set = new HashSet<>(Arrays.asList(array));

System.out.println("Set: " + set);

When you run the program, the output will be:

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.

Then, we initialize set with the elements of the converted list.

Example 2: Convert Array to Set using stream

import java.util.*;

public class ArraySet {

public static void main(String[] args) {

String[] array = {"a", "b", "c"};

Set<String> set = new HashSet<>(Arrays.stream(array).collect(Collectors.toSet()));

System.out.println("Set: " + set);


}

The output of the program is same as Example 1.

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.

Example 3: Convert Set to Array

import java.util.*;

public class SetArray {

public static void main(String[] args) {

Set<String> set = new HashSet<>();

set.add("a");

set.add("b");

set.add("c");

String[] array = new String[set.size()];

set.toArray(array);
System.out.println("Array: " + Arrays.toString(array));

When you run the program, the output will be:

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.

Java Program to Convert Byte Array to Hexadecimal

In this program, you'll learn different techniques to convert byte array to hexadecimal in Java.

Example 1: Convert Byte Array to Hex value

public class ByteHex {

public static void main(String[] args) {

byte[] bytes = {10, 2, 15, 11};

for (byte b : bytes) {

String st = String.format("%02X", b);

System.out.print(st);

}
}

When you run the program, the output will be:

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.

Example 2: Convert Byte Array to Hex value using byte operations

public class ByteHex {

private final static char[] hexArray = "0123456789ABCDEF".toCharArray();

public static String bytesToHex(byte[] bytes) {

char[] hexChars = new char[bytes.length * 2];

for ( int j = 0; j < bytes.length; j++ ) {

int v = bytes[j] & 0xFF;

hexChars[j * 2] = hexArray[v >>> 4];

hexChars[j * 2 + 1] = hexArray[v & 0x0F];

return new String(hexChars);

}
public static void main(String[] args) {

byte[] bytes = {10, 2, 15, 11};

String s = bytesToHex(bytes);

System.out.println(s);

The output of the program is same as Example 1.

Vous aimerez peut-être aussi