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

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

Monday, July 18, 2022

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 is asked with a condition not to use any inbuilt method or any inbuilt data structure like list or set.

Steps for solution

A simple solution to find common elements between two arrays in Java is to loop through one of the array 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

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

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-

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

Tuesday, December 21, 2021

Find The Maximum Element in Each Row of a Matrix Java Program

In this post we’ll see a Java program to find the maximum element in each row of a matrix.

For example if the matrix is as follows-

3  7  9 
12 89 23 
1  17 32

Then the output should be-

Maximum element in row 1- 9
Maximum element in row 2- 89
Maximum element in row 3- 32

Java program to find maximum element in each row of a matrix

Initially user will be prompted to enter the matrix elements to create a matrix. Also create an array having the same length as the number of rows in the matrix.

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. After the row is iterated (outer loop finishes one iteration) assign the maximum number to the corresponding index of the created array.

public class MatrixMax {
  public static void main(String[] args) {
    //create matrix by taking input from user
    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();
    // call method to find max element per row
    findMaxEachRow(matrix);
  }

  private static void findMaxEachRow(int[][] matrix){ 
    int[] result = new int[matrix.length];
    for (int i = 0; i < matrix.length; i++) {
      // Assign first element of the row as 
      // maximum in first iteration
      int maxNum = matrix[i][0];
      for (int j = 0; j < matrix[i].length; j++) {
        if(maxNum < matrix[i][j]){
          maxNum = matrix[i][j];
        }
        result[i] = maxNum;
      }     
    }
      
    // Display results
    for (int i = 0; i < result.length; i++) {
      System.out.println("Maximum element in row " + (i + 1) + "- " + result[i]);
    }
  }
}

Output

Enter number of rows: 
3
Enter number of columns: 
3
Enter matrix numbers: 
Enter numbers for row - 1 and press enter
12 20 67
Enter numbers for row - 2 and press enter
56 34 55
Enter numbers for row - 3 and press enter
1 2 78
Matrix as entered

12 20 67 
56 34 55 
1  2  78 
Maximum element in row 1- 67
Maximum element in row 2- 56
Maximum element in row 3- 78

If you are asked to find the minimum element in each row of a matrix then you need to change just this line-

if(maxNum < matrix[i][j]) to if(minNum > matrix[i][j])

Variable maxNum is changed to minNum for readability.

That's all for this topic Find The Maximum Element in Each Row of a 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 Subtraction Java Program
  2. Find Largest And Smallest Number in a Given Array Java Program
  3. How to Display Pyramid Patterns in Java - Part1
  4. Java Program to Display Prime Numbers
  5. Reverse Each Word in a String Java Program

You may also like-

  1. How to Convert Date to String in Java
  2. Invoking Getters And Setters Using Reflection in Java
  3. Producer-Consumer Java Program Using volatile
  4. How to Read Excel File in Java Using Apache POI
  5. Java Multithreading Interview Questions And Answers
  6. Is String Thread Safe in Java
  7. Java Object Cloning - clone() Method
  8. Dependency Injection in Spring Framework

Monday, September 6, 2021

Find Largest And Smallest Number in a Given Array Java Program

This post is about writing a Java program to find the largest and the smallest number in a given array or it can also be rephrased as- Find the maximum and minimum number in a given array.

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

Solution to find the largest and the smallest number in an array

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

Then iterate the array and compare each array element with the max number if max number is less than the array element then assign array element to the max number.

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

Java code

public class FindMaxMin {
 public static void main(String[] args) {
  int numArr[] = {56, 36, 48, 49, 29, 458, 56, 4, 7};
  
  // start by assigning the first array element
  // to both the variables
  int maxNum = numArr[0];
  int minNum = numArr[0];
  // start with next index (i.e. i = 1)
  for(int i = 1; i < numArr.length; i++){
   if(maxNum < numArr[i]){
    maxNum = numArr[i];
   }else if(minNum > numArr[i]){
    minNum = numArr[i];
   }  
  }
  System.out.println("Largest number -  " 
     + maxNum + " Smallest number - " + minNum);
 }
}

