To find the greatest of three values in Java, you can use a simple if
statement to compare the values and return the maximum one.
Here's an example of how you can do this:
int a = 5; int b = 10; int c = 15; int max = a; if (b > max) { max = b; } if (c > max) { max = c; } System.out.println("The greatest of the three values is " + max);
This code will print "The greatest of the three values is 15".
You can also use the Math.max()
method to find the maximum of three values:
int a = 5; int b = 10; int c = 15; int max = Math.max(a, Math.max(b, c)); System.out.println("The greatest of the three values is " + max);
This code will also print "The greatest of the three values is 15".
Note that these examples assume that the values are of type int
. If the values are of a different type, such as double
or String
, you will need to use a different approach to compare the values. For example, you can use the compareTo()
method for String
objects or the Double.compare()
method for Double
objects.