Published April 23, 2024

Array In Java

image

An array is a data structure that stores a fixed-size sequential collection of elements of the same type values. It provides a convenient way to store and access multiple values of the same data type under a single variable name and differentiate each element using index number.
 

An array is a data structure that stores a fixed-size sequential collection of elements of the same type values. It provides a convenient way to store and access multiple values of the same data type under a single variable name and differentiate each element using index number.

Differences between Java Array and C/C++ Array:

Dynamic Memory Allocation: 
In C/C++, arrays are allocated using dynamic memory allocation techniques like malloc() or new[], whereas in Java, arrays are created using the new keyword without specifying the size explicitly.

Bounds Checking: 
Java arrays perform bounds checking at runtime to prevent array index out of bounds errors, while C/C++ arrays do not perform bounds checking by default.

Length Property: 
Java arrays have a length property to get the size of the array, while C/C++ arrays do not have a built-in mechanism to determine their size.

Passing to Functions: 
In C/C++, arrays are typically passed to functions by passing a pointer to the first element, whereas in Java, arrays are passed by reference.

Advantages of Using Arrays:
Compactness: 
Arrays allow you to store multiple values under a single variable name, making the code more compact and readable.

Efficiency: 
Arrays provide constant-time access to elements using their index, making it efficient to retrieve or modify elements.

Ease of Iteration: 
Arrays can be easily iterated over using loops, making it convenient to perform operations on all elements.

Array Declaration, Instantiation, and Initialization:
Declaration: 
Declaring an array involves specifying the data type of the array elements and the array name. For example: int[] numbers;

Instantiation: 
Instantiating an array involves creating a new array object using the new keyword and specifying the size of the array. For example: numbers = new int[5];

Initialization: 
Initializing an array involves assigning values to the elements of the array. This can be done either at the time of declaration or later using a loop or individual assignments. 
For Example: int[] numbers = {1, 2, 3, 4, 5};

initializing an array in one line, syntax is:
dataType [ ] arrayName = {val1, val2, val3, val4}
String [] greetings = {"Hello", "Hi", "Great", "Thanks", "Welcome"};
 
How to Loop Through an Array in Java:
    for (int i = 0; i < greetings.length; i++) {
            System.out.println("Element at index " + i + " : " + greetings[i]);
        }
    
    // declare the variable and allocate memory
        int[] myArray = new int[]{1, 2, 3};
        for (int i = 0; i < 3; i++) {
            System.out.println(myArray[i]);
        }
        
        

 array with the enhanced for loop:
 for (dataType variable : nameOfArray) {
    // Code to execute
}


String [] namesTwo = {"Quincy", "Abbey", "Kolade", "Chris", "Kayode"};

        for (String names : namesTwo) {
            System.out.println(names);
        }
        
int[][] myArray = new int[4][2];
 
  // declare the variable and allocate memory
        int[][] myArray = new int[4][2];
        myArray[2][1] = 1;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print(myArray[i][j] + " ");
            }
            System.out.println();
        }

Use Case1:
You are required to get any N numbers and find out biggest and smallest number out of N numbers.

Use Case2:
You are required to get any N numbers, count numbers even and odd numbers from array.

Use Case3:
You are required to get any N numbers, count and find out sum of multiple of T from the array.

Use Case4:
You are required to get any N numbers, display the duplicate number and number of time repeated in the array.

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
  
public class DuplicatesInArray 
{
    //Method 1 : Brute Force Method
      
    private static void findDuplicatesUsingBruteForce(int[] inputArray)
    {
        for (int i = 0; i < inputArray.length; i++) 
        {
            for (int j = i+1; j < inputArray.length; j++) 
            {
                if(inputArray[i] == inputArray[j])
                {
                    System.out.println("Duplicate Element : "+inputArray[i]);
                }
            }
        }
    }
   
    //Method 2 : Sorting Method
      
    private static void findDuplicatesUsingSorting(int []inputArray)
    {
        Arrays.sort(inputArray);
          
        for (int i = 0; i < inputArray.length-1; i++)
        {
            if(inputArray[i] == inputArray[i+1])
            {
                System.out.println("Duplicate value : " + inputArray[i]);
            }
        }
    }
      
    //Method 3 : Using HashSet
      
