If Else Statement

Compare Two Numbers Java Example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

2 Comments

  • //Another method using ? Operator

    public class CompareTwoNumbers
    {
    public static void main(String Args[])
    {
    int num1,num2,temp;
    num1=10;
    num2=20;

    temp = (num1 > num2) ? num1 : (num1 == num2) ? 0 : num2; /*If (num1>num2) num1 will be printed. Else if (num1==num2) 0 will be printed. Else num2 is printed.*/

    System.out.println(“Greater no. is “+temp);
    }
    }

  • import java.util.Scanner;

    public class CompareTwoNumber {
    public static void main(String[] args) {
    System.out.println(“enter First number”);
    Scanner input = new Scanner(System.in);
    int mum1 = input.nextInt();
    System.out.println(“enter the second number”);
    int mum2 = input.nextInt();
    if(mum1>mum2){
    System.out.println(mum1+”is geater than”+mum2);
    }
    else if(mum2>mum1){
    System.out.println(mum2+ “is greater than”+ mum1);
    }
    else
    System.out.println(mum1 + “are equal” +mum2);
    }
    }

Sponsors

Facebook Fans

Online Shopping – Flipkart