Jump to content

Recommended Posts

Hi, I just discovered the "ternary operator" for if else and found the page on this website for it, here: https://www.w3schools.com/java/java_conditions.asp under "Short Hand If...Else (Ternary Operator)." The description states that it can be used "if you have only one statement to execute" but I believe that to be innacurate (or at least worded improperly/confusingly) and should be fixed. For example, the following code I've attached seems to work just fine:2008555422_ScreenShot2019-10-18at1_53_16.thumb.png.69a93248a50ec460830f2314d809bd69.png

Likewise I've tested this format on another method with a length of 26 of these statements, (as opposed to just the two above), and so it appears the statments can be strung together practically without limit. I just figured the information should be a little clearer. There aren't many people who would try to test something which says it won't work.

Link to post
Share on other sites

You would be correct. Ternaries can perform multiple statements of execution. I'll point out that you're still executing one statement by nesting ternaries but the ability is there.

However to use ternaries to execute multiple statements, would be... not ideal. Why would you not use an if...else?

Additionally nesting ternaries exponentially reduces readability past the first.

Link to post
Share on other sites
  • 6 months later...

Hello, @lodyne

Please try this code,To If Else using ternery operator.

public class testpls {

       public static void main(String[] args){

        int time=22;

        System.out.println(time<=18 ? "Good day. " : time<=22 ? "Good Evening." : "Good Night.." );



I hope this code will be usefull for you.

Thank You.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...