Showing posts with label Java array. Show all posts
Showing posts with label Java array. Show all posts

Friday, October 17, 2025

Java Program to Find The Frequency of Array Elements

In this post we'll see how to write Java program to find the frequency of elements in an array.

For example-

Input: int[] nums = {1,2,2,3,1,4};
Output- 
1 2
2 2
3 1
4 1

Java program for counting the occurrences of each element in an array can be written using the following approaches.

  1. Using nested loops
  2. Using a frequency array
  3. Using HashMap
  4. Using Java Stream API

Java program to find the frequency of elements in an array using nested loops

With this approach you will have an outer loop, traversing the array one element at a time and an inner loop, starting from the next element (j=i+1) and traversing through the whole array to check if the element currently pointed by the outer loop is found again, if yes then increment the occurrence count for that element.

An extra boolean array is needed to mark the elements that are already visited so that the same element is not counted again.

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    countOccurrencesNL(nums);
  }
  
  public static void countOccurrencesNL(int[] nums) {
    int len = nums.length;
    boolean[] visited = new boolean[len];
    for(int i = 0; i < len; i++) {
      if(visited[i]) {
        continue;
      }
      int count = 1;
      int n = nums[i];
      for(int j = i + 1; j < len; j++) {
        if(n == nums[j]) {
          // mark as visited so that it is not picked again
          visited[j] = true;
          count++;
        }
      }
      System.out.println(n + " " +count);
    }
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

Since there are nested loops with each traversing the whole array of size n therefore the time complexity of this approach is O(n2).

One Boolean array of the same size as the array is also needed so the time complexity is O(n).

Java program to find the frequency of elements in an array using frequency array

In order to count the occurrences of element in an array you can create another frequency array. For that the logic is as given below-

  1. Find the maximum element in the given array and create another frequencyArray with a size equal to maxElement + 1.
  2. The index of frequencyArray represents the element of the given array, and the value at that index stores its frequency. For that iterate through the given array and increment the count at the corresponding index in the frequecyArray.

This logic is suitable for an array with positive values and having values with in a limited range.

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    int[] freqArray = countOccurrences(nums);
    // iterate the frequency array
    for(int i = 0; i < freqArray.length; i++) {
      if(freqArray[i] != 0)
        System.out.println(i + " " + freqArray[i]);
  }
  
  public static int[] countOccurrences(int[] nums) {
    int max = Integer.MIN_VALUE;
    // Find the max element in the array
    for(int n : nums) {
      max = Math.max(max, n);
    }
    // Create frequency array
    int[] freqArray = new int[max + 1];
    for (int n : nums) {          
      freqArray[n]++;
    }
    return freqArray;
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

If the max element in the given array is k then in order to display the count for each element, we need three separate iterations as per the logic which means O(n) + O(n) + O(k).

Which can be taken as O(n) if the range is limited.

A frequency array of size k is needed so the space complexity is O(k).

Java program to find the frequency of elements in an array using HashMap

Another way to write a Java program to count the occurrences of each element in an array is to use a HashMap. Logic for this approach is as given below-

  1. Iterate over the array and store array element as key and its frequency as value in the HashMap.
  2. Check if key (array element) already exists in the Map, if yes then increment the value by 1. If not present then add the element as key and value as 1.
import java.util.HashMap;
import java.util.Map;

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    countOccurrencesMap(nums);
  }
  
  public static void countOccurrencesMap(int[] nums) {
    Map<Integer, Integer> freqMap = new HashMap<>();
    for(int n : nums) {
      freqMap.put(n, freqMap.getOrDefault(n, 0)+1);
    }
    for(Map.Entry<Integer,Integer> entry : freqMap.entrySet()){
          System.out.println(entry.getKey() + " " + entry.getValue());
    }
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

There is one iteration of the array to store elements in the HashMap. For each element, the getOrDefault() and put() operations on a HashMap have an average time complexity of O(1). Therefore, the total time complexity of this logic is O(n).

Since HashMap stores only unique elements, so the space complexity is O(k), considering the number of unique elements is k.

Java program to find the frequency of elements in an array using Java Stream API

The Collectors.groupingBy() method in Java Stream API can be used to group element with their repective count. For counting another method Collectors.counting() is used.

boxed() method in Java Stream API is also required to convert primitive int to Integer for stream operations.

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FrequencyArray {

  public static void main(String[] args) {
    int[] nums = {1,2,2,3,1,4};
    countOccurrencesStream(nums);
  }
  
  public static void countOccurrencesStream(int[] nums) {
    //Map<Integer, Integer> freqMap = new HashMap<>();
    Map<Integer, Long> freqMap = Arrays.stream(nums)
                      .boxed()
                      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
    for(Map.Entry<Integer,Long> entry : freqMap.entrySet()){
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
  }
}

Output

1 2
2 2
3 1
4 1

Time and space complexity of this approach

Arrays.stream() traverses the whole array which is O(n), in the same pass boxed() converts int to Integer and grouping is done by incrementing the count in the HashMap or by adding a new element, put() and get() methods in HahsMap are considered O(1). Thus the time complexity of this approach is O(1).

Since HashMap stores only unique elements, so the space complexity is O(k), considering the number of unique elements is k. Worst case is O(n) if all the array elements are unique.

That's all for this topic Java Program to Find The Frequency of Array Elements. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Find The Maximum Element in Each Row of a Matrix Java Program
  2. Array Rotation Java Program
  3. How to Remove Elements From an Array Java Program
  4. Count Number of Words in a String Java Program
  5. Count Number of Times Each Character Appears in a String Java Program

You may also like-

  1. Java Program - Sieve of Eratosthenes to Find Prime Numbers
  2. Writing a File Asynchronously Java Program
  3. Java Program to Detect And Remove Loop in a Linked List
  4. How to Display Time in AM-PM Format in Java
  5. Java Map computeIfPresent() With Examples
  6. Method Overloading in Python
  7. Angular Route Parameters - Setting and Fetching
  8. React Virtual DOM

Tuesday, October 7, 2025

Two Sum - Elements in Array With Given Sum Java Program

In the post Two Sum - Array Indices With Given Sum Java Program we saw how to write Java program for the given problem statement to find the indices. There is another variant of two sum problem where you may be asked to find all the pairs in the array that add up to the given target. So, rather than indices of the elements in the array you need to find the numbers itself that add up to the target.

For example:

1. Input: int[] arr = {4, 7, 5, 6}, target = 10
Output: (4, 6)

2. Input: int[] arr = {4, 6, 5, -10, 8, 5, 5,20}, target = 10
Output: (-10,20) (4,6) (5,5)

3. Input: int[] arr = {18, 12, 4, 2, 1, 5, 10}, target = 6
Output: (1,5) (2,4)

Java program for this problem statement can be written using one of the following approaches.

  1. Using nested loops which is not a very efficient solution.
  2. Using HashSet which is more efficient.
  3. By sorting the array and using two pointers.

1. Find pairs in an array using nested loops - Java Program

If you write the program, to find all the pair of numbers in an array that add up to the given target, using nested loops then you will have an outer loop that traverses through the array elements and an inner loop which starts from one more than the current outer loop iterator value.

public class PairsInArray {

  public static void main(String[] args) {
    int[] numArr = new int[] {4, 6, 5, -10, 8, 5, 5,20};
    int target = 10;
    findThePairs(numArr, target);
  }
  
  // With two loops 
  private static void findThePairs(int inputArray[], int target){
    String result = "";
    int len = inputArray.length;
    for(int i = 0; i < len; i++) {
      for(int j = i+1; j <len;j++) {
        int sum = inputArray[i] + inputArray[j];
        if(sum == target) {
          result = result + "(" + inputArray[i] + "," + inputArray[j] + ") ";
          break;
        }      
      }
    }
    // display all the pairs
    System.out.println(result);
  }
}

Output

(4,6) (5,5) (-10,20) (5,5)

Time and space complexity with nested loops

Since there are two loops, outer loop traversing all the elements and inner loop traversing through rest of the array to find another number to get the sum as target. Thus, the time complexity is O(n2).

Space complexity is O(1) as no auxiliary space is required with this approach.

2. Find pairs in array using HashSet - Java Program

In this approach HashSet is used to store array elements. You need to traverse array only once so only single loop is needed, in each iteration for the current element you calculate its difference with the target. Then, check in the Set to verify if there is any element already stored in the Set which is equal to this difference. If yes, that is the pair you are looking for.

public class PairsInArray {

  public static void main(String[] args) {
    int[] numArr = new int[] {4, 6, 5, -10, 8, 5, 5,20};
    int target = 10;
    findPairSet(numArr, target);
  }
  
  // Using HashSet
  public static void findPairSet(int inputArray[], int target) {
    String result = "";
    Set<Integer> pairSet = new HashSet<Integer>();
    for(int i = 0; i < inputArray.length; i++) {
      int c = target - inputArray[i];
      if(pairSet.contains(c)) {
        result = result +  "("+c + ", " + inputArray[i] + ")";
      }
      pairSet.add(inputArray[i]);
      
    }
    System.out.println(result);
  }
}

Output

(4, 6)(5, 5)(5, 5)(-10, 20)

As you can see from the output, with this approach and with nested loops you may have elements that are used more than once, extra logic is needed to take care of this. With two pointers approach you don't have this issue.

Time and space complexity with HashSet approach

Since there is only a single loop iterating the array and HashSet operations to check for value and to add elements are considered O(1) so the time complexity of this solution is O(n).

Extra space for HashSet is needed, which in worst case may store all the elements of the array so the space complexity is O(n).

3. Find pairs in array using Two pointers - Java Program

In this solution two pointer logic is used where the left pointer starts from the beginning of the array and the right pointer starts from the end of the array. Then you need to check if arr[left] + arr[right] = target, if yes you have got a pair, otherwise based on whether the sum is less than or greater than the target, you need to increment left pointer or decrement right pointer.

Array should be sorted to make it work with the two-pointer approach so that is the pre-computation required with this approach.

public class PairsInArray {

  public static void main(String[] args) {
    int[] numArr = new int[] {4, 6, 5, -10, 8, 5, 5,20};
    int target = 10;
    findPairsTwoPointer(numArr, target);
  }
  
  // With one loop - 2 pointer
  private static void findPairsTwoPointer(int inputArray[], int target){
    String result = "";
    int len = inputArray.length;
    int low = 0;
    int high = len - 1;
    // sort the array
    Arrays.sort(inputArray);
    
    while(low < high) {
      if(inputArray[low] + inputArray[high] == target){
        result = result + " (" + inputArray[low] + "," + inputArray[high] + ")";
        low++;
        high--;
            
      }else if(inputArray[low] + inputArray[high] < target){
        low++;             
      }else{
        high--;
      }
    }
    
    System.out.println(result);
  }
}

Output

(-10,20) (4,6) (5,5)

Time and space complexity with Two-pointer approach

Sorting the array is O(n log n), then traversing the loop is O(n) operation so the total time complexity is O(n log n) + O(n). Which simplifies to O(n log n).

As extra space only some variables are initialized which is not significant so the space complexity is O(1).

This is an efficient solution if array is already sorted.

That's all for this topic Two Sum - Elements in Array With Given Sum Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Find Largest And Smallest Number in a Given Array Java Program
  2. Array Rotation Java Program
  3. Find Duplicate Elements in an Array Java Program
  4. KMP Algorithm For Pattern Search - Java Program
  5. Printing Numbers in Sequence Using Threads Java Program

You may also like-

  1. Bubble Sort Program in Java
  2. Linear Search (Sequential Search) Java Program
  3. Queue Implementation in Java Using Linked List
  4. Read or List All Files in a Folder in Java
  5. HashSet Vs LinkedHashSet Vs TreeSet in Java
  6. CopyOnWriteArraySet in Java With Examples
  7. Controlled and Uncontrolled Components in React
  8. Angular ngIf Directive With Examples

Two Sum - Array Indices With Given Sum Java Program

In this post we'll see the Java program for two sum problem which states that "Given an array of integers and an integer target, return indices of the two numbers which add up to target." You return the first pair you get, if there is no pair return "No such pair exists"

For example:

1. Input: int[] arr = {4, 7, 5, 6}, target = 10
Output: [0, 3]
arr[0] + arr[3] = 4 + 6 = 10

2. Input: int[] arr = {4, 7, 5, 8}, target = 10
Output: "No such pair exists"

3. Input: int[] arr = {2, 3, 4, 1, 5}, target = 5
Output: [0, 1]

If you have to write a Java program for getting indices of the elements in the array that sum up to the given target, then you can use one of the following approaches-

  1. Using nested loops which is not a very efficient solution.
  2. Using HashMap which is more efficient.

Two sum problem using nested loops - Java Program

In this approach there is an outer loop that traverse through the array and an inner loop which starts from one more than the current outer loop index value.

public class TwoSum {

  public static void main(String[] args) {
    int[] arr = new int[] {4, 5, -10, 8, 6};
    int target = 10;
    int[] indicesArr = findPairsNestedLoops(arr, target);
    if(indicesArr.length == 2) {
      System.out.println("Indices are " +  indicesArr[0] + " " + indicesArr[1]);
    }else {
      System.out.println("No such pair exists");
    }
  }
  
  private static int[] findPairsNestedLoops(int[] arr, int target) {
    for(int i = 0; i < arr.length; i++) {
      for(int j = i+1; j < arr.length; j++) {
        if(arr[i] + arr[j] == target) {
          return new int[] {i, j};
        }
      }
    }
    return new int[] {};
  }
}

Output

Indices are 0 4

Time and space complexity with nested loops

Since there are two loops, outer loop traversing all the elements and inner loop traversing through rest of the array to find another number to get the sum as target. Thus, the time complexity is O(n2).

Space complexity is O(1) as no auxiliary space is required with this approach.

2. Two sum problem using HashMap - Java Program

In this approach to find indices of the two numbers which add up to target in a given array, HashMap is used to store array elements as key and its index in the array as value.

You need to traverse array only once, so only single loop is needed, in each iteration for the current element you calculate the difference with the target. Then, check in the Map to verify if there is any element already stored in the Map which is equal to this difference. If yes, that is the pair you are looking for.

public class TwoSum {

  public static void main(String[] args) {
    int[] arr = new int[] {4, 5, -10, 8, 6};
    int target = 10;
    int[] indicesArr = findPairsUsingMap(arr, target);
    if(indicesArr.length == 2) {
      System.out.println("Indices are " +  indicesArr[0] + " " + indicesArr[1]);
    }else {
      System.out.println("No such pair exists");
    }
  }
  
  private static int[] findPairsUsingMap(int[] arr, int target) {
    Map<Integer, Integer> sumMap = new HashMap<>();
    for(int i = 0; i < arr.length; i++) {
      // get the differnce from the target
      int otherKey = target - arr[i];
      // check if there is any element in the Map equal to this difference
      if(sumMap.containsKey(otherKey)) {
        return new int[] {sumMap.get(otherKey), i};
      }
      sumMap.put(arr[i], i);
    }
    return new int[] {};
  }
}

Output

Indices are 0 4

Time and space complexity with HashMap solution

Since there is only a single loop iterating the array and HashMap operations to check for key and to add elements are considered O(1) so the time complexity of this solution is O(n).

Extra space for HashMap is needed, which in worst case may store all the elements of the array so the space complexity is O(n).

There is another variation of the two sum problem where rather than indices you need to find the pair of elements in the array that add up to the target. Refer this post- Two Sum - Elements in Array With Given Sum Java Program to see solution for it.

That's all for this topic Two Sum - Array Indices With Given Sum Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Find Common Elements Between Two Arrays Java Program
  2. Find Largest and Second Largest Number in Given Array Java Program
  3. Find Duplicate Elements in an Array Java Program
  4. Longest Prefix Suffix Java Program
  5. What is In-place Algorithm

You may also like-

  1. Insertion Sort Program in Java
  2. Ternary Search Program in Java
  3. How to Reverse a Doubly Linked List in Java
  4. Java Program to Get All The Tables in a DB Schema
  5. How to Use ngFor and ngIf in Same Element in Angular
  6. Unmodifiable or Immutable Map in Java
  7. String in Java Tutorial
  8. How to Iterate Dictionary in Python

Friday, October 3, 2025

How to Find Common Elements Between Two Arrays Java Program

This post is about writing a Java program to find common elements between two given arrays. It is a common interview question where it may be asked with a condition not to use any inbuilt method or any inbuilt data structure like List or Set or you may be asked to write using any inbuilt data structure.

Here we'll see Java program to find common elements between two arrays using both approaches.

1. Find Common Elements Between Two Arrays With Nested Loops - Java Program

If you are using nested loops approach to find common elements between two arrays then you can loop through one of the arrays in the outer loop and then traverse through the other array in an inner loop and compare the element of the outer array with all the elements of the inner array. If similar element is found print it and break from the inner loop.

Find common elements between two given arrays of integers

 
public class FindCommonElement {
 public static void main(String[] args) {
  int[] numArray1 = {1, 4, 5};
  int[] numArray2 = {6, 1, 8, 34, 5};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i] == numArray2[j]){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }  
 }
}

Output

 
1
5

Find common elements between two arrays of strings

Logic to find common elements between two arrays remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.

 
public class FindCommonElement {
 public static void main(String[] args) {
  String[] numArray1 = {"Java", "Scala", "Python"};
  String[] numArray2 = {".Net", "Scala", "Clojure", "Java", 
    "Java Script", "Python"};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i].equals(numArray2[j])){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
 }
}