Output

Largest number -  458 Smallest number - 4

That's all for this topic Find Largest And Smallest Number in a 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. Find Largest and Second Largest Number in Given Array Java Program
  2. How to Find Common Elements Between Two Arrays Java Program
  3. Find Duplicate Elements in an Array Java Program
  4. How to Remove Elements From an Array Java Program
  5. Matrix Multiplication Java Program

You may also like-

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Find All Permutations of a Given String Java Program
  3. How to Convert Date to String in Java
  4. How to Read File From The Last Line in Java
  5. Creating Tar File And GZipping Multiple Files in Java
  6. How to Remove Elements From an ArrayList in Java
  7. Executor And ExecutorService in Java With Examples
  8. Java Reflection API Tutorial

Tuesday, June 1, 2021

Find Duplicate Elements in an Array Java Program

If you have to write a Java program to find duplicate elements in an array one option you have is to loop through the array taking one element at a time and then compare it with all the other elements of the array in order to find the duplicates. Though this solution works fine but the problem here is you are looping though the array twice making the time complexity of this solution O(n2). Because of the double iteration program will be slow.

Another option to find duplicate elements in an array is to sort the array first and then compare the adjacent element in a loop. Since array is sorted so the repeated elements would be adjacent to each other so you don't need an inner loop to compare current element with all the elements of the array. Thus the time complexity of this solution is O(nlogn + n). Time required for sorting is O(nlogn) and iteration of the array requires O(n) time.

To further minimize the execution time you can think of using a data structure like HashSet which will reduce the time complexity to O(n).

Since Set doesn't allow duplicate elements trying to do that will return false. So you can have a logic where you iterate an array and try to add element to the HashSet, if adding an element to the HashSet returns false that means a duplicate element. As I said since array is iterated only once so time complexity is O(N) here but a new data structure is created, apart from array you are also creating a Set, so space complexity increases here, extra space used is O(N).

Let's see Java program to find duplicate elements in an array using all of the approaches discussed above.


Looping through unsorted Array and comparing elements to find duplicates

Here you have an outer loop that iterates the array one element at a time and another loop that starts from the next element and iterates through all the elements of the array and compares it with the current element.

public class DuplicateArrayElement {
  public static void main(String[] args) {
    int[] numArray = {2, 6, 7, 6, 2, 19, 1, 19};
    for(int i = 0; i < numArray.length; i++){
      for(int j = i + 1; j < numArray.length; j++){
        if(numArray[i] == numArray[j]){
          System.out.println("Duplicate element found " + numArray[j]);
        }
      }
    }    
  }
}

Output

Duplicate element found 2
Duplicate element found 6
Duplicate element found 19

Finding duplicate elements in a sorted Array

public class DuplicateArrayElement {
  public static void main(String[] args) {
    int[] numArray = {8, 1, 7, 6, 2, 19, 1, 19};
    // sort array
    Arrays.sort(numArray);
    for(int i = 0; i < numArray.length - 1; i++){
      if(numArray[i] == numArray[i+1]){
        System.out.println("Duplicate element found " + numArray[i]);
      }
    }
  }
}

Output

Duplicate element found 1
Duplicate element found 19

Using HashSet to find duplicate elements in an array

In this solution to find duplicate elements in an array in Java, iteration of the array is done and elements of the array are added to the set.

Here thing to understand is- If set already contains the element, call to add method of the set leaves the set unchanged and returns false. So, whenever false is returned that means a duplicate element.

public class DuplicateArrayElement {
  public static void main(String[] args) {
    int[] numArray = {2, 6, 7, 6, 2, 19, 1, 19};
    Set<Integer> numSet = new HashSet<Integer>();
    for(int num : numArray){
      // If add returns false
      if(!numSet.add(num)){
        System.out.println("Duplicate element found " + num);
      }
    }
  }
}