    private static void findDuplicatesUsingHashSet(int []inputArray)
    {
        HashSet<Integer> set = new HashSet<Integer>();
          
        for (int element : inputArray) 
        {
            if( ! set.add(element))
            {
                System.out.println("Duplicate value : "+element);
            }
        }
    }
      
    //Method 4 : Using HashMap
      
    private static void findDuplicatesUsingHashMap(int[] inputArray)
    {
        HashMap<Integer, Integer> map = new HashMap<>();
          
        for (int element : inputArray) 
        {   
            if(map.get(element) == null)
            {
                map.put(element, 1);
            }
            else
            {
                map.put(element, map.get(element)+1);
            }
        }
          
        Set<Entry<Integer, Integer>> entrySet = map.entrySet();
          
        for (Entry<Integer, Integer> entry : entrySet) 
        {               
            if(entry.getValue() > 1)
            {
                System.out.println("Duplicate value : "+entry.getKey()+" - found "+entry.getValue()+" times.");
            }
        }
    }
      
    //Method 5 : Using Java 8 Streams
    private static void findDuplicatesUsingJava8(int[] inputArray) 
    {   
        Set<Integer> uniqueElements = new HashSet<>(); 
        Set<Integer> duplicateElements =  Arrays.stream(inputArray)
                                                .filter(i -> !uniqueElements.add(i))
                                                .boxed()
                                                .collect(Collectors.toSet());    
        System.out.println(duplicateElements);
    }  
    public static void main(String[] args) 
    {
        int[] inputArray = new int[] {111, 333, 555, 777, 333, 444, 555};
        System.out.println("======Duplicates Using Brute Force======");   
        findDuplicatesUsingBruteForce(inputArray); 
        System.out.println("======Duplicates Using Sorting======"); 
        findDuplicatesUsingSorting(inputArray); 
        System.out.println("======Duplicates Using HashSet======");         
        findDuplicatesUsingHashSet(inputArray); 
        System.out.println("======Duplicates Using HashMap======");        
        findDuplicatesUsingHashMap(inputArray);        
        System.out.println("======Duplicates Using Java 8 Streams======");        
        findDuplicatesUsingJava8(inputArray);
    }
}

Use Case5:
You are required to get any N numbers, find second largest element in an array of integers?
public class MainClass
{
    static int secondLargest(int[] input)
    {
        int firstLargest, secondLargest;
        //Checking first two elements of input array
        if(input[0] > input[1])
        {
            //If first element is greater than second element
            firstLargest = input[0];
            secondLargest = input[1];
        }
        else
        {
            //If second element is greater than first element
            firstLargest = input[1];
            secondLargest = input[0];
        }
  
        //Checking remaining elements of input array
        for (int i = 2; i < input.length; i++)
        {
            if(input[i] > firstLargest)
            {
                //If element at 'i' is greater than 'firstLargest'
                secondLargest = firstLargest;
                firstLargest = input[i];
            }
            else if (input[i] < firstLargest && input[i] > secondLargest)
            {
                //If element at 'i' is smaller than 'firstLargest' and greater than 'secondLargest'
                secondLargest = input[i];
            }
        }
        return secondLargest;
    }
    public static void main(String[] args)
    {
        System.out.println(secondLargest(new int[] {45, 51, 28, 75, 49, 42}));
        System.out.println(secondLargest(new int[] {985, 521, 975, 831, 479, 861}));
        System.out.println(secondLargest(new int[] {9459, 9575, 5692, 1305, 1942, 9012}));
        System.out.println(secondLargest(new int[] {47498, 14526, 74562, 42681, 75283, 45796}));
    }
}


Use Case6:
--------------
You are required to get any two array, write a method called equalityOfTwoArrays() to check the equality of two arrays.
Test Case1:
Input:
int[] arrayOne = {2, 5, 1, 7, 4};
int[] arrayTwo = {2, 5, 1, 7, 4};

Output:
Both arrays are identical

Test Case2:
Input:
int[] arrayOne = {2, 5, 1, 7, 4,8};
int[] arrayTwo = {2, 5, 1, 7, 4};

Output:
Both arrays are not identical

Test Case3:
Input:
int[] arrayOne = {2, 5, 1, 7, 4};
int[] arrayTwo = {7, 5, 1, 2, 4};

