Nested conditional operator interpreted as String - jsf

In my Java EE 7 / JSF / EL 3.0 project, I need to define the style class of a tag depending of the condition:
if x < a, then the class is LT-A
else if x > b, then the class BT-B
else the class is BETWEEN-A-B
The only solution I could find is using a nested conditional operator:
styleClass="#{x<a ? 'LT-A' : (x>b ? 'BT-B' : 'BETWEEN-A-B')}"
However, my problem is that the (x>b ? 'BT-B' : 'BETWEEN-A-B') part gets interpreted as a String (and thus is rendered as-is instead of actually evaluated).
Is something wrong with the syntax?

The < and > are being misinterpreted. If you use lt and gt everything should work just fine.
Here's a full list of EL logical operators:
and - Logical operator alternative to (&&)
false - Boolean literal
le - Relation operator less than or equal to alternative to (<=)
not - Logical operator reverse alternative to (!)
div - Arithmetic operator division alternative to (/)
ge - Relational operator greater or equal to alternative to (>=)
lt - Relational operator less than alternative to (<)
null - Null literal
empty - The empty operator is a prefix operation that can be used to determine whether a value is null or empty.
gt - Relational operator greater than alternative to (>)
mod - Arithmetic operator modulo alternative to (%)
or - Logical operator alternative to (||)
eq - Logical operator alternative to (==)
instanceof - Java Keyword to do a Class comparison between Objects
ne - Relational operator not equal alternative to (!=)
true - Boolean literal
courtesy of javaevangelist.blogspot.co.at

Related

On use of parenthesis

So I was looking over some A-Levels Computer Science past papers, and stumbled into this:
Now, my first reaction was that there is no need for parenthesis on line 6. Reason being that algebraic operators take precedence over comparisons which take precedence over boolean ones.
As a small example from Java:
int a = 100;
int b = 100;
int c = 100;
int d = 100;
if( ((c+d) > 180) && ((a+b+c+d)) >= 320)
System.out.println("greater");
if(c+d > 180 && a+b+c+d >=320)
System.out.println("greateragain");
Both if statements are evaluated to true.
So, am I right in thinking parenthesis are only for human readability in this case or...?
You can say: "The use of parentheses makes the precendence of evaluation explicit, disregarding of the operator precendence of the language in use."
The comments above describe well that operator precendence is language specific. For example, in Pascal, logical operators such as AND seem to have higher precendence than math operators, and interpreted as binary AND. In contrast in C, the && has lower precedence, hence you can save some parentheses.
Therefore, it sounds like a wise idea to always use parentheses in case of a possible ambiguity, or at least until you're mastering the language in use.
BASIC was one of the early languages that took advantage of the fact that logical operators and bit-wise operators can share the same mnemonic.
In the example - c+d > 180 AND a+b+c+d >= 320 could (by a stretch of the imagination) have been interpreted as (c + d) > (180 AND a) + b + c + (d > 320). For this reason it is necessary to add brackets to eremove all ambiguity.

is it safe to use comparison operators on BigDecimal in groovy/grails?

