Java Tutorial
🔍
Java ProgramsBasics & I/OSubtract Two Numbers

Subtract Two Numbers in Java

beginner·  Basics & I/O  ·  Arithmetic

Problem

Subtracting two numbers with the - operator finds the difference between them.

Given two integers, subtract the second from the first and print the result.

Input
10, 4
Output
Difference: 6

Java Program

Java
public class SubtractTwoNumbers { public static void main(String[] args) { int a = 10; int b = 4; int difference = a - b; // order matters here System.out.println("Difference: " + difference); } }

Output

Difference: 6

Core Logic

The - operator subtracts the second value from the first, evaluated left to right just like standard arithmetic.

How It Works
  1. 1a holds 10 and b holds 4.
  2. 2a - b evaluates to 6, the result of subtracting b from a.
  3. 3The result is stored in difference and printed alongside a label.
With a = 10 and b = 4, a - b evaluates to 6, so the program prints "Difference: 6".
💡

Key Point: Order matters with subtraction — a - b and b - a give different (often negatively signed) results, unlike addition or multiplication.

Key Concepts

- operatorintarithmetic

Related Programs