Output

 
Java
Scala
Python

Time and Space Complexity of This Approach

If first array has n elements and second array has m elements. Then outer loop runs n times and the inner loop may run upto m times. So, the time complexity is O(n X m).

No Extra space is needed in this approach so space complexity is O(1).

2. Find Common Elements Between Two Arrays Using HashSet - Java Program

If you are asked to write Java program to find common elements between two arrays where you can use inbuilt data structures then using HashSet provides a better performing solution than solution using nested loops.

Steps for solution are as given below

  1. Add all the elements of the first array in the HashSet.
  2. For each element of the second array, check if it is already in the set. If yes, that means a common element.
  3. Store such common elements in a separate Set. That way you won't get duplicates.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CommonElementArray {
  public static void main(String[] args) {
    
    String[] strArray1 = {"Java", "Scala", "Clojure"};
    String[] strArray2 = {".Net", "Scala", "Java", "Java Script", "Python"};
    CommonElementArray obj = new CommonElementArray();
    obj.findCommonElements(strArray1, strArray2);
  }
  
  public void findCommonElements(String[] strArray1, String[] strArray2) {
    Set<String> set = new HashSet<>();
    Set<String> commonElements = new HashSet<String>();
    // Add elements of first array in HashSet
    for(String s: strArray1) {
      set.add(s);
    }
    
    for(String s: strArray2) {
      // check element (of second array) is already in the set
      // if yes that means a common element, store it in another set
      if(set.contains(s))
        commonElements.add(s);
    }
    System.out.println("Common elements are- " + commonElements);
  }
}

