I'm trying to return a different value using a simple if/else to check for an even number in Java.
if (move % 2 == 0) {
return "o";
} else {
return "O";
}
I know in JavaScript you can use
if () : a ? b ;
Can this be used in Java?
Yes, you can use the ternary operator in Java:
return (move % 2 == 0) ? "o" : "O";
Just don't expect it to be any faster than the if-else.
Yes, you can use the conditional operator in Java:
return (move % 2 == 0) ? "o": "O";
It won't make your program any faster, but it's a little more concise and if you are familiar with the conditional operator, you will probably find it easier to read.
But conversely, if you don't know this operator it will be hard to guess what the code does.
Yes you can. It's called a ternary operator
Usage:
true ? case1 : case2; // returns case1
false ? case1 : case2; // returns case2
Instead of "optimizing" the if versus the ternary operator ? you should focus on the move % 2 == 0. If move is an integer and not a floating point variable this may be faster:
if( move & 1 == 0 )
return "E";
else
return "O";
Bit operations are usually faster than division or modulo calculations.
(conditional) ? if-true-statement : if-false-statement;
Yes it can, check out the Wikipedia page for Ternary Operators
There's no way you can use an if-statement in a more or less efficient way.
... and further more - keep in mind that, and this does not only apply for if-statements:
You should never try to optimize expressions used, for performance reasons - write code that focuses on readability (and in term, maintainability). The reason for this is that there's a JIT (Just-in-time compiler) that will optimize the bytecode, and modify the instructions you've specified in your byte-code.
If you're thinking about using the ternary operator, then consider, will this lead to harder to understand code (if you're multiple people working on the code). If it's just you working on the code then do as you please - and yes:
Object var = boolean-expression ? some-value : another-value;
is much more compact than:
Object var;
if (boolean-expression)
var = some-value;
else
var = another-value;
If you really need this to be blindingly fast, which is pretty dubious, you should also consider a lookup table:
static final char[] moveChar = {"o", "O"};
// ...
return moveChar[move % 2];
But I wouldn't implement any of the suggestions given here without timing them, and I wouldn't do anything at all until it had been proven that what you have now is really a bottleneck, by which I mean that it consumes more than about 50% of the CPU time.
Related
I'm writing small program, and want to get access to an element in array with the loop. And I need to increment "array index" variable for next iteration.
Here is the code:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].equalsIgnoreCase("O") ? false : winner[turn];
turn++;
Is it possible to make one line of code from it?
PS: I'm trying to write less lines only for myself. It's a training for brain and logic.
Well, it can be done for sure:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].
equalsIgnoreCase("O") ^ winner[turn++];
Look that there is not even ternary operator there.
But not because it is shorter it is better (and certainly not clearer). So I'd recommend you do it in these many lines:
String aSubField = subField[(int)Math.floor(i / 10.0)][i % 10];
if (aSubField.equalsIgnoreCase("O"))
winner[turn] = false;
turn++;
Look, even there is no need to assign the value in case the comparison yields false.
[edit]
YAY! Just found my XOR was wrong ... that's just the problem with golf, it tooks a lot of time to figure it is wrong .... (in this case, if the cond is true but the previous value is false, it won't work).
So let me golf it other way :)
winner[turn] = !subField[i/10][i%10].equalsIgnoreCase("O") & winner[turn++];
Note the ! and the &
[edit]
Thanks to #Javier for giving me an even more compact and confuse version :) this one:
winner[turn++] &= !subField[i/10][i%10].equalsIgnoreCase("O");
Let's break it down a bit. What you have is:
winner[turn] = (some condition) ? false : (expression involving turn)
(increment turn)
Well, why not increment turn in the array access? That means it'll be incremented by the time you evaluate expressions on the right hand side, but you can easily adjust it back to its previous value as needed.
winner[turn++] = (some condition) ? false : (expression involving (turn - 1) )
I'm really sorry for what must be a really stupid question. I don't exactly have formal training in java and a lot of times, when looking through code, I might see something like:
( ) ? :
as in something like:
for (str == null) ? getString(this) : dontGetit(nope.this);
honestly i don't even know exactly it is or if it's remotely close, but hopefully one could recognize the scheme. I was hoping one could perhaps link some documentation on this because i have trouble even searching for it.
It is ternary operator in Java. Read here : http://www.janeg.ca/scjp/oper/ternary.html
it an ternary operator used to evaluate boolean expressions. It is equivalent to if-else statement.
Syntax:
variable_name= (boolean expression) ? value to assign if true : value to assign if false
using terenary operator:
boolean isHappy = true;
String mood = (isHappy == true)?"I'm Happy!":"I'm Sad!";
using if-else:
if(isHappy) {
mood="I'm Happy";
}
else {
mood = "I'm, Sad!";
}
this is conditional or ternary operator in java
( a ) ? b : c;
if a is true b will be executed or run
if a is false c will be executed or run
It's the ternary operator . It's good in sets, and a shortcut for iteration
java ternary operator
Here's an easy ex.:
boolean isObese = true;
String mood = (isObese == true)?"I need to quit fast-food!":"I'm healthy!";
..source
It's called ternary operator, it can be allocated to a variable and it is equivalent of an if-then-else statement.
Have a look at this tutorial and pay attention on something that hasn't been underlined enough by the other answers: the fact that the ternary operator is an expression that can be allocated to a variable or can be returned directly by a method. It has a functional feel into it.
I'd like to know some cases in Java (or more generally:
in programming) when it is preferred in boolean expressions to use the unconditional AND (&) instead of the conditional version (&&).
I know how they work, but I cannot think about a case when use the single & is worth it.
I have found cases in real life where both sides of the expression were really cheap, so it shaved off a nanosecond or two to avoid the branch and to use the unconditional & instead of &&. (These were extremely high-performance math utilities, though; I would almost never use this in other code, and I wouldn't have done it anyway without exhaustive benchmarking to prove it was better.)
(To give specific examples, x > 0 is going to be super cheap and side-effect-free. Why bother risking a branch misprediction to avoid a test that's going to be so cheap anyway? Sure, since it's a boolean the end result is going to be used in a branch anyway, but if (x >= 0 && x <= 10) involves two branches, and if (x >= 0 & x <= 10) involves only one.)
The only difference is that && and || stop the evaluation as soon as it is known. So for example:
if (a != null && a.get() != null)
works well with &&, but with & you could get a NullPointerException if a is null.
The only case I can think about where you want to use & is if the second operand has a side effect, for example (probably not the best example but you get the point):
public static void main(String[] args) {
int i = 1;
if (i == 0 & ++i != 2) {
}
System.out.println(i); //2
i = 1;
if (i == 0 && ++i != 2) {
}
System.out.println(i); //1
}
However, this looks like smelly code to me (in both cases).
The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.
A single & will run both sides regardless.
So, as a contrived example, you might have:
if (account.isAllowed() & logAccountAndCheckFlag(account))
// Do something
In that example, you might always want to log the fact that the owner of the account attempted to do something.
I don't think I have ever used a single & in commercial programming though.
Wikipedia has nicely described the Short Circuit Evaluation
Where do you prefer non short-circuit operators ?
From the same link:
Untested second condition leads to unperformed side effect
Code efficiency
Short-circuiting can lead to errors in branch prediction on modern
processors, and dramatically reduce performance (a notable example is
highly optimized ray with axis aligned box intersection code in ray
tracing)[clarification needed]. Some compilers can detect such cases
and emit faster code, but it is not always possible due to possible
violations of the C standard. Highly optimized code should use other
ways for doing this (like manual usage of assembly code)
If there are side effects that must happen, but that's a little ugly.
The bitwise AND (&) is mostly useful for just that - bitwise math.
Input validation is one possible case. You typically want to report all the errors in a form to the user in a single pass instead of stopping after the first one and forcing them to click submit repeatedly and only get a single error each time:
public boolean validateField(string userInput, string paramName) {
bool valid;
//do validation
if (valid) {
//updates UI to remove error indicator (if present)
reportValid(paramName);
} else {
//updates UI to indicate a problem (color change, error icon, etc)
reportInvalid(paramName);
}
}
public boolean validateAllInput(...) {
boolean valid = true;
valid = valid & validateField(userInput1, paramName1);
valid = valid & validateField(userInput2, paramName2);
valid = valid & validateField(userInput3, paramName3);
valid = valid & validateField(userInput4, paramName4);
valid = valid & validateField(userInput5, paramName5);
return valid;
}
public void onSubmit() {
if (validateAllInput(...)) {
//go to next page of wizard, update database, etc
processUserInput(userInput1, userInput2, ... );
}
}
public void onInput1Changed() {
validateField(input1.Text, paramName1);
}
public void onInput2Changed() {
validateField(input2.Text, paramName2);
}
...
Granted, you could trivially avoid the need for short circuit evaluation in validateAllInput() by refactoring the if (valid) { reportValid() ... logic outside of validateField(); but then you'd need to call the extracted code every time validateField() was called; at a minimum adding 10 extra lines for method calls. As always it's a case of which tradeoff's work best for you.
If the expression are trivial, you may get a micro-optimisation by using & or | in that you are preventing a branch. ie.
if(a && b) { }
if(!(a || b)) { }
is the same as
if (a) if (b) { }
if (!a) if (!b) { }
which has two places a branch can occur.
However using an unconditional & or |, there can be only one branch.
Whetehr this helps or not is highly dependant on what the code is doing.
If you use this, I sugegst commenting it to make it very clear why it has been done.
There isn't any specific use of single & but you can consider the following situation.
if (x > 0 & someMethod(...))
{
// code...
}
Consider that someMethod() is doing some operation which will modify instance variables or do something which will impact behavior later in processing.
So in this case if you use && operator and the first condition fails it will never go in someMethod(). In this case single & operator will suffice.
Because & is a bit-wise operator, you can do up to 32-checks in a single operation concurrently. This can become a significant speed gain for this very specific use cases. If you need to check a large number of conditions, and do it often and the cost of boxing/unboxing the conditions are amortized by the number of checks, or if you store your data on-disk and on-RAM in that format (it is more space efficient to store 32 conditions in a single bitmask), the & operator can give a huge speed benefit over a series of 32 individual &&. For example if you want to select all units that can move, is an infantry, has weapon upgrade, and is controlled by player 3, you can do:
int MASK = CAN_MOVE | INFANTRY | CAN_ATTACK | HAS_WEAPON_UPGRADE | PLAYER_3;
for (Unit u in allunits) {
if (u.mask & MASK == MASK) {
...;
}
}
See my other answers on a related question for more on the topic.
The only benefit I can think of is when you need to invoke a method or execute a code, no matter the first expression is evaluated to true or false:
public boolean update()
{
// do whatever you want here
return true;
}
// ...
if(x == y & update()){ /* ... */}
Although you can do this without &:
if(x == y){/* ... */}
update();
Short-circuiting can lead to errors in branch prediction on modern processors, and dramatically reduce performance (a notable example is highly optimized ray with axis aligned box intersection code in ray tracing)[clarification needed].
This question already has answers here:
Which "if" construct is faster - statement or ternary operator?
(6 answers)
Closed 6 years ago.
I am prone to "if-conditional syndrome" which means I tend to use if conditions all the time. I rarely ever use the ternary operator. For instance:
//I like to do this:
int a;
if (i == 0)
{
a = 10;
}
else
{
a = 5;
}
//When I could do this:
int a = (i == 0) ? 10:5;
Does it matter which I use? Which is faster? Are there any notable performance differences? Is it a better practice to use the shortest code whenever possible?
Does it matter which I use?
Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.
Which is faster?
Neither.
Is it a better practice to use the shortest code whenever possible?
Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).
If there's any performance difference (which I doubt), it will be negligible. Concentrate on writing the simplest, most readable code you can.
Having said that, try to get over your aversion of the conditional operator - while it's certainly possible to overuse it, it can be really useful in some cases. In the specific example you gave, I'd definitely use the conditional operator.
Ternary Operator example:
int a = (i == 0) ? 10 : 5;
You can't do assignment with if/else like this:
// invalid:
int a = if (i == 0) 10; else 5;
This is a good reason to use the ternary operator. If you don't have an assignment:
(i == 0) ? foo () : bar ();
an if/else isn't that much more code:
if (i == 0) foo (); else bar ();
In performance critical cases: measure it. Measure it with the target machine, the target JVM, with typical data, if there is a bottleneck. Else go for readability.
Embedded in context, the short form is sometimes very handy:
System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ());
Yes, it matters, but not because of code execution performance.
Faster (performant) coding is more relevant for looping and object instantiation than simple syntax constructs. The compiler should handle optimization (it's all gonna be about the same binary!) so your goal should be efficiency for You-From-The-Future (humans are always the bottleneck in software).
The answer citing 9 lines versus one can be misleading: fewer lines of code does not always equal better.
Ternary operators can be a more concise way in limited situations (your example is a good one).
BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!
Also consider future maintainability, if-else is much easier to extend or modify:
int a;
if ( i != 0 && k == 7 ){
a = 10;
logger.debug( "debug message here" );
}else
a = 3;
logger.debug( "other debug message here" );
}
int a = (i != 0 && k== 7 ) ? 10 : 3; // density without logging nor ability to use breakpoints
p.s. very complete StackOverflow answer at To ternary or not to ternary?
Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.
Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null is supplied for a parameter value.
For example:
public void myMethod(int par1, String optionalPar2) {
String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}
In the above example, passing null as the String parameter value gets you a default string value instead of a NullPointerException. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Moreover, this pattern enables you to make the String parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:
public void myMethod(int par1) {
return myMethod(par1, null);
}
It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.
In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.
For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:
if (i == 0)
{
a = 10;
b = 6;
c = 3;
}
else
{
a = 5;
b = 4;
d = 1;
}
a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6 : 4;
c = (i == 0) ? 3 : 9;
d = (i == 0) ? 12 : 1;
I prefer the latter so that you know you haven't missed an assignment.
Try to use switch case statement but normally it's not the performance bottleneck.
Is it bad to write:
if (b == false) //...
while (b != true) //...
Is it always better to instead write:
if (!b) //...
while (!b) //...
Presumably there is no difference in performance (or is there?), but how do you weigh the explicitness, the conciseness, the clarity, the readability, etc between the two?
Update
To limit the subjectivity, I'd also appreciate any quotes from authoritative coding style guidelines over which is always preferable or which to use when.
Note: the variable name b is just used as an example, ala foo and bar.
It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) over if (b) or even worse if (flag).
As to the performance concern, the compiler optimizes it away at any way.
As to the authoritative sources, I can't find something explicitly in the Java Code Conventions as originally written by Sun, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.
You should not use the first style. I have seen people use:
if ( b == true )
if ( b == false )
I personally find it hard to read but it is passable. However, a big problem I have with that style is that it leads to the incredibly counter-intuitive examples you showed:
if ( b != true )
if ( b != false )
That takes more effort on the part of the reader to determine the authors intent. Personally, I find including an explicit comparison to true or false to be redundant and thus harder to read, but that's me.
This is strongly a matter of taste.
Personally I've found that if (!a) { is a lot less readable (EDIT: to me) than if (a == false) { and hence more error prone when maintaining the code later, and I've converted to use the latter form.
Basically I dislike the choice of symbols for logic operations instead of words (C versus Pascal), because to me a = 10 and not b = 20 reads easier than a == 10 && !(b==20), but that is the way it is in Java.
Anybody who puts the "== false" approach down in favour of "!" clearly never had stared at code for too long and missed that exclamation mark. Yes you can get code-blind.
The overriding reason why you shouldn't use the first style is because both of these are valid:
if (b = false) //...
while (b = true) //...
That is, if you accidentally leave out one character, you create an assignment instead of a comparison. An assignment expression evaluates to the value that was assigned, so the first statement above assigns the value false to b and evaluates to false. The second assigns true to b, so it always evaluates to true, no matter what you do with b inside the loop.
I've never seen the former except in code written by beginners; it's always the latter, and I don't think anyone is really confused by it. On the other hand, I think
int x;
...
if(x) //...
vs
if(x != 0) //...
is much more debatable, and in that case I do prefer the second
IMHO, I think if you just make the bool variable names prepended with "Is", it will be self evident and more meaningful and then, you can remove the explicit comparison with true or false
Example:
isEdited // use IsEdited in case of property names
isAuthorized // use IsAuthorized in case of property names
etc
I prefer the first, because it's clearer. The machine can read either equally well, but I try to write code for other people to read, not just the machine.
In my opinion it is simply annoying. Not something I would cause a ruckus over though.
The normal guideline is to never test against boolean. Some argue that the additional verbosity adds to clarity. The added code may help some people, but every reader will need to read more code.
This morning, I have lost 1/2 hour to find a bug. The code was
if ( !strcmp(runway_in_use,"CLOSED") == IPAS_FALSE)
printf(" ACTIVE FALSE \n"); else
printf(" ACTIVE TRUE \n");
If it was coded with normal convention, I would have seen a lot faster that it was wrong:
if (strcmp(runway_in_use, "CLOSED"))
printf(" ACTIVE FALSE \n"); else
printf(" ACTIVE TRUE \n");
I prefer the long approach, but I compare using == instead of != 99% of time.
I know this question is about Java, but I often switch between languages, and in C#, for instance, comparing with (for isntance) == false can help when dealing with nullable bool types. So I got this habbit of comparing with true or false but using the == operator.
I do these:
if(isSomething == false) or if(isSomething == true)
but I hate these:
if(isSomething != false) or if(isSomething != true)
for obvious readability reasons!
As long as you keep your code readable, it will not matter.
Personally, I would refactor the code so I am not using a negative test. for example.
if (b == false) {
// false
} else {
// true
}
or
boolean b = false;
while(b == false) {
if (condition)
b = true;
}
IMHO, In 90% of cases, code can be refactored so the negative test is not required.
This is my first answer on StackOverflow so be nice...
Recently while refactoring I noticed that 2 blocks of code had almost the exact same code but one used had
for (Alert alert : alerts) {
Long currentId = alert.getUserId();
if (vipList.contains(currentId)) {
customersToNotify.add(alert);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
and the other had
for (Alert alert : alerts) {
Long currentId = alert.getUserId();
if (!vipList.contains(currentId)) {
customersToNotify.add(alert);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
so in this case it made sense to create a method which worked for both conditions like this using boolean == condition to flip the meaning
private void appendCustomersToNotify(List<Alert> alerts
List<Alert> customersToNotify, List<Long> vipList, boolean vip){
for (Alert alert : alerts) {
Long currentId = alertItem.getUserId();
if (vip == vipList.contains(currentId)) {
customersToNotify.add(alertItem);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
}
I would say it is bad.
while (!b) {
// do something
}
reads much better than
while (b != true) {
// do something
}
One of the reasons the first one (b==false) is frowned upon is that beginners often do not realize that the second alternative (!b) is possible at all. So using the first form may point at a misconception with boolean expressions and boolean variables. This way, using the second form has become some kind of a sjiboleth: when someone writes this, he/she probably understands what's going on.
I believe that this has caused the difference to be considered more important than it really is.
While both are valid, to me the first feels like a type error.
To me b == false looks as wrong as (i == 0) == false. It is like: huh?
Booleans are not an enum with 2 possible values. You don't compare them. Boolean are predicates and represent some truth. They have specific operators like &, |, ^, !.
To reverse the truth of an expression use the operator '!', pronounch it as "not".
With proper naming, it becomes natural: !isEmpty reads "not is empty", quite readable to me.
While isEmpty == false reads something like "it is false that it is empty", which I need more time to process.
I won't go into all of the details at length because many people have already answered correctly.
Functionality-wise, it gives the same result.
As far as styling goes, it's a matter of preference, but I do believe !condition to be more readable.
For the performance argument, I have seen many say that it makes no difference, but they have nothing to justify their claims. Let's go just a bit deeper into that one. So what happens when you compare them?
First, logically:
if(condition == false)
In this case, if is comparing its desired value to execute with the value between the parentheses, which has to be computed.
if(!condition)
In this case, if is directly compared to the opposite(NOT) of the condition. So instead of 2 comparisons, it is one comparison and 1 NOT operation, which is faster.
I wouldn't just say this without having tested it of course. Here is a quick screenshot of the test I did. !condition is nearly twice as fast over 10 million iterations.
https://imgur.com/a/jrPVKMw
EDIT: I tested this in C#, compiled with visual studio. Some compilers may be smarter and optimize it properly, which would make the performance the same.