Correct way to use multiple conditions in If statement? - java

In my code I want to check if the status of a Dog object is not that of 3 Enums:
if((dogList.get(i).getStatus()!= dogStatus.SLEEPING
|| dogList.get(i).getStatus()!= dogStatus.WALKING
||dogList.get(i).getStatus()!= dogStatus.EATING )){
//do something
}
Is this the correct way to combine the 3 || conditions? I ask as my program is not behaving as I expect.

You want
if (status != SLEEPING && status != WALKING...)
Note the '&&', since you want to check it's not WALKING and it's not SLEEPING and so on

The direct answer to your question is that you should use && not ||, as explained well in this answer. However, since you are using an enum, you can tidy this up by using switch.
switch (dogList.get(i).getStatus()) {
case SLEEPING:case EATING:case WALKING:
break;
default:
// write your code here.
}
(Technically this is not exactly the same as your (corrected) version as that executes the code if the result is null, whereas switch throws a NullPointerException).

Related

Java - How to ensure correct command line args are entered using try catch?

Sorry that I am a noob...
I have a method which takes two specific command line arguments to create an object:
Number data = new Number(arg[0], arg[1]);
The acceptable arguments are:
arg[0] can only be: 10, 20 or 30.
arg[1] can only be: 2, 4 or 6.
How do I create a try and catch exception which ensures that two arguments have been provided and that the arguments are acceptable?
Thank you for your time in advance.
You definitely do not control the flow using try-catch - it's bad practice. For this reason, there is if-else statement.
boolean conditionArg0 = arg[0] == 10 || arg[0] == 20 || arg[0] == 30;
boolean conditionArg1 = arg[1] == 2 || arg[1] == 4 || arg[1] == 6;
if (conditionArg0 && conditionArg1) {
// input is fine, go on
} else {
// display error
}
You should check first if the array arg has at least 2 values, otherwise, the NullPointerException will be thrown.
In case of more allowed values is better to use Set<Integer> and search if the value is present. If the allowed values follow a pattern (ex. divisible by 10), then it's better to use the calculation instead of the Set.
Edit: Why is controlling the flow using try-catch considered a bad practice? It has been discussed many times here and here. There are a lot of arguments and I find the most important that (took from here):
Exceptions are for exceptional situations, not for normal flow control. One should use exception handling for handling unanticipated/exceptional situations, not as normal program flow, because otherwise, an uncaught exception will tell you much less.
Semantically, the use of if-else is a clean way to control the flow. You should always start with if-else and refactor in case the number of compared elements increase significantly.
Based on the comments,
First check if the length of the inputs is exactly 2.
Check for equality.
Code:
if(arg!=null && arg.length==2){
if( (arg[0].equals("10") || arg[0].equals("20") || arg[0].equals("30"))
&& (arg[1].equals("2") || arg[1].equals("4") || arg[1].equals("6")) ) {
Number data = new Number(arg[0], arg[1]);
}
else{
//Handle wrong input(s)
}
}
else{
//Handle wrong input(s)
}
By creating your custom exception class but it is not good idea. using if else is easy and good