Output

Common elements are- [Scala, Java]

Time and Space Complexity of This Approach

If first array has n elements and second array has m elements. Then adding all the elements of the first array to the Set takes O(n) time because adding element to the HashSet is O(1) thus for n elements it is O(n).

Verifying that element is already there or not using contains is O(1) operation. So, for m elements it is O(m).

So, the total time complexity is O(n + m).

Extra space requirement is there for adding n elements in the HashSet and common elements (let's say k) in another Set. So, the space complexity is O(n + k)

That's all for this topic How to Find Common Elements Between Two Arrays Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Remove Duplicate Elements From an Array in Java
  2. How to Remove Elements From an Array Java Program
  3. Array in Java
  4. Matrix Addition Java Program
  5. If Given String Sub-Sequence of Another String in Java

You may also like-

  1. Convert String to Byte Array Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Lambda Expression Comparator Example
  4. Java Program to Create Your Own BlockingQueue
  5. AtomicInteger in Java With Examples
  6. New Date And Time API in Java With Examples
  7. How HashMap Works Internally in Java
  8. Spring MessageSource Internationalization (i18n) Support

Thursday, September 1, 2022

Reflection in Java - Array

In this post you'll see how you can manipulate an array using Reflection API in Java. Array in Java is also a class so many of the methods in java.lang.Class may be used with the array.

Reflection in Java also provides a specific class java.lang.reflect.Array for arrays. In this post we'll see how you can get information about Array using Reflection API.

How to identify array using reflection

If you want to determine if a class member is a field of array type that can be done by invoking Class.isArray() method.

For example let’s say we have a class TestClass which has one array field numArray. In another class ReflectArray using the class.isArray() method it is determined if there is any array in the TestClass.

TestClass

public class TestClass {
 private int value;
 private int[] numArray;
 public int getValue() {
  return value;
 }
 public void setValue(int value) {
  this.value = value;
 }
 public int[] getNumArray() {
  return numArray;
 }
 public void setNumArray(int[] numArray) {
  this.numArray = numArray;
 }
}

ReflectArray

import java.lang.reflect.Field;

public class ReflectArray {
  public static void main(String[] args) {
    try {
      Class<?> c = Class.forName("org.netjs.prog.TestClass");
      Field[] fields = c.getDeclaredFields();
      for (Field f : fields) {
        Class<?> type = f.getType();
        // Looking for array
        if(type.isArray()){
          System.out.println("Array found " + f.getName());
        }
      }            
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Array found numArray

Creating new array using Java reflection

Using reflection API in Java you can dynamically create arrays of arbitrary type and dimensions using java.lang.reflect.Array.newInstance() method.

int[] testArray = (int[])Array.newInstance(int.class, 5);
System.out.println("length of array " + testArray.length);

Output

length of array 5

Getting and setting array using reflection

Using Java reflection API you can get or set an entire array. You can set an entire array using Field.set(Object obj, Object value) method. To retrieve an entire array use Field.get(Object obj) method.

If you want to get or set an array individual element by element, Array class has methods for that also. In order to set or get an int array you can use setInt(Object array, int index, int i) and getInt(Object array, int index) methods. Same way if you have a float array you can use setFloat(Object array, int index, float f) and getFloat(Object array, int index) methods.

There is also a method which takes Object for value as parameter that can be used with any type- set(Object array, int index, Object value) and get(Object array, int index) methods.

int[] testArray = (int[])Array.newInstance(int.class, 5);
System.out.println("length of array " + testArray.length);
// Setting values using setInt and set methods
Array.setInt(testArray, 0, 1);
Array.set(testArray, 1, 2);
Array.setInt(testArray, 2, 3);

// Getting values using getInt and get methods
System.out.println("First element " + Array.get(testArray, 0));
System.out.println("Second element " + Array.getInt(testArray, 1));
System.out.println("Third element " + Array.getInt(testArray, 2));

Output

length of array 5
First element 1
Second element 2
Third element 3

That's all for this topic Reflection in Java - Array. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Reflection in Java - Getting Field Information
  2. Reflection in Java - Getting Method Information
  3. Reflection in Java - Getting Constructor Information
  4. Generating Getters And Setters Using Reflection in Java
  5. Invoking Getters And Setters Using Reflection in Java

You may also like-

  1. How to Pass Command Line Arguments in Eclipse
  2. Nested class and Inner class in Java
  3. BigDecimal in Java With Examples
  4. SerialVersionUID And Versioning in Java Serialization
  5. Type Erasure in Java Generics
  6. AutoBoxing and UnBoxing in Java
  7. Is String Thread Safe in Java
  8. CopyOnWriteArrayList in Java With Examples

Wednesday, August 3, 2022

Find Maximum And Minimum Numbers in a Given Matrix Java Program

This post is about writing a Java program to find the maximum and minimum numbers in a given matrix (2D Array).

Solution to Find largest and smallest number in a matrix

Logic here is to have two variables for maximum and minimum numbers, initially assign the element at the first index of the matrix to both the variables.

Then iterate the matrix one row at a time and compare each column element with the max number if max number is less than the column element then assign column element to the max number.

If max number is greater than the column element then check if minimum number is greater than the column element, if yes then assign column element to the minimum number.

Java program to find largest and smallest number in a matrix

In the first part of the program matrix elements are entered and the end matrix is displayed then the maximum and minimum numbers are found using the above mentioned logic.

public class MatrixMinMax {

 public static void main(String[] args) {
  int rows; 
  int columns;
  Scanner scanner = new Scanner (System.in);
  // 
  System.out.println("Enter number of rows: ");
  rows = scanner.nextInt(); 
  
  System.out.println("Enter number of columns: "); 
  columns = scanner.nextInt(); 
  
  int[][] matrix = new int [rows][columns];
  
  System.out.println("Enter matrix numbers: "); 
  for (int i = 0; i < rows; i++) {
   System.out.println("Enter numbers for row - " + (i+1) + " and press enter"); 
   for (int j = 0; j < columns; j++) {
    matrix[i][j] = scanner.nextInt();
   }
  }
  scanner.close();
  // Displaying entered matrix
  System.out.println("Matrix as entered");
  for (int i = 0; i < matrix .length; i++) {
    System.out.println();
    for (int j = 0; j < matrix[i].length; j++) {
     System.out.print(matrix[i][j] + " ");
    }
  }
  System.out.println();
  findMinMax(matrix);
 }
 
 // Method to find max and min
 private static void findMinMax(int[][] matrix){
  //  start by assigning the first matrix element
  // to both the variables
  int maxNum = matrix[0][0];
  int minNum = matrix[0][0];
  for (int i = 0; i < matrix.length; i++) {
   for (int j = 0; j < matrix[i].length; j++) {
    if(maxNum < matrix[i][j]){
     maxNum = matrix[i][j];
    }else if(minNum > matrix[i][j]){
     minNum = matrix[i][j];
    }
   }
  }
  System.out.println("Largest number: " 
    + maxNum + " Smallest number: " + minNum);
 }
}

Output

Enter number of rows: 
3
Enter number of columns: 

3
Enter matrix numbers: 
Enter numbers for row - 1 and press enter
2 5 8
Enter numbers for row - 2 and press enter
17 4 9
Enter numbers for row - 3 and press enter
22 34 3
Matrix as entered

2  5  8 
17 4  9 
22 34 3 
Largest number: 34 Smallest number: 2

That's all for this topic Find Maximum And Minimum Numbers in a Given Matrix Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Multiplication Java Program
  2. Find Largest and Second Largest Number in Given Array Java Program
  3. How to Find Common Elements Between Two Arrays Java Program
  4. Find Duplicate Elements in an Array Java Program
  5. How to Remove Elements From an Array Java Program

You may also like-

  1. How to Read Properties File in Java
  2. Unzip File in Java
  3. Producer consumer Java Program using volatile
  4. Arrange Non-Negative Integers to Form Largest Number Java Program
  5. Java Collections Interview Questions And Answers
  6. Lambda Expressions in Java 8
  7. Bounded Type Parameter in Java Generics
  8. Ternary Operator in Java With Examples

Monday, July 25, 2022

Matrix Addition Java Program

When you add two matrices addition is done index wise you add the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

As example– If you are adding two matrices of order 3X3

matrix addition java program

Thus the resultant matrix is-

matrix addition

Also remember these points when adding one matrix with another-

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix added with (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix addition Java program

 
import java.util.Scanner;

public class MatrixAddition {
  public static void main(String[] args) {
    int rowM, colM;
    Scanner in = new Scanner(System.in);
    
    System.out.print("Enter Number of Rows and Columns of Matrix : ");
    rowM = in.nextInt();
    colM = in.nextInt();
    
    int M1[][] = new int[rowM][colM];
    int M2[][] = new int[rowM][colM];
    int resMatrix[][] = new int[rowM][colM];
        
    System.out.print("Enter elements of First Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter elements of Second Matrix : ");    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
        
    // Addition logic 
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        resMatrix[i][j] = M1[i][j] + M2[i][j];
      }
    }
        
    // Printing the result matrix 
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

Enter Number of Rows and Columns of Matrix :  3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1

Result Matrix : 
 3   10  5 
 2   9   12 
 13  11  3 

That's all for this topic Matrix Addition Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Multiplication Java Program
  2. Array in Java
  3. Remove Duplicate Elements From an Array in Java
  4. Find Largest and Second Largest Number in Given Array Java Program
  5. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program

You may also like-

  1. Java Program to Display Prime Numbers
  2. Factorial program in Java
  3. Count Number of Times Each Character Appears in a String Java Program
  4. Encapsulation in Java
  5. Java Variable Types With Examples
  6. How HashMap Works Internally in Java
  7. AtomicInteger in Java With Examples
  8. Dependency Injection in Spring Framework

Friday, July 1, 2022

Find Largest and Second Largest Number in Given Array Java Program

This post is about writing a Java program to find the top two numbers (largest and second largest) in a given array.

Condition here is that you should not be using any inbuilt Java classes or methods (i.e. Arrays.sort) or any data structure.

Solution to find largest and second largest number in an array

Logic here is to have two variables for first and second number and iterate the array. Compare each array element with the first number if first number is less than the array element then assign existing first number to second number and array element to the first number.

If first number is greater than the array element then check if second element is less than the array element, if yes then assign array element to the second number.

Largest and second largest number in array Java program

public class FindTopTwo {

 public static void main(String[] args) {
  int numArr[] = {2, 5, 14, 1, 26, 65, 123, 6};
  // Assign lowest possible int value
  int firstNum = Integer.MIN_VALUE;
  int secondNum = Integer.MIN_VALUE;
  
  for(int i = 0; i < numArr.length; i++){
   if(firstNum < numArr[i]){
    secondNum = firstNum;
    firstNum = numArr[i];
   }else if(secondNum < numArr[i]){
    secondNum = numArr[i];
   } 
  }
  System.out.println("Top two numbers : First -  " 
     + firstNum + " Second " + secondNum);
 }
}

Output

Top two numbers : First -  123 Second 65

That's all for this topic Find Largest and Second Largest Number in Given Array Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Remove Elements From an Array Java Program
  2. Matrix Addition Java Program
  3. How to Find Common Elements Between Two Arrays Java Program
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. Remove Duplicate Elements From an Array in Java

You may also like-

  1. Count Number of Times Each Character Appears in a String Java Program
  2. Invoking Getters And Setters Using Reflection in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Spring NamedParameterJdbcTemplate Insert, Update And Delete Example
  6. How to Create Immutable Class in Java
  7. BigDecimal in Java With Examples
  8. Interface Default Methods in Java

Tuesday, June 28, 2022

Remove Duplicate Elements From an Array in Java

Write a Java program to remove duplicate elements from an array is a frequently asked interview question and you may be asked to do it without using any of the collection data structure like List or Set or you may be asked to do it using Collection API classes first and then without using any of those classes.

In this post we’ll see Java programs for removal of duplicate elements in an array using Collection API classes, without Collection API and using Java Stream API.


Using Collection API

One way to remove duplicate elements from an array in Java is to copy your array elements to a HashSet. As you know HashSet only stores unique elements so any repetition of an element will be discarded. Using this property of HashSet once you copy all the array elements to a HashSet you’ll have a Set with only unique elements. Now you can again copy the elements from your Set to create an array which will be your array with duplicate elements removed.

Remove Duplicate Elements From an Array using HashSet

 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

  public static void main(String[] args) {
    int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
    int[] outArr = removeDuplicatesUsingSet(intArr);
    System.out.println("Original array");
    for(int i : intArr){
      System.out.print(i+" ");
    }
    System.out.println("");
    System.out.println("after removal");
    for(int i : outArr){
      System.out.print(i+" ");
    }
  }
    
  /**
  * @param input
  * @return
  */
  public static int[] removeDuplicatesUsingSet(int[] input){
    // Adding array elements to a list
    List<Integer> tempList = new ArrayList<Integer>();
    for(int i : input){
      tempList.add(i);
    }
    // creating a set using list     
    Set<Integer> set = new HashSet<Integer>(tempList);
    Integer[] output = new Integer[set.size()];
    int[] arrOut = new int[output.length];
    set.toArray(output);
    int j =0;
    for(Integer i : output){
      arrOut[j++] = i;
    }
    return arrOut;
  }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 3 5 6 7 8 12 

Few things to note here are-

  1. If you are using Set then ordering with in the array doesn’t matter i.e. Array doesn’t have to be sorted.
  2. Ordering of the original array will not be retained once elements are stored in the Set.
  3. In the above code I have used int[] array (array of primitives) that’s why there are some extra steps like creating Array of Integer[] (Integer objects) as toArray() method of the Set works only with objects. If you have an array of objects then you don’t need these extra steps.

Remove Duplicate Elements From an Array using LinkedHashSet

In the above Java code to delete element from an array using HashSet, ordering of the array elements is not retained, if you want ordering to be retained then use LinkedHashSet instead.

 
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {

  public static void main(String[] args) {
    int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
    int[] outArr = removeDuplicatesUsingSet(intArr);
    System.out.println("Original array");
    for(int i : intArr){
      System.out.print(i+" ");
    }
    System.out.println("");
    System.out.println("after removal");
    for(int i : outArr){
      System.out.print(i+" ");
    }
  }
    
  /** 
   * @param input
   * @return
   */
   public static int[] removeDuplicatesUsingSet(int[] input){
    // Adding array elements to a list
    List<Integer> tempList = new ArrayList<Integer>();
    for(int i : input){
      tempList.add(i);
    }
    // creating a set using list     
    Set<Integer> set = new LinkedHashSet<Integer>(tempList);
    Integer[] output = new Integer[set.size()];
    int[] arrOut = new int[output.length];
    set.toArray(output);
    int j =0;
    for(Integer i : output){
      arrOut[j++] = i;
    }
    return arrOut;
  }
}

Output

Original array
1 2 2 5 1 6 12 7 12 12 3 8 
after removal
1 2 5 6 12 7 3 8 

Now you can see ordering of the array elements is retained. For duplicate elements first occurrence of the element is retained.

Java Example without using Collection

If you have to remove duplicate elements of the array without using any of the Collection API classes then you can use the following code.

In the program input array is sorted first so that all the duplicate elements are adjacent to each other. By doing that you need only a single loop for comparison.
For removing duplicate elements you need to shift all the elements after the duplicate to the left. Another thing to note here is that array size is fixed once defined, when duplicate element is removed and you shift element after the duplicate to the left that creates space on the right side of the array. To remove that space you need to truncate the array by using copyOf() method of the Arrays utility class.

public class DuplicateRemoval1 {
  /** 
   * @param input
   * @return
  */
  public static int[] removeDuplicates(int[] intArr){
    int i = 1;
    int j = 0;
    Arrays.sort(intArr);
    System.out.println("Sorted array");
    for(int x : intArr){
      System.out.print(x+" ");
    }
    while(i < intArr.length){
      if(intArr[i] == intArr[j]){
        i++;
      }else{
        intArr[++j] = intArr[i++];
      }   
    }
    // This is required to truncate the size of the array
    // otherwise array will retain its original size
    int[] output = Arrays.copyOf(intArr, j+1);
    return output;
  }

  public static void main(String[] args) {
    int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
    int[] outArr = removeDuplicates(intArr);
    System.out.println("");
    System.out.println("after removal");
    for(int i : outArr){
      System.out.print(i+" ");
    }
  }
}

Output

Sorted array
1 1 2 2 3 5 6 7 8 12 12 12 
after removal
1 2 3 5 6 7 8 12 

Time and space complexity

As per the description of the Arrays.sort() method its time complexity is O(n*logn). Then array is traversed in the while loop which takes O(n) time thus the time complexity of the above code is O(n*logn+n).

Using Java Stream to remove duplicates from array

Java Stream API (From Java 8) also provides an option to remove duplicate elements from an array. You can use distinct() method in Java Stream to remove duplicate elements.

int[] intArr = {1, 2, 2, 5, 1, 6, 12, 7, 12, 12, 3, 8};
int tempArr[] = Arrays.stream(intArr).distinct().toArray();
       
System.out.println("");
System.out.println("after removal");
for(int i : tempArr){
 System.out.print(i+" ");
}

Output

after removal
1 2 5 6 12 7 3 8

That's all for this topic Remove Duplicate Elements From an Array in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Remove Duplicate Elements From an ArrayList in Java
  2. Matrix Multiplication Java Program
  3. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  4. How to Find Common Elements Between Two Arrays Java Program
  5. Array in Java

You may also like-

  1. Split a String Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. How to Read File From The Last Line in Java
  4. Unzip File in Java
  5. Difference Between Comparable and Comparator in Java
  6. How HashMap Works Internally in Java
  7. Map Operation in Java Stream API
  8. Java Concurrency Interview Questions And Answers

Saturday, June 25, 2022

Matrix Subtraction Java Program

When you subtract two matrices subtraction is done index wise. You subtract the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

For example if you are subtracting two matrices of order 3X3-

matrix subtraction in Java

Which results in-

Image

Also remember these points when subtracting one matrix with another-

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix minus (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix subtraction Java program

 
import java.util.Scanner;

public class MatrixSubtraction {

  public static void main(String[] args) {
    int rowM, colM;
    Scanner in = new Scanner(System.in);
    
    System.out.print("Enter Number of Rows and Columns of Matrix : ");
    rowM = in.nextInt();
    colM = in.nextInt();
        
    int M1[][] = new int[rowM][colM];
    int M2[][] = new int[rowM][colM];
    int resMatrix[][] = new int[rowM][colM];
    
    System.out.print("Enter elements of First Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter elements of Second Matrix : ");
    
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
        
    // Subtraction logic 
    for(int i = 0; i < rowM; i++){
      for(int j = 0; j < colM; j++){
        resMatrix[i][j] = M1[i][j] - M2[i][j];
      }
    }
        
    // Printing the result matrix 
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

 
Enter Number of Rows and Columns of Matrix : 3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1
 
Result Matrix : 
 -1  -4  3 
  2   1  0 
 -5  -5  1 

That's all for this topic Matrix Subtraction Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Multiplication Java Program
  2. Matrix Addition Java Program
  3. Remove Duplicate Elements From an Array in Java
  4. Factorial Program in Java
  5. Fibonacci Series Program in Java

You may also like-

  1. How to Display Pyramid Patterns in Java - Part2
  2. Zipping Files And Folders in Java
  3. How to Read File From The Last Line in Java
  4. How to Run a Shell Script From Java Program
  5. Object class in Java
  6. Type Wrapper Classes in Java
  7. Lock Striping in Java Concurrency
  8. How ArrayList Works Internally in Java

Saturday, April 16, 2022

Array Rotation Java Program

Write a Java program to rotate an array to the left or right by n steps is a frequently asked Java interview question.

For example if your array is– {1,2,3,4,5,6,7,8} then rotating elements of array by 2 steps to the right will make the array as {7,8,1,2,3,4,5,6} where as rotating to the left by 2 positions will give the output as {3,4,5,6,7,8,1,2}

Array rotation program- Solution

In this post two solutions are given for array rotation program-

  1. Using temporary array and array copying. See example.
  2. Rotating one element at a time using loops. See example.

Array rotation program- Using temp array

Solution using temporary array works as follows-

  1. If you have to rotate by 2 steps i.e. n=2 then copy n elements to a temporary array.
  2. Shift rest of the elements to the left or right based on rotation requirement.
  3. Copy elements from the temp array to the original array in the space created by shifting the elements.

In the program we actually copy all the elements to the temp array and then copy back to original array.

public class ArrayRotation {
  public static void main(String[] args) {
    int[] numArr={1,2,3,4,5,6,7,8};
    //rotateLeft(numArr, 4);
    rotateRight(numArr, 3);
  }
    
  private static void rotateLeft(int[] numArr, int steps){
    // create temp array
    int[] temp = new int[numArr.length];
    // copy elements to the temp array
    for(int i = 0; i < steps; i++){
      temp[(numArr.length-steps)+ i] = numArr[i];
    }
    // copy rest of the elements from the original array
    int i = 0;
    for(int j = steps; j < numArr.length; j++, i++){
      temp[i] = numArr[j];
    }
    //copy from temp to original 
    System.arraycopy(temp, 0, numArr, 0, numArr.length);    
    System.out.println("Array after left rotation- " + Arrays.toString(numArr));
  }
    
  private static void rotateRight(int[] numArr, int steps){
    // create temp array
    int[] temp = new int[numArr.length];
    // copy elements to the temp array
    for(int i = 0; i < steps; i++){
      temp[i] = numArr[(numArr.length-steps)+ i];
    }
    // copy rest of the elements from the original array
    int i = steps;
    for(int j = 0; j < numArr.length - steps; j++, i++){
      temp[i] = numArr[j];
    }
    System.out.println("Array after right rotation- " + Arrays.toString(temp));
  }
}

Output

Array after right rotation- [6, 7, 8, 1, 2, 3, 4, 5]

Array rotation program- using loops

This Java program for array rotation uses inner and outer for loops for shifting and copying elements.

Solution using loops works as follows-
  1. Copy the first element (in case of left rotation) or last element (in case of right rotation) in a temporary variable.
  2. Shift elements to the left or right as per rotation requirement in an inner loop one step at a time.
  3. Once out of inner loop copy the element stored in temp variable to its final position.
public class ArrayRotation {
  public static void main(String[] args) {
    int[] numArr={1,2,3,4,5,6,7,8};
    rotateLeft(numArr, 2);
    //rotateRight(numArr, 3);
  }
    
  private static void rotateLeft(int[] numArr, int steps){
    for(int i = 0; i < steps; i++){
      // store the first element
      int temp = numArr[0];
      for(int j = 0; j < numArr.length - 1; j++){
        // shift element to the left by 1 position
        numArr[j] = numArr[j + 1];
      }
      // copy stored element to the last
      numArr[numArr.length - 1] = temp;
    }
    System.out.println("Array after left rotation- " + Arrays.toString(numArr));
  }
    
  private static void rotateRight(int[] numArr, int steps){
    for(int i = 0; i < steps; i++){
      int temp = numArr[numArr.length-1];
      for(int j = numArr.length-1; j > 0; j--){
        numArr[j] = numArr[j -1];
      }
      // copy stored element to the beginning
      numArr[0] = temp;
    }
    System.out.println("Array after right rotation- " + Arrays.toString(numArr));
  }
}

Output

Array after left rotation- [3, 4, 5, 6, 7, 8, 1, 2]

That's all for this topic Array Rotation Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Find Common Elements Between Two Arrays Java Program
  2. Matrix Subtraction Java Program
  3. Java Lambda Expression Callable Example
  4. Producer-Consumer Java Program Using volatile
  5. Fibonacci Series Program in Java

You may also like-

  1. Difference Between Two Dates in Java
  2. How to Compile Java Program at Runtime
  3. Quick Sort Program in Java
  4. Write to a File in Java
  5. Map.Entry Interface in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Marker Interface in Java
  8. Spring Bean Life Cycle

Wednesday, March 2, 2022

Array in Java With Examples

An array in Java is a container object that holds values of a single type. These elements are stored in a contiguous memory location and referred by a common name. Note that this common name (variable) is an object which holds reference to the array.


Pictorial representation of an Array in Java

Let’s say you have an array numArr of length 10 and numArr is of type int. That means numArr is a variable that references the memory allocated for this int array.

array in java

Important points about array in Java

  1. Array holds a fixed number of elements.
  2. Length of an array is specified when an array is created. Once length of an array is specified it remains fixed.
  3. Array in Java is index based and the index starts from 0. So the first element is stored in the array at index 0.

Types of array

Array in Java can be of single dimension (one dimensional) or multi dimensional. So there are two types of arrays-

  • Single dimensional– It is essentially a sequence of elements of similar types.
  • Multi dimensional– It is essentially an array of arrays, in one dimensional array there is one row with multiple columns where as in multi-dimensional array there are multiple rows with multiple columns.

Java Array declaration and initialization

To declare an array in Java you have to provide array’s type and array’s name. An array’s type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array.

As example; if you want to declare an array, numArr of type int, it can be done as-

 int[] numArr;

here int denotes the type and numArr is the name of the array.

You can also place the brackets after the array name so this is also right-

 int numArr[];

But Java doc says “However, convention discourages this form; the brackets identify the array type and should appear with the type designation.” So let’s stick to type[] arrayName form.

Note that declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

In order to create an array in Java you can use one of the following options-

  1. Creating array using new operator.
  2. Initializing array while it is declared.

Creating array in Java using new operator

General form of creating an array (in case of single dimensional array) using new operator is as follows-

arrayName = new type[size]

Here,

  • type– Specifies the type of the data.
  • size– Specifies the number of elements in an array.
  • arrayName– array variable that holds reference to the created array.

As example-

int[] numArr; // array declared
numArr = new int[10]; // array created

When the above array is created using new operator, memory for 10 int elements is allocated and the array variable numArr holds the reference to that memory.

Of course you can combine these two steps into one to make it more compact and readable-

int[] numArr = new int[10];

One important thing to note here is that the array created by using new operator will automatically initialize its elements to the default value, which is-

  1. 0 for numeric types.
  2. false for boolean.
  3. null for an array of class objects.

As example– If you have created an array which holds element of type int and print all the values just after creating it you will get all values as zeroes.

public class ArrayDemo {
  public static void main(String[] args) {
    int[] numArr = new int[10];
    for(int i = 0; i < numArr.length; i++){
      System.out.println("Value at index " + i + " is " + numArr[i]);
    }
  }
}

Output

Value at index 0 is 0
Value at index 1 is 0
Value at index 2 is 0
Value at index 3 is 0
Value at index 4 is 0
Value at index 5 is 0
Value at index 6 is 0
Value at index 7 is 0
Value at index 8 is 0
Value at index 9 is 0

Here few things to note are-

  1. As soon as array is created using new operator memory is allocated for all the elements (in this case 10).
  2. Since default for numeric type is zero so all the elements of the array have value zero.
  3. Array in Java is zero index based, which means, for array of length 10 start index is 0 and last index is 9.
  4. If you don't create an array and just declare it, then the compiler prints an error like the following, and compilation fails: Variable numArr may not have been initialized

Initializing array while it is declared

Another way to create and initialize an array in Java is to provide values in between the braces when the array is declared.

int[] numArr = {1, 2, 3, 4, 5};

Here the length of the array is determined by the number of values provided between braces and separated by commas.

How to access array elements in Java

You can access array elements using the array index which is 0 based i.e. first element of the array is at index 0.

public class ArrayIndex {
 public static void main(String[] args) {
  int[] numArr = new int[5];
  // 4th element of the array
  numArr[3] = 7;
  // 1st element
  numArr[0] = 9;
  
  for(int i = 0; i < numArr.length; i++){
   System.out.println("Value at index " + i + " is " + numArr[i]);
  }
 }
}

Output

Value at index 0 is 9
Value at index 1 is 0
Value at index 2 is 0
Value at index 3 is 7
Value at index 4 is 0

Java run-time array index check

Java has strict run-time check for any out of range index. For example if the length of the array is 10 then the index range for the array is 0-9. Any attempt to use index out of this range, either negative number or positive number, will result in a run-time exception ArrayIndexOutOfBoundsException.

public class ArrayIndex {
 public static void main(String[] args) {
  int[] numArr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  //results in error (index is 0-9)
  int value = numArr[10];
 }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
 at org.netjs.examples1.ArrayIndex.main(ArrayIndex.java:8)

Array of objects in Java

You can also create an array of objects. As already mentioned above, at the time of creation of an array of objects, all the elements will be initialized as null for an array of class objects. What that means for each element of an array of object you will have to provide the object reference too.

As example-

Employee[] empArr = new Employee[10]; // array creation
Employee emp = new Employee();
empArr[0] = emp; // object reference

Multi-dimensional arrays in Java

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets. As example, if you want to create a 2-D array of String called names-

String[][] names. 

Each element, therefore, must be accessed by a corresponding number of index values.

Multi-dimensional array Java Example

public class ArrayDemo {
  public static void main(String[] args) {
    int[][] numArr = new int[3][3];
    // providing values for array
    for(int i = 0; i < 3; i++){
      for(int j = 0; j < 3; j++){
        numArr[i][j] = i + j;
      }
    }
    // Displaying array elements
    for(int i = 0; i < 3; i++){
      for(int j = 0; j < 3; j++){
        System.out.print(" " + numArr[i][j]);
      }
      System.out.println();
    }       
  }
}

Output

 0 1 2
 1 2 3
 2 3 4
 

That's all for this topic Array in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Package in Java
  2. Access Modifiers in Java - Public, Private, Protected and Default
  3. Find Duplicate Elements in an Array Java Program
  4. Find Largest and Second Largest Number in Given Array Java Program
  5. Matrix Multiplication Java Program

You may also like-

  1. String in Java Tutorial
  2. Association, Aggregation and Composition in Java
  3. Initializer Block in Java
  4. Lambda Expression Examples in Java
  5. Effectively Final in Java 8
  6. Deadlock in Java Multi-Threading
  7. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  8. Difference Between Checked And Unchecked Exceptions in Java