0
0
Javaprogramming~10 mins

Ternary operator in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign the smaller of two numbers to the variable min using the ternary operator.

Java
int a = 10;
int b = 20;
int min = (a < b) ? [1] : b;
Drag options to blanks, or click blank then click option'
Ab
Ba
C10
D20
Attempts:
3 left
💡 Hint
Common Mistakes
Using b instead of a for the true case.
Confusing the order of values in the ternary operator.
2fill in blank
medium

Complete the code to assign "Even" or "Odd" to the variable result based on whether num is even or odd.

Java
int num = 7;
String result = (num % 2 == 0) ? [1] : "Odd";
Drag options to blanks, or click blank then click option'
A"Even"
B"Odd"
Cnum
D"Number"
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the true and false values.
Using the variable num instead of string literals.
3fill in blank
hard

Fix the error in the ternary expression to correctly assign the absolute value of number to absValue.

Java
int number = -5;
int absValue = (number >= 0) ? number : [1];
Drag options to blanks, or click blank then click option'
A0
Bnumber
C-number
Dnumber * -1
Attempts:
3 left
💡 Hint
Common Mistakes
Using number instead of its negation for negative values.
Using number * -1 which is correct but less common than -number.
4fill in blank
hard

Fill both blanks to create a ternary expression that assigns "Pass" if score is 50 or more, otherwise "Fail".

Java
int score = 65;
String grade = (score [1] 50) ? [2] : "Fail";
Drag options to blanks, or click blank then click option'
A>=
B<
C"Pass"
D"Fail"
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of >= in the condition.
Swapping the strings "Pass" and "Fail".
5fill in blank
hard

Fill all three blanks to create a ternary expression that assigns the maximum of x and y to max.

Java
int x = 15;
int y = 25;
int max = ([1] [2] [3]) ? x : y;
Drag options to blanks, or click blank then click option'
Ax
By
C<
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in the condition.
Swapping x and y in the condition or result.