Reading and interpreting a logical expression in a program - java

How do you usually read logical expressions in a program? For example:
(1 == x) && ( 2 > x++)? (x=1)
What is the purpose of ? and what is the way of thinking for generating the right answer for the expression?

The following statement:
var value = (boolean expression) ? some value if `true` : some value if `false`
Is a special conditional statement which makes use of a Ternary Operator (?:) to assign values, based on the boolean expression, to the variable.
It's a much more concise way of expressing this conditional statement:
var value;
//this is the boolean expression you evaluate before the question mark
if (boolean expression is true) {
//this is what you assign after the question mark
value = some value if true;
}
else {
//this is what you assign after the colon
value = some other value if false;
}
So based on your example (syntactically faulty btw), that would be something like:
if ((1 == x) && (2 > x++)){
x = 1;
}
else {
/*This is the value that would be put after the colon
*(which is missing in your example, and would cause a compiler error)
*/
x = some other value;
}
Which would translate to:
x = (1 == x) && (2 > x++) ? 1 : some other value

This statement does not even compile, ? is used with : as a ternary operator.
After (x=1) you should have the else branch, just an example:
(1 == x) && ( 2 > x++) ? (x=1) : (x = 2)
The way this boolean expression is evaluated is the following, suppose x is 1 :
(1 == x) = true
(2 > x++) = false
true && false = false
You expression will always be false regardless of the value of your x

In addition to the relevant comments about ?: where the colon is required, the following is also needed to "understand" the operation of the code in example :
Evaluation order of && implies that ´ ( 2 > x++) ´ will not be evaluated al all unless ´(1 == x)´ is true. Meaning in particular that the side-effect from x++ will not occur.
´x=1´ is an assignment so at first glance that doesn't look like an expression that evaluates to a value, but in java assignments are themselves expressions that take on the value being assigned.

(1 == x) && ( 2 > x++)? (x=1);
? stands for ternary operation. , if left of ? is true then it follows immediate right side.
In your case if ( 2 > x++) is true then value of x will be 1. but to travel towards ( 2 > x++) your left expression have to be true which means x==1, so if
(1 == x) is true and so( 2 > x++) is true then your overall condition to true.

Related

what is the meaning and use of line... int ct = count.containsKey(ch) ? count.get(ch) : 0; in the code? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

what does "0" stand for in conditional operator? [duplicate]

