Jump to content

If Else


Iodyne

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 comment
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 comment
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 comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...