d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Can Someone Explain This Code
Add Reply New Topic New Poll
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Apr 25 2017 06:28am
Code
isCar = true;
boolean wasCar = isCar ? true : false;
if(wasCar)
System.out.println("wasCar is true");


Particularily this line:

boolean wasCar = isCar ? true : false;
Member
Posts: 3,197
Joined: May 4 2013
Gold: 1,457.00
Apr 25 2017 06:39am
it's ternary operator. Equivalent to writing


Code

if (isCar) {
wasCar = true;
} else {
wasCar = false;
}
Member
Posts: 36,123
Joined: Jul 18 2008
Gold: 2,407.00
Apr 25 2017 06:44am
I hate ternary operators. Imo not as readable and I'm sure the compiler doesn't care if it's a ternary operator or if/else.
Member
Posts: 3,197
Joined: May 4 2013
Gold: 1,457.00
Apr 25 2017 06:49am
It has its places, and you'll start to appreciate it as soon as you start working with language that doesn't support them :/ (eg. golang)

eg. it's super useful when using any kind of templating for any reason (rendering website, filling email or document ...)

Code
<p class="<%= activate ? "active" : "disabled" %>">foo</p>


This post was edited by nuvo on Apr 25 2017 06:52am
Member
Posts: 31,293
Joined: Mar 25 2009
Gold: 0.00
Apr 25 2017 06:50am
hmm ok thanks guys, makes sense :)
one question though


wouldn't this alone:
boolean wasCar = isCar ? true : false;

^make it so if isCar = true, wasCar = true?
you don't need if (wascar)?
Member
Posts: 3,197
Joined: May 4 2013
Gold: 1,457.00
Apr 25 2017 06:52am
This whole code is pretty useless and you could
Code

wasCar = isCar

and it would do exactly the same, and then wasCar would still be useless as you say.
Member
Posts: 1,039
Joined: Jul 8 2008
Gold: 1,939.50
Apr 25 2017 04:57pm
They are a very good tool to know how to use. There are many places you can use a ternary in place of an if/else and make the code more maintainable, but don't overdo it and nest them.
Member
Posts: 6,953
Joined: Sep 27 2003
Gold: 518.50
Apr 25 2017 07:15pm
Ternaries are great when you need an expression instead of a statement, but they're losing relevancy as more programming languages are embracing the "everything is an expression" philosophy. Take Rust, for example:
Code
let res = if something { value1 } else { value2 };

Almost every language has a conditional expression of some sort.

This post was edited by ASBands on Apr 25 2017 07:16pm
Member
Posts: 73
Joined: Dec 18 2015
Gold: Locked
May 3 2017 09:57am
:D
Member
Posts: 12,080
Joined: May 3 2017
Gold: Locked
Trader: Scammer
May 3 2017 03:12pm
Messy code
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll