Java program to find the largest among three numbers
To find the largest among three numbers in Java, you can use a simple if-else statement to compare the three numbers and determine which one is the largest. Here's an example program that demonstrates this:
public class LargestOfThree { public static void main(String[] args) { int num1 = 10; int num2 = 20; int num3 = 30; int largest = num1; if (num2 > largest) { largest = num2; } if (num3 > largest) { largest = num3; } System.out.println("Largest number among " + num1 + ", " + num2 + ", and " + num3 + " is: " + largest); } }
In this program, we define three integer variables num1
, num2
, and num3
and initialize them with some values. We then define a variable largest
and initialize it with the value of num1
.
We then use if-else statements to compare the values of num2
and num3
with largest
. If num2
or num3
is greater than largest
, we update the value of largest
to that number.
After comparing all three numbers, we print out the largest number to the console using the System.out.println
method.
When you run the program, the output will be:
Largest number among 10, 20, and 30 is: 30
As you can see, the program successfully finds the largest among three numbers and prints it to the console.