How to use 'or' in Java? - java

I'm quite new to Java, and can't figure out how to use 'or'. What is the Java equivalent?
I've already tried && and || but eclipse does not recognise it.
This is part of my code:
if (action.equals ("run") || ("sprint")) {
System.out.println("you ran");
}
else {
System.out.println("else");
}

I've already tried && and || but eclipse does not recognise it.
That's very strange, but just to cover the basics: Let's assume you have the variable a and it contains the value 5. Then:
if (a == 5 || a == 7)
...will be true, because the first part of the expression (a == 5) is true. So the statement "a equals 5 or a equals 7" is true.
The || operator can only be used, in Java, where a boolean (true or false) expression is expected, such as in an if statement like the above. So pretty much in an if or a conditional operator (that ?...: thing, sometimes called the ternary operator).
Re your edit, the problem is that both sides of your || operator aren't true or false ("boolean") expressions. Your statement:
if (action.equals ("run") || ("sprint")){
breaks down like this:
if (
action.equals ("run")
|| // ("or")
("sprint")
)
the second part of that isn't a true/false, it's a string. The correct way to express that in Java (or nearly any other programming language) is:
if (action.equals ("run") || action.equals ("sprint")){
Now both sides of the || result in true/false exprssions:
if (
action.equals ("run")
|| // ("or")
action.equals ("sprint")
)
The reason for this is that the second part may have nothing whatsoever to do with action, and so the compiler can't assume you mean to re-use it in the second part of the expression. You might, for instance, want to use || with two completely unrelated things:
if (action.equals("run") || somethingElse.equals("run")) {

Ok. ("sprint") is not a Boolean expression. Since a if condition expects a Boolean expression your code returns an error. You should change the line with:
if (action.equals ("run") || action.equals("sprint")){

The equals method returns a boolean and the || operator wants two booleans on each side.
You're doing an action.equals("run") on one side but then a ("sprint") on the other which isn't a boolean expression.
Change your code like so:
if (action.equals("run") || action.equals("sprint")){

Related

How to put 2 condition in one statement actiolistener in java? [duplicate]

I'm a beginner in coding. I was recently working with to create a chatting programme where a user will chat with my computer. Here is a part of the code:
System.out.println("Hello, what's our name? My name is " + answer4);
String a = scanner1.nextLine();
System.out.println("Ok, Hello, " + a + ", how was your day, good or bad?");
String b = scanner2.nextLine();
**if (b.equals("good"))** { //1
System.out.println("Thank goodness");
} else **if (b.equals("it was good"))** { //2
System.out.println("Thank goodness");
} else **if (b.equals("bad"))** { //3
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
} else **if (b.equals("it was bad"))**{ //4
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
if(age<18){System.out.println("How was school?");}
else if (age>=18){System.out.println("How was work?");}
The conditions of the if statements are in Bold (surrounded with **). In case of first and the second condition I want my application to do same thing. Similarly third and fourth condition. I thought it was possible to somehow group them in if statement.
I tried with below code but it doesn't compile:
if (b.equals("good"), b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad"),(b.equals("it was bad"))) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
Can someone correct it for me?
You can use logical operators to combine your boolean expressions.
&& is a logical and (both conditions need to be true)
|| is a logical or (at least one condition needs to be true)
^ is a xor (exactly one condition needs to be true)
(== compares objects by identity)
For example:
if (firstCondition && (secondCondition || thirdCondition)) {
...
}
There are also bitwise operators:
& is a bitwise and
| is a bitwise or
^ is a xor
They are mainly used when operating with bits and bytes. However there is another difference, let's take again a look at this expression:
firstCondition && (secondCondition || thirdCondition)
If you use the logical operators and firstCondition evaluates to false then Java will not compute the second or third condition as the result of the whole logical expression is already known to be false. However if you use the bitwise operators then Java will not stop and continue computing everything:
firstCondition & (secondCondition | thirdCondition)
Here are some common symbols used in everyday language and their programming analogues:
"," usually refers to "and" in everyday language. Thus, this would translate to the AND operator, &&, in Java.
"/" usually refers to "or" in everyday language. Thus, this would translate to the OR operator, ||, in Java.
"XOR" is simply "x || y but both cannot be true at the same time". This translates to x ^ y in Java.
In your code, you probably meant to use "or" (you just used the incorrect "incorrect solution" :p), so you should use "||" in the second code block for it to become identical to the first code block.
Hope this helped :)
You're looking for the "OR" operator - which is normally represented by a double pipe: ||
if (b.equals("good") || b.equals("it was good")) {
System.out.println("Thank goodness");
} else if (b.equals("bad") || b.equals("it was bad")) {
System.out.println("Why was it bad?");
String c = scanner3.nextLine();
System.out.println("Don't worry, everything will be ok, ok?");
String d= scanner10.nextLine();
}
This is probably more answer than you need at this point. But, as several others already point out, you need the OR operator "||". There are a couple of points that nobody else has mentioned:
1) If (b.equals("good") || b.equals("it was good")) <-- If "b" is null here, you'll get a null pointer exception (NPE). If you are genuinely looking at hard-coded values, like you are here, then you can reverse the comparison. E.g.
if ("good".equals(b) || "it was good".equals(b))
The advantage of doing it this way is that the logic is precisely the same, but you'll never get an NPE, and the logic will work just how you expect.
2) Java uses "short-circuit" testing. Which in lay-terms means that Java stops testing conditions once it's sure of the result, even if all the conditions have not yet been tested. E.g.:
if((b != null) && (b.equals("good") || b.equals("it was good")))
You will not get an NPE in the code above because of short-circuit nature. If "b" is null, Java can be assured that no matter what the results of the next conditions, the answer will always be false. So it doesn't bother performing those tests.
Again, that's probably more information than you're prepared to deal with at this stage, but at some point in the near future the NPE of your test will bite you. :)
You can have two conditions if you use the double bars(||). They mean "Or". That means only ONE of your conditions has to be true for the loop to execute.
Something like this:
if(condition || otherCondition || anotherCondition) {
//code here
If you want all of conditions to be true use &&. This means that ALL conditions must be true in order for the loop to execute. if any one of them is false the loop will not execute.
Something like this:
if(condition && otherCondition && anotherCondition) {
//code here
You can also group conditions, if you want certain pairs of them to be true. something like:
if(condition || (otherCondition && anotherCondition)) {
//code here
There is a simpler way.
if (b.contains("good")) {
...
}
else if (b.contains("bad")) {
...
}

Java: Short-circuting && after OR

I understand && and || are short circuited in Java (whereas & and | are not)
However, I do not understand why the following code (which starts off with short circuited OR but ends with && condition) is also short circuited:
String x, y;
if ( x.contains("this") || x.contains("that") && y.contains("something else")!= true)
I would think that even if condition x.contains("this") evaluates to true the program will still need to evaluate the last condition y.contains("something else") != true because there's the && operator before the last condition. But apparently this isn't the case.
Can anyone explain why?
Two factors are in play here to determine the order of evaluation:
Operation precedence, and
Short-circuiting rules
Since && has higher precedence than ||, operator && "stays closer to its operands", so your expression is parsed as follows:
Because both && and || operators are left-to-right associative*, Java evaluates this expression left-to-right, stopping as soon as it determines the outcome. In case the string contains "this" substring, evaluation stops without evaluating the &&.
Note: If you are not sure of the order of operations, you can always force the order that you want by parenthesizing parts of your predicate. If the expression is not entirely obvious to you, good chances are that it is going to be non-obvious to other readers, so adding some extra parentheses is a good idea.
* Some operators are right-to-left associative. For example, assignment operator a[i] = b + c evaluates b + c before evaluating a[i]. Thanks T.J. Crowder for a great comment.
This is because of operator precedence.
The equivalent form of your (a || b && c) is (a || (b && c))
Cf. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
...even if condition x.contains("this") evaluates to true the program will still need to evaluate the last condition y.contains("something else") != true...
Nope. :-) The operands to the || in that expression are
x.contains("this")
and
x.contains("that") && y.contains("something else")!= true
...because && has higher precedence than || (details). So if you have a || b && c, it's a || (b && c) (just like a + b * c is a + (b * c) rather than (a + b) * c). The precedence defines how the operands are grouped.
If you want the expression grouped differently, you can use () to group it.
if ( (x.contains("this") || x.contains("that")) && y.contains("something else")!= true)
It has to do with operator precedence. Most standard operators are binary, that is they take two inputs and produce an output. Whenever you have an expression with more than two operators, the compiler uses precedence and associativity rules to figure out how to transform that expression into one where it's clear what inputs each operations has.
In your case, you have an expression like A || B && C. && has higher precedence than ||, so the compiler will interpret it as A || (B && C), not like (A || B) && C, which you might get at by just looking at the expression.
This means that it's enough for A to be true for the whole expression to be true.
This is the way the syntax works in java as the && operations are grouped before the || opertaion, therefore when it reads the equation (A || B && C) it only see's comparing A || D (where D is really B && C). So when A is evaluated as True, it doesn't even need to evaluate B && C.
Refer to this link for further syntax related questions on the order of operations
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
&& is an operator with a higher precedence than ||.
Operators with higher precedence are evaluated before operators with lower precedence.
So here :
if ( x.contains("this") || x.contains("that") && y.contains("something else")!= true)
These two expressions are evaluated together :
x.contains("that") && y.contains("something else")!= true
So you get a conditional statement with a form such as :
if (something || somethingElse)
something is true, so somethingElse is never evaluated.
And the whole conditional statement is true.
Java have some operator precedence. You need to understand it to work with it.
First of all
In your if statement, you have two logical operators: || and &&.You know about short circuited. But you need to know that the &&operator will run first than ||.
AND operator (&&)
The && operator will, first, verify the left condition. There's no need to check two of them, to && return true, if the first one is true, then he can check the second.
OR operator (||)
The || operator will execute right after &&. It will verify if the two conditions return false, for this reason he needs to verify both.
Parentheses
You should know, but to make it work the way you want, you need to use parentheses (). To do it in the way you need, use () to present a new rule to your if statement:
if ( (x.contains("this") || x.contains("that")) && y.contains("something else")!= true)

Java If block with multiple statements

I have a question about IF clause in Java.
I have and expression:
if ((someObject != null & connectedToTheInternet) || operate) {
// some action
}
Is my logic right: if someObject != null equals to true and connectedToTheInternet equals false then we have (someObject != null & connectedToTheInternet) equals false and then we have the following block:
if (false || operate) {
// some action
}
And if operate equals true then // some action will be triggered?
Just a first note: logical AND operator is "&&" and not just "&" (bitwise AND).
Following, your answer is YES... JVM will run conditions following your thinking.
By the way, I suggest you to read something abot short-circuit of these operators: it can be interesting if you are learning.
For example if you have if (a && (b || c) and a==false, then JVM won't evaluate b or c conditions because false && ... will be always false.
The same in the case of if (a || b || c && d): if a==true then JVM will ignore the other parts and consider it as true because true || .... will be always true.
Yes. if-clauses are evaluated from left to right. If no parenthesis are used, && has precedence, even higher precedence has ! (not) - similar to multiplication (AND), addition (OR) and negative numbers (-) in math (e.g. "A && (B || C) != A && B || C == (A && B) ||C") - I recommend to use parenthesis if you are unsure. This makes it possible to combine != null checks and calls to methods in the same if statement (e.g., if (object!=null && object.dosomething())).
Btw. there is a difference between & and && (short-circuit), when & is used, the second condition gets evaluated even if the first is false already. When && is used, Java doesn't check the second condition if the first one is false as the whole term cannot be true anymore - this is only important when the second condition is not a boolean variable but a method (which gets called or not -> side effects; this "skipping" is called short-circuit). Same for || and | where the second operator might not get evaluated if the first is already true (in case of ||).
Normally only ||and && are used.
Just for completeness: & is also the bitwise AND operator in Java.
if (false || operate) {
// some action
}
If operate true then if block executing.

Do while loop comparing Strings

I'm trying to do a "do while" loop with a nested if statement. I'm trying to compare two possible values for a String variable "word". If !word.equals "deeppan or thin" do something, else do something. But its not liking me using the or || comparator .. Any suggestions would be welcome.
do {
word = scan.next();
if ( !word.equalsIgnoreCase( "Deeppan" || "thin" ) ) {
System.out.print("Sorry you must specify a Deeppan or thin base, try again: ");
} else {
break;
}
} while ( true );
equalsIgnoreCase takes a single string argument, not a logical expression. You can combine them with || or && though:
if (!word.equalsIgnoreCase( "Deeppan") && !word.equalsIgnoreCase("thin" ))
You have to do it like this:
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin")) {
Think about the || which i switched to &&, because the if should only be true, if the value is not the first AND not the second one!
This part is wrong, that's not how you use the boolean || operator, and anyway the logic is incorrect:
if (!word.equalsIgnoreCase("Deeppan" || "thin"))
It should be like this, comparison-operator-comparison, and notice the correct way to state the comparison for the effect you want to achieve:
if (!(word.equalsIgnoreCase("Deeppan") || word.equalsIgnoreCase("thin")))
Or equivalently, using De Morgan's laws (and easier to read and understand, IMHO):
if (!word.equalsIgnoreCase("Deeppan") && !word.equalsIgnoreCase("thin"))
You have a few issues going on. First:
"Deeppan" || "thin"
is attempting to use the boolean "OR" operator to compare two strings. The "OR" operator can only compare boolean results and returns a boolean that is the result of the comparison:
System.currentTimeMillis() == 123455667 || object.equals(this) // both sides are boolean results.
true || false // returns 'false'
But let's pretend for a second that "Deeppan" || "thin" is OK (remember, it isn't) and the compiler knows that you want to compare the two strings. It still leaves the issue that the OR operator returns a boolean result (true or false), which you are then attempting to pass into the method equalsIgnoreCase on the word variable. equalsIgnoreCase takes a String argument, not a boolean. This is the second compilation issue. As has been pointed out, what you need is to check for the conditions separately and OR the result to get the final boolean
if("Deeppan".equalsIgnoreCase(word) || "thin".equalsIgnoreCase(word)) {
// do something
}
("Deeppan" || "thin")
is a boolean expression. equalisIgnoreCase takes a string. Therefore you need to make two seperate calls and OR the (boolean) results

How does Java deal with multiple conditions inside a single IF statement

Lets say I have this:
if(bool1 && bool2 && bool3) {
...
}
Now. Is Java smart enough to skip checking bool2 and bool3 if bool1 was evaluated to false? Does java even check them from left to right?
I'm asking this because i was "sorting" the conditions inside my if statements by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.
Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.
This means that the following code is completely safe:
if(p != null && p.getAge() > 10)
Also, a || b never evaluates b if a evaluates to true.
Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?
Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.
if(s != null && s.length() > 0)
or
if(s == null || s.length() == 0)
BTW if you use & and | it will always evaluate both sides of the expression.
Please look up the difference between & and && in Java (the same applies to | and ||).
& and | are just logical operators, while && and || are conditional logical operators, which in your example means that
if(bool1 && bool2 && bool3) {
will skip bool2 and bool3 if bool1 is false, and
if(bool1 & bool2 & bool3) {
will evaluate all conditions regardless of their values.
For example, given:
boolean foo() {
System.out.println("foo");
return true;
}
if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.
Yes,that is called short-circuiting.
Please take a look at this wikipedia page on short-circuiting

Categories