Output

Duplicate element found 2
Duplicate element found 6
Duplicate element found 19

That's all for this topic Find Duplicate Elements in an 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 Iterate a HashMap of ArrayLists of String in Java
  2. How to Remove Duplicate Elements From an Array Java Program
  3. How to Find Common Elements Between Two Arrays Java Program
  4. Find Largest and Second Largest Number in Given Array Java Program
  5. How to convert Array to ArrayList in Java

You may also like-

  1. Zipping Files And Folders in Java
  2. Java Program to Get All DB Schemas
  3. Difference Between Array And ArrayList in Java
  4. Difference Between Abstract Class And Interface in Java
  5. Java ArrayBlockingQueue With Examples
  6. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  7. Java ThreadLocal Class With Examples
  8. Ternary Operator in Java With Examples

Thursday, March 4, 2021

Matrix Multiplication Java Program

In this post we'll see a Java program to multiply two matrices which also gives you an idea about working with two dimensional arrays.

When you multiply two matrices with each other, you actually do a "dot product" of rows and columns. For example if you are multipying a 3X3 matrix with a 3X2 matrix-

matrix multiplication in Java
Matrix multiplication

The result you get can be explained as follows-

s11 = r11Xp11 + r12Xp21 + r13Xp31
s12 = r11Xp12 + r12Xp22 + r13Xp32
s21 = r21Xp11 + r22Xp21 + r23Xp31
s22 = r21Xp12 + r22Xp22 + r23Xp32
s31 = r31Xp11 + r32Xp21 + r33Xp31
s32 = r31Xp12 + r32Xp22 + r33Xp32

When you are writing a Java program to multiply two matrices-

You need an outer loop that will run as many times as there are rows in the first matrix.
Then you’ll have a second loop that will run as many times as the number of columns in the second matrix.
Then you’ll have a third loop that will run as many times as there are columns in the first matrix.

Also remember these points when multiplying one matrix with another-

  1. The number of columns of the first matrix is equal to the number of rows of the second matrix.
  2. The resultant matrix will have the same number of rows as in the first matrix and same number of columns as in the second matrix.

Matrix multiplication Java program

 
import java.util.Scanner;

public class MatixMultiplication {

  public static void main(String[] args) {
    int rowM1, colM1;
    int rowM2, colM2;
    
    Scanner in = new Scanner(System.in);
    System.out.print("Enter Number of Rows and Columns of First Matrix : ");
    rowM1 = in.nextInt();
    colM1 = in.nextInt();
    
    System.out.print("Enter elements of First Matrix : ");
    int M1[][] = new int[rowM1][colM1];
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM1; j++){
        M1[i][j] = in.nextInt();
      }
    }
    System.out.println("First Matrix : " );
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM1; j++){
        System.out.print(" " +M1[i][j]+"\t");
      }
      System.out.println();
    }
        
    System.out.print("Enter Number of Rows and Columns of Second Matrix : ");
    rowM2 = in.nextInt();
    colM2 = in.nextInt();
    if(colM1 != rowM2){
      throw new IllegalArgumentException("The number of columns of the first matrix should equal the number of rows of the second matrix.");
    }
    System.out.print("Enter elements of Second Matrix : ");
    int M2[][] = new int[rowM2][colM2];
    for(int i = 0; i < rowM2; i++){
      for(int j = 0; j < colM2; j++){
        M2[i][j] = in.nextInt();
      }
    }
    System.out.println("Second Matrix : " );
    for(int i = 0; i < rowM2; i++){
      for(int j = 0; j < colM2; j++){
        System.out.print(" " +M2[i][j] + "\t");
      }
      System.out.println();
    }
    //same number of rows as in the first matrix and 
    //same number of columns as in the second matrix
    int resMatrix[][] = new int[rowM1][colM2];
    int sum = 0;
    int row = 0;
    for(int i = 0; i < rowM1; i++){
      for(int j = 0; j < colM2; j++){
        sum = 0;
        for(int k = 0; k < colM1; k++){
          sum = sum + M1[i][k] * M2[k][j];
        }
        resMatrix[i][j] = sum;
      }
    }
        
    System.out.println("Result Matrix : " );
    for(int i = 0; i < resMatrix.length; i++){
      for(int j = 0; j < colM2; j++){
        System.out.print(" " +resMatrix[i][j]+"\t");
      }
      System.out.println();
    }
  }
}