Output:
Both arrays are identical


First Method : Using Iterative Method
public class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {   
        int[] arrayOne = {2, 5, 1, 7, 4};       
        int[] arrayTwo = {2, 5, 1, 7, 4};      
        boolean equalOrNot = true;        
        if(arrayOne.length == arrayTwo.length)
        {
            for (int i = 0; i < arrayOne.length; i++)
            {
                if(arrayOne[i] != arrayTwo[i])
                {
                    equalOrNot = false;
                    break;
                }
            }
        }
        else
        {
            equalOrNot = false;
        }
          
        if (equalOrNot)
        {
            System.out.println("Two Arrays Are Equal");
        }
        else
        {
            System.out.println("Two Arrays Are Not equal");
        }
    }
}

Second Method : Using Arrays.equals() Method
class EqualityOfTwoArrays
{
    public static void main(String[] args)
    {
        String[] s1 = {"java", "j2ee", "struts", "hibernate"};
        String[] s2 = {"jsp", "spring", "jdbc", "hibernate"}; 
        String[] s3 = {"java", "j2ee", "struts", "hibernate"}; 
        System.out.println(Arrays.equals(s1, s2));        //Output : false
        System.out.println(Arrays.equals(s1, s3));      //Output : true
    }
}

Use Case 7: 
-------------
Print all missing number between 1 to 15 of the given integer arrays:
1 <= |A| <= 15
Test case 1:
Input:
[1,2,8,14]
Expected Output:
3,4,5,6,7,9,10,11,12,13,15

Test case 2:
Input:
[3,4,5,6,7,11,12,13,15]
Expected Output:
2,8,9,10,14

Test case 3:
Input:
[1,3,4,5,6,7,10,11,12,13,15]
Expected Output:
2,8,9,14
    public static void showAllMissingNumbers(){
        int arr[]= {1,2,8,14};
        int arr2[]=new int[15];
        Arrays.sort(arr);
        //adding values from 1 to 15
        for(int i=0;i<15;i++) {
            arr2[i]=i+1;
        }

        for(int n:arr) {
            arr2[n-1]=0;
        }
        for(int i=0;i<15;i++) {
            if(arr2[i]!=0) {
                System.out.println(arr2[i]);
            }
        }
    }
    
Use Case8:
------------
You are required to get an array of integers having their each element as given below:
1 <= |A| <= 106
-106 <= Ai <= 106

Test case 1:
Input:
[1,2,0]

Expected Output:
3

Test case 2:
Input:
[3,4,-1,1]

Expected Output:
2

Test case 3:
Input:
[-8,-7,-6]

Expected Output:
1

Example Explanation
Explanation 1:
3 is the first positive missing integer.
Explanation 2:
2 is the first positive missing integer.
Explanation 3:
1 is the first positive missing integer

Use Case9:
-------------
You are required to get N numbers of values and T value as input.
Find all pairs of elements in an integer array whose sum is equal to a given number T.

Test case1:
Input:
    findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);

Expected output:
Pairs of elements whose sum is 10 are :
-10 + 20 = 10
4 + 6 = 10
5 + 5 = 10

Test case2:
Input:
    findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);

Output:
Pairs of elements whose sum is 20 are :
-5 + 25 = 20
8 + 12 = 20
9 + 11 = 20

Test case3:
Input:  
     findThePairs(new int[] {12, 13, 10, 15, 8, 40, -15}, 25);

Output:
Pairs of elements whose sum is 25 are :
-15 + 40 = 25
10 + 15 = 25
12 + 13 = 25


