Java – Arrays Basics
In this tutorial, you’ll learn about Arrays in Java and how you can use the one dimensional arrays and two dimensional arrays in your Java applications.
[toc]
Introduction of Arrays in Java
An array in Java is a collection of similar types of elements with a contiguous memory location. In an array, we can store the same data structure elements. Java array inherits the Object class and implements the Serializable as well as Clone-able interfaces. We can store primitive values or objects in an array in Java. Java supports single and multidimensional arrays.
Let’s see them in detail.
Array Indices
Indexing an array starts with 0: [0], which is the first element. Elements in an array of N integers can be searched using
- Binary search
- Linear search
- Guava
- Stream api
- Using array list
- Using recursion
One Dimensional Array
One dimensional array contains one row and one column of element of same data structure which makes it linear in structure.
Syntax for one-dimensional arrays
The general form of a one-dimensional array declaration is
type var-name[]; OR type[] var-name;
In this syntax , type declares the element type of the array.
Example of 1D Array
Input
public class Main{ public static void main(String args[]){ int a[]=new int[5]; a[0]=111; a[1]=112; a[2]=113; a[3]=114; a[4]=115; for(int i=1;i<a.length;i++) System.out.println(a[i]); }}
Output
112 113 114 115
Array Literal
The null literal is used to represent the absence of an object, and can also be used to represent the absence of an array. For example:
String [] name = null;
If you know the size and variables of array, array literals can be used.
Accessing Array Elements using For Loop
The elements in the array can be accessed through the following methods.
Using for loop
You can use a “for loop” to access the array element. While using the ‘for loop’ a counter variable accesses each element of the array.
Sample program using for loop to access the elements of an array
import java.io.*; public class Main { public static void main(String args[]) throws IOException { int ar[] = { 111, 112, 113, 114, 115, 116, 117, 118 }; int i, a; for (i = 0; i < ar.length;i++) { a = ar[i]; System.out.print(a + " "); } } }
Output:
111 112 113 114 115 116 117 118
Using for each loop
‘For each’ is a traversing technique, were this loop optimizes the code, save typing and time.
Here we declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
Sample program using for each to access the elements in an array.
import java.io.*; public class Main { public static void main(String args[]) throws IOException { int ar[] = { 111, 112, 113, 114, 115,}; int a; for (int i : ar) { a = i; System.out.print(a + " "); } } }
Output:
111 112 113 114 115
Array of Objects
An array is a collection of the same data type that dynamically creates objects. Java allows us to store objects in an array. In Java, the class is also a user-defined data type. An array that conations class type elements are known as an array of objects. Here, it stores the reference variable of the object.
Creating an Array of Objects
You can use any of the following statements to create an array of objects.
Syntax:
ClassName obj[]=new ClassName[array_length]; Or ClassName[] objArray; Or ClassName objeArray[];
Sample program for creating an array of objects
public class Main { public static void main(String args[]) { Product[] obj = new Product[5] ; obj[0] = new Product(11111,"Samsung"); obj[1] = new Product(22222,"Apple"); obj[2] = new Product(33333,"Vivo"); obj[3] = new Product(44444,"Oppo "); obj[4] = new Product(43590,"Huawei "); System.out.println("Product Object 1:"); obj[0].display(); System.out.println("Product Object 2:"); obj[1].display(); System.out.println("Product Object 3:"); obj[2].display(); System.out.println("Product Object 4:"); obj[3].display(); System.out.println("Product Object 5:"); obj[4].display(); } } class Product { int pro_Id; String pro_name; Product(int pid, String n) { pro_Id = pid; pro_name = n; } public void display() { System.out.print("Product Id = "+pro_Id + " " + " Product Name = "+pro_name); System.out.println(); } }
Output:
Product Object 1: Product Id = 11111 Product Name = Samsung Product Object 2: Product Id = 22222 Product Name = Apple Product Object 3: Product Id = 33333 Product Name = Vivo Product Object 4: Product Id = 44444 Product Name = Oppo Product Object 5: Product Id = 55555 Product Name = Huawei
Java Multidimensional Arrays
A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself. Java supports 2-dimensional and 3-dimensional arrays. Let us see the 2D arrays in detail.
2-dimensional array in Java
The 2D array is a collection of rows and columns. These arrays are created to implement a relational database look like data structure. Holding bulk data at once and its related functions can be handled easily using 2D array.
How to initialize a 2d array in Java?
Here is how we can initialize a 2-dimensional array in Java.
Initialization – Syntax:
array_name[row_index][column_index] = value; For example: arr[0][0] = 1;
Sample program for using 2D arrays in Java
class Main { public static void main(String[] args) { int[][] a = { {111, 112, 113}, {114, 115, 116, 119}, {117}, }; 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); } }
Output:
Length of row 1: 3 Length of row 2: 4 Length of row 3: 1
Jagged Array in Java
What is Jagged Array?
Jagged array is a type of multidimensional array where the member arrays are of different size i.e., we can create a 2-D array but with a variable number of columns in each row. These types of arrays are also known as jagged arrays.
Declaration and Initialization of Jagged array:
Syntax
data_type array_name[][] = new data_type[n][]; array_name[] = new data_type[n1] array_name[] = new data_type[n2] array_name[] = new data_type[n3] . . . array_name[] = new data_type[nk]
Arrays and Exceptions
1. NullPointerException -In Java a NullPointerException is a class which also extends RuntimeException. There are the following conditions where the NullPointerException is generated.
- Calling the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
2. NegativeArraySizeException -This error is when you wants create an array with a negative size.
NegativeArraySizeException is a class in Java which extends RuntimeException.
3. ArrayIndexOutOfBoundsException – This type of error is generated when an array has been accessed with an illegal index.
4. IndexOutOfBoundsException – This type of exception is by all indexing pattern data types such as an array string and a vector etc. when it is accessed out of the index (range). IndexOutOfBoundException is also a separate class in Java and it extends RuntimeException.
5. ClassCastException – The ClassCastException is thrown when the following code has attempted to cast an object to a subclass of which it is not an instance.
6. ArrayStoreException – This type of exception is to indicate that an attempt has been made to store the wrong type of object into an array of objects.
How to Pass Arrays to Methods?
You can pass arrays to a method just like normal variables. When you pass an array to a method as an argument, so basically the address of the array in the memory is passed. Therefore, any changes to this array in the method will affect the array.
Example
Input
import java.util.Scanner; public class Main { public static int x(int [] array) { int x = 0; for(int i=0; i<array.length; i++ ) { if(array[i]>x) { x = array[i]; } } return x; } public static int y(int [] array) { int y = array[0]; for(int i = 0; i<array.length; i++ ) { if(array[i]<y) { y = array[i]; } } return y; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created::"); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } System.out.println("Maximum value in the array is::"+x(myArray)); System.out.println("Minimum value in the array is::"+y(myArray)); } }
Output
Enter the size of the array that is to be created: 5 Enter the elements of the array :: 111 112 113 114 115 Maximum value in the array is: 115 Minimum value in the array is: 111
How to Return Arrays from Methods in Java?
We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.
Input
import java.util.Arrays; import java.util.Scanner; public class Main { public static int[] createArray() { Scanner sc = new Scanner(System.in); System.out.println("Enter the size of the array that is to be created:: "); int size = sc.nextInt(); int[] myArray = new int[size]; System.out.println("Enter the elements of the array ::"); for(int i=0; i<size; i++) { myArray[i] = sc.nextInt(); } return myArray; } public static void main(String args[]) { int arr[] = createArray(); System.out.println("Array created is :: "+Arrays.toString(arr)); } }
Output
Enter the size of the array that is to be created:: 5 Enter the elements of the array :: 111 112 113 114 115 Array created is :: [111, 112, 113, 114, 115]
How to Clone Arrays in Java?
Clone methods create a new array of the same size. Let’s see how to clone a array through a program.
Sample program for cloning an array in Java
Input
public class Main { public static void main(String[] args) { int a[] = { 111, 112, 113 }; int b[] = a.clone(); b[0]++; System.out.println("Contents of a[] "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println("\n\nContents of b[] "); for (int i = 0; i < b.length; i++) System.out.print(b[i] + " "); } }
Output
Contents of a[] 111 112 113 Contents of b[] 111 112 113
