Operator to choose upon the condition - java

I have a table which contain two columns in database status and diff_id status column may contain these values
DFG_SGG_RGRG
NULL
EF_SFEG_FTT
IFEF_RGG
abc_id may contain these values
null
43546
45346
45746
53465
Now I am getting these values in an object t ,so I have to make an condition where status column is null and abc_id should have value 435465666L so I have prefer to write an if like shown below please advise is it correct as I am confused between && operator || operator
if ( if f.getStatus()== null || abc_id() .longValue()==435465666L )
{
//perform the logic
}
Please advise - is it correct approach?

& = "and"
&& = "and, but only if preceding condition was true"
| = "or"
|| = "or, but only if preceding condition was false"

If you're saying:
AND - use &&
OR - use ||
Remebmer also that && takes precedence over ||.

If both conditions must be true you need to use the && operator.
if (f.getStatus()== null && abc_id().longValue()==435465666L )
{
//perform the logic
}
Using the && operator causes a condition to be true only if both conditions are true. For example:
System.out.println(true && false); //prints false
System.out.println(false && false); //prints false
System.out.println(true && true); //prints true
System.out.println(false && true); //prints false
The || operator causes a condition to be true if one of the conditions is true.
System.out.println(true || false); //prints true
System.out.println(false || false); //prints false
System.out.println(true || true); //prints true
System.out.println(false || true); //prints true

use
if (f.getStatus()== null && abc_id().longValue() == 435465666L )
{
//perform the logic
}

Related

OR operator inside of If statements