public class PairsOfElementsInArray{
    static void findThePairs(int inputArray[], int inputNumber){
        //Sorting the given array
        Arrays.sort(inputArray);
  
        System.out.println("Pairs of elements and sum is "+inputNumber+" are : ");
  
        //Initializing i to first index
        int i = 0;
  
        //Initializing j to last index
        int j = inputArray.length-1;
  
        //Till i crosses j, perform the following task
        while (i < j)
        {
            //If inputArray[i]+inputArray[j] is equal to inputNumber
            if(inputArray[i]+inputArray[j] == inputNumber)
            {
                //then Print inputArray[i] and inputArray[j]
                System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
  
                //Increment i
                i++;
  
                //Decrement j
                j--;
            }
  
            //If inputArray[i]+inputArray[j] is smaller than inputNumber
            else if (inputArray[i]+inputArray[j] < inputNumber)
            {
                //then increment i
                i++;
            }
  
            //If inputArray[i]+inputArray[j] is greater than inputNumber
            else if (inputArray[i]+inputArray[j] > inputNumber)
            {
                //then decrement j
                j--;
            }
        }
    }
    public static void main(String[] args)
    {
        findThePairs(new int[] {4, 6, 5, -10, 8, 5, 20}, 10);
        findThePairs(new int[] {4, -5, 9, 11, 25, 13, 12, 8}, 20);
        findThePairs(new int[] {12, 13, 10, 15, 8, 40, -15}, 25);
        findThePairs(new int[] {12, 23, 10, 41, 15, 38, 27}, 50);
    }
}


Use Case10:
-------------
You are required to write a method who get an integer array and a number,
Find continuous sub array whose sum is equal to a given number?

Test case 1:
Input:
findSubArray(new int[]{42, 15, 12, 8, 6, 32}, 26);

Expected Output:
Continuous sub array of [42, 15, 12, 8, 6, 32] whose sum is 26 is
12 8 6

Test case 2:
Input:
findSubArray(new int[]{12, 5, 31, 13, 21, 8}, 49);

Expected Output:
Continuous sub array of [12, 5, 31, 13, 21, 8] whose sum is 49 is
5 31 13

Test case 3:
Input:
findSubArray(new int[]{15, 51, 7, 81, 5, 11, 25}, 41);

Expected Output:
Continuous sub array of [15, 51, 7, 81, 5, 11, 25] whose sum is 41 is
5 11 25


Solution:
import java.util.Arrays;
 
public class SubArrayWhoseSumIsNumber
{
    static void findSubArray(int[] inputArray, int inputNumber)
    {
        //Initializing sum with the first element of the inputArray
  
        int sum = inputArray[0];
  
        //Initializing starting point with 0
  
        int start = 0;
  
        //Iterating through inputArray starting from second element
  
        for (int i = 1; i < inputArray.length; i++)
        {
            //Adding inputArray[i] to the current 'sum'
  
            sum = sum + inputArray[i];
  
            //If sum is greater than inputNumber then following loop is executed
  
            //sum becomes either smaller than or equal to inputNumber
  
            while(sum > inputNumber && start <= i-1)
            {
                //Removing starting elements from the 'sum'
  
                sum = sum - inputArray[start];
  
                //Incrementing start by 1
  
                start++;
            }
  
            //If 'sum' is equal to 'inputNumber' then printing the sub array
  
            if(sum == inputNumber)
            {
                System.out.println("Continuous sub array of "+Arrays.toString(inputArray)+" whose sum is "+inputNumber+" is ");
  
                for (int j = start; j <= i; j++)
                {
                    System.out.print(inputArray[j]+" ");
                }
  
                System.out.println();
            }
        }
    }
  
    public static void main(String[] args)
    {
        findSubArray(new int[]{42, 15, 12, 8, 6, 32}, 26);
  
        findSubArray(new int[]{12, 5, 31, 13, 21, 8}, 49);
  
        findSubArray(new int[]{15, 51, 7, 81, 5, 11, 25}, 41);
    }
}


Use Case 11: 
Managing Product Inventory using Java Array.
We have a Product with attributes such as id, name, price, and quantity. The ProductInventory class manages an array of Product objects, allowing us to add products to the inventory and display the current inventory in java array.

public class Product {
    private int productId;
    private String name;
    private double price;
    private int quantity;

    // Constructor
    public Product(int productId, String name, double price, int quantity) {
        this.productId = productId;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    // Getters and setters
    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
}

public class ProductInventory {
    private Product[] products; // Array to store products
    private int size; // Current size of inventory

    // Constructor
    public ProductInventory(int capacity) {
        products = new Product[capacity]; // Instantiating array with given capacity
        size = 0; // Initially inventory is empty
    }

    // Method to add a product to inventory
    public void addProduct(Product product) {
        if (size < products.length) {
            products[size] = product; // Adding product to array
            size++; // Incrementing size
            System.out.println("Product added to inventory.");
        } else {
            System.out.println("Inventory is full. Cannot add more products.");
        }
    }

