Java statements which are also expressions, please explain - java

Please help me interpret this sentence from a purely terminological point of view:
"Technically, because variable assignments can be used as values for further assignments or operations, they can be considered to be both statements and expressions."
What does technically mean? What is not technically?
In case of
a = (b = 1);
What we know:
a = (b = 1);
is statement.
(b = 1)
is an expression.
Question 1:
is
a = (b = 1);
also an expression?
Or it is only an expression when written like this
a = (b = 1)
without semi colon and used in another statement or expression?
Quesion 2:
Is
(b = 1)
also a statement (given it is an assignment)? Or every statement must end with ; ?
Question 3.
Is b an expression within
(b = 1)
Or it is just a variable?
Is 1 an expression within
(b = 1)
Or it is just a literal?
Is a an expression within
a = (b = 1)
Or it is just a variable?
Regardin Q3 some clarification:
I guess literals and variables can be expressions when they are on their own. For example in the statement:
a = 1;
1 is an expression.
But is it also true for 1 inside expression of the example statement:
a = (b = 1);

An expression is anything which can be evaluated to a value, so a = (b = 1) is an expression (it is an assignment expression where the right-hand operand is another assignment expression).
The code a = (b = 1); is a statement; note the semicolon ; at the end of it. Specifically, it is an expression statement. An expression statement is a statement formed by writing an expression followed by a semicolon. (Not every type of expression is allowed as an expression statement, for example 1 + 1; is not a valid statement.)
So strictly speaking, the semicolon makes the two pieces of code different. But if we are not being formal then we could say that a = (b = 1) can be written either as an expression or a statement.
To answer the rest of your questions about what is or isn't a statement or an expression, I suggest checking the Java Language Specification:
Chapter 14. Blocks and Statements
Chapter 15. Expressions

Related

how this Ternary Operator work with this statemnt?

i just generate this methode to find max val in some matrix and somehowe i was able to change int val insdie Ternary Operator (java 8)
int max=0, indexToReturn=0;
int size= arr[0].length;
for (int i=1 ; i < size ; i++)
{
//
// ¯\_(ツ)_/¯
max = (!(arr[j][indexToReturn] > arr[j][i])) ? indexToReturn= i : arr[j][indexToReturn] ;
}
return max > 0 || indexToReturn==size-1 ? arr[j][indexToReturn] : null;
(the method compile and working)
im not realy sure evan how its compile from what i saw online Ternary Operator syntax :
variable = Expression1 ? Expression2: Expression3
can someone explain me what im missing here ?
The reason this works is because an assignment is an expression. The value of an assignment is the value assigned. This sounds theoretical, so let us look at an example:
int i, k;
i = (k = 5);
System.out.println(i);
System.out.println(k);
Ideone demo
The value of the expression k = 5 is the assigned value 5. This value is then assigned to i.
Armed with this knowledge, we see that indexToReturn= i is an expression that evaluates to the value of i. When we swap Expression2 and Expression3, the ternary operator breaks because the = i is not evaluated as part of the ternary operator (due to operator precedence). If we set parentheses around Expression2, it works as expected.
I would discourage using the fact that an assignment is an expression. (Ab)using this fact often leads to hard-to-understand code.

Parenthesis, Comma Operator and Ternary operator combination equivalent in java

