How To Subtract Two Matrices in Java

Matrix operations are important in a number of programming problems in the areas of image processing, probability theory and physics simulation. Matrix subtraction is simple, and it involves subtracting each entry in the second matrix from the corresponding entry in the first matrix.

The following Java program demonstrates matrix subtraction. This example uses constant matrices hard-coded in Java, but you can easily change getMatrixA or getMatrixB to read them from files or from command line. Also note how we derive number of rows and columns from the data.

/**
 * Demonstrates matrix subtraction in java
 */
public class MatrixSubtraction {
    
    public static void main(String[] args) {
        MatrixSubtraction ms = new MatrixSubtraction();
        ms.subtractMatrices();
    }

    /**
     * Gets two matrices, subtracts them and prints the result on console.
     */
    private void subtractMatrices() {
        int[][] matrixA = getMatrixA();
        int[][] matrixB = getMatrixB();
        
        int[][] matrixResult = subtractMatrices(matrixA, matrixB);
        printMatrix(matrixResult);
    }

    /**
     * Returns first matrix
     * @return 
     */
    private int[][] getMatrixA() {
        int[][] matrixA = new int[][] {
                                {8,2,4},
                                {5,2,9}    
     
                            };
        return matrixA;
    }
    
    /**
     * Returns second matrix
     * @return 
     */
    private int[][] getMatrixB() {
        int[][] matrixB = new int[][] {
                                {7,1,3},
                                {4,1,8}
                                
                            };
        return matrixB;
    }

    //Subtracts two matrices. 
    private int[][] subtractMatrices(int[][] matrixA, int[][] matrixB) {
        int rows=matrixA.length;
        int cols=matrixA[0].length;
        
        int[][] sum = new int[rows][cols];
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                sum[i][j] = matrixA[i][j] - matrixB[i][j];
            }
        }
        return sum;
    }
    
    /**
     * Prints the matrix on command line.
     * @param matrix 
     */
    public void printMatrix(int[][] matrix) {
        int rows=matrix.length;
        int cols=matrix[0].length;
        
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                System.out.print(" "+matrix[i][j]);
            }
            System.out.println();
        }
    }
}

How to Add Two Matrices in Java

Matrix operations are important in a number of algorithms. It is used in graph theory, geometry, probability theory and image processing. Matrix addition is simple, each entry in first matrix is added to the corresponding entry in the second matrix to get the entry in the result matrix.

The following sample program illustrates matrix addition in Java. This example uses constant matrices hard-coded in Java, but you can easily change functions getMatrixA() or getMatrixB() to read them from files or from command line. Also note how we derive number of rows and columns from the matrix data.

/**
 * Add two matrices. 
 */
public class MatrixAddition {
    
    public static void main(String[] args) {
        MatrixAddition ma = new MatrixAddition();
        ma.addMatrices();
    }

    /**
     * Gets two matrices, adds them and prints the result on console.
     */
    private void addMatrices() {
        int[][] matrixA = getMatrixA();
        int[][] matrixB = getMatrixB();
        
        int[][] matrixResult = addMatrices(matrixA, matrixB);
        printMatrix(matrixResult);
    }

    /**
     * Returns first matrix
     * @return 
     */
    private int[][] getMatrixA() {
        int[][] matrixA = new int[][] {
                                {4,5,3},
                                {2,1,3},    
                                {7,6,1}
                            };
        return matrixA;
    }
    
    /**
     * Returns second matrix
     * @return 
     */
    private int[][] getMatrixB() {
        int[][] matrixB = new int[][] {
                                {4,1,8},
                                {3,0,2},    
                                {9,1,1}
                            };
        return matrixB;
    }

    //Adds two matrices. 
    private int[][] addMatrices(int[][] matrixA, int[][] matrixB) {
        int rows=matrixA.length;
        int cols=matrixA[0].length;
        
        int[][] sum = new int[rows][cols];
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                sum[i][j] = matrixA[i][j] + matrixB[i][j];
            }
        }
        return sum;
    }
    
    /**
     * Prints the matrix on command line.
     * @param matrix 
     */
    public void printMatrix(int[][] matrix) {
        int rows=matrix.length;
        int cols=matrix[0].length;
        
        for(int i=0;i<rows;i++) {
            for(int j=0;j<cols;j++) {
                System.out.print(" "+matrix[i][j]);
            }
            System.out.println();
        }
    }
}