    // Method to display all products in inventory
    public void displayInventory() {
        System.out.println("Product Inventory:");
        for (int i = 0; i < size; i++) {
            System.out.println("Product ID: " + products[i].getProductId() +
                    ", Name: " + products[i].getName() +
                    ", Price: $" + products[i].getPrice() +
                    ", Quantity: " + products[i].getQuantity());
        }
    }

    // Main method to test ProductInventory class
    public static void main(String[] args) {
        ProductInventory inventory = new ProductInventory(5);

        // Adding products to inventory
        inventory.addProduct(new Product(1, "Laptop", 999.99, 10));
        inventory.addProduct(new Product(2, "Smartphone", 499.99, 20));
        inventory.addProduct(new Product(3, "Tablet", 299.99, 15));

        // Displaying inventory
        inventory.displayInventory();
    }
}


Use Case 12:
You are required write java code to handle Employee having empId, firstName, designation,  salary and deptName, Create a class called EmployeManager with help of array which help to addEmployee, modEmployee, delEmployeeById, getEmployees, searchEmployeeById, searchEmployeeByName containing passed String, searchEmployeesByDeptName, searchEmployees between range of two salary given.

Solution Code:
public class Employee {
    private int empId;
    private String firstName;
    private String designation;
    private double salary;
    private String deptName;

    // Constructor
    public Employee(int empId, String firstName, String designation, double salary, String deptName) {
        this.empId = empId;
        this.firstName = firstName;
        this.designation = designation;
        this.salary = salary;
        this.deptName = deptName;
    }

    // Getters and setters
    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
}

public class EmployeeManager {
    private Employee[] employees; // Array to store employees
    private int size; // Current size of employee list

    // Constructor
    public EmployeeManager(int capacity) {
        employees = new Employee[capacity]; // Instantiating array with given capacity
        size = 0; // Initially employee list is empty
    }

    // Method to add an employee
    public void addEmployee(Employee employee) {
        if (size < employees.length) {
            employees[size] = employee; // Adding employee to array
            size++; // Incrementing size
            System.out.println("Employee added successfully.");
        } else {
            System.err.println("Employee list is full. Cannot add more employees.");
        }
    }

    // Method to modify employee details by ID
    public void modEmployee(int empId, String firstName, String designation, double salary, String deptName) {
        for (int i = 0; i < size; i++) {
            if (employees[i].getEmpId() == empId) {
                employees[i].setFirstName(firstName);
                employees[i].setDesignation(designation);
                employees[i].setSalary(salary);
                employees[i].setDeptName(deptName);
                System.out.println("Employee details modified successfully.");
                return;
            }
        }
        System.err.println("Employee with ID " + empId + " not found.");
    }

    // Method to delete employee by ID
    public void delEmployeeById(int empId) {
        for (int i = 0; i < size; i++) {
            if (employees[i].getEmpId() == empId) {
                for (int j = i; j < size - 1; j++) {
                    employees[j] = employees[j + 1];
                }
                size--;
                System.out.println("Employee with ID " + empId + " deleted successfully.");
                return;
            }
        }
        System.err.println("Employee with ID " + empId + " not found.");
    }

    // Method to get all employees
    public Employee[] getEmployees() {
        Employee[] allEmployees = new Employee[size];
        System.arraycopy(employees, 0, allEmployees, 0, size);
        return allEmployees;
    }

    // Method to search employee by ID
    public Employee searchEmployeeById(int empId) {
        for (int i = 0; i < size; i++) {
            if (employees[i].getEmpId() == empId) {
                return employees[i];
            }
        }
        return null; // Employee not found
    }

    // Method to search employee by name (containing passed string)
    public Employee[] searchEmployeeByName(String name) {
        Employee[] matchingEmployees = new Employee[size];
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (employees[i].getFirstName().contains(name)) {
                matchingEmployees[count++] = employees[i];
            }
        }
        return Arrays.copyOfRange(matchingEmployees, 0, count);
    }

