Creating and Using Java Array Tutorial

Welcome to the creating and using Java array tutorial offered by Simplilearn. The tutorial is a part of the Java Certification Training Course.

Let us begin by looking into the objectives of this tutorial in the next section.

Objectives

At the end of this creating and using one-dimensional Java array tutorial, you will be able to -

  • Declare, initialize, and use a one-dimensional Java array,

  • Declare, initialize, and use multidimensional Java arrays.

In the next section, let us start by declaring a one-dimensional Java array.

Declaring One-dimensional Java Array

An array is a data structure that stores elements of similar data types.

For example, if we want to store three different integer variables A, B, and C in our RAM, the computer would allocate space for these variables wherever it finds space in the system.

Thus, there would not be any specific memory area to select, because, it completely depends on the system in terms of where it is going to allocate space for the three variables A, B, and C. This means that, when it comes to retrieving these values, the system will have to do three read operations from three different memory locations to get these values back.

On the other hand, since all the three values are storing integer variables, we can allocate a block of memory which is continues where we can store all our values back to back. In this case, the moment the computer retrieves the start point of the storage area it knows that the rest of the values are right after that so the retrieval and the storage of data is much faster as compared to creating multiple variables.

Arrays can be declared using square brackets.

char [ ] s;

Point[ ] p;  //where Point is a class

[image]

In the above code, we are declaring a character array of point p, where the point p is a custom class that we have created. Once the array is declared, we will have multiple chambers or elements in the array in which we can store values and the array would have a length or dimension based on how many values we would want to store in it.

The array in java is index based; the first element of the array is stored at the zero index, the second element is stored at index number one. Thus, If we want to retrieve the first value, we need to give a box bracket of zero, which will get us the first value.

In the next section, we will learn about initializing one-dimensional Java array.

Initializing One-dimensional Java Array

To initialize all variables, including the elements of the array, it is essential to secure the system.

Initialization Example:

To initialize all variables including elements of arrays, it is essential to secure the system. Thus, from the initialization example above, we have an array called names which is an array of strings which has three values assigned to it.

We can use this syntax shown in the first initialization example or the second one which is simpler and says - string, box bracket indicating an array, and name which is the name of the array. Then, we allocate memory for the array of size three. Therefore, when the first line of code executes, all it does is on the stack, it creates a pointer called names.

The moment the second line of the code executes, we say that it is an array with three elements of the type string, so it'll start pointing onto the heap segment of the memory and we will allocate a space for three string values to be stored, which are John, James, and Simon in this case. Thus, the asterisk names array name will point to the start address in the memory where the entire array block has got allocated.

String[ ] names =

{

“John”,

“James”,

“Simon”

};

This code is equal to:

String[ ] names;

names = new String [3];

names [0] = “John”;

names [1] = “James”;

names [2] = “Simon”;

In the next section, we will learn about creating one-dimensional Java array.

Creating a One-dimensional Java Array

We can create Java arrays using the new keyword.

S = new char[26];

Here, we have created an array ‘S’ equal to the new character 26.

[image]

From the image given above, we see the main method of Java getting loaded onto the stack. The ‘this’ pointer, which is a reference to the current method or object is referencing the method.

Then we see the array “s”, actually getting allocated on the stack.

This will now point to the heap. The heap memory of the segment of the ram, which will actually have the twenty-six blocks defined will store individual characters.

[image at 26.53]

public char[ ] CreateArray ()

{

char[ ] S;

S= new char[26];

for (int i=0; i<26; i++)

{

S[i] = (char) (‘A’ + i);

}

return S;

}

Here, in the code, we have a create array function which declares a character array this initializes memory with the new keyword for the character array with twenty-six blocks. The for loop runs from zero to twenty-six and states that S of i or ( S[i] ) is zero initially. Thus, S[0] or S of zero will be the character typecast of the alphabet A plus zero.

This will be stored at S of zero or S[0]. Similarly, on the next iteration of the for loop, ‘i’ will become 1, then 2, and henceforth it will be converted to a character and stored in S[0], S[1], S[2]; that is, S of zero, S of one, S of two. Hence, every block in the allocated memory area of the heap will have an individual value stored in the array and finally, we just return the array.

Thus, we have the main method on the stack, ‘this’ is the pointer to the current object calling the method, ‘S’ is the array, and ‘S’ is pointing to a memory location, which has a  block of code allocated continuously which will have values starting from A and going right up to Z and that is stored on the heap as shown in the above image.

[image at 6.40]

p = new Point[10];

public Point[ ] CreateArray ()

{

Point[ ] p;

p= new Point[10];

for (int i=0; i<10; i++)

{

p[i] = new Point (i, i+1);

}

return p;

}

Here, we find an array of the custom class. We have an array of a class called a point. We are creating an array and allocating memory for ten point objects.