Can any one explain what below statement is doing ? Actually I want to translate code shown here in java, so its real code
w = (m<3?y--,m+=13:m++,d+153*m/5+15*y+y/4+19*c+c/4+5);
I searched a lot but not able to found what this statement is doing. Can anyone explain it and help me to convert it into Java code ? I never seen combination of Unary Operators in Ternary Operators in C language. Sorry for simple question if it is but I did not understand it.
This:
w = (m<3?y--,m+=13:m++,d+153*m/5+15*y+y/4+19*c+c/4+5);
Works out to be the same as this:
if (m<3) {
y--;
m+=13;
} else {
m++;
}
w = (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5);
Now for the explanation. There is an instance of the ternary operator here. The second clause is an expression which allows for the comma operator, while the third clause is a conditional expression meaning it can't include the comma operator (not without surrounding parenthesis, at least). This means that the first comma you see is part of the second clause while the second comma marks the end of the conditional.
So the expression with implicit parenthesis would look like this:
w = (((m<3)?(y--,m+=13):m++), (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5));
And the part that makes up the conditional is:
(m<3)?(y--,m+=13):m++
And because this is the left operand of the comma operator, the result of the expression isn't used so it can be pulled out of the larger expression:
(m<3)?(y--,m+=13):m++
w = (d + (153*m/5) +(15*y) + (y/4) + (19*c) + (c/4) + 5);
And the conditional can then be further translated into an if/else block as above.
I'll try.
m<3?
Is essentially
if (m < 3)
If it evaluates as true, y is decremented and 13 is added to m.
If it evaluates as false, m is incremented and then I think that w is set to whatever the result of "d+153m/5+15y+y/4+19*c+c/4+5" is.
You can de-obfuscate it quite a bit by dropping the conditional and comma operators:
if(m<3)
{
y--;
m+=13;
}
else
{
m++;
}
w = d + 153*m/5 + 15*y + y/4 + 19*c + c/4 + 5;

Wtat does it mean "^=" [duplicate]

