Java Programming - Operators and Assignments - Discussion

6. 

What will be the output of the program?

class Test 
{
    public static void main(String [] args) 
    {
        int x=20;
        String sup = (x < 15) ? "small" : (x < 22)? "tiny" : "huge";
        System.out.println(sup);
    }
}

[A]. small
[B]. tiny
[C]. huge
[D]. Compilation fails

Answer: Option B

Explanation:

This is an example of a nested ternary operator. The second evaluation (x < 22) is true, so the "tiny" value is assigned to sup.


Tshepo Lucas Malema said: (Aug 26, 2011)  
Creat a JApplet that asks a user to enter a passwoed into a JTextField and then to press enter.

Nagaraju said: (Sep 9, 2011)  
class Test
{
public static void main(String [] args)
{
int x=20;
String sup = (x < 15) ? "small" : (x < 22)? "tiny" : "huge";
System.out.println(sup);
}
}

In this program the output is tiny, how it is possible in this program given

//int x=20;

String sup = (x < 15) ? "small" : (x < 22)? "tiny" : "huge";
System.out.println(sup);

// it gives the second evaluation is true then output will be tiny, huge.

Karthi said: (May 29, 2012)  
What is nested ternary operator.

Pooja Niranjane said: (Oct 28, 2013)  
In above program the ternary operator perform operation right to left.

So first of all evaluates (x<22) ?"tiny":"huge";.

20 < 22 it return true.

And get the answer tiny.

Then statement like (x<15) ?"small":"tiny";.

20 <15 it return false.

And get the answer tiny.

So answer is tiny.

Pooja Niranjane said: (Oct 28, 2013)  
Nested ternary means nested if else,
Like :

if(x<22)
{
if(x<15)
{
printf("small");
}
printf("tiny");
}
else
{
printf("huge");
}

Jacek said: (Nov 30, 2014)  
Hi community.

I know only condition "if", where I can condition like in this line:

(x < 15)? "small" : (x < 22)? "tiny" : "huge".

I would check it in API but I have no idea where it looking for.

Thank you in advanced.

Nasreen said: (Mar 24, 2015)  
Any one please write a program to find whether the given input is alphabet or special character or numeral using conditional operator and if it is alphabet, convert into upper case.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.