Skip to main content

Command Palette

Search for a command to run...

Java Programming : Greater of two numbers

Updated
1 min readView as Markdown
Java Programming : Greater of two numbers

Example

Input 
enter first number 5
enter second number 6 
Output
The larger number is 6

Required to Know

Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out.print(), Use of If-else, and Use of Data types.

Steps

  • Take two numbers as input from the user.

  • If the first_number is greater than the second_number, print first_number. Otherwise, print second_number.

Condition

if(first_number>second_number){
    print(first_number)
}
else{
    print(second_number)
}

Program

import java.util.Scanner;

public class greater {

    /**
     * This class compares two numbers and prints the larger number.
     */

    public static void main(String[] args) {

        // Create a Scanner object to read user input.
        Scanner sc = new Scanner(System.in);

        // Prompt the user to enter two numbers.
        System.out.print("Enter two numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();

        // Check if a is greater than b.
        if (a > b) {

            // Print a.
            System.out.println("The larger number is " + a);

        } else {

            // Print b.
            System.out.println("The larger number is " + b);

        }
    }
}

More from this blog

TheCodingcoder

60 posts

Empowering the coding community by simplifying complex tasks.