Java Program to Divide Two Numbers

Introduction

In this tutorial, we will learn how to write a Java program to divide two numbers. Division is one of the basic arithmetic operations in Java and is performed using the division operator (/).

We will explore different approaches to divide two numbers in Java:

  • Using the division operator (/) with predefined integer values.
  • Taking two numbers as input from the user using the Scanner class.
  • Using a helper method to perform the division.

Let’s explore each approach step by step.

Divide Two Numbers in Java Using the Division (/) Operator

Problem Statement

Write a Java program to divide two numbers without taking input from the user. Store two integer values directly in variables, divide the first number by the second number, and display the result on the console.

Formula Used

quotient = firstNumber / secondNumber

Input Format

In this program, you do not need to take input from the user. You assign directly two numbers to variables inside the Java program. For example:

int firstNumber = 50;
int secondNumber = 10;

Output Format

The program should display the two numbers and their quotient on the console in the exact format shown below:

First Number : 50
Second Number : 10
Quotient : 5

Constraints

  • Do not use Scanner, BufferedReader, or command-line arguments.
  • Store the numbers directly in predefined variables.
  • Use the int primitive data type for this example.
  • Use the division operator (/) to divide two numbers in Java.
  • The second number must not be zero because division by zero is not permitted for integer arithmetic in Java.
  • The program must execute inside the main() method entry point.

Expected Solution Approach

You can solve this program in four simple steps:

  1. Declare an integer variable named firstNumber and assign it the value 50.
  2. Declare another integer variable named secondNumber and assign it the value 10.
  3. Divide firstNumber by secondNumber using the division operator (/) and store the result in a variable named quotient.
  4. Display the quotient using System.out.println() on the console.

Core Calculation Statement

int quotient = firstNumber / secondNumber;

Complete Java Program to Divide Two Numbers

Here is the complete Java program to divide two numbers step by step with comments.

/**
 * Demonstrates basic integer division using hardcoded variables
 * and standard console output in Java.
 */
public class DivideTwoNumbers {

    public static void main(String[] args) {
        // Step 1: Declare and initialize dividend and divisor
        int firstNumber = 50;
        int secondNumber = 10;

        // Step 2: Compute the quotient using the division operator (/)
        int quotient = firstNumber / secondNumber;

        // Step 3: Print the formatted results to the console
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("Quotient      : " + quotient);
    }
}

Console Output:

First Number : 50 
Second Number : 10 
Quotient : 5

Step-by-Step Explanation

Step 1: Declare the Class

