Ankaj Gupta
August 03, 2020

Java program for subtraction of two number

Java program for subtraction two Integers

In this section, you will learn how to subtract two numbers in Java. Let's see :

1.) First program :

In this program, we specify the value of both the numbers in the program itself.

Let's try to create a simple example :

  ➤ Example : subtract two numbers with predefined value;

class SubtractTwoNumbers {
      public static void main(String[] args) {      
      int x = 15, y = 10, subtract;
      subtract = x - y;
      
      System.out.println("Subtraction of two numbers is : "+subtract);
   }
}
Explanation :

 Example 1 : explanation

    In the above program, we have created three integer variables x, y and subtract, then stored (15 and 10) values in x and y.

  • Then, x and y are subtract using the - operator, and its result is stored in another variable subtract.

  • Finally, subtract is printed on the screen using System.out.println() function.

2.) Second program :

In this program, we will take two inputs from the user(entered by the user) and prints the subtract.

Note : Scanner class is a part of package(java.util), so we required to import this package in our Java program.

Let's try to create a simple example :

  ➤ Example : subtract two numbers with user input(Scanner);

import java.util.Scanner;
class SubtractTwoNumbers 
{
   public static void main(String args[]) {      
      int x, y, subtract;

      System.out.println("Enter two integers to calculate their subtraction : ");
      Scanner in = new Scanner(System.in);
     
      x = in.nextInt();
      y = in.nextInt();
      subtract = x - y;
     
     System.out.println("Subtraction of two numbers is : "+subtract);
   }
}
Explanation :

 Example 2 : explanation

    In the above program, we have created three integer variables x, y and subtract, then create a Scanner class so that you can take input from the user for x and y.

  • Then, x and y are subtract using the - operator, and its result is stored in another variable subtract.

  • Finally, subtract is printed on the screen using System.out.println() function.

Java program Java programming

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts