Java program to find the largest among three numbers

Write a java program to find the largest among three numbers

In this program, we will find the largest among three numbers using if else statements.

Let understand about Ternary operation,

It is a part of the java conditional statement. It contains three operands. It evaluates a Boolen expression and assigned a value based on the result. We can use it in place of the if-else statement. 

The syntax of the ternary operator is Variable name = (expression) ? value if true:value if false

If above expression returns true the value before the colon is assigned to the variable Variable name, else the value after the colon is assigned to the variable.

In the blow program, three numbers -6.6, 1.3 and 3.5 are stored in variables n1, n2 and n3 respectively.

For find the largest, the following conditions are checked using if else statements

  • If n1 is greater or equals to both n2 and n3, n1 is the largest.
  • If n2 is greater or equals to both n1 and n3, n2 is the greatest.
  • Else, n3 is the greatest.

The greatest number can also be found using a nested if..else statement.

  • Program:

public class Largest {

    public static void main(String[] args) {

        double n1 = -6.6, n2 = 1.3, n3 = 3.5;

        if( n1 >= n2 && n1 >= n3)
            System.out.println(n1 + " is the largest number.");

        else if (n2 >= n1 && n2 >= n3)
            System.out.println(n2 + " is the largest number.");

        else
            System.out.println(n3 + " is the largest number.");
    }
}

  • Output:

3.5 is the largest number.

  • Visit:

Java program to print an Integer Here
Java program to add two integers Here
Java program to find ASCII value of a character Here
Java program to compute quotient and remainder Here
Java program to swap two numbers Here
Java program to check whether a given number is even or odd Here
Java program to check whether an alphabet is vowel or consonant Here

0 comments