public class DivideTwoNumbers {

This statement defines a public class named DivideTwoNumbers. In Java, all executable logic must reside inside a class definition.

Step 2: Define the main() Method

public static void main(String[] args) {

The main() method is the standard entry point method required by the Java Virtual Machine (JVM) to start program execution.

Step 3: Declare and Initialize the Variables

int firstNumber = 50;
int secondNumber = 10;

Here, two integer variables are declared and initialized with the values 50 and 10. The firstNumber = 50 is the dividend and secondNumber = 10 is the divisor.

Step 4: Perform the Division

int quotient = firstNumber / secondNumber;

The division operator (/) divides firstNumber by secondNumber. Since both operands are integers, Java computes the integer division 50 / 10 = 5. After division, the result 5 is assigned to the integer variable quotient.

Step 5: Display the Result

System.out.println("Quotient : " + quotient);

The System.out.println() displays the input values and the final computed quotient using string concatenation (+).

Understanding Integer Division in Java

When both operands (values) are integers, Java performs integer division. In this case, Java drops everything after the decimal point. It does not round to the nearest number—it simply discards the fractional part. For example:

public class IntegerDivisionExample {
    public static void main(String[] args) {
        // Declare and initialize two integer variables
        int firstNumber = 25;
        int secondNumber = 4;

        // Perform integer division (truncates decimal part)
        int quotient = firstNumber / secondNumber;

        // Display the result
        System.out.println("Quotient = " + quotient);
    }
}

Console Output:

Quotient = 6

Although mathematically 25 / 4 is 6.25, the result is 6 because both operands are integers. Java removes the fractional part (.25) entirely and keeps only the whole number 6 rather than rounding up or down.

Java Program to Divide Two Numbers and Get a Decimal Result

To preserve the decimal portion, at least one of the operands must be a floating-point type (double or float). If both operands are integers, Java truncates the decimal before storing it into a double.

Three Ways to Achieve a Decimal Result:

1. Declare variables directly as double:

double a = 25;
double b = 4;
double result = a / b; // 6.25

2. By explicit type casting:

int a = 25;
int b = 4;
double result = (double) a / b; // 6.25

3. Use a decimal literal (4.0 or 4d):

int a = 25;
double result = a / 4.0; // 6.25

Complete Java Program

public class DecimalDivisionExample {
    public static void main(String[] args) {
        int firstNumber = 25;
        int secondNumber = 4;

        // Cast one operand to double to enforce floating-point division
        double decimalQuotient = (double) firstNumber / secondNumber;

        // Display results
        System.out.println("First Number  : " + firstNumber);
        System.out.println("Second Number : " + secondNumber);
        System.out.println("Decimal Result: " + decimalQuotient);
    }
}

Console Output:

First Number  : 25
Second Number : 4
Decimal Result: 6.25

Common Pitfall to Avoid

// INCORRECT: Integer division happens first (25 / 4 = 6), then converts to 6.0.
double wrongResult = firstNumber / secondNumber; // Results in 6.0, not 6.25

// CORRECT: (double) firstNumber converts 25 to 25.0 first, yielding 25.0 / 4 = 6.25
double correctResult = (double) firstNumber / secondNumber; // Results in 6.25

Java Program to Divide Two Numbers Using the Scanner Class

Problem Statement

Write a Java program that prompts the user to enter two integers via standard input (System.in), computes the quotient of the first number divided by the second using the / operator, and displays the result on the console.

For example:

  • Input: Dividend = 100, Divisor = 20
  • Output: Quotient: 5

The program should validate that the divisor is not zero before performing integer division to prevent an unhandled ArithmeticException.

Complete Java Program

Here is the complete Java program to divide two numbers by taking input from the user:

import java.util.Scanner;

public class DivideTwoNumbersScanner {
    public static void main(String[] args) {
        // Step 1: Create a Scanner object for user input.
        Scanner scanner = new Scanner(System.in);

        // Step 2: Read two numbers from the user
        System.out.print("Enter first number (dividend): ");
        int firstNumber = scanner.nextInt();

        System.out.print("Enter second number (divisor): ");
        int secondNumber = scanner.nextInt();

        // Step 3: Validate divisor to prevent ArithmeticException (/ by zero) and perform division
        if (secondNumber == 0) {
            System.out.println("Error: Division by zero is not allowed.");
        } else {
            // Compute the quotient
            int quotient = firstNumber / secondNumber;

            // Step 4: Display the formatted output
            System.out.println("-------------------------");
            System.out.println("First Number  : " + firstNumber);
            System.out.println("Second Number : " + secondNumber);
            System.out.println("Quotient      : " + quotient);
        }

        // Step 5: Close scanner resource
        scanner.close();
    }
}

Console Output:

Enter first number (dividend): 100
Enter second number (divisor): 20
-------------------------
First Number  : 100
Second Number : 20
Quotient      : 5

Zero Divisor Check

Enter the first integer (dividend): 100
Enter the second integer (divisor): 0
Error: Division by zero is not allowed.

Java Program to Divide Two Numbers Using a Helper Method

Problem Statement

Write a Java program to divide two numbers by defining a dedicated helper method that performs the division operation and returns the result.

Complete Java Program

import java.util.Scanner;
public class DivisionWithHelperMethod {

    // Helper method to compute division.
    public static double divide(double dividend, double divisor) {
        if (divisor == 0) {
            System.out.println("Error: Division by zero is undefined.");
            return Double.NaN;
        }
        return dividend / divisor;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 1. Input handling
        System.out.print("Enter dividend: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter divisor: ");
        double num2 = scanner.nextDouble();

        // 2. Business logic delegation via helper method
        double result = divide(num1, num2);

        // 3. Output presentation
        if (!Double.isNaN(result)) {
            System.out.printf("Result: " +result);
        }

        scanner.close();
    }
}

Console Output:

Enter dividend: 25
Enter divisor: 4
Result: 6.25

Follow-up Challenge

Challenge: Find Quotient and Remainder

Write a Java program that accepts two integers (dividend and divisor) from the user and computes both the integer quotient and the remainder using the division (/) and modulo (%) operators. For example:

First number = 17
Second number = 5

Expected output:

Quotient = 3
Remainder = 2
DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.