The Java way to compare two BigDecimals is to use the compareTo() method, and check if the result is -1, 0 or 1.
BigDecimal a = new BigDecimal("1.23")
BigDecimal b = new BigDecimal("3.45")
if (a.compareTo(b) > 0)) { }
I have seen that some people are using this format in grails:
if (a > b) { }
Does this work correctly? I.e. will it get the decimals correct, or is it converting to float or similar and comparing that?
How about using "==" vs using equals()?
What is the consequence of something like this:
BigDecimal a = new BigDecimal("1.00")
BigDecimal b = new BigDecimal("1")
assert (a==b)
It seems to work, but we have had it so engrained in Java not to do this kind of thing.
How about +=? e.g.
a+=b?
Would this be the same as
a = a.add(b)
Where does one find this kind of thing out? I have two groovy books, and unfortunately neither mention BigDecimal comparison or arithmetic, only the conversion/declaration.
Groovy allows overloading of operators. When a type implements certain methods then you can use a corresponding operator on that type.
For + the method to implement is plus, not add.
For greater than or less than comparisons, Groovy looks for a compareTo method on the object, and for == it looks for a method named equals. (If you want to compare references as if using == in Java, you have to use is.)
Here's a table of common math operators and the method used to overload them:
Operator Method
a + b a.plus(b)
a - b a.minus(b)
a * b a.multiply(b)
a / b a.divide(b)
a++ or ++a a.next()
a-- or --a a.previous()
a << b a.leftShift(b)
You can see that BigDecimal overloads some of these methods (you get operator overloading for plus, minus, multiply, and divide, but not for next, previous, or leftShift):
groovy:000> BigDecimal.methods*.name
===> [equals, hashCode, toString, intValue, longValue, floatValue, doubleValue,
byteValue, shortValue, add, add, subtract, subtract, multiply, multiply, divide,
divide, divide, divide, divide, divide, remainder, remainder, divideAndRemainde
r, divideAndRemainder, divideToIntegralValue, divideToIntegralValue, abs, abs, m
ax, min, negate, negate, plus, plus, byteValueExact, shortValueExact, intValueEx
act, longValueExact, toBigIntegerExact, toBigInteger, compareTo, precision, scal
e, signum, ulp, unscaledValue, pow, pow, movePointLeft, movePointRight, scaleByP
owerOfTen, setScale, setScale, setScale, stripTrailingZeros, toEngineeringString
, toPlainString, round, compareTo, getClass, notify, notifyAll, wait, wait, wait
, valueOf, valueOf, valueOf]
You get ==, >, <, >=, and <= based on how your object implements equals and compareTo.
So the operator is causing methods declared already in BigDecimal, or added to BigDecimal by groovy, to get called. It is definitely not doing any kind of conversion to a primitive type like float in order to be able to use the operators on primitives.
The table is taken from this developerworks article by Andrew Glover and Scott Davis, which has more details and includes example code.
Groovy does a wonderful job of managing numbers and to infinite precision. First thing you should know is that any number that has a dot in it is by default a BigDecimal -- the reason for the infinite precision. Here is an example of what this means exactly. Consider this snippet:
System.out.println(2.0 - 1.1);
System.out.println(new BigDecimal(2.0).subtract(new BigDecimal(1.1)));
System.out.println(new BigDecimal("2.0").subtract(new BigDecimal("1.1")));
// the above will give these:
0.8999999999999999
0.899999999999999911182158029987476766109466552734375
0.9
This shows the endurance we have to go through to get something decent in Java. In Groovy, this is all you have to do:
println 2 - 1.1​
to get your 0.9! Try this on the Groovy web console. Here, the second operand is a BigDecimal, so the entire calculation is in BigDecimal, and precision is what Groovy would strive for to finish off clean in this case.
But how? This is because almost every operator in Groovy is mapped onto method calls on objects under the hood, so a + b is a.plus(b), and a==b translates to a.compareTo(b). It is therefore safe to assume what you assumed and this is the Groovy way of doing things: write less, expressively, and Groovy will do the work for you. You can learn about all this in the Groovy-lang documentation page with examples all over.
The short answer is yes, it's safe to use == for BigDecimal comparison in Groovy.
From the Groovy documentation Behaviour of == section:
In Java == means equality of primitive types or identity for objects. In Groovy == translates to a.compareTo(b)==0, if they are Comparable, and a.equals(b) otherwise. To check for identity, there is is. E.g. a.is(b).

How will comparison operators (spaceship operator) be handled in ternary operators

This question is a little preemptive, as php 7 is not even released yet. I'm curious how the spaceship operator will be handled in the context of ternary operators.
so if I have a pre-spaceship ternary expression such as:
$foo = 1;
$bar = 0;
echo 'foo is ' . ( ($foo > $bar) ? 'greater than' : ( ($foo < $bar ) ? 'less than' : 'equal to' ) ) . ' bar.';
what would be the equivalent ternary operator using a comparison operator? Are ternaries going to have some means of handling this scenario? I use ternary operators quite a lot and am curious if there is some way to streamline the code in various instances where a comparison operator would be relevant.
The spaceship operator, as you can see from the documentation of its RFC, was though mainly to be used when having to deal with orderings.
I don't think it could be of help in shortening the code that you posted, mainly beacuse the ternary operator expects a boolean value and the ternary operator returns a "true" value (1 and -1) in both cases when the the values are different. In other words, when you cast its return value to a boolean, the spaceship operator is equivalent to the != operator.
Anyway, you could experiment with it on 3v4l.org, like I did here
Here's a clever approach for using the spaceship operator <=> as a poor man's three-way "ternary", also using an arrow function and array destructuring.
<?php
$relation = fn($a, $b) => [
-1 => 'less than',
0 => 'the same as',
1 => 'greater than'
][$a <=> $b];
$bar = 2;
// loop $foo from 1 through 3
foreach (range(1,3) as $foo) {
echo "foo is " . $relation($foo, $bar) . " bar.\n";
}
?>
Output:
foo is less than bar.
foo is the same as bar.
foo is greater than bar.
But watch out: it's clever, and clever code always requires more mental horsepower to understand, which makes it less maintainable. So there's the warning.

Groovy different results on using equals() and == on a GStringImpl

