0
0
Javaprogramming~10 mins

Ternary operator in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Ternary Operator in Java
📖 Scenario: You are creating a simple program that decides if a person is an adult or a minor based on their age.
🎯 Goal: Build a Java program that uses the ternary operator to check if a person is an adult (18 or older) or a minor (under 18) and prints the result.
📋 What You'll Learn
Create an integer variable age with the value 20
Create a string variable status that uses the ternary operator to set 'Adult' if age is 18 or more, otherwise 'Minor'
Print the status variable
💡 Why This Matters
🌍 Real World
Deciding between two options quickly based on a condition is common in apps, like showing messages based on user age.
💼 Career
Understanding the ternary operator helps write concise and readable code, a skill useful for any Java developer.
Progress0 / 4 steps
1
Create the age variable
Create an integer variable called age and set it to 20.
Java
Need a hint?

Use int age = 20; inside the main method.

2
Create the status variable using the ternary operator
Create a string variable called status that uses the ternary operator to set it to "Adult" if age is 18 or more, otherwise "Minor".
Java
Need a hint?

Use String status = age >= 18 ? "Adult" : "Minor"; to assign the value.

3
Print the status variable
Write a System.out.println statement to print the value of the status variable.
Java
Need a hint?

Use System.out.println(status); to show the result.

4
Run the program to see the output
Run the program. It should print Adult because the age is 20.
Java
Need a hint?

The program prints Adult because 20 is greater than or equal to 18.