How to Run External Program in Java

From your Java program, it is possible to run other applications in your operating system. This enables you to make use of system programs and command line utilities from your Java program. Here are some typical uses of this feature when running your Java program in Windows,

  • You want to invoke a Windows program such as Notepad
  • You want to invoke a command line utility such as Check disk (chkdsk) or IP information (ipconfig)
  • You want to  access the Windows command interpreter and access some of its features such as "dir" command or "find" command. In this case, please note that the program you want to access is cmd.exe and commands like "dir" and "find" are arguments to cmd.exe. Also when directly invoked, cmd.exe doesn't terminate. If you want cmd.exe to terminate immediately, you should pass the /C argument.

We have provided sample programs for each of the use cases above. The overall approach here is same (we will use Runtime.exec method), but there are some subtle differences you need to be aware of.

The following program demonstrates how you can execute a Windows program such as Notepad from your Java program,

/**
 * Runs external application from this Java program
 */
public class RunProgram {

    public static void main(String[] args) {
        RunProgram rp = new RunProgram();
        rp.openNotePad();
    }

    /**
     * Runs Notepad program in the Windows system. Please note that this assumes
     * you are running this program on Windows.
     */
    private void openNotePad() {
        Runtime rt = Runtime.getRuntime();
        try {
            Process p = rt.exec("notepad");
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

This following example demonstrates how you can execute a command line program in Windows from your Java program. This program will also print the results of the command. Note that in this case we are using another version of the Runtime.exec method. This program runs "ipconfig" command with /all command line argument. This would print the complete IP address configuration of the system.

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Runs another application from a Java program
 */
public class RunProgram2 {

    public static void main(String[] args) {
        RunProgram2 rp = new RunProgram2();
        rp.printIPInfo();
    }

    /**
     * Print complete IP address info using the command ipconfig /all
     */
    private void printIPInfo() {
        Runtime rt = Runtime.getRuntime();
        String[] commandAndArguments = {"ipconfig","/all"};
        try {
            Process p = rt.exec(commandAndArguments);
            String response = readProcessOutput(p);
            System.out.println(response);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Reads the response from the command. Please note that this works only
     * if the process returns immediately.
     * @param p
     * @return
     * @throws Exception 
     */
    private String readProcessOutput(Process p) throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String response = "";
        String line;
        while ((line = reader.readLine()) != null) {
            response += line+"\r\n";
        }
        reader.close();
        return response;
    }
}

 

In the final example, we invoke the command line program (cmd.exe) of the Windows system and then execute commands supported by it. By default cmd.exe is blocking and to terminate it immediately you need to pass the command line option /C. The following program prints the directory listing of C drive (C:\) using the "dir" command of "cmd.exe".

import java.io.BufferedReader;
import java.io.InputStreamReader;


public class RunProgram3 {

    public static void main(String[] args) {
        RunProgram3 rp = new RunProgram3();
        rp.getDirectoryListing();
    }

    /**
     * Runs cmd.exe from Java program and then invokes dir command to list C:\ drive.
     * The /C option is necessary for the program
     */
    private void getDirectoryListing() {
        Runtime rt = Runtime.getRuntime();
        String[] commandAndArguments = {"cmd","/C","dir","c:\\"};
        try {
            Process p = rt.exec(commandAndArguments);
            String listing = readProcessOutput(p);
            System.out.println(listing);
            //p.waitFor();
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * Reads the response from the command. Please note that this works only
     * if the process returns immediately.
     * @param p
     * @return
     * @throws Exception 
     */
    private String readProcessOutput(Process p) throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String response = "";
        String line;
        while ((line = reader.readLine()) != null) {
            response += line+"\r\n";
        }
        reader.close();
        return response;
    }
}

 

If you are not reading the response from the external program and if you want to wait for the external program to finish before you continue processing, you can use the Process.waitFor() method. This will block your program till the external program completes execution.

How to Check Whether a Year is Leap Year in Java

Usually there are 365 days in a year. However once every four years, there are 366 days in year. This year is called leap year and on a leap year, February has 29 days. However not all years divisible by 4 are leap years. Following are the rules to determine whether a year is leap year or NOT,

  • A leap year is evenly divisible by 4
  • An year evenly divisible by 4 is NOT a leap year if it is also evenly divisible by 100, UNLESS it is also evenly divisible by 400. Note that an year evenly divisible by 400 is always a leap year since it is also evenly divisible by 4.

The following Java program uses the above rules to find out whether a given year is leap year or not.


import java.util.Scanner;

/**
 * The following program checks whether a given year is a leap year.
 * Takes the input year from command line.
 */
public class LeapYear {
    
    public static void main(String[] args) {
        
        LeapYear ly = new LeapYear();
        Scanner sn = new Scanner(System.in);
        System.out.print("Please enter year to check:");
        int year = sn.nextInt();
        
        if(ly.isLeapYear(year)) {
            System.out.println("Year "+year+" is a leap year");
        }else {
            System.out.println("Year "+year+" is NOT a leap year");
        }
    }
    
    /**
     * An year is leap year if it satisfies the following 3 criteria,
     * 1. Divisible by 4
     * 2. If it is divisible by 4 and 100 it is NOT leap year unless it is
     * also divisible by 400. Since an year divisible by 400 is also divisible 
     * by 4 and 100, you can just check for 400 in code.
     * @param year
     * @return 
     */
    private boolean isLeapYear(int year) {
        if((year%4==0 && year%100!=0) || year%400==0) {
            return true;
        }else {
            return false;
        }
    }
}

 

Another way to find whether a year is leap year is to find out whether the year has 366 days. This can be easily achieved using Calendar API in Java. The following example shows how Java calendar API can be used to check for leap year,


import java.util.Calendar;
import java.util.Scanner;

/**
 * The following program checks whether a given year is a leap year.
 * Takes the input year from command line.
 */
public class LeapYear2 {
    
    public static void main(String[] args) {
        
        LeapYear2 ly = new LeapYear2();
        Scanner sn = new Scanner(System.in);
        System.out.print("Please enter year to check:");
        int year = sn.nextInt();
        
        if(ly.isLeapYear(year)) {
            System.out.println("Year "+year+" is a leap year");
        }else {
            System.out.println("Year "+year+" is NOT a leap year");
        }
    }
    
    /**
     * A leap year has 366 days and we use Java calendar API
     * to check whether given year has more than 365 days!
     * @param year
     * @return 
     */
    private boolean isLeapYear(int year) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        return c.getActualMaximum(c.DAY_OF_YEAR) > 365;
    }
}

How To Reverse a String in Java

There are a multiple ways to solve a programming problem. There may be library classes that may be very useful in solving programming problems. If you don't know these classes and methods, you will end up  spending time writing your own methods and wasting time. We would use the programming problem of reversing a given String to illustrate this.

If you have a String such as "Hello", the reverse would be "olleH". The logic is easy to find, start from the end of the given string and then take each character till the beginning. Append all these characters to create the reversed String. The following program implements this logic to reverse a given String,

import java.util.Scanner;
/**
 * Reverse a String given by user. Write our own reversing logic 
 */
public class ReverseString1 {
    
    public static void main(String[] args) {
        ReverseString1 rs = new ReverseString1();
        System.out.print("Please enter String to reverse:");
 
        Scanner sn = new Scanner(System.in);
        String input = sn.nextLine();
        String output = rs.reverseString(input);
        System.out.println("The reverse form of "+input+" is "+output);
    }

    /**
     * Our custom method to reverse a string.
     * @param input
     * @return 
     */
    private String reverseString(String input) {
        String reversedString = "";
        char[] characters = input.toCharArray();
        for(int i=characters.length-1;i>=0;i--) {
            reversedString+=characters[i];
        }
        return reversedString;
    }
}

However there is a much easier way to reverse Strings. The StringBuilder class of Java has a built-in reverse method! The following program demonstrates the usage of this library method. This is much better since we can implement it faster and can be sure that the library method is well tested reducing the amount of bugs in your code. This is the approach you should follow when writing Java programs. Always make use of Java library classes or reliable third party libraries to solve your problem.

import java.util.Scanner;
/**
 * Reverse a String given by user using Java library methods
 */
public class ReverseString2 {
    
    public static void main(String[] args) {
        ReverseString1 rs = new ReverseString1();
        System.out.print("Please enter String to reverse:");
 
        Scanner sn = new Scanner(System.in);
        String input = sn.nextLine();
        StringBuffer sb = new StringBuffer(input);
        String output = sb.reverse().toString();
        System.out.println("The reverse form of "+input+" is "+output);
    }
}