Published on Jan 02, 2024
Welcome to our Tech Bite. Today, we will delve into the concept of the ternary operator in Java.
The ternary operator, often called the conditional operator, offers a concise method for expressing if-then-else statements in Java. Let’s delve into its functionality with an example. In this Java program, we will Determine the maximum of two numbers utilising the ternary operator.
Firstly, we declare a class named.
“Ternary” to encapsulate our program.
Inside the class, we have the “main” method, the program’s entry point, which accepts an array of strings as arguments.
We then declare and initialise two integer variables, n1 and n2, with the values 35 and 55, respectively.
Next, we display the values of n1 and n2 using print statements.
After that, we use the ternary operator to determine the maximum of n1 and n2. If n1 is greater than n2, then the value of n1 is assigned to the variable “max”; otherwise, the value of n2 is assigned.
Finally, we display the maximum
value using another print statement.
Let’s run this program and see what happens.
Greetings, our code has been executed; as you can see in the output, the largest number has been printed.
Our Java program uses the ternary operator to find the maximum of two numbers.
Thank you for joining us today. Stay tuned for more Java Videos.
Join global tech minds at LSET for a hands-on journey into AI & Machine Learning Innovation.
Limited Seats Sign Up Today!
This will close in 0 seconds