    // Method to search employees by department name
    public Employee[] searchEmployeesByDeptName(String deptName) {
        Employee[] matchingEmployees = new Employee[size];
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (employees[i].getDeptName().equalsIgnoreCase(deptName)) {
                matchingEmployees[count++] = employees[i];
            }
        }
        return Arrays.copyOfRange(matchingEmployees, 0, count);
    }

    // Method to search employees with salary between given range
    public Employee[] searchEmployeesBySalaryRange(double minSalary, double maxSalary) {
        Employee[] matchingEmployees = new Employee[size];
        int count = 0;
        for (int i = 0; i < size; i++) {
            if (employees[i].getSalary() >= minSalary && employees[i].getSalary() <= maxSalary) {
                matchingEmployees[count++] = employees[i];
            }
        }
        return Arrays.copyOfRange(matchingEmployees, 0, count);
    }
}

public class EmployeeApp{

    // Main method to test EmployeeManager class
    public static void main(String[] args) {
        EmployeeManager manager = new EmployeeManager(10);

        // Adding employees
        manager.addEmployee(new Employee(101, "John Doe", "Software Engineer", 50000, "IT"));
        manager.addEmployee(new Employee(102, "Alice Smith", "HR Manager", 60000, "HR"));

        // Modifying employee details
        manager.modEmployee(101, "John Doe", "Senior Software Engineer", 60000, "IT");

        // Deleting employee by ID
        manager.delEmployeeById(102);

        // Displaying all employees
        System.out.println("All Employees:");
        Employee[] allEmployees = manager.getEmployees();
        for (Employee employee : allEmployees) {
            System.out.println(employee.getEmpId() + ": " + employee.getFirstName() + " - " +
                    employee.getDesignation() + " - " + employee.getSalary() + " - " + employee.getDeptName());
        }

        // Searching employee by ID
        System.out.println("Employee with ID 101:");
        Employee empById = manager.searchEmployeeById(101);
        if (empById != null) {
            System.out.println(empById.getEmpId() + ": " + empById.getFirstName() + " - " +
                    empById.getDesignation() + " - " + empById.getSalary() + " - " + empById.getDeptName());
        } else {
            System.err.println("Employee not found.");
        }

        // Searching employees by name
        System.out.println("Employees with name containing 'John':");
        Employee[] empByName = manager.searchEmployeeByName("John");
        for (Employee employee : empByName) {
            System.out.println(employee.getEmpId() + ": " + employee.getFirstName() + " - " +
                    employee.getDesignation() + " - " + employee.getSalary() + " - " + employee.getDeptName());
        }

        // Searching employees by department name
        System.out.println("Employees in IT department:");
        Employee[] empByDept = manager.searchEmployeesByDeptName("IT");
        for (Employee employee : empByDept) {
            System.out.println(employee.getEmpId() + ": " + employee.getFirstName() + " - " +
                    employee.getDesignation() + " - " + employee.getSalary() + " - " + employee.getDeptName());
        }

        // Searching employees by salary range
        System.out.println("Employees with salary between 40000 and 60000:");
        Employee[] empBySalaryRange = manager.searchEmployeesBySalaryRange(40000, 60000);
        for (Employee employee : empBySalaryRange) {
            System.out.println(employee.getEmpId() + ": " + employee.getFirstName() + " - " +
                    employee.getDesignation() + " - " + employee.getSalary() + " - " + employee.getDeptName());
        }
    }
}

java.util.Array:
The java.util.Arrays class provides various utility methods for working with arrays in Java. It includes methods for sorting arrays, searching for elements, comparing arrays, filling arrays with values, and converting arrays to strings. 

Understanding and using the methods of java.util.Arrays can greatly simplify and enhance array manipulation tasks in Java. Java developers can write more efficient and concise code for array manipulation tasks.

sort(T[] a): Sorts the specified array of objects into ascending order.
int[] numbers = {5, 2, 7, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 5, 7, 9]


binarySearch(T[] a, T key): Searches the specified array for the specified object using the binary search algorithm.
int[] numbers = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(numbers, 3);
System.out.println("Index of 3: " + index); // Output: Index of 3: 2


equals(T[] a, T[] b): Returns true if the two specified arrays of objects are equal to one another.
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean isEqual = Arrays.equals(arr1, arr2);
System.out.println("Arrays are equal: " + isEqual); // Output: Arrays are equal: true

fill(T[] a, T val): Assigns the specified value to each element of the specified array of objects.
int[] numbers = new int[5];
Arrays.fill(numbers, 10);
System.out.println(Arrays.toString(numbers)); // Output: [10, 10, 10, 10, 10]