Output

 
Enter Number of Rows and Columns of First Matrix : 2
3
Enter elements of First Matrix : 1
2
3
4
5
6
First Matrix : 
 1  2  3 
 4  5  6 
Enter Number of Rows and Columns of Second Matrix : 3
2
Enter elements of Second Matrix : 7
8
9
10
11
12
Second Matrix : 
 7   8 
 9   10 
 11  12 
Result Matrix : 
 58   64 
 139  154 

That's all for this topic Matrix Multiplication 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. Array in Java With Examples
  2. Matrix Subtraction Java Program
  3. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  4. Find Duplicate Elements in an Array Java Program
  5. Check Given Strings Anagram or Not Java Program

You may also like-

  1. How to Display Pyramid Patterns in Java - Part1
  2. How to Convert String to Date in Java
  3. Java Program to Convert a File to Byte Array
  4. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  5. Marker interface in Java
  6. Switch Case Statement in Java With Examples
  7. String in Java Tutorial
  8. Dependency Injection in Spring Framework

Thursday, February 4, 2021

How to Remove Elements From an Array Java Program

Writing a Java program to remove element from an array may look like a simple task but it comes with its own set of problems. Those problems stem from the fact that array in Java is fixed in length. Which means you can't just remove an element from the given index in an array, you will need to shift all the elements that are after the element that has to be removed, to the left to fill the gap left by the removed element.

Once the element are shifted to fill the gap that leaves space at the end of the array (remember array size is fixed). Array size will not reduce after removing the element and the element that is at the end will be repeated to fill the empty space.

Let's try to clarify it with an example-

Here the array removal is done without using any third party tool (like Apache common utils) or any data structure provided by the Java language (Like Collection classes).

So the steps followed to remove element from an array are-

  1. Ask the user to enter the element to be removed.
  2. Search in the array for the given element.
  3. If found shift all the element after that index to the left by one element. As example if element to be deleted is at index i then remove all the elements from index i+1 to array.length by one element which means element at i+1 will come at index i.

Java program to remove element from an array

 
import java.util.Scanner;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
    
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        // shifting elements
        for(int j = i; j < intArr.length - 1; j++){
            intArr[j] = intArr[j+1];
        }
        break;
      }
    }
      
    System.out.println("Elements -- " );
    for(int i = 0; i < intArr.length; i++){
      System.out.print(" " + intArr[i]);
    }                
  }
}

Output

Enter Element to be deleted : 5
Elements -- 
 1 2 12 7 3 8 8

If you notice last element 8 is repeated to fill the space that is left after shifting the elements.

Now when you have basic idea about the scenarios that you need to take care of while removing element from an array let's see what all alternatives are there to do that.


Using new array

When you remove an element from an array, you can fill the empty space with 0, space or null depending on whether it is a primitive array, string array or an Object array.

Other alternative is to create a new array and copy the elements in that array. New array should have size of old array’s size – 1.

Let’s see an example where new array is used-

 
import java.util.Scanner;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
    int[] newArr = null;
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
        
    /*for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){          
        for(int j = i; j < intArr.length - 1; j++){
          intArr[j] = intArr[j+1];
        }
        break;
      }
    }*/
        
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        newArr = new int[intArr.length - 1];
        for(int index = 0; index < i; index++){
          newArr[index] = intArr[index];
        }
        for(int j = i; j < intArr.length - 1; j++){
          newArr[j] = intArr[j+1];
        }
        break;
      }
    }
    System.out.println("Elements -- " );      
    for(int i = 0; i < newArr.length; i++){
      System.out.print(" " + newArr[i]);
    }                
  }
}