What is the best way to exit loop in Java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What is the best way to end a loop in Java?
This:
boolean exit = false;
while((a < 5) && (exit = false)){
if(a == 3)
exit = true;
else
a++;
}
Or this:
while((a < 5){
if(a == 3)
break;
else
a++;
}
Some people may find that break are harder to debug (personally, I prefer using flag) but it is principally a matter of opinion.
Imagine a loop body which contains over 500 lines of code, with some break statements located everywhere, it may be harder for you to visualise all the possibilities of exiting the loop.
Another reason of why I like using a flag is that you can give a signifiant name to the ending point instead of simply break.
Note that you can also use a flag in a for loop example :
boolean flag = false;
for(int i = 0; !flag && i < 10; i++) {
// some treatment
}
It may be interesting however, to know that when dealing with loop, there is the continue keyword which allow you to not exit the loop, but skip directly to the next iteration.
What is the best way to finish a loop in Java?
If there was really a best way between both, Java would probably not allow the other ;)
I guess the most important is to use the same convention as your co-worker so the code does not differ from class to class.
break exist for a reason, right!
while(a < 5){
if(a == 3)
break;
else
a++;
}
Very simple answer, go for the break, less flags, less to debug, easier to maintain. It is simple to change from a while to for loop without any modifications in the logic. Think of a scenario where you would need to add more conditions...
My opinion is if you don't understand the usage of break and continue then you might go for the flag all the time. But there is not only one answer. Your question is what option is better for exit the loop and from your two examples the option is simple. My opinion is the break one.
Now some will use the flag, and some the break, and they give code samples for which will fit better. But this is not your question!
I can give you lots of examples, where some I would go for the flag and other for the break and some a mix of both. It depends on what my loop is about to handle.
break is to mark that if we reach this condition, we will go out of the loop emiditely. Which is very important in some loop logic.
Even though when you/co-worker add more logic, before or after that condition, still the loop will exit where it reaches the break.
Sometimes you maybe want to flag that you reached a condition but want still to go thru all the instructions the loop covers, and here does a bool help you to stop the loop but after it went thru all the logic.
If you don't use flag/break in a right way your system can act very strange, specially when adding new logic.
Remember that you also can use break and continue with a label, which is not so common but good to know.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
The first snippet is syntactically wrong - = is the assignment operator. You were looking for the equality operator, ==:
while ((a < 5) && (exit == false)) {
Or better yet, since exit is a boolean, just evaluate it directly:
while (a < 5 && !exit) {
Other than that, you should always strive to follow the convention of the project you're working on. If it's coding styles prefers breaks - just use them. If it prohibits them, don't.
Once you throw project guideline considerations out the window, it's completely a matter of preference. Personally, I tend to prefer the break statement, especially if I have several conditions to evaluate. E.g.:
while (a < 5) {
// do stuff
if (a == 3) {
break;
}
// do more stuff
if (b >= 19) {
break;
}
// etc...
}
But ultimately, you should evaluate it on a case-to-case basis. Preferring breaks, like I do, doesn't mean you should blindly always use them. Choose whatever makes the code look better and easier to maintain.
I depends on what you mean by "best" ? With the break, you exit the loop early, so that is more efficient.
I would prefer the first, cause goto is considered harmful. And an exit is like a goto. But more important: Please always use {} when writing a if clause.
Also, when using a condition, give it a name. It is almost simpler to understand ageBelow18 instead of today.getYear() < customer.getBirthday().getYear(); (the code is not correct, I know).
Both those options you have presented aren't as good as two alternatives.
Seeing as you directly exit the loop after a simple comparison then the best option is:
while (a < 5 && a != 3) {
a++;
}
This is because you need to check both conditions before executing the body, and you don't need to do anything special when exiting the loop.
However, if you need to do need a bit of special logic when a certain condition is hit then you should use a while true loop and breaks.
while (true) {
if (a >= 5) {
break; // nothing special, just exit
} else if (a == 3) {
a *= 2; // double a before exiting loop
break;
}
a++;
}
The while (true) shows that the only way to exit the loop is with a break, so the programmer should keep an eye out for them. The breaks should also be grouped together at the top of the loop body, so they act as guards preventing the loop body from being executed if their condition is hit.
I would choose the break statement since:
Code is more clean
No need for extra code declarations
Debug the code is easier
It's common to mess with a lot of flags declared on the condition. You will not want to get a lot of nested conditions on the same line.
There is also exist the continue keyword that will let you to skip parts of the code if necessary.

if(x!=y) vs if(x==y)

I have run the PMD plugin in Eclipse against my code and I'm getting a high priority warning for code similar to the one shown below:
if(singleRequest !=null){
// do my work
}else{
// do my other work
}
PMD says `Avoid if (x != y) ..; else ..;
And the description of the error looks like this:
In an "if" expression with an "else" clause, avoid negation in
the test. For example, rephrase:
if (x != y) diff(); else same();
as:
if (x == y) same(); else diff();
Most "if (x != y)" cases without an "else" are often return
but I still can't understand the impact on my code. If someone could guide me with an example, I would appreciate it.
A number of PMD rules are more style opinions than correctness alerts. If you don't agree with this rule or the rule doesn't match your project's coding standards, you could consider suppressing warnings or even configuring PMD to enforce only the rules you like
PMD is a tool. PMD works based on heuristics. Someone decided upon this heuristic; that negative conditionals with else statements are not "good style".
However, in this case, as I have argued in my comments, the code posted is how I would write it. (In particular with x != null, but not exclusively to this construct.)
This is because I don't look at the conditional (excepting as it can be simplified; e.g. removing double-negatives as shown by Jim Kin) but rather I look at the logic of the branches or "flow".
That is, I place the positive branch first. In this case I contend that
if (x != null) {
doValid // positive branch
} else {
doFallback
}
is semantically equivalent to
if (isValid(x)) { // it looks like a "positive conditional" now
doValid // still positive branch
} else {
doFallback
}
and is thus positive branch first.
Of course, not all situations have such a "clear" positive flow, and some expressions might be expressed much easier in a negative manner. In these cases I will "invert" the branches - similar to what PMD is suggesting - usually with a comment stating the action at the top of the block if the positive branch/flow was reversed.
Another factor that may influence the conditional choice used is "immediate scope exiting" branches like:
if (x == null) {
// return, break, or
throw new Exception("oops!");
} else {
// But in this case, the else is silly
// and should be removed for clarity (IMOHO) which,
// if done, avoids the PMD warning entirely
}
This is how I consistently (a few occasional exceptions aside) write my code: if (x != null) { .. }. Use the tools available; and make them work for you. See Steven's answer for how PMD can be configured to a more suitable "taste" here.
It's a readability issue. Consider
if ( x != y )
{
}
else // "if x doesn't not equal y"
{
}
vs.
if ( x == y )
{
}
else // "if x doesn't equal y"
{
}
The latter example is more immediately identifiable. Mind you, I see nothing wrong with using negatives... it can make a lot more sense, consider
if ( x != null )...
The only reason I would avoid using the negative-case is if it resulted in double-negatives, which might be confusing.
e.g.
if (!checkbox.disabled) {
// checkbox is enabled
}
else {
// checkbox is disabled
}
Who reads your code? You do. The compiler does. Or maybe the assistant of the lecturer. A co-worker, who can't make difference between == and != ? Hope not.
I can only think negatives being bad in complex expressions. (Context being: at least for me. I know I've frustrated in debugging in my head while(!expr && !expr2 || expr3) { })
ch=getch(); if (ch!='a') is a pattern that is easily extended to
if (ch!='a' || ch!='b') which is always true, while sounding semantically correct.
From performance standpoint, it's best to sort the probabilities.
if (more_probable) {
....
unconditional_jump_to_end_of_block;
} else {
...
}
This choice should lead to better performance, as the there is no mis-prediction penalty in the more probable branch.
if (p && p->next) evaluated from performance standpoint gives poor results.
You have to avoid having "not equals" in the if condition. This is because when someone else looks at your code, there is a real possibility that the person might ignore the != and might jump to wrong conclusion about the logic of your program.
For your case, you may have to interchange the if logic with else logic and change != to ==
It's a balancing case of code readability vs. code organization. The warning is basically suggesting that it's confusing for people reading the code to navigate the negation of a negative.
My personal rule of thumb is, whatever you expect to be the "normal" case is what you should test for in the if. Consider:
if (x != y) {
// do work here...
} else {
throw new IllegalArgumentException();
}
In this situation I'd say that the important work is being done in the x != y case, so that's what you should test for. This is because I like to organize code so that the important work comes first, followed by handling for exceptional cases.
It's because "good style" says that if possible tests should be "positive", so:
if (singleRequest == null){
// do my other work
} else {
// do my work
}
Is easier to read because the test is "positive" (ie "equals" not "not equals"), and ultimately better readability leads to less bugs.
Edited
This is particularly the case with test like:
if (!str.equals("foo")) {
you can easily miss the ! at the front, but if you make the test positive, it's a lot cleaner.
The only time you should have a negative test is when there's no else block - then a negative test is unavoidable unless you have an empty true block, which itself is considered a style problem.
Not really an answer, but you can minimise the overall complexity and improve readability by returning or failing early and then continuing without indentation:
if (something == null) {
throw new IllegalArgumentException("something must not be null");
}
// continue here

Condition that is true and false at the same time in C or Java [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What's the “condition” in C interview question?
Can something like this be done?
Code:
if(condition) {
printf("Hello")
} else {
printf("World");
}
Result: Hello World
What should be the condition to be used to make that possible ?
Please help. Thanks in advance.
No.
The else statement will only execute if the if didn't.
You can cheat to get this result in C:
#include <stdio.h>
#define else printf(" ");
int main()
{
int condition = 1;
if(condition) {
printf("Hello");
}
else {
printf("World");
}
}
Output:
Hello World
The only idea that comes into my mind is something like
if (printf("Hello") > 0)
printf("");
else
printf(" world");
but it's not the same thing, you can't execute both branches of an if/else: one of two is chosen.
The instructor is expecting you to fill in fork() as the condition. This is not general C code but Unix/POSIX code, and works by splitting the process into a parent process and child process. fork returns the child process id (a nonzero number, thus true) in the parent and 0 (false) in the child.
Another potential way to solve the problem, if you can add code elsewhere, is to write setjmp(jmp_buf) as the condition, and add a longjmp(jmp_buf, 1); after the conditional. However this seems to break the rules of the problem.
if/elses are either/ors. Either the if portion is executed or the else, but never both.
No, the statement is if ... else, not if ... and then also maybe. The condition is evaluated once, and the branch is chosen.
Its insane, but:
int test = 0;
String s = "";
switch (test) {
case 0: s += "Hello";
default: s += "World";
}
System.out.println(s);
Boolean type variables in both languages do not allow what you want to do. The whole point is that they must be one or the other.
To accomplish what you want, you probably need a custom type.
//This type allows for quantum weirdness
public class NotABool{
public boolean isTrue = false;
public boolean isFalse = false;
//Funky setMethod
void set(boolean value){
//...
}
}
NotABool nab = new NotABool();
if (NotABool.isTrue){
//Print "Hello"
}
if (NotABool.isFalse){
//Print "World"
}
Can you clarify what you're trying to accomplish?
The functionality you are describing looks more like the switch structures.
In Java, you can only switch on int and enum types, but in C, you can switch on string as well as int types.
It would look like so:
int i = 0;
switch (i) {
case 0:
System.out.print("Hello ");
case 1:
System.out.print("World!");
break;
}
The resulting output would be "Hello World!"
When i is 0, it matches the first case and executes the code until the next break; statement is found. If i was 1, it would only print out "World!".
In general, no, it's not possible. The way the if/else is translated to Java bytecode (and in either case, to machine code), one process will run exactly one of the two branches of the statement. If we didn't have if/else, we'd end up using goto to synthesize it, and that would look a lot like this:
if (condition) goto if_block;
else_block:
printf("World");
goto after_ifelse;
if_block:
printf("Hello");
after_ifelse:
As you can see, if the condition's true (even if it could somehow also be false!), the process will follow the 'if' branch and skip past the other. There's no way to get around this in a single process; any way would require changing the code of the program, or broken hardware (particularly RAM or CPU), or enough radiation to kill you. And every compiler and environment i know of treats if/else that way, though it's common to have the else case after the if (and invert the condition), which makes the (quite valid) assumption that any boolean condition that's not true is false.
Now with all that said...in C, it's semi possible, but not in the way you're thinking -- and not on every OS. On *nix systems, there's a system call usually called fork(), which allows one process to become two (thereby sidestepping the "one process will run exactly one branch" limitation).
if (fork())
printf("Hello");
else
printf("World");
But (1) this code has an inherent race condition -- both branches are now set to run, but either one could run before the other. You'd need to wait on the child process. And (2) this isn't a "condition", it's a function call. If you're not allowed to add code, then this should not be available as an answer.
Or you could do some evil macro stuff to translate the else into something else entirely. But anyone reading your code later would want to hunt you down and confiscate your keyboard, and that's if they're nice.

Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

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.

Categories

Resources