Skip to main content

Unit 5 Java Array

 

Array in Java

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

declaration: An "array declaration" names the array and specifies the type of its elements.

Initialisation : Initialisation is when you provide an initial value for a variable.

Instantiation : Instantiation is where an object (class instance) is created.

Syntax to Declare an Array in Java

1.      dataType[] arr;  

2.      dataType []arr; 

3.      dataType arr[];                       data types : int, char float, string

Instantiation of an Array in Java

arr=new datatype[size];  

declaration, instantiation and initialization in same time

int a[]={33,3,4,5};  

Example

1.      class ArrExample{  

2.      public static void main(String[] args){  

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

4.      a[0]=1;

5.      a[1]=2;  

6.      a[2]=0;    

7.      a[3]=4

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

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

10.  }

11.  }  

Syntax of for-each loop

for (type var : array) {

   statements using var;

}

Java Program to print the array elements using for-each loop  

1.      class Arr1{  

2.      public static void main(String []args){  

3.      int arr[]={33,3,4,5};  

4.      for(int i:arr)  

5.      System.out.println(i);  

6.      }

}  

Types of Arrays in Java

Java mainly supports two types of arrays:

  1. Single-Dimensional Array

  2. Multi-Dimensional Array

1. Single-Dimensional Array (1D Array)

Definition

A single-dimensional array stores data in a linear form (either row-wise or column-wise).
It can be visualized as a single row of elements.

Characteristics

  • Stores elements of the same data type

  • Accessed using a single index

  • Index starts from 0

  • Size is fixed once declared

Declaration Syntax

datatype[] arrayName = new datatype[size];

Example: Array Input and Output Program

import java.util.Scanner; public class ArrayInputExample { public static void main(String[] args) { int n; Scanner sc = new Scanner(System.in); System.out.print("How many numbers: "); n = sc.nextInt(); int[] array = new int[n]; System.out.println("Enter the elements of the array:"); for (int i = 0; i < n; i++) { array[i] = sc.nextInt(); } System.out.println("Array elements are:"); for (int i = 0; i < n; i++) { System.out.println(array[i]); } } }

Explanation

  • User enters number of elements

  • Elements are stored using a for loop

  • Elements are printed using another loop

2. Multi-Dimensional Array

Definition

A multi-dimensional array stores data in row and column format (matrix form).
It is also called an array of arrays.

Uses

  • Matrix operations

  • Table-like data storage

  • Mathematical computations

Declaration Syntax

datatype[][] arrayName = new datatype[rows][columns];

Example: Matrix Addition Program

import java.util.Scanner; class AddMatrix { public static void main(String[] args) { int row, col, i, j; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows:"); row = in.nextInt(); System.out.println("Enter the number of columns:"); col = in.nextInt(); int mat1[][] = new int[row][col]; int mat2[][] = new int[row][col]; int res[][] = new int[row][col]; System.out.println("Enter the elements of matrix 1:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { mat1[i][j] = in.nextInt(); } } System.out.println("Enter the elements of matrix 2:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { mat2[i][j] = in.nextInt(); } } // Matrix addition for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { res[i][j] = mat1[i][j] + mat2[i][j]; } } System.out.println("Sum of matrices:"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { System.out.print(res[i][j] + "\t"); } System.out.println(); } } }

For-Each Loop in Java Arrays

The for-each loop is used to traverse array elements one by one without using index values.

Syntax

for (dataType variable : array) { // loop body }

Example: Printing Array Using For-Each Loop

class TestArray1 { public static void main(String[] args) { int arr[] = {33, 3, 4, 5}; for (int i : arr) { System.out.println(i); } } }

Advantages

  • Simple and readable

  • No risk of index out-of-bounds error

  • Best for printing or reading elements

Arrays Class in Java

The Arrays class belongs to the java.util package and provides static methods for array manipulation.

·        length is not a method of Arrays class

·        It is a property of array

Array Length Property

Example

public class Main {
    public static void main(String[] args) {
        String[] fruits = {"apple", "banana", "orange", "kiwi"};
        System.out.println(fruits.length);
    }
}

Output

4

equals()

Checks whether two arrays are equal or not. Two arrays are equal if they have the same length and same elements in the same order.

Example: equals()

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] stuG = {"Simran", "Pratima", "Aakirti"};
        String[] stuB = {"Raj", "Mousam", "Sishir"};
        System.out.println(Arrays.equals(stuG, stuB));
    }
}

Output

false

compare()

Compares two arrays element by element (lexicographically).
Returns:

·        0 if both arrays are equal

·        Negative value if first array is smaller

·   Positive value if first array is larger

Example: compare()

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] stuG = {"Simran", "Pratima", "Aakriti"};
        String[] stuB = {"Raj", "Mousam", "Sishir"};
        System.out.println(Arrays.compare(stuG, stuB));
    }
}

sort()

Sorts the elements of an array in ascending order.
For numbers → smallest to largest
For strings → alphabetical order

Example: sort()

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] books = {"COA", "Java", "Maths", "OS", "English"};
        Arrays.sort(books);
        for (String i : books) {
            System.out.println(i);
        }
    }
}

fill()

Fills all elements of an array with a single specified value.
Used to initialize or reset array values.

Example: fill()

import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
        String[] fruits = {"Banana", "Orange", "Apple", "Mango"};
 
        Arrays.fill(fruits, "Kiwi");
 
        for (String i : fruits) {
            System.out.println(i);
        }
    }
}

copyOf()

Creates a new array by copying elements from an existing array.
The original array remains unchanged.

Example: copyOf()

import java.util.Arrays;
public class ExampleCopyOf {
    public static void main(String[] args) {
        int[] a1 = {1, 2, 3, 4, 5};
        int[] a2 = Arrays.copyOf(a1, a1.length);
 
        System.out.println("Original Array: " + Arrays.toString(a1));
        System.out.println("Copied Array: " + Arrays.toString(a2));
    }
}

deepEquals()

Compares multi-dimensional arrays completely.
Checks all rows, columns, and nested elements.

Example: deepEquals()

import java.util.Arrays;
public class ExampleDeepEquals {
    public static void main(String[] args) {
        int[][] arr1 = {{1, 2}, {3, 4}};
        int[][] arr2 = {{1, 2}, {3, 4}};
        int[][] arr3 = {{5, 6}, {7, 8}};
        System.out.println(Arrays.deepEquals(arr1, arr2));
        System.out.println(Arrays.deepEquals(arr2, arr3));
    }
}

Output

true
false

Comments

Post a Comment

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...

Unit 5 SEP

  Software analysis and Design tools Software Analysis and Design Tools are special computer programs that help developers and designers in every stage of making software. These tools make it easier to understand, plan, design, and document a software system so that the final product works well and meets user needs. They help in collecting requirements by recording what users want, modeling the system using diagrams such as flowcharts and UML, and designing the structure and interface of the software. These tools also help in creating documentation for clear communication, analyzing the design to find and fix problems early, and supporting teamwork by allowing different people to work together on the same project smoothly. Introduction of ER Model The Entity-Relationship (ER) Model is a conceptual model used to design and represent the logical structure of a database . It shows entities, their attributes, and relationships among them. Example: A Student enr...