We then run the for loop so that, at p[0] or p of zero, we store a new point object which will have two values - ‘i’ is zero and ‘i’ plus one will be one, and these are the coordinates of the x and y coordinates of the point.

We then run the for loop again, and ‘i’ will increment to one. Thus, p[1] or p of one will store the next value which is one and two.

Hence, we can find the main method being loaded onto the stack. The ‘this’ pointer which has a reference to the current object and the pointer p which is of type point which is pointing to the block of arrays or the block of code or the entire array block which is allocated on the heap.

Thus, p of zero or p[0] will actually have a point object inside it, so there will be an object stored inside and that object will further have two values, zero, which is the value of i and i plus one which will be one.

Similarly, in the second element of the array, which is p of one or p[1]; this would be p of zero or p[0] which will be the first element inside the array. This is going to be p of one or p[1] which will be the second element in the array.

Hence, it is a zero-based index, p of one will return the second element. The second element is again a point object, which has two values - i and i plus one. So the current value of i after the for loop is being executed the second time will be 1, and i plus one will be two. So these are the x and y coordinates of the second point object. And similarly, all the point objects will get stored in the respective memory location continuously back to back as an array data structure.

In the next section, we will look at an example to declare, instantiate, initialize, and print the Java array.

How about investing your time in Java Certification Course? Take a look at the course preview NOW!

Declare, Instantiate, Initialize, and Print Java Array—Example

Given below is an example of how to declare, instantiate, initialize, and print an array.

In this example, we have an integer array defined by five elements. It is a zero-based index, thus ‘a of zero’ of a[0] is ten, ‘a of one’ or a[1] will hold the value twenty, ‘a of two’ or a[2] will hold the value sixty, ‘a of three’ or a[3] will hold the value forty, and so on.

Next, if we want to print it, we can say integer i equals zero. The integer i should go up to the length of the array which is “ a.length, i++ ” and we simply keep printing, a[i]. Therefore, since i will have an initial value of zero, so a[0] will print 10. Similarly, a[1] will print 20 and so on. Therefore, these are the outputs obtained for the values stored inside the array.

class Testarray

{

public static void main(String args[ ])

{

int a[ ]=new int[5];                     //declaration and instantiation

a[0]=10; //initialization

a[1]=20;

a[2]=60;

a[3]=40;

a[4]=50;

//printing array

for(int i=0;i<a.length;i++)         //length is the property of array

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

}}

Output:

10

20

60

40

50

In the next section, we will learn creating an the Java array using the new keyword.

Creating the Java Array Using New Keyword

Let us now create an array using the new keyword.

// Declaration of allocating memory to an array

int iarr[ ] = new int[3];

// Initializing elements

iarr[0] = 1;

iarr[1] = 2;

iarr[2] = 3;

//Display array elements

System.out.println(iarr[0]);

System.out.println(iarr[1]);

System.out.println(iarr[2]);

// Or Use for loop to display elements

for (int i = 0; i < iarr.length; i = i + 1)

{

System.out.print(iarr[i]);

System.out.print(" ");

}

Output:

10

20

60

40

50

Here, we have an integer array directly initialized to new integer three. This will create an array of three elements. In the first element of the array, we are trying to print store a value, which is one, two and three in the second and the third element respectively. Since it is a zero-based index, it will start at zero, one, and two and then we print out those values. We can hence use a for loop to get the printing done.

In the next section, we will look at an example to learn how to delete an element from the Java array.

Delete an Element from the Java Array—Example

In this example, we will learn how to delete an element from an array and also learn accepting values from the end user so that the end user can provide those values to us. Once the values are provided to us, we should be able to accept them into our program and then insert them into the array.

import java.util.Scanner;

public class Delete

{

public static void main(String[ ] args)

{

int n, x, flag = 1, loc = 0;

Scanner s = new Scanner(System.in);

System.out.print("Enter no. of elements you want in array:");

n = s.nextInt();

int a[ ] = new int[n];

System.out.println("Enter all the elements:");

for (int i = 0; i < n; i++)

{

a[i] = s.nextInt();

}

System.out.print("Enter the element you want to delete:");

x = s.nextInt();

for (int i = 0; i < n; i++)

{

if(a[i] == x)

{

flag =1;

loc = i;

break;

}

else

{

flag = 0;

}

}

if(flag == 1)

{

for(int i = loc+1; i < n; i++)

{

a[i-1] = a[i];

}

System.out.print("After Deleting:");

for (int i = 0; i < n-2; i++)

{

System.out.print(a[i]+",");

}

System.out.print(a[n-2]);

}

else

{

System.out.println("Element not found");

}

}

}

Here, we are declaring four variables, n, x, flag, and location (loc).