else if (!emailGet.endsWith(".com") && !emailGet.endsWith(".info")){
errors += "Email should end with .info or .com";
}
Why is && playing the role of an "OR" statement, but when I use "OR" itself it does nothing. The only way I can get the code to tell me if one or the other statement is true, is by using && which evaluates 2 statements unlike "OR", the logic behind using && makes no sense to me. Am I missing something?
Note the following concepts about || and && operators:
When multiple conditions are combined with &&, the evaluation of the conditions continues as long as conditions evaluate as true. If any condition evaluates as false, the further evaluation stops and the combination results in false. The combination results in true only when all the conditions evaluate as true.
When multiple conditions are combined with ||, the evaluation of the conditions continues as long as conditions evaluate as false. If any condition evaluates as true, the further evaluation stops and the combination results in true. The combination results in false only when all the conditions evaluate as false.
Based on these concepts,
!emailGet.endsWith(".com") && !emailGet.endsWith(".info")
is same as
!(emailGet.endsWith(".com") || emailGet.endsWith(".info"))
Let's analyse them in the following scenarios:
Let's say emailGet = "a#b.com"
!emailGet.endsWith(".com") && !emailGet.endsWith(".info") => !(true) && !emailGet.endsWith(".info") => false && !emailGet.endsWith(".info") => false.
!(emailGet.endsWith(".com") || emailGet.endsWith(".info")) => !(true || emailGet.endsWith(".info")) => !(true) => false.
Let's say emailGet = "a#b.info"
!emailGet.endsWith(".com") && !emailGet.endsWith(".info") => !(false) && !emailGet.endsWith(".info") => true && !(true) => true && false => false.
!(emailGet.endsWith(".com") || emailGet.endsWith(".info")) => !(false || true) => !(true) => false.
Let's say emailGet = "a#b.c"
!emailGet.endsWith(".com") && !emailGet.endsWith(".info") => !(false) && !emailGet.endsWith(".info") => true && !(false) => true && true => true.
!(emailGet.endsWith(".com") || emailGet.endsWith(".info")) => !(false || false) => !(false) => true.
I think the negatives in combination with and (&&) and or (||)
caused misunderstanding.
if (!emailGet.endsWith(".com") && !emailGet.endsWith(".info")) {
errors += "Email should end with .info or .com";
}
if (emailGet.endsWith(".com") || emailGet.endsWith(".info")) {
sucesses += "Email did end with .info or .com";
}
if (!(emailGet.endsWith(".com") || emailGet.endsWith(".info"))) {
errors += "Email should end with .info or .com";
}
It is always:
! <this-case> && ! <other-case>
<this-case> || <other-case>
Should you see
! <this-case> || ! <other-case> // *** ERROR *** always true
<this-case> && <other-case> // *** ERROR *** always false
you know it is wrong.
Yes, in java the boolean operator for conditional or is ||.(represented by two vertical bars or "pipes", not lowercase L's) Similarly you've already found the boolean operator for conditional and which is &&. These two are not the same although they will both evaluate to true when both statements are true.

Why is FindBugs showing warning for redundant null check

if (first != null && second != null && !first.equals(second)) {
// not null & not equal
} else if (first == null ^ second == null) {
// not both null and not both not null
// (first == null && second != null) || (first != null && second == null)
} else {
// both null or equal
}
FindBugs is complaining about else if (first == null ^ second == null) {...}
Since you wrote in the comment: not both null it's a good thing that FindBugs showed you your (potential) mistake since you should have used && (AND) not ^ (XOR):
first != null && second != null
or alternatively:
!(first == null || second == null)
UPDATE:
The OP change the comment to: "not both null and not both not null" this condition requires a different if:
(first == null && second != null) || (first != null && second == null)
which is equivalent to:
first == null ^ second == null
only that the former version is more readable.
Probably because it is only software.
The ^ operator is a bitwise operator as opposed to a logical operator. While technically correct the precedence of the operators makes the expression confusing should the logical expressions grow. I don't use FindBugs but I would call the 3rd line suspect - Wrap it in parentheses or rewrite it.
...
} else if ((first == null) ^ (second == null)) {
...
^ can behave like a logical operation as long as the operands are boolean values. Because the precedence is different for each logical and bitwise operator, you should always group with parentheses since the order of evaluation will not be left to right but will be based on the table here: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Your expression "not both null" and "not both not null" comes out like this:
(first == null) || second == null) && !((first == null && second == null))
Which is pretty confusing but it is what you are asking for.
I am not sure what you are doing in the blocks but it might be easier to write the entire block like this:
if(first!=null && !first.equals(second)) {
// first is not null and the first and second are not equal
} else if (second!=null && !second.equals(first)) {
// second is not null and first and second are not equal
} else {
// all that is left is that first and second are both null OR neither one is null but they are equal
}
The warning says: redundant null check. Thus, FindBugs thinks that you are redundantly checking the nullity of the variables. Try if this code also triggers the warning:
Boolean firstNull = (first == null);
Boolean secondNull = (second == null);
Boolean equalFirstSecond = first.equals(second);
if (!firstNull && !secondNull && !equalFirstSecond) {
// not null & not equal
} else if (firstNull ^ secondNull){
// not both null and not both not null
} else {
// both null or equal
}
if (first != null && second != null && !first.equals(second)) {
You don't need to test second != null here. The equals() call does that.
} else if (first == null ^ second == null) {
You should return false in this case, assuming this is an equals() method itself.
If FindBugs doesn't like it with this change I would ignore it, it doesn't know what it's talking about. It's not perfect. Put in an exception rule.

servlet request.getParameterValues(fieldName) returns null and throw exception

i want to get parameters values and sometimes i do not send them and it return me null
and its ok . but when i preform check on the return string array the servlet throws a java.lang.NullPointerException
and i just what to do nothing when its null. ( continue the flow )
String[] values = null;
if(request.getParameterValues(fieldName).length>0)
{
values = request.getParameterValues(fieldName);
if(null!=values || values.length>0) // HERE IT throws NullPointerException
{
Collections.addAll(strlist, values);
}
}
It should be
if(null!=values && values.length>0)
because, if your values is null(evaluating to false), the OR condition in your statement, executes the other part of the OR, which throws the NPE.
If you give an && there, it'll SHORT-CIRCUIT the statement evaluation when it encounters a false at null!=values.
It's the AND && operator that should be used to test if both conditions are met, which is what you need in you instance.
if (null != values && values.length > 0)
in and unlike or if values is null it wont go for next check.
if(null!=values && values.length>0) // change to and
{
Collections.addAll(strlist, values);
}
also refer && (AND) and || (OR) in IF statements
&& and || follow short-circuit evaluation.
That is these operators wont execute right side expressions if not needed.
for && operator if false at LHS, then it wont execute next expressions
for || operator if true at LHS, then it wont execute next expressions
so for your condition check it needs && operation for avoiding NullPointerException
if(null!=values && values.length>0)

How to call a Java function in the 'when' part of the drools rule?

I have been searching for a while now, but I can't find the exact answer to my question anywhere, or if I find something similar, it doesn't works.
I want to call a simple java method in the when part of the rule.
My code looks like this:
rule "Ret Rule"
when
Map(this["LOYAL"] == "true")
Map(this["LOYALTYPROMORETENTION"] == "true")
PromotionValidityPeriod(promotionName == "VIVACLUB Loyalty Promo 2013 25 percent")
$customer: Customer( segment == "Residential" , $assets : assets )
$o: Order( ( (DPOrderType == 17 && retentionReason == "RET") || (DPOrderType == 2 && reason == "557") ) , $ct: contractTerms == 24, $olis: orderLineItems )
$tariff: OrderLI( part in ("DT2319", "DT2320"), actionCode not in ("Delete", "INVALID"), $parentId : parentId) from $olis
OrderLI( part == "DT2316", nodeId == $parentId, actionCode not in ("Delete", "INVALID"), $assetId : assetId ) from $olis
/*Asset( assetId == $assetId,
( (contractTerms != null && contractEndDate != null && eval(CalculationsHelper.getFullMonthDifference(new Date(), contractEndDate) < 3 ))
|| (contractTerms == null) ) ) from $assets*/
$li : OrderLI( $newTariff : part in ("DT2319", "DT2320"), parentId == $parentnodeid, actionCode == "Add") from $olis
$del : OrderLI( $oldTariff : part, parentId == $parentnodeid, actionCode == "Delete", productType == "Calling Plan") from $olis
eval(OrderDwrController.setTransitionCondition(fromTariff == $oldTariff, toTariff == $newTariff) == true
then
Offer of = new Offer("DT2331", $parentId, 7);
System.out.println($tariffOld);
of.getOrderLineItemAttributes().add(new OrderLIAttribute("DURATION", "" + $ct));
of.getOrderLineItemAttributes().add(new OrderLIAttribute("Discount of MRC", "25%"));
of.getOrderLineItemAttributes().add(new OrderLIAttribute("VIVACOM TV Package", $tariff.getProductNameENU()));
of.setProductNameENU("VIVACLUB Loyalty Promo 2013 25 percent");
$o.addOffer(of);
of.setLoyaltyPromo(true);
$o.addTextForOffer(of, new Integer[]{173});
end
The particular line where I have a problem is the very last one in the when part:
eval(OrderDwrController.setTransitionCondition(
fromTariff == $oldTariff, toTariff == $newTariff) == true
I just want to call a simple function
(OrderDwrController.setTransitionCondition(
fromTariff == $oldTariff, toTariff == $newTariff))
like the one above mine
(eval(CalculationsHelper.getFullMonthDifference(
new Date(), contractEndDate) < 3 ))
The function is static, returns a boolean value. I have imported the class in the beginning of the file.
What am I doing wrong?
1st of all you didnt close the eval().
2nd if you upgrade your drools you could just write java expressions in the then section and it'll be faster than eval()
Sorry for posting an answer instead of just replying to you (Don't have enough reputation yet :))
Whatever you put inside an eval must evaluate to a boolean. I am not sure yours is. That could be the problem.
Hope that helps
Cheers,
Avinash

Unknown while loop usage

This page a user must choose between one of 2 checkboxes 5 times. So I wrote this:
if (box1a.isSelected() == true || box1b.isSelected() == true) {
if (box2a.isSelected() == true || box2b.isSelected() == true) {
if (box3a.isSelected() == true || box3b.isSelected() == true) {
if (box4a.isSelected() == true || box4b.isSelected() == true) {
if (box5a.isSelected() == true || box5b.isSelected() == true) {
with some other things he does when it is true.
} else {
new Error("You must select an answer at all the questions");
}
Then he only returns a error if you don't check one of the top checkboxes. Then cleary I need a while loop in there but i don't know how to uhm do it. I know how a while loop works but don't know how It would look in this situation. Please help
Also now I have to do the same with text fields and using th same methode that I got answered by you guys doesn't work. any advise?
if ((box1a.isSelected() || box1b.isSelected()) &&
(box2a.isSelected() || box2b.isSelected()) &&
(box3a.isSelected() || box3b.isSelected()) &&
(box4a.isSelected() || box4b.isSelected()) &&
(box5a.isSelected() || box5b.isSelected()))
{
//true stuff
}
else
{
new Error("You must select an answer at all the questions");
}
You should never shouldn't test for true with ==. It is poor style, better to just use the return value from isSelected()
if ((box1a.isSelected() == true || box1b.isSelected() == true) &&
(box2a.isSelected() == true || box2b.isSelected() == true) &&
(box3a.isSelected() == true || box3b.isSelected() == true) &&
(box4a.isSelected() == true || box4b.isSelected() == true) &&
(box5a.isSelected() == true || box5b.isSelected() == true)) {
//DO SOMETHING IF TRUE
}
else {
new Error("You must select an answer at all the questions");
}
No looping needed ^_^
why don't you use radio button (with a default radio button checked) in this case ?
A general strategy would be something like this:
bool flag = true;
do{
//search for input
if (/*the input is valid*/)
flag = false;
}while (flag);
But if you hard code so many options, you might have the wrong design. Try something like a radio button like Jerome C. suggested.
if(!box1a.isSelected() && !box1b.isSelected()) {
// You must select an answer at all the questions
}
else if (box1a.isSelected() && box1b.isSelected() && box2a.isSelected() && box2b.isSelected() && box3a.isSelected() && box3b.isSelected() && box4a.isSelected() && box4b.isSelected() && box5a.isSelected() && box5b.isSelected()) {
// with some other things he does when it is true.
}
A few points to note here.
Avoid using class names like Error as they're normally used for genuine java.lang.Error logic.
If you have a boolean, you don't need to use a == operator.
Not sure why you want a while-loop. If you are thinking that the user must "stay in the loop" while the your condition (all 5 questions answered) is not met, then it is unnecessary. The Event Dispatch Thread (EDT) will continue running the "loop" for you.
On the other hand, if you are looking for a compact way to verify all of your checkboxes, you can change how they are declared from (assuming) javax.swing.JCheckbox box1a; etc. to either a fixed array or an ArrayList which you can then iterate over with a for-loop.

Categories

Resources