copyOf(T[] original, int newLength): Copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length.
int[] source = {1, 2, 3, 4, 5};
int[] destination = Arrays.copyOf(source, 3);
System.out.println(Arrays.toString(destination)); // Output: [1, 2, 3]

toString(T[] a): Returns a string representation of the contents of the specified array.
int[] numbers = {1, 2, 3, 4, 5};
String str = Arrays.toString(numbers);
System.out.println(str); // Output: [1, 2, 3, 4, 5]

multiple-choice questions on arrays:

Q1. Which of the following is a valid declaration of an array in Java?
a) int[] numbers;
b) array numbers[];
c) int numbers[];
d) numbers[] int;

Q2.What does the following statement do in Java?
int[] numbers = new int[5];
a) Declares an array of integers with size 5.
b) Initializes an array of integers with 5 elements.
c) Declares and initializes an array of integers with size 5.
d) None of the above.

Q3.What is the index of the last element in an array of size 10 in Java?
a) 9
b) 10
c) 11
d) 0

Q4.Which of the following statements is true about arrays in Java?
a) Arrays can store elements of different data types.
b) Arrays can be resized after initialization.
c) Elements in an array are always stored in contiguous memory locations.
d) Arrays can only store a fixed number of elements.

Q5.What is the default value of elements in an array of primitive type int in Java?
a) 0
b) 1
c) -1
d) null

Q6.Which of the following statements is true about arrays of custom class types in Java?
a) Arrays of custom class types are not allowed in Java.
b) Arrays of custom class types can only store primitive data types.
c) Arrays of custom class types can store objects of the specified class or its subclasses.
d) Arrays of custom class types must be initialized using the new keyword.

Q7.What is the correct way to declare an array of custom class type Employee in Java?
a) Employee[] employees;
b) employees[] Employee;
c) Employee employees[];
d) employees[] Employee[];

Q8.In Java, when an array of custom class type is declared, what is initialized for each element?
a) A reference to an object of the specified class.
b) A default object of the specified class.
c) A null reference.
d) The memory address of the specified class.

Q9.Which of the following statements initializes an array of Employee objects with 5 elements in Java?
a) Employee[] employees = new Employee[5];
b) Employee[5] employees;
c) Employee[5] = new Employee[];
d) Employee[5] = new Employee();

Q10.How can you access the firstName field of the third Employee object in an array named employees?
a) employees[2].firstName;
b) employees[3].getFirstName();
c) employees[3].FirstName;
d) employees[2].getFirstName();

Q11. Which of the following is an advantage of using arrays in Java?
a) Arrays can store elements of different data types.
b) Arrays can be resized after initialization.
c) Arrays provide constant-time access to elements.
d) Arrays can dynamically adjust their size.

Q12.What is the correct way to find the length of an array named arr in Java?
a) arr.size();
b) arr.length();
c) arr.length;
d) size(arr);

Q13.Which method is used to copy elements from one array to another in Java?
a) System.arrayCopy()
b) Arrays.copy()
c) Array.copy()
d) copyArray()


Q14.Which of the following statements correctly declares a two-dimensional array in Java?
a) int[][] matrix = new int[3][3];
b) int[][] matrix = new int[3,3];
c) int matrix[][] = new int[3,3];
d) int matrix[] = new int[3][3];

Q15. What is the purpose of the enhanced for loop in Java?
a) To iterate over the elements of an array.
b) To modify the elements of an array.
c) To resize the array dynamically.
d) To access the index of each element in the array.

Q16.Which method is used to sort an array in ascending order in Java?
a) Arrays.sort()
b) sortArray()
c) System.sort()
d) Array.sort()

Q17.What does the Arrays.toString() method do in Java?
a) Converts an array to a string representation.
b) Converts a string to an array.
c) Converts an array to a list.
d) Converts a list to an array.

Q18. Which of the following statements is true about the clone() method in Java?
a) It creates a deep copy of the array.
b) It creates a shallow copy of the array.
c) It creates a copy of the array with reversed elements.
d) It creates a copy of the array with sorted elements.