We are creating an object of the scanner class, which holds a reference to system.in, this allows us to accept values from the end user. We will import the package that provides us with this capability since we are using an API which is the default core Java capability.

We are telling the user to enter the number of elements you want in the array, s.nextInt( ) captures the value the user enters and stores it in the variable n.

Suppose the user says that they want an array of five elements and enters five, the integer array gets declared and initialized with the size of five.

We then tell the user to enter all the elements that he wants to store in the array of size five or length five. We run a for loop and we keep saying s.nextInt(), whether the user can enter individual values that he wants to store in a of zero or a[0], a of one or a[1], a of two or a[2], so the entire array will have values populated inside them based on the input given by the user.

The user will determine which the element they want to delete. In the locations zero, one, two, three, we can store values, ten, twenty, thirty, forty. We then ask the user if they want to delete forty or ten or any other. It then stores that value in the variable x.

We will then run a for loop so we can run through the entire iterate to the entire array. The moment a of i or a[i] is equal equal to the value x, that is, if(a[i] == x) ; and the moment we reach forty, this is the value we want to search for. We then set the flag to one indicating that we have found the value, we set the location to i, so the location will now be three; saying that this is where the value that you are searching for to be deleted is located and we simply break out of the code. This means that the for loop will simply exit.

Next, we check if the flag is equal to one. If the flag is one, it indicates that the element to delete has been found in the array. In such a case we run another for loop starting from integer i equal to location plus one; so if the location is three, since it is a zero-based index, three plus one gives four. Hence, forty is at the fourth position in the array.

Therefore, the loop runs from zero up to the fourth position, this is done because, since this element is now empty, we want to shift elements from the left to the right such that there is no empty gap in between and ultimately delete the value forty. Thus, a[i-1] = a[i], which means that whatever value is present in a[3] will get shifted to a[2] and the value that was previously entered will get deleted. After deleting the array, we run the for loop again so that we print the updated array post deletion. If the value of the flag is not one, The if condition “if(flag == 1)” will not execute, it will instead go to the else and print out that the Element not found, and therefore we won’t be able to delete anything from the array.

In order to run this program, you can simply execute it, either from the command prompt or directly in eclipse.

$ javac Delete.java
$ java Delete
Enter number of elements you want in the array: 5
Enter all the elements: 3 5 8 1 4
Enter the element you want to delete: 5
After Deleting: 3 8 1 4

You could enter the number of elements you want in the array, which is five. Next, You enter all the values. Thus, from the four values, we want to store, and the values we want to delete from that is the element five. With the value five, you can see the updated array which is three eight one four. Which means that all these values shifted to the left and occupied that space and the data that was there, which is number five, has got deleted.

In the next section, we will learn how to create a multi-dimensional Java array using the new keyword.

Creating a Multi-dimensional Java Array Using New Keyword

A multi-dimensional array would have two dimensions, a left, and a right dimension.

[image at 0.14]

So the data would be stored in a row and column-based index, which is also called a matrix. This means that, if we declare an array of four by four, we can start storing values in it in the format shown above.

We have, a[0][0]; which means zero in the first row and the first column, giving the value in the first cell. We can say, a[1][0] to position the value in the respective grid which is placed below the previously entered value and this is also called a two-dimensional array.

Let us now understand how to initialize.

int [ ] [ ] twoDim = new int [4] [5];

twoDim [0] = new int [5];

twoDim [1] = new int [5];

int [ ] [ ] twoDim = new int [4] [5];

Here we have a two-dimensional array. In the “ int [ ] [ ] twoDim = new int [4] [5]; ” we have two dimensions, which is equal to the new integer, four and five. Thus we have a system of four arrays of five elements each which give rise to the grid as shown in the image above.

The first array has been initialized to two-dimension of zero will have five elements, two- dimension of one will also have five elements. This involves creating a two-dimensional array of four arrays of five integers each.

In the next section, we will learn about initializing the multi-dimensional Java array using the new keyword.

You too can join the high-earners club. Enroll our Java Certification Course and earn more today.

Initializing Multi-dimensional Java Array Using New Keyword

Here is an example of a two-dimensional array.

int iarr[ ][ ] = new int[2][3];

iarr[0][0] = 1; // Initializing elements

iarr[0][1] = 2;

iarr[0][2] = 3;

iarr[1][0] = 4;

iarr[1][1] = 5;

iarr[1][2] = 6;

System.out.println(iarr[0][0]); //Display array elements

System.out.println(iarr[0][1]);

System.out.println(iarr[0][2]);

System.out.println(iarr[1][0]);

System.out.println(iarr[1][1]);

System.out.println(iarr[1][2]);

for (int i = 0; i < iarr.length; i = i + 1)

{

for(int j=0; j < iarr[i].length; j = j + 1)

{

System.out.print(iarr[i][j]);

System.out.print(" ");

}

}

