What and Why Arrays ?
Array is an object, it is able to allow more than one element of the same Data type as per indexing, where index values may start with 0 and up to size-1.
In Java applications, to represent multiple elements of the same data types we have to use Arrays.
EX-1: To represent Student Marks we will use Integer Array.
EX-2: To represent Employee Qualifications we will use String Array.
EX-3: To represent User skill set we will use String array.
EX-4: To represent movie ratings we will use a float array.
——
——
Array in Java is treated as an Object, and gets created in the Heap area.
In Java, an array is a data structure used to store a collection of elements of the same data type. Arrays are a fundamental part of the Java programming language and provide a way to work with multiple values of the same type efficiently.
In Java, there are two types of Arrays.
- Single Dimensional Arrays
- Multidimensional Arrays
Single Dimensional Arrays
It is able to represent data in a single dimension or in a single row.
There are two approaches to declare and utilize arrays.
- Declare and Initialize
- Declare then Initialize
Declare and Initialize
In this approach, we will declare the array and we will initialize the array in a single line.
Syntax:
DataType[] refVar = {Val_1, val_2,....val_n};EX: int[] intArray = {10,20,30,40,50}; int[] numbers = {1, 2, 3, 4, 5};
int[] numbers2 = new int[]{1, 2, 3, 4, 5};
// ERROR - array creation with both dimension expression and initialization is illegal int[] numbers1 = new int[5]{1, 2, 3, 4, 5}; → INVALIDSystem.out.println(numbers); // [I@1c655221
char[] chars = {'h', 'e', 'l', 'l', 'o'};
System.out.println(chars[0]); // h
Declare then Initialize
In this approach, we will declare the array in one line and we will initialize the array in the next lines.
Syntax:
DataType[] refVar = new DataType[Size];
refVar[0] = val_1;
refVar[1] = val_2;
—---
—---
refVar[size-1] = val_n;
If you don’t provide initialization, all the elements are assigned a default value based on the data type.
EX:
int[] intArray = new int[5];
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;
EX-1:
class Test{
public static void main(String[] args){
//int[] intArray = {10,20,30,40,50};
int[] intArray = new int[5];
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;
System.out.println(intArray);
System.out.println(intArray.length);
System.out.println(intArray[0]);
System.out.println(intArray[3]);
System.out.println(intArray[7-5]);
//ArrayIndexOutOfBoundsException
//System.out.println(intArray[intArray.length]);
System.out.println(intArray[intArray.length-5]);
}
}
In Java applications, to retrieve all elements from an array we have to use for loop, because in Java applications for loop is suggestible when we know the number of loop iterations in advance before writing the loop, in this case Array Length is equal to the number of loop iterations , here we are able to find the array size by using ‘length’ variable.
EX-2:
class Test{
public static void main(String[] args){
int[] intArray = {10, 20, 30, 40, 50};
for(int index = 0; index < intArray.length; index++){
System.out.println(intArray[index]);
}
}
}
EX:
class Test{
public static void main(String[] args){
int eno = 111;
String ename = "Durga";
float esal = 50000.0f;
String eaddr = "Hyd";
String[] equals = {"BTech", "MTech", "PHD"};
String[] eskillSet = {"JAVA", "PYTHON", "AWS"};
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Salary : "+esal);
System.out.println("Employee Address : "+eaddr);
System.out.print("Qualifications : ");
for(int index = 0; index < equals.length; index++){
System.out.print(equals[index]+" ");
}
System.out.println();
System.out.print("Employee Skill Set : ");
for(int index = 0; index < eskillSet.length; index++){
System.out.print(eskillSet[index]+" ");
}
}
}
D:\Fullstack10AM>javac Test.java
D:\Fullstack10AM>java Test
Employee Details
-----------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd
Qualifications : BTech MTech PHD
Employee Skill Set : JAVA PYTHON AWS
Declaration and Initialization
You can declare an array by specifying the data type of its elements, followed by square brackets []. You can initialize an array when you declare it, or you can initialize it later using the new keyword.
// Declaration and Initialization
int[] numbers = {10, 20, 30, 40, 50};
Another way to initialize an array is by specifying its size:
// all elements are assigned default value based on data type
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};
int[] numbers2 = new int[]{1, 2, 3, 4, 5};
int[] numbers3 = new int[5];
// ERROR - array creation with both dimension expression and initialization is illegal
int[] numbers1 = new int[5]{1, 2, 3, 4, 5}; → INVALID
→ Array size can never be a negative value.
Array Initialization After Declaration
If you declare an array without initializing it, you can initialize it later by specifying the array elements.
int[] numbers; // Declaration
numbers = new int[3]; // Initialization
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
System.out.println(numbers); // [I@1c655221
Accessing array elements
Array elements are accessed using zero-based indexing, which means the first element is at index 0, the second at index 1, and so on.
int firstElement = numbers[0]; // Access the first element
int secondElement = numbers[1]; // Access the second element
Array Length
You can find the length (the number of elements) of an array using the length attribute.
int arrayLength = numbers.length;
// length property we use to get the length of an array in Java.
Iterating through an Array
You can use loops like for or foreach to iterate through the elements of an array.
for (int i = 0; i < numbers.length; i++) {
// Access and work with numbers[i]
}
// Enhanced for loop (for-each)
for (int number : numbers) {
// Access and work with 'number'
}
Takeaways
1. Arrays can store only homogeneous type data, not heterogeneous. Only similar data.
2. Array size is fixed – cannot grow (or) shrink.
3. Array demands contiguous memory location.
Traversing array elements
Enhanced for loop doesn’t have control over array index.
Traverse using for-each loop (Enhanced for loop)
To retrieve elements from the arrays if we use the conventional for loop then we are able to get the following problems.
- We have to maintain a separate variable for looping purposes.
- We must execute the conditional expression at each and every iteration , where the conditional expressions are strengthful expressions, they may take more memory and more execution time.
- We must perform increment or decrement over the loop variable.
- In this approach, we are able to read array elements by providing index values explicitly, here there may be a chance of getting ArrayIndexOutOfBoundsException.
All the above problems are able to reduce java applications performance.
To overcome all the above problems we have to use the “for-Each” loop provided by JDK 1.5 version.
Syntax:
for(ArrayDataType element: ArrayRefVar){
—-----
}
In the above forEach loop, JVM will perform the following actions.
- JVM will recognize the provided Array reference variable and find the size of the Array.
- JVM will perform the number of iterations over the loop body up to the size of the array.
- At each and every iteration, JVM will pick the element from the array , assign that element to the variable in for-Each Loop and execute the loop body.
It will be repeated up to all elements of the Array.
EX:
class Test{
public static void main(String[] args){
String[] strArray = {"AAA", "BBB", "CCC", "DDD"};
for(String element: strArray){
System.out.println(element);
}
}
}
EX:
class Test{
public static void main(String[] args){
int eno = 111;
String ename = "Durga";
float esal = 50000.0f;
String eaddr = "Hyd";
String[] equals = {"BTech", "MTech", "PHD"};
String[] eskillSet = {"JAVA", "PYTHON", "AWS"};
System.out.println("Employee Details");
System.out.println("-----------------------");
System.out.println("Employee Number : "+eno);
System.out.println("Employee Name : "+ename);
System.out.println("Employee Salary : "+esal);
System.out.println("Employee Address : "+eaddr);
System.out.print("Qualifications : ");
for(String qual: equals){
System.out.print(qual+" ");
}
System.out.println();
System.out.print("Employee Skill Set : ");
for(String skill: eskillSet){
System.out.print(skill+" ");
}
}
}
D:\Fullstack10AM>javac Test.java
D:\Fullstack10AM>java Test
Employee Details
-----------------------
Employee Number : 111
Employee Name : Durga
Employee Salary : 50000.0
Employee Address : Hyd
Qualifications : BTech MTech PHD
Employee Skill Set : JAVA PYTHON AWS
2-D arrays
You can find the length (the number of rows) of the outer array using the length attribute just like you would for a regular one-dimensional array. For example:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int numberOfRows = matrix.length; // Number of rows - 3
Enhanced for loop with 2-D array
Multi-dimensional Arrays
Multi Dimensional Arrays are able to represent the data in more than one level or Dimension.
There are two approaches to represent Multidimensional Arrays.
- Declare and Initialize
- Declare then Initialize
Declare and Initialize
In this approach, we are able to declare the array and initialize the array in a single line.
Syntax:DataType[]....[] refVar ={{{.....},{.}...{}},{{},{}...{}},.....{{},{}...{}}};
EX:int[][] intArray = {{1,2,3},{2,3,4},{3,4,5}};
Declare then Initialize
In this approach, we will declare the array in one line and we will initialize the array in other lines.
Syntax:DataType[][]...[] refVar = new DataType[size-1][size-2]...[size-n];
refVar[0][0]...[0] = val-1;
refVar[0][0]...[1] = val_2;
—-
—-
refVar[0][0]...[size_n-1] = val_x;
—---
—---
refVar[0][size_2-1]...[size_n-1] = Val_y;
—--
—--
refVar[size_1-1[size_2-1]...[size_n-1] = val_z;
EX:
int[][] intArray = new int[3][3];
intArray[0][0] = 1;
intArray[0][1] = 2;
intArray[0][2] = 3;
intArray[1][0] = 2;
intArray[1][1] = 3;
intArray[1][2] = 4;
intArray[2][0] = 3;
intArray[2][1] = 4;
intArray[2][2] = 5;
class Test{
public static void main(String[] args){
int[][] intArray = new int[3][3];
intArray[0][0] = 1;
intArray[0][1] = 2;
intArray[0][2] = 3;
intArray[1][0] = 2;
intArray[1][1] = 3;
intArray[1][2] = 4;
intArray[2][0] = 3;
intArray[2][1] = 4;
intArray[2][2] = 5;
System.out.println(intArray);
System.out.println(intArray.length);
System.out.println(intArray[2]);
System.out.println(intArray[2].length);
System.out.println(intArray[1][2]);
//System.out.println(intArray[2][3]);--> ArrayIndexOutOfBoundsException
//System.out.println(intArray[3][1]);--> ArrayIndexOutOfBoundsException
System.out.println(intArray[intArray.length-1][intArray.length-2]);
//System.out.println(intArray[intArray[1][0]+1][intArray[2].length-1]); --> ArrayIndexOutOfBoundsException
System.out.println(intArray[intArray[0].length-2][intArray[1].length-1]);
}
}
D:\Fullstack10AM>javac Test.java
D:\Fullstack10AM>java Test
[[I@4617c264
3
[I@36baf30c
3
4
4
4
class Test{
public static void main(String[] args){
int[][] intArray = {{1,2,3},{2,3,4},{3,4,5}};
for(int row = 0; row < intArray.length; row++){
for(int col = 0; col < intArray[row].length; col++){
System.out.print(intArray[row][col]+"\t");
}
System.out.println();
}
System.out.println();
for(int[] row: intArray){
for(int element: row){
System.out.print(element+"\t");
}
System.out.println();
}
}
}
D:\Fullstack10AM>javac Test.java
D:\Fullstack10AM>java Test
1 2 3
2 3 4
3 4 5
1 2 3
2 3 4
3 4 5
Jagged Arrays
A jagged array, also known as an “array of arrays,” is an array in Java where each element is itself an array of possibly different lengths. Unlike a rectangular or multidimensional array, where each row has the same number of columns, a jagged array allows for variable column lengths within each row. This concept provides flexibility when working with data structures that have irregular shapes.
In Java, you can create jagged arrays by declaring and initializing arrays of different lengths. Here’s an example:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] {1, 2, 3};
jaggedArray[1] = new int[] {4, 5};
jaggedArray[2] = new int[] {6, 7, 8, 9};
In this example, jaggedArray is a 2D array where the first row contains three elements, the second row contains two elements, and the third row contains four elements.
Jagged arrays are particularly useful when you have data that naturally varies in size, such as a collection of lists, rows in a matrix where each row has a different number of columns, or other data structures where the number of elements in each “subarray” is not uniform.
Keep in mind that when working with jagged arrays, you need to ensure that you properly initialize each “subarray” before accessing its elements to avoid NullPointerException.
EX:
Reading array elements from user
import java.util.Scanner;
public class LaunchAr1
{
public static void main(String[] args)
{
int []ar=new int[5];
Scanner sc=new Scanner(System.in);
// length property we use to get the length of an array in Java
for(int i=0;i<ar.length; i++)
{
System.out.println("Enter the marks of student : "+ i);
ar[i]=sc.nextInt();
}
System.out.println("The marks of student stored in array are: ");
for(int i=0;i<ar.length;i++)
{
System.out.print(ar[i] + " ");
}
System.out.println();
}
}
Array of user-defined objects
I have a sample class like this :
Creating an array of student class objects :
Let’s break down the statement:
Student[] stdArr: This declares a variable namedstdArrwhich is an array ofStudentobjects. The[]indicates thatstdArris an array.new Student[4]: This part of the statement initializes the array. It creates a new array ofStudentobjects with a size of 4. However, at this stage, the array elements are uninitialized, meaning they contain default values according to the type of the elements. For objects likeStudent, the default value isnull.
After this line executes, you have an array named stdArr containing 4 elements, all of which are initially set to null. You can then assign Student objects to individual elements of the array.
Traversing array containing user defined objects
Array Class names
[I: This represents a one-dimensional array of integers. Here,[denotes that it’s an array, andIrepresents the base type of the array, which isint. So,[Iis the class name for a one-dimensional array of integers.[[I: This represents a two-dimensional array of integers. Here,[[denotes that it’s a two-dimensional array (array of arrays), andIagain represents the base type of the array, which isint. So,[[Iis the class name for a two-dimensional array of integers.
You can extend this pattern for arrays of other types as well. For example:
[Ljava.lang.String;: This represents a one-dimensional array of strings. Here,[denotes an array, andLjava.lang.String;represents the base type of the array, which isjava.lang.String.[[Ljava.lang.String;: This represents a two-dimensional array of strings.
And so on. The [ characters denote the number of dimensions of the array, and the characters following them denote the base type of the array.
// Declaring and initializing an array
int[] numbers = {1, 2, 3, 4, 5};
// printing the array name
System.out.println(numbers); // [I@1c655221
// printing array class name
System.out.println(numbers.getClass().getName()); // [I
Sorting array elements
Arrays.sort() method — The Arrays.sort() method in Java is used to sort arrays of primitive types and objects. It’s part of the java.util.Arrays class and provides overloaded methods to sort arrays of different types.
For arrays of primitive types like int, double, char, etc., you can directly use Arrays.sort() method.
For arrays of objects, you need to ensure that the objects implement the Comparable interface or provide a custom Comparator to define the sorting order.
Array with Object type data
Object is the parent of all classes in Java.
class Telusko {
}
class Alien {
}
public class MyClass {
public static void main(String args[]) {
Object[] objs = new Object[3];
objs[0] = new Telusko();
objs[1] = new Alien();
}
}
Takeaway from Array concept
1. Array is an index based data structure to store a large volume of homogenous(Similar) type of data.
2. In Java, an array is treated as an Object, hence memory is allocated on the Heap area.
datatype[] arrayName = new datatype[size];
3. To get length of an array, we use length property → arrayName.length (It’s not a method)
4. In Java, arrays are guarded with boundaries. How many array index locations we have asked while creating an array, only that many indexes we can use. If we try to surpass the index of the array beyond what we have asked for while creating it, it will lead to ArrayIndexOutOfBoundsException.
5. We cannot give size of an array as negative → NegativeArraySizeException
6. Size of an array must be of int type
Disadvantages with Arrays
1. It can store only Homogeneous type of data [not actually a disadvantage].
2. Size is fixed, It cannot grow or shrink in size. If we try to change the size of an array after array declaration, then a new array Object will be created and the old array object will neither grow or show.
3. It Demands contiguous memory locations
4. No direct class methods to work with data or array elements, we have to depend on Arrays utility class.
Working with 1-D (Single dimensional) arrays in Java
Working with single-dimensional arrays in Java involves creating, initializing, accessing, and manipulating arrays of elements of the same type. Here’s a guide to working with single-dimensional arrays:
Declaration and Initialization:
// Declare an array of integers
int[] numbers;
// Initialize the array with a specific size
numbers = new int[5];
// Alternatively, combine declaration and initialization
int[] numbers = new int[5];Assigning Values:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;Accessing Values:
int firstElement = numbers[0];
int thirdElement = numbers[2];Iterating Through an Array:
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}Array Length:
int length = numbers.length;Initializing Arrays with Values:
int[] numbers = {10, 20, 30, 40, 50};Array Bounds:
- The index of the first element in an array is 0.
- The last element’s index is one less than the array’s length (
length - 1). - Accessing an index outside the bounds of the array will result in an
ArrayIndexOutOfBoundsException.
Copying Arrays:
int[] copy = Arrays.copyOf(numbers, numbers.length);Sorting Arrays:
Arrays.sort(numbers);Searching Arrays:
int index = Arrays.binarySearch(numbers, 30);Multi-Dimensional Arrays:
int[][] matrix = new int[3][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
// …Single-dimensional arrays are versatile data structures in Java, commonly used for storing collections of similar elements and providing efficient access and manipulation capabilities. Understanding how to work with arrays is fundamental for Java developers.
Using enhanced for loop
public class Main {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};
// Traverse the array using the enhanced for loop
for (int number : numbers) {
System.out.println(number);
}
}
}
This loop iterates over each element of the numbers array sequentially, printing each element to the console. The enhanced for loop simplifies the syntax for iterating over arrays and enhances code readability compared to traditional for loops when you only need to access elements sequentially.
Limitations with enhanced for loop
- No Access to Index: Unlike traditional for loops, the enhanced for loop does not provide access to the index of the current element being iterated over. This can be limiting in scenarios where you need to know the index of elements, such as when modifying elements in the array or accessing adjacent elements.
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
// Unable to determine the index of 'number'
}
- Read-Only Access: The enhanced for loop only provides read-only access to elements in the collection. If you need to modify elements while iterating, you’ll need to use a traditional for loop with index manipulation.
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
numbers[i] *= 2; // Modifies each element
}
- Not Suitable for Parallel Iteration: If you need to iterate over multiple arrays or collections in parallel, the enhanced for loop is not suitable. In such cases, using traditional for loops with explicit index management is more appropriate.
int[] numbers1 = {1, 2, 3};
int[] numbers2 = {4, 5, 6};
for (int i = 0; i < numbers1.length; i++) {
System.out.println(numbers1[i] + numbers2[i]); // Parallel iteration
}
- Iterable Collections Only: The enhanced for loop can only be used with collections that implement the
Iterableinterface or arrays. It cannot be used with other data structures or custom classes unless they implementIterable.
Anonymous Arrays
Nameless array is called an Anonymous Array.
IN general, in Java applications, we will pass anonymous arrays as parameters to the methods when we want to pass an array as parameter.
Syntax:new DataType[]{Val1, Val2,...Val_n};
class Bank{
public void displayCustomersNames(String[] customerNames){
for (String customerName: customerNames){
System.out.println(customerName);
}
}
}
public class Main {
public static void main(String[] args) {
Bank bank = new Bank();
//String[] customersNames = {"AAA","BBB","CCC","DDD","EEE","FFF"};
//String[] customersNames = new String[] {"AAA","BBB","CCC","DDD","EEE","FFF"};
bank.displayCustomersNames(
new String[] {"AAA","BBB","CCC","DDD","EEE","FFF"});
}
}
AAA
BBB
CCC
DDD
EEE
FFF