Short IF - ELSE statement
The "ternary expression" x ? y : z
can only be used for conditional assignment. That is, you could do something like:
String mood = inProfit() ? "happy" : "sad";
because the ternary expression is returning something (of type String
in this example).
It's not really meant to be used as a short, in-line if-else
. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).
So the proper way to do this would just be with an if-else block:
if (jXPanel6.isVisible()) {
jXPanel6.setVisible(true);
}
else {
jXPanel6.setVisible(false);
}
which of course can be shortened to
jXPanel6.setVisible(jXPanel6.isVisible());
Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).
Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.
Shorthand for if-else statement
Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
The ternary operator lets us write shorthand if..else
statements exactly like you want.
It looks like:
(name === 'true')
- our condition
?
- the ternary operator itself
'Y'
- the result if the condition evaluates to true
'N'
- the result if the condition evaluates to false
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
Shorthand If/Else statement with two statements inside IF
No you cannot do that. The "small version" of the if/else is called the conditional operator. It is the only operator in c++ taking three operands and commonly also simply called "the ternary operator". From here:
Exp1 ? Exp2 : Exp3;
where Exp1, Exp2, and Exp3 are expressions. Notice the use and
placement of the colon. The value of a ? expression is determined like
this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and
becomes the value of the entire ? expression. If Exp1 is false, then
Exp3 is evaluated and its value becomes the value of the expression.
And for some clarification what is an expression see this question. break
is not an expression, but a statement, hence you cannot use it inside a ternary.
Anyhow I would advise you not to hide the break
within more stuff in a single line. In a loop a break
is something extremely important and it makes sense to make it stand out from the "normal" buissness that happens inside the loop. If I dont immediately see a break
(or a return
) in a loop then I assume that it does its full iteration. Overlooking a break
can cause mayor confusion and misunderstanding.
Short form for Java if statement
Use the ternary operator:
name = ((city.getName() == null) ? "N/A" : city.getName());
I think you have the conditions backwards - if it's null, you want the value to be "N/A".
What if city is null? Your code *hits the bed in that case. I'd add another check:
name = ((city == null) || (city.getName() == null) ? "N/A" : city.getName());
IF-ELSE statement shortcut in C
The operator ?:
must return a value. If you didn't have the "else" part, what would it return when the boolean expression is false? A sensible default in some other languages may be null, but probably not for C. If you just need to do the "if" and you don't need it to return a value, then typing if
is a lot easier.
shorthand c++ if else statement
Yes:
bigInt.sign = !(number < 0);
The !
operator always evaluates to true
or false
. When converted to int
, these become 1
and 0
respectively.
Of course this is equivalent to:
bigInt.sign = (number >= 0);
Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true
or false
.
Short java if else if else statement
If you want to convert something like:
if(A) {
return X;
}
else if(B) {
return Y;
}
else {
return Z;
}
You can write this as:
A ? X : (B ? Y : Z);
You thus write the else if
as a condition in the else-part (after :
) of the upper expression.
However, I would strongly advice against too much cascading. The code becomes extremely unreadable and the ? :
code structure was never designed for this.
combined usage of shorthand c if else statement and break in a loop resulted an error
The conditional operator ?:
and if
statements aren't compatible replacements.
The conditional operator can only be used with scalar (arithmetic or pointer) operands; it cannot be used for program flow control. So it can't contain break
and similar. In addition, it comes with a couple of subtle hiccups such as implicit type promotion and operator precedence issues. The only advantage of ?:
over if
is pretty much that it returns a value.
My rule of thumb is that if you can use if
instead of ?:
, then do it.
This gives safer and (usually) more readable code. The main use of ?:
is when writing various function-like macros (which is something that should be avoided in the first place). Some rare exceptions exist where ?:
does give more readable code, but my general advice is to just stay clear of it.
Returning using a shortened if else statement in Python
The form
print("Yes") if x == 1 else print("No")
is not generally considered Pythonic, since ... if ... else ...
is an expression and you're throwing away the value that the expression produces (always None
). You can use print("Yes" if x == 1 else "No")
which is Pythonic since the value of the conditional expression is used as the argument to print
.
The form
return total if x == 1 else return half
cannot work since return
is a statement and must occur at the beginning of a logical line. Instead, use
return total if x == 1 else half
(which is parsed the same as return (total if x == 1 else half)
).
The code
print(total) if x == 1 else print(half) if x == 2
wouldn't work either - the conditional expression is ... if ... else ...
, i.e. each if
must be paired with an else that follows it; your second if
is missing the else
clause; you could use
print(total) if x == 1 else print(half) if x == 2 else print('something else')
Again, this wouldn't be considered very pythonic; but you could use
print(total if x == 1 else half if x == 2 else 'something else')
not that it would be much better either.
Finally, if you're participating in a code golf
print("Yes" if x == 1 else "No")
can be shortened to
print(('No', 'Yes')[x == 1])
by using the fact that True == 1
and False == 0
and using these to index a tuple.
Advice needed on shorthand if else shorthand
day += -7 if day == 7 else 1
The way you read this is "Add negative 7 to day
if day == 7
, otherwise, add 1 to day
"
Dagorodir's original answer does not work, because it will subtract (day
+ 1) from the current value of day if day != 7
. So using your example with the the starting value of 5 for day
, the result of running the code from the other answer is -1
.
Related Topics
How to Clear Permgen Space Error in Tomcat
If Parenthesis Has a Higher Precedence Then Why Is Increment Operator Solved First
How to Determine the Primitive Type of a Primitive Variable
How to Change the Color of Specific Words in a Jtextpane
How to Pass a Value from One Jsp to Another Jsp Page
How to Enable Wire Logging for a Java Httpurlconnection Traffic
String S = New String("Xyz"). How Many Objects Has Been Made After This Line of Code Execute
Why Is the Tostring() Method Being Called When I Print an Object
How to Stop Parsing Xml Document with Sax at Any Time
Drag and Drop Custom Object from Jlist into Jlabel
Rejectedexecutionexception Inside Single Executor Service
Creating Unicode Character from Its Number
Jackson - How to Process (Deserialize) Nested JSON
Jaxb :Need Namespace Prefix to All the Elements
Java How Expensive Is a Method Call
Java 8 Chained Method Reference
Changing Java Platform on Which Netbeans Runs
Org.Openqa.Selenium.Webdriverexception: Unknown Error: Call Function Result Missing 'Value'