Output

Enter Element to be deleted : 
5
Elements -- 
 1 2 12 7 3 8

Enter Element to be deleted : 8
Elements -- 
 1 2 5 12 7 3

With copying the element to the new array problem of empty space is solved.

Using ArrayUtils to remove element from an array

If you can use Apache commons in your application then there is a utility class ArrayUtils that can be used to remove elements from an array.

 
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        // Using ArrayUtils
        intArr = ArrayUtils.remove(intArr, i);
        break;
      }
    }
        
    System.out.println("Elements -- " );
    for(int i = 0; i < intArr.length; i++){
      System.out.print(" " + intArr[i]);
    }
  }
}

Output

Enter Element to be deleted : 2
Elements -- 
 1 5 12 7 3 8

Using System.arraycopy() method to remove element from an array

Description of the System.arraycopy method

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) - Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

If you use the same array as source and destination you will have the same issue of repeating element as discussed in the first program as the array length is fixed. In the example code new array is used as destination.

 
import java.util.Arrays;
import java.util.Scanner;

public class ElemRemoval {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        removeElement(intArr, i);
        break;
      }
    }       
  }
    
  public static void removeElement( int [] arr, int index ){
    // Destination array
    int[] arrOut = new int[arr.length - 1];
    int remainingElements = arr.length - ( index + 1 );
    // copying elements that come before the index that has to be removed
    System.arraycopy(arr, 0, arrOut, 0, index);
    // copying elements that come after the index that has to be removed
    System.arraycopy(arr, index + 1, arrOut, index, remainingElements);
    System.out.println("Elements -- "  + Arrays.toString(arrOut));
  }
}

Output

Enter Element to be deleted : 5
Elements -- [1, 2, 12, 7, 3, 8]

Using ArrayList to remove element from an array

If you want to remove element from an array using Collection API provided by the Java language then you can convert array to an ArrayList and then remove element from the ArrayList. Shuffling and all would be taken care of by the ArrayList itself. Once the element is removed you can again convert the ArrayList to an array.

 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ElemRemoval {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Integer[] intArr = {1, 2, 5, 12, 7, 3, 8};            
    System.out.print("Enter Element to be deleted : ");
    int elem = in.nextInt();
        
    System.out.println("Original Array " + Arrays.toString(intArr));        
    for(int i = 0; i < intArr.length; i++){
      if(intArr[i] == elem){
        intArr = removeElementUsingCollection(intArr, i);
        break;
      }
    }
    System.out.println("Array after removal of Element -- " );
    for(int i = 0; i < intArr.length; i++){
      System.out.print(" " + intArr[i]);
    }
        
    public static Integer[] removeElementUsingCollection( Integer[] arr, int index ){
      List<Integer> tempList = new ArrayList<Integer>(Arrays.asList(arr));
      tempList.remove(index);
      return tempList.toArray(new Integer[0]);
    }
}

Output

Enter Element to be deleted : 2
Original Array [1, 2, 5, 12, 7, 3, 8]
Array after removal of Element -- 
 1 5 12 7 3 8

That's all for this topic How to Remove Elements From an 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. Find Duplicate Elements in an Array Java Program
  2. Remove Duplicate Elements From an Array in Java
  3. Matrix Subtraction Java Program
  4. Difference Between Array And ArrayList in Java
  5. How ArrayList Works Internally in Java

You may also like-

  1. Split a String Java Program
  2. Format Date in Java Using SimpleDateFormat
  3. How to Create PDF From XML Using Apache FOP
  4. How to Create Deadlock in Java
  5. Difference Between equals() Method And equality Operator == in Java
  6. Arithmetic and Unary Operators in Java
  7. Java Object Cloning - clone() Method
  8. Java Nested Class And Inner Class