This question already has answers here:
Ternary Operator
(4 answers)
Closed 4 years ago.
Consider the following code:
i = (i == array.length-1) ? 0 : i + 1;
As I understand, the conditional operator works as follows:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
What does 0 execute?
I do not think the "positive conditional test result" really has a formal name.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html
?: Ternary (shorthand for
if-then-else statement)
using a boolean example
isConditionTrue = 1 == 2 ? true : false;
this in your example
i = (i == array.length-1) ? 0 : i + 1;
has the same result as
if (i == array.length-1)
{i= 0 ;}
else {i = i + 1;}
This is known as the Elvis Operator (see [https://en.wikipedia.org/wiki/Elvis_operator]) and given the following example:
x = A ? B : C;
... it means that if A is evaluated to 'true' than x gets assigned the value B otherwise it gets assigned the value C.
In your example it means, that if 'i==array.length-1' then 'i' is set to '0' otherwise 'i' is set to 'i+1'.

Evaluation Respects Parentheses and Precedence - java

As per the Java Language Specification:
Evaluation Respects Parentheses and Precedence
aside from using mathematical operation like:
int i = 3;
int j = 3 * (9 + 3);
System.out.println(j); //results to 36
are there any other examples that this rule apply? I tried using
int i = 0;
int z = 0;
if(i++ < 5 || (++z <0 && 5 > z++) || 6 < ++i){
System.out.println("Routed here");
}
System.out.println("i: " + i);
System.out.println("z: " + z);
but it results to i: 1 and z:0. It seems that the evaluation on that if example is still from left to right.
With ||, Java uses the concept of short circuiting, while evaluating expressions. Therefore, in this:
if(i++ < 5 || (++z <0 && 5 > z++) || 6 < ++i){
since the very first expression i++ < 5 returns true, hence rest of the expression will not be evaluated, i.e. never visited, hence will bring a change only in the value of i and no other thingy.
Quote from Java Docs:
The Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR
The following program, ConditionalDemo1, tests these operators:
class ConditionalDemo1 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
}
Parentheses and precedence don't have anything to do with the order in which expressions are evaluated at run time. That is, if you think putting parentheses around an expression means that it will get evaluated earlier, or that an operator with higher precedence is evaluated earlier, you're misunderstanding the concept.
Operator precedence answers questions like this: In the expression
a * b + c
Which operator does the compiler "bind" to arguments first? If + had a higher precedence, it would grab the arguments near it before * could, so to speak; so that the result would be that b and c are added, and the result is multiplied by a. That is, it would be equivalent to
a * (b + c)
But in most programming languages (with some exceptions such as APL), the * has higher precedence. That means the arguments are bound to * before they're bound to +, which means that a and b are multiplied, and the result is added to c, i.e.
(a * b) + c
Similarly, in the expression
a + b * c
the result is that b and c are multiplied, and the result is added to a.
a + (b * c)
You can put parentheses around parts of the expressions to change how the arguments are bound; thus, if you want to add a and b and multiply the sum by c, you can say
(a + b) * c
But it's very important to note: All this controls how the expression is interpreted at compile time. But at runtime, the arguments are always evaluated left-to-right. When the program is run, ALL of the above expressions will cause the program to evaluate a, then b, then c. This doesn't matter if a, b, and c are variables, but if they were method calls, it could possibly matter. In Java, when the program is run, things are always evaluated from left to right. (This is not true of other languages; most languages that I know of let the compiler choose the order.)
And when it comes to || and && (or similar operators in some other languages), once again at run time, the left argument is always evaluated first. The right argument may or may not be evaluated. Parentheses and operator precedence control how the expression is interpreted if you have an expression like some-expression-1 || some-expression-2 && some-expression-3, but they do not change the order of evaluation at run time.
As soon as the test can be evaluated to true or false the execution jumps inside the if block. In your case, i equals 0 which is lighter than than 5 so the test evaluates to true.
(true OR a OR b) is true independently from the values of a and b, which are not evaluated (and incrementations are not applied).
It would be the same with (false AND a AND b) except it would always skip the block.
Check the order of your expressions, split them into separate tests or get your incrementations out of the test. The following code is equivalent to your example but with the output you expected :
int i = 0;
int z = 1;
if(i < 5 || (z < 0 && 5 > z+2) || 6 < i+2){
System.out.println("Routed here");
}
i += 2;
z += 2;
System.out.println("i: " + i);
System.out.println("z: " + z);

What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

What is the difference between & and && in Java?

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & operator is used to do Bit-wise operations on two integer types.
Recently I came to know that & operator can also be used verify whether both its boolean operands are true, the only difference being that it checks the RHS operand even if the LHS operand is false.
Is the & operator in Java internally overloaded? Or is there some other concept behind this?
& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false
(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.
(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).
EDIT:
exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.
exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.
Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.
For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.
For all other argument types and combinations, a compile-time error should occur.
&& is a short circuit operator whereas & is a AND operator.
Try this.
String s = null;
boolean b = false & s.isEmpty(); // NullPointerException
boolean sb = false && s.isEmpty(); // sb is false
I think my answer can be more understandable:
There are two differences between & and &&.
If they use as logical AND
& and && can be logical AND, when the & or && left and right expression result all is true, the whole operation result can be true.
when & and && as logical AND, there is a difference:
when use && as logical AND, if the left expression result is false, the right expression will not execute.
Take the example :
String str = null;
if(str!=null && !str.equals("")){ // the right expression will not execute
}
If using &:
String str = null;
if(str!=null & !str.equals("")){ // the right expression will execute, and throw the NullPointerException
}
An other more example:
int x = 0;
int y = 2;
if(x==0 & ++y>2){
System.out.print(“y=”+y); // print is: y=3
}
int x = 0;
int y = 2;
if(x==0 && ++y>2){
System.out.print(“y=”+y); // print is: y=2
}
& can be used as bit operator
& can be used as Bitwise AND operator, && can not.
The bitwise AND " &" operator produces 1 if and only if both of the bits in
its operands are 1. However, if both of the bits are 0 or both of the bits are different then this operator produces 0. To be more precise bitwise AND " &" operator returns 1 if any of the two bits is 1 and it returns 0 if any of the bits is 0. 
From the wiki page:
http://www.roseindia.net/java/master-java/java-bitwise-and.shtml
it's as specified in the JLS (15.22.2):
When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
The "trick" is that & is an Integer Bitwise Operator as well as an Boolean Logical Operator. So why not, seeing this as an example for operator overloading is reasonable.
‘&&’ : - is a Logical AND operator produce a boolean value of true or false based on the logical relationship of its arguments.
For example: - Condition1 && Condition2
If Condition1 is false, then (Condition1 && Condition2) will always be false, that is the reason why this logical operator is also known as Short Circuit Operator because it does not evaluate another condition. If Condition1 is false , then there is no need to evaluate Condtiton2.
If Condition1 is true, then Condition2 is evaluated, if it is true then overall result will be true else it will be false.
‘&’ : - is a Bitwise AND Operator. It produces a one (1) in the output if both the input bits are one. Otherwise it produces zero (0).
For example:-
int a=12; // binary representation of 12 is 1100
int b=6; // binary representation of 6 is 0110
int c=(a & b); // binary representation of (12 & 6) is 0100
The value of c is 4.
for reference , refer this http://techno-terminal.blogspot.in/2015/11/difference-between-operator-and-operator.html
&& and || are called short circuit operators. When they are used, for || - if the first operand evaluates to true, then the rest of the operands are not evaluated. For && - if the first operand evaluates to false, the rest of them don't get evaluated at all.
so if (a || (++x > 0)) in this example the variable x won't get incremented if a was true.
With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.
The difference lies behind the scene where the information is being processed. When you right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:
left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false
When you write an expression (a != 0) && ( b != 0) when a= 0 and b = 1, the following happens:
a != 0 -->false
expression returns false
Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.
Besides && and || being short circuiting, also consider operator precedence when mixing the two forms.
I think it will not be immediately apparent to everybody that result1 and result2 contain different values.
boolean a = true;
boolean b = false;
boolean c = false;
boolean result1 = a || b && c; //is true; evaluated as a || (b && c)
boolean result2 = a | b && c; //is false; evaluated as (a | b) && c
& is a bitwise operator plus used for checking both conditions because sometimes we need to evaluate both condition.
But && logical operator go to 2nd condition when first condition give true.
all answers are great, and it seems that no more answer is needed
but I just wonted to point out something about && operator called dependent condition
In expressions using operator &&, a condition—we’ll call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful.
In this case, the dependent condition should be placed after the && operator to prevent errors.
Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10 / i == 2) must appear after the && operator to prevent the possibility of division by zero.
another example (myObject != null) && (myObject.getValue() == somevaluse)
and another thing: && and || are called short-circuit evaluation because the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression
References: Java™ How To Program (Early Objects), Tenth Edition
In respect of the AND and OR operators, Java has got two types of evaluation namely Short-Circuit evaluation and full evaluation.
&& || Short-Circuit Evaluation
Short-Circuit evaluation enables you to not evaluate the right-hand side of AND and OR expressions, when the overall result can be predicted from the left-side value.
int numberOne = 1;
int numberTwo = 2;
boolean result = false;
// left-side is false so the the overall result CAN be predicted without evaluating the right side.
// numberOne will be 1, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) && (++numberOne == numberTwo);
System.out.println(numberOne); // prints 1
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints false
// left-side is true so the the overall result CAN NOT be predicted without evaluating the right side.
// numberOne will be 2, numberTwo will be 2, result will be true
result = (numberTwo > numberOne) && (++numberOne == numberTwo);
System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints true
& | ^ Full Evaluation
Although in some cases it is possible to predict the result, It is necessary to evaluate the right-hand side.
int numberOne = 1;
int numberTwo = 2;
boolean result = false;
// left-side is false so the the overall result will be false BUT the right side MUST be evaluated too.
// numberOne will be 2, numberTwo will be 2, result will be false
result = (numberOne > numberTwo) & (++numberOne == numberTwo);
System.out.println(numberOne); // prints 2
System.out.println(numberTwo); // prints 2
System.out.println(result); // prints false
Notice:
Notice that for XOR (^) there is no short-circuit, because both sides are always required to determine the overall result.
Notice that other possible names for Short-Circuit evaluation are minimal evaluation and McCarthy evaluation.
It is not recommenced to mix boolean logic and actions in the same expression
& can also act as a Bitwise AND operator which is very academic and can be used in cryptography. When both bits are 1, the result is 1, or either of the bits is not 1, the result is 0. (Check the following code)
AND Bitwise example:
byte a = 5; // 00000101
byte b = 3; // 00000011
byte c = (byte) (a & b); // 00000001 (c is 1)
Almost every point of comparison is very well covered in all the answers. I just want to add one example. To demonstrate how the output changes based on which operator we use. Consider the below example
int a = 10;
if(++a==10 & ++a==12) {
++a;
}
System.out.println(a); //12
In the above code, We are using bitwise & operator. So It will evaluate both the arguments(left and right) irrespective of the individual result.
so a will increment 2 times within if condition. But as the condition will not become true, It will not enter inside the if-loop and 3rd increment will not happen. So the final value of a would become 12 in this case.
Now suppose, in the same above example If we use short-circuit && operator. then after evaluating ++a==10 to false, It will not go to check the second argument. And Hence the final value of a would-be 11.
int a = 10;
if(++a==10 && ++a==12) {
++a;
}
System.out.println(a); //11
Based on this, We can say that performance of bitwise & operator is relatively low compare to the short-circuit && operator. As bitwise operator will go to evaluate both the arguments irrespective of the result of the first argument. While && operator will stop evaluating the second argument if the first argument's result is false.
One more difference between these two is, Bitwise & operator is applicable for boolean as well as integral types. While short-circuit && operator is applicable only for the boolean type.
We can write
System.out.println(4 & 5); // 4
But if We try to write like ,
System.out.println(4 && 5);
Then it will give an error saying,
bad operand types for binary operator '&&'

Categories