I have a long set of comparisons to do in Java, and I'd like to know if one or more of them come out as true. The string of comparisons was long and difficult to read, so I broke it up for readability, and automatically went to use a shortcut operator |= rather than negativeValue = negativeValue || boolean.
boolean negativeValue = false;
negativeValue |= (defaultStock < 0);
negativeValue |= (defaultWholesale < 0);
negativeValue |= (defaultRetail < 0);
negativeValue |= (defaultDelivery < 0);
I expect negativeValue to be true if any of the default<something> values are negative. Is this valid? Will it do what I expect? I couldn't see it mentioned on Sun's site or stackoverflow, but Eclipse doesn't seem to have a problem with it and the code compiles and runs.
Similarly, if I wanted to perform several logical intersections, could I use &= instead of &&?
The |= is a compound assignment operator (JLS 15.26.2) for the boolean logical operator | (JLS 15.22.2); not to be confused with the conditional-or || (JLS 15.24). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively.
In other words, for boolean b1, b2, these two are equivalent:
b1 |= b2;
b1 = b1 | b2;
The difference between the logical operators (& and |) compared to their conditional counterparts (&& and ||) is that the former do not "shortcircuit"; the latter do. That is:
& and | always evaluate both operands
&& and || evaluate the right operand conditionally; the right operand is evaluated only if its value could affect the result of the binary operation. That means that the right operand is NOT evaluated when:
The left operand of && evaluates to false
(because no matter what the right operand evaluates to, the entire expression is false)
The left operand of || evaluates to true
(because no matter what the right operand evaluates to, the entire expression is true)
So going back to your original question, yes, that construct is valid, and while |= is not exactly an equivalent shortcut for = and ||, it does compute what you want. Since the right hand side of the |= operator in your usage is a simple integer comparison operation, the fact that | does not shortcircuit is insignificant.
There are cases, when shortcircuiting is desired, or even required, but your scenario is not one of them.
It is unfortunate that unlike some other languages, Java does not have &&= and ||=. This was discussed in the question Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=).
It's not a "shortcut" (or short-circuiting) operator in the way that || and && are (in that they won't evaluate the RHS if they already know the result based on the LHS) but it will do what you want in terms of working.
As an example of the difference, this code will be fine if text is null:
boolean nullOrEmpty = text == null || text.equals("")
whereas this won't:
boolean nullOrEmpty = false;
nullOrEmpty |= text == null;
nullOrEmpty |= text.equals(""); // Throws exception if text is null
(Obviously you could do "".equals(text) for that particular case - I'm just trying to demonstrate the principle.)
You could just have one statement. Expressed over multiple lines it reads almost exactly like your sample code, only less imperative:
boolean negativeValue
= defaultStock < 0
| defaultWholesale < 0
| defaultRetail < 0
| defaultDelivery < 0;
For simplest expressions, using | can be faster than || because even though it avoids doing a comparison it means using a branch implicitly and that can be many times more expensive.
Though it might be overkill for your problem, the Guava library has some nice syntax with Predicates and does short-circuit evaluation of or/and Predicates.
Essentially, the comparisons are turned into objects, packaged into a collection, and then iterated over. For or predicates, the first true hit returns from the iteration, and vice versa for and.
If it is about readability I've got the concept of separation tested data from the testing logic. Code sample:
// declare data
DataType [] dataToTest = new DataType[] {
defaultStock,
defaultWholesale,
defaultRetail,
defaultDelivery
}
// define logic
boolean checkIfAnyNegative(DataType [] data) {
boolean negativeValue = false;
int i = 0;
while (!negativeValue && i < data.length) {
negativeValue = data[i++] < 0;
}
return negativeValue;
}
The code looks more verbose and self-explanatory. You may even create an array in method call, like this:
checkIfAnyNegative(new DataType[] {
defaultStock,
defaultWholesale,
defaultRetail,
defaultDelivery
});
It's more readable than 'comparison string', and also has performance advantage of short-circuiting (at the cost of array allocation and method call).
Edit:
Even more readability can be simply achieved by using varargs parameters:
Method signature would be:
boolean checkIfAnyNegative(DataType ... data)
And the call could look like this:
checkIfAnyNegative( defaultStock, defaultWholesale, defaultRetail, defaultDelivery );
It's an old post but in order to provide a different perspective for beginners, I would like give an example.
I think the most common use case for a similar compound operator would be +=. I'm sure we all wrote something like this:
int a = 10; // a = 10
a += 5; // a = 15
What was the point of this? The point was to avoid boilerplate and eliminate the repetitive code.
So, next line does exactly the same, avoiding to type the variable b1 twice in the same line.
b1 |= b2;
List<Integer> params = Arrays.asList (defaultStock, defaultWholesale,
defaultRetail, defaultDelivery);
int minParam = Collections.min (params);
negativeValue = minParam < 0;
|| logical boolean OR
| bitwise OR
|= bitwise inclusive OR and assignment operator
The reason why |= doesn't shortcircit is because it does a bitwise OR not a logical OR.
That is to say:
C |= 2 is same as C = C | 2
Tutorial for java operators

Ternary operator, syntax error when using assignment

The following 3 lines of code below compile OK. (Please note that this code is an example of "artificial Java coding", and consequently wouldn't be seen in professionally written code.)
int x, y;
boolean b=true;
x = b ? y=1 : 2; // Compiles OK.
If I now change the code in line #3 above, so that it looks like the following code line below, the compiler generates an error.
// Change the position of the "y assignment", and now the code doesn't compile.
x = b ? 1 : y=2;
Here is the syntax error message:
Can someone please explain this behaviour (to a rookie Java learner)? Thank you.
Short:
This is because of operator precedence. The first case is equal to this:
x = (b ? (y=1) : 2); // Compiles OK.
While the second is:
x = (b ? 1 : y) = 2;
The first one compiles indeed fine, because an assignment gets evaluated to the new value. So, if b is true, it will cause to be both x and y equal to 1. The second one is like saying: x = 1 = 2. So, yes, to fix this compiler error, add paratheses to your statement:
x = (b ? 1 : (y = 2)); // Outer () are not needed, but is clearer, IMHO.
Longer:
First of all, operator precedence in Java says that the assignment operators have lower priority than the conditional ternary operator. This means that your second expression is equivalent to:
x = (b ? 1 : y) = 2;
As you can see, this looks plain wrong. Indeed, JLS §15.26 says this:
There are 12 assignment operators; all are syntactically right-associative (they group right-to-left). Thus, a=b=c means a=(b=c), which assigns the value of c to b and then assigns the value of b to a.
The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. (This explains the compile time error you face)
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.
Applying right-associativity:
x = ((b ? 1 : y) = 2);
Finally we can see why this generates a compiler error: the result of a ternary conditional operator is not a variable (which is actually not in the JLS as far as I can find, however the compiler tells you in a simple test case like this one: https://ideone.com/kMr7Xv).
See "Java operator precedence".
Meanwhile, use:
x = (b ? 1 : (y=2));
Java operator precedence is as follows
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
here ternary comes before assignment operation. so your statement will be like this
x= ( ternary evaluation )= assignment value
if you still want set value for y , when b is false, you may use () for 'y=2' bring inside ternary evaluation.
x = b ? 1 : (y=2);
Brother, try putting expressions in brackets.
X= (b? 1 : (y=2));
this will work fine.

What is the difference between '==' and '='?

I know that one of them is bitwise and the other is logical but I can not figure this out:
Scanner sc = new Scanner(System.in);
System.out.println("Enter ur integer");
int x=sc.nextInt();
if(x=0)//Error...it can not be converted from int to boolean
System.out.println("...");
The error means that x cannot be converted to boolean or the result of x=0 can not be converted to boolean.
== checks for equality.
= is assignment.
What you're doing is:
if( x = Blah ) - in Java this statement is illegal as you can not test the state of an assignment statement. Specifically, Java does not treat assignment as a boolean operation, which is required in an if statement. This is in contrast with C/C++, which DOES allow you to treat assignment as a boolean operation, and can be the result of many hair-pulling bugs.
When you write 'x = 0' you are saying "Store 0 in the variable x". The return value on the whole expression is '0' (it's like this so you can say silly things like x = y = 0).
When you write 'x == 0' it says "Does x equal 0?". The return value on this expression is going to be either 'true' or 'false'.
In Java, you can't just say if(0) because if expects a true/false answer. So putting if(x = 0) is not correct, but if(x == 0) is fine.
== is a comparison operator, and = is assignment.
== is an equality check. if (x == 0) // if x equals 0
= is an assignment. x = 0; // the value of x is now 0
I know the question has been answered, but this still comes up from time to time not as a programmer error but as a typographical error (i.e., the programmer knew what he meant, but failed). It can be hard to see, since the two look so similar.
I've found that a way to help avoid doing this is to put the constant expression on the left-hand-side, like so:
if (0 == x)
...
That way, if I accidentally use only one "=" sign, the compiler will fail with an error about assigning to a constant expression, whether or not the assignment operator is left-associative and whether the if conditional expects a strongly-typed Boolean.
if(x=0)
Here you're assigning the value of 0 to the variable x. The if statement in Java can't evaluate an integer argument as it can in many other languages. In Java, if requires a boolean. Try
if(x == 0)
to do a comparison.
Interpret the error to mean
"The expression
x=0
cannot be converted to Boolean."
Just to clarify about C/C++ - assignment is evaluated to the right operand
if(a = n)
is evaluated to n, so (n = 1) is true (n = 0) is false
One interesting note: Since assignment operator evaluates to the right operand, the following is valid in Java(albeit not pretty):
if (( x = blah ) > 0) ...
Parenthesis are needed because of operator precedence ( '>' binds stronger than '=').
As others have already said, '=' is assignment; '==' is compare.
in your program change
if(x=0)
to
if(x==0)
"==" checks for equality
"=" Is used for assignment.
It is giving you error cause you're assigning value to x in if(), where you're supposed to check for the equality. Try changing it to equality instead of assignment operator.
As others stated, = assigns while == compares.
However, these statements have their own values as well.
The = operator returns the value of its right-hand operand. This is how statements like a = b = c = 5 work: they are parsed as a = (b = (c = 5)), which evaluates to a = (b = 5) and then a = 5.
The == operator returns a boolean that is true if its operands are equal. The if statement runs its body if its argument is true. Thus, if headers like if (5 == 5) translate to if (true). This is why sometimes you see infinite while loops with header while (true); the while loop runs "while" toe argument is true.
If you had a boolean in your if statement, it would give no error and run the code if the value being assigned (or "compared to") was true. This is why it is so important to never mix up the = and == operators, especially when working with booleans.
Hope this helped!!

Categories

Resources