OR and AND functions in java? - java

What are the OR and AND operators in Java? I've tried or, system.or, and all sorts of stuff, but haven't found anything.

Well let me break it up for you..........
Short Circuit And & Or operator:
AND Gate : &&
OR Gate : ||
Non-Short Circuit And & Or operator:
AND Gate : &
OR Gate : |
Difference between Short and Non-Short Circuit Operator:
if (false && true) // As the 1st statement is false it won't evaluate the 2nd condition
if (false & true) //Even though the 1st statement is false, it will still evaluate the 2nd condition

Um, what do you mean by "logic gates"? Do you mean || and &&?

|| is what you use for OR.
&& is what you use for AND.

Check Summary of Operators # Oracle
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

and is && and or is ||
See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Are you looking for || which is OR and && which is AND operators?

Or -> ||
And -> &&
As an example
if a == 1 and b == 2 -> if (a == 1 && b == 2)

there have to import logicgate.*
is should able to let the program use AND , OR , and NOT gate (not sure for others)
example :
create variable using AND class and 2 extra variable for process
And and = new And();
int no1 = 10 , no2 = 20;
next, do the process using AND gate logic
int answer = and.doOperation(no1,no2);
same workflow using others logic gates

Related

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.

need explanation on past paper, & Operator [duplicate]

This question already has answers here:
What is the difference between & and && in Java?
(15 answers)
Closed 9 years ago.
I'm doing past paper for exam
public static void triangleTest( int a, int b, int c)
{
if ( a > 0 & b > 0 & c > 0 )
{
if ( a==b || b==c );
{
System.out.println("Equilateral");
}
else if ( a==b || a==c || b!=c )
System.out.println("Scalene");
}
else if ( a+b>c && a+c>b || b+c>a );
{
System.out.println(Isoceles);
}
}
else
{
System.out.println("");
}
}
I have been given this code and told to find mistakes, and when i checked the answers
if ( a > 0 & b > 0 & c > 0 )
this has been identified as mistake and && were meant to be used instead of & I ran the code and it worked fine with &, so my question would be what's what's the reasoning behind this?
& evaluates both values
where as && checks the first one if it's false it sets result as false.
If you are using & it will check second condition although first is false.
While in && it will not check next condition if first is false.
In some case it may cause exceptions.
For ex:
// Some Code
if ( a != null & a.length() > 0 ){
//coding part
}
above code will throw NullPointerException with & if a is null. because it will check second condition every time either first is true or false.
so it will go like this...
// Some Code
if ( a !=null && a.length() > 0 ){
//coding part
}
For more : refer this SO Que
& is a bitwise operator whereas && is a logical and operator.
Principles of short circuit does not apply in bitwise and operator i.e &.
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
Short circuiting leads to efficient code
&& is the logical and and it is short circuited. & is the bitwise and. Although for other cases it is very different; for booleans the (practical) difference is just that it doesn't short circuit.
Short circuiting means it skips evaluating conditions that can't affect the outcome. For exampple
if(cheapTest() && expensiveTest() && expensiveTest2())
If the first test is false the expresion must be false, so it can not bother with the expensive tests.
if(FALSE && DONTCARE && DONTCARE)
The reverse is true for | vs ||.
Protection against exceptions
This can be even more important where the second test may raise exceptions if evaluated, for example
if (someObject!=null && someObject.someTest())
In this case if someObject is null then someObject.someTest() never runs, this is a common pattern when null values are expected. Where you to use the bitwise and both tests would run in all cases and if someObject was null you would recieve a NullPointerException

How to use 'or' in 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")){

What does "?" and ":" do in boolean statements? [duplicate]

This question already has answers here:
java ternary operator
(2 answers)
Closed 9 years ago.
I think this question is a general programming question,
but let's assume I'm asking this for Java.
what does the following statement do ?
return a ? (b || c) : (b && c);
I have seen the syntax with ?'s and :'s in many topics at SO, this particular one I found in Check if at least two out of three booleans are true
But I don't know what they mean, so how to use them, and I believe it's something very useful for me.
Thanks !
That's the conditional operator. It means something like:
condition ? value-if-true : value-if-false;
So in your case, it returns b || c if a is true, and b && c if a is false.
This is known as a ternary statement; it's shorthand for an if-else block - you can google that for more info.
Your example is equivalent to
if (a) {
return (b || c);
} else {
return (b && c);
}
condition ? first statement : second statement
if condition is true then first statement is executed otherwise the second statement
It's the ternary operator, the whole statement expands to something more like this:
if a == true then
if b == true or c == true then
return true
else
if b == true and c == true then
return true
As your link says a much more elegant way to check if at least 2 out of three booleans are true when applied in this way!
its an conditional operator... jst like if and else....
e.g----
a<b ? 4 :5 where a= 2 and b=5
as a is less then b.... then this operator will return 4... else it return 5....
in short... if your condition i.e statement before ? is correct then it returns 1st value.. i.e statement before colon.... else it returns 2nd value......
According to your code,
return a ? (b || c) : (b && c);
Result will be like this :
if a == true , then result = b || c
otherwise result = b && c
its a ternary operator & used in most of the languages C,C++, java, Javascript

Categories