Q19. Which of the following is true about multidimensional arrays in Java?
a) All rows must have the same number of elements.
b) Multidimensional arrays can only have two dimensions.
c) The size of each dimension must be specified at the time of declaration.
d) Multidimensional arrays are not supported in Java.

Q20. How can you initialize a two-dimensional array in Java?
a) int[][] matrix = { {1, 2}, {3, 4}, {5, 6} };
b) int[][] matrix = new int[3][2];
c) Both a and b.
d) None of the above.


Q21. Which method is used to compare two arrays for equality in Java?
a) Arrays.equals()
b) Arrays.compare()
c) Arrays.compareTo()
d) Arrays.compareEquals()

Q22.What happens if you try to access an index outside the bounds of an array in Java?
a) It throws a NullPointerException.
b) It throws an ArrayIndexOutOfBoundsException.
c) It returns null.
d) It returns the default value of the array's type.

Q1.Correct Option: a) int[] numbers;
Explanation: Option (a) declares an array of integers named numbers, using the preferred syntax for array declaration in Java.

Q2.Correct Option: a) Declares an array of integers with size 5.
Explanation: This statement declares an array named numbers capable of holding integers and initializes it with space for 5 elements.

Q3.Correct Option: a) 9
Explanation: In Java, array indices start from 0, so the index of the last element in an array of size 10 is 9.

Q4.Correct Option: c) Elements in an array are always stored in contiguous memory locations.
Explanation: Arrays in Java store elements in contiguous memory locations, allowing for efficient memory usage and access.

Q5.Correct Option: a) 0
Explanation: The default value of elements in an array of primitive type int in Java is 0.

Q6.Correct Option: c) Arrays of custom class types can store objects of the specified class or its subclasses.
Explanation: Arrays in Java can store objects of any class type, including custom class types and their subclasses.

Q7.Correct Option: a) Employee[] employees;
Explanation: Option (a) correctly declares an array named employees capable of holding objects of type Employee.

Q8.Correct Option: c) A null reference.
Explanation: When an array of custom class type is declared in Java, each element is initialized with a null reference by default.

Q9.Correct Option: a) Employee[] employees = new Employee[5];
Explanation: Option (a) initializes an array named employees capable of holding Employee objects with space for 5 elements.

Q10.Correct Option: d) employees[2].getFirstName();
Explanation: Array indices in Java start from 0, so to access the third Employee object in the array, you need to use index 2. Then, you can access the firstName field using the getter method.

Q11.Correct Option: c) Arrays provide constant-time access to elements.
Explanation: Arrays in Java provide constant-time access to elements, allowing for efficient retrieval and manipulation of data.

Q12.Correct Option: c) arr.length;
Explanation: The length property is used to find the length of an array in Java, so option (c) is correct.

Q13.Correct Option: a) System.arrayCopy()
Explanation: The System.arrayCopy() method is used to copy elements from one array to another in Java.

Q14.Correct Option: a) int[][] matrix = new int[3][3];
Explanation: Option (a) correctly declares a two-dimensional array named matrix with dimensions 3x3 in Java.

Q15.Correct Option: a) To iterate over the elements of an array.
Explanation: The enhanced for loop in Java is used to iterate over the elements of an array or collection.

Q16.Correct Option: a) Arrays.sort()
Explanation: The Arrays.sort() method is used to sort an array in ascending order in Java.

Q17.Correct Option: a) Converts an array to a string representation.
Explanation: The Arrays.toString() method is used to convert an array to a string representation in Java.

Q18.Correct Option: b) It creates a shallow copy of the array.
Explanation: The clone() method in Java creates a shallow copy of the array, meaning it copies the references to the elements rather than creating new copies of the elements themselves.

Q19.Correct Option: a) All rows must have the same number of elements.
Explanation: In Java, all rows of a multidimensional array must have the same number of elements.

Q20.Correct Option: c) Both a and b.
Explanation: Both options (a) and (b) are correct ways to initialize a two-dimensional array in Java.

Q21.Correct Option: a) Arrays.equals()
Explanation: The Arrays.equals() method in Java is used to compare two arrays for equality. 

Q22.Correct Option: b) It throws an ArrayIndexOutOfBoundsException.
Explanation: Trying to access an index outside the bounds of an array in Java results in an ArrayIndexOutOfBoundsException being thrown.

Download Lecture Pdf..

Reviews

Leave a Comment