In this example, we are declaring an array of two by three, which means that in the code line - “ int iarr[ ][ ] = new int[2][3]; ” there will be three elements like zero, one, and two; that is, there will be integer 0, integer 1, integer 2. This is how we can create a grid of elements.

Therefore, the array [0][0] will have a value of one, [0][1] will have the value of 2, and so on.

We then simply print the value from the [0][0] one to [1][0], [1][2]. We can also perform this with the help of the nested for loop using the code - “ for (int i = 0; i < iarr.length; i = i + 1) ” ; the inner loop will run from - “ for(int j=0; j < iarr[i].length; j = j + 1) ” . When we want to print out the value,  you can find that, if i=0, j=0, it will initially be zero, after that the inner for loop will run again and i will incriminate to one. In the next iteration, it will become [0][1].

Once that’s done, it will once again become [0][2]. After that, if the length is met, it will jump to the outer array and i will become 1. Thus, on the next run-

  • i will be one and j will be zero,

  • I will be one and j will be two

  • I will be one and j will be three, etc.

This is how the loop will run and pick out all the values in the same manner that we have stored and displayed them.

In the next section, we will learn how to declare a multi-dimensional Java array.

Declaring a Multi-dimensional Java Array

Multi-dimensional arrays in Java are different from those in other languages. In Java, you can create an array, arrays of arrays, and so on. The syntax for this as shown below -

Syntax:

dataType[ ][ ] arrayRefVar;  

In the next section, we will learn the primitive Java array.

Primitive Array

When we create a primitive array, default values will be assigned, but when you create an array of objects, the object references will be null. In Java 8, you can use the Stream APIs to do the boxing and conversion to convert from a primitive array to an object array which is of type object.

In the example shown, you see a primitive array, it is an array of the primitive type int.

List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());

Here again, you see an array of the primitive type int.

  1. int counts[ ] ;

  2. int[ ] counts ; // 1 and 2 are equivalent

  3. boolean flags [ ] ; // extra spaces are not significant

  4. String names[ ] ;

  5. MyClass[ ][ ] things ; // a two-dimensional array of objects

Let us learn about each of these in brief-

  • Both “int counts[ ]” and “int[ ] counts” are similar,

  • In the “boolean flags [ ]”, you can find an array of the primitive type boolean.

  • In “String names[ ]”, you can find an array of the type string. It inherits from the type object, and hence, it is of the type string.

  • “MyClass[ ][ ] things” is a two-dimensional array, which is of the type object, which is of type my class.

Here is an example where you see how to convert the primitive array to list.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class ArrayExample2

{

public static void main(String[] args)

{

int[ ] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

//List<Integer> list = IntStream.of(number).boxed().collect(Collectors.toList());

List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList());

System.out.println("list : " + list);

}

}

Here, we have an integer at int[ ] number, which is equal to multiple sets of values. This is a simple primitive array like we have been declaring. We now have the list of integers equal to Array.stream - “ List<Integer> list = Arrays.stream(number).boxed().collect(Collectors.toList()); ” we are passing the Array.boxed.collect and converting it to a list. This when output, gives values separated by commas like a list object.

In the next section, we will learn the java.util.Arrays class.

java.util.Arrays Class

java.util.Arrays is a static class that allows that is to be viewed as lists. It contains various methods for manipulating arrays (such as sorting and searching) and if you convert it to a list you have benefits like calling methods to sort and search values in the list. The methods in this class through another point or exception if the specified reference is null.

Some of the key methods in java.util.Arrays class are:

Method Name

Description

binarySearch (array, value)

returns the index of the given value in a sorted array (or < 0 if not found)

binarySearch (array, minIndex, maxIndex, value)

returns the index of given value in a sorted array between indexes min/max – 1 (< 0 if not found)

copyOf (array, length)

returns a new resized copy of an array

equals (array1, array2)

returns true if the two arrays contain the same elements in the same order

fill (array, value)

sets every element to the given value

sort (array)

arranges the elements into sorted order

toString (array)

returns a string representing the array, such as “[10, 30, -25, 17]”

Syntax:

Arrays.methodName (parameters)

Summary

Let us summarize what we have learned in this creating and using Java arrays tutorial:

  • An array is a data structure that stores elements of similar data types.

  • You can create arrays using a new keyword.

  • Arrays can be declared using square brackets after the variable name.

  • Initializing all variables, including elements of arrays, is essential to secure the system.

  • In multi-dimensional arrays, data is stored in a row- and column-based index.

  • When we create a primitive array, default values will be assigned, but object references

  • will be null.

  • java.util.Arrays is a static class that allows arrays to be viewed as lists.

Conclusion

With this, we come to an end to the creating and using Java arrays tutorial.

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 12 Oct -24 Nov 2019, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*