According to the Groovy docs, the == is just a "clever" equals() as it also takes care of avoiding NullPointerException:
Java’s == is actually Groovy’s is() method, and Groovy’s == is a clever equals()!
[...]
But to do the usual equals() comparison, you should prefer Groovy’s ==, as it also takes care of avoiding NullPointerException, independently of whether the left or right is null or not.
So, the == and equals() should return the same value if the objects are not null. However, I'm getting unexpected results on executing the following script:
println "${'test'}" == 'test'
println "${'test'}".equals('test')
The output that I'm getting is:
true
false
Is this a known bug related to GStringImpl or something that I'm missing?
Nice question, the surprising thing about the code above is that
println "${'test'}".equals('test')
returns false. The other line of code returns the expected result, so let's forget about that.
Summary
"${'test'}".equals('test')
The object that equals is called on is of type GStringImpl whereas 'test' is of type String, so they are not considered equal.
But Why?
Obviously the GStringImpl implementation of equals could have been written such that when it is passed a String that contain the same characters as this, it returns true. Prima facie, this seems like a reasonable thing to do.
I'm guessing that the reason it wasn't written this way is because it would violate the equals contract, which states that:
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
The implementation of String.equals(Object other) will always return false when passed a GSStringImpl, so if GStringImpl.equals(Object other) returns true when passed any String, it would be in violation of the symmetric requirement.
In groovy a == b checks first for a compareTo method and uses a.compareTo(b) == 0 if a compareTo method exists. Otherwise it will use equals.
Since Strings and GStrings implement Comparable there is a compareTo method available.
The following prints true, as expected:
println "${'test'}".compareTo('test') == 0
The behaviour of == is documented in the Groovy Language Documentation:
In Java == means equality of primitive types or identity for objects. In Groovy == means equality in all cases. It translates to a.compareTo(b) == 0, when evaluating equality for Comparable objects, and a.equals(b) otherwise. To check for identity (reference equality), use the is method: a.is(b). From Groovy 3, you can also use the === operator (or negated version): a === b (or c !== d).
The full list of operators are provided in the Groovy Language Documentation for operator overloading:
Operator
Method
+
a.plus(b)
-
a.minus(b)
*
a.multiply(b)
/
a.div(b)
%
a.mod(b)
**
a.power(b)
|
a.or(b)
&
a.and(b)
^
a.xor(b)
as
a.asType(b)
a()
a.call()
a[b]
a.getAt(b)
a[b] = c
a.putAt(b, c)
a in b
b.isCase(a)
<<
a.leftShift(b)
>>
a.rightShift(b)
>>>
a.rightShiftUnsigned(b)
++
a.next()
--
a.previous()
+a
a.positive()
-a
a.negative()
~a
a.bitwiseNegate()
Leaving this here as an additional answer, so it can be found easily for Groovy beginners.
I am explicitly transforming the GString to a normal String before comparing it.
println "${'test'}".equals("test");
println "${'test'}".toString().equals("test");
results in
false
true

x>y && z==5 - how are parts of this expression called?

I know && is the logical operator here, also conditions on the left and on the right are operands, right?
Like:
1+1 is an expression where + is the operator and the numbers are operands. I just do not know whether the condition itself is called the operand as well because it get compared by an operator. I guess so.+
Thanks
What are the parts called?
>, &&, and == are all operators. Operands are the values passed to the operators. x, y, and z are the initial operands. Once x > y and z == 5 are evaluated, those boolean results are used as the operands to the && operator which means the expressions themselves are not the operands to &&, the results of evaluation those expressions are the operands.
When you put operands and an operator together, you get an expression (i.e. x > y, z == 5, boolResult == boolResult)
How are they evaluated?
In most (if not all) languages x > y will be evaluated first.
In languages that support short circuiting, evaluation will stop if x > y is false. Otherwise, z == 5 is next.
Again, in languages that support short circuiting, evaluation will stop if z == 5 is false. Otherwise, the && will come last.
>, &&, and == are all operators. Operands are the values passed to the operators. x, y, and z are the initial operands. Once x > y and z == 5 are evaluated, those boolean results are used as the operands to the && operator.
One alternative would be to turn to the grammar of C#
It states the following:
conditional-and-expression && inclusive-or-expression
Just generalizing it as "expressions" is probably accurate enough :)
If your question is really what the parts left and right of the && are called, I’d say “expression”, maybe “boolean expression”.
Conditions, or in case of ||: Alternatives
In c# the && is an operator and the left and right are expressions. In an if statement, if the left evaluates to true the right will never be evaluated.
It's a boolean comparison expression that's comprised of two separate boolean comparison expressions.
Depending on the language, how this is interpreted depends on operator precedence. Since it looks like a C-like dialect, I'll assume && is short-circuit AND. (More explanation here).
Order of operations would be left to right as the equality testers (>, >=, <=, ==, !=) have equal precedence to boolean operations (&&, ||).
x > y would be evaulated, and if true, z == 5 would be evaluated, and then the first and second results would be ANDed together. However, if x > y was false, the expression would immediately return false, due to short-circuiting.
You're correct that x>y and z==5 are operands, and && is an operator. In addition, both of these operands in turn contain their own operands and operators. These are called complex operands
So:
x>y and z==5 are operands to the operator &&
x and y are operands to the operator >
z and 5 are operands to the operator ==
Regarding the individual component parts and how to name them:
Both == and > are comparison operators, which compare the values of two operands.
== is an equality operator, and evaluates to true if the left operand is equal to the right operand.
> is a greater than operator, and evaluates to true if the left operand is greater than the right operand.
&& is a logical operator, specifically logical AND. It evaluates to true if both the left and the right operand are true.
When referring to each operand, it's standard to refer to them by their position, i.e. the left operand and right operand - although there's no "official" name - first and second operand work equally well. Note that some operators such as ! have only one operand, and some even have 3 (the ternary operator, which takes the form condition ? true_value : false_value

Resources