Equivalent boolean statements have different results - java

I am confused about how && operator is working
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
Above statement is coming as true
while
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
is evluaated as false.Only difference between the 2 statements are braces.
As an additional input i have checked it with debugger and
StringUtils.isNotEmpty(cartModification.getStatusCode() =true
cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)=true
I just added extra parenthesis in the second part and it was evaluated as true, Data is same as i have pointed out in question.

Since the commentbox isn't really approriate for this one:
How about trying this in a single run.
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
System.out.println("First try is true");
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
System.out.println("Second try is true");
No matter what, you should either get no or two lines (since both statements are the same).
Note it's possible that just one line is printed, this means that any call on getStatusCode() invokes a change on any value used in at least one of the conditions.

Related

Understanding if statements

I have done thorough research on If statements in java, but I can't for the life of me understand them.
I get that you're supposed to put in a sort of true or false statement and if it meets the requirements of the if Statement then it does something. I however do not fully understand how to write them. If someone can possibly write an example and explain it that would be much appreciated.
If statements are sometimes hard to understand if they aren't explained well. In hopes to help I'll show you some examples and explain how they work.
First you need to understand that an if statement is not as simple as True or False. It works more as if the given situation in code meets the requirements you set for it between the parenthesis it will run the code inside the brackets of the if statement.
Example 1:
int x = 5;
if(x == 5)
{
System.out.println(" X is equal to 5");
}
Whats happening hear is you are initializing the int x to be 5 and then the if statements runs to see if x is equal to 5. Since it is the code inside the if statement is run and it prints out the sentence. X is equal to 5.
If the the int x was equal to anything but five in this situation the if statement would not run the code inside because it failed to meet the requirements. Similarly you can use different operators such as; does not equal(!=), greater than or less than(<, >), and greater to or equal to and less than or equal to(<=, >=).
If you want to get more complex you can go as far as to add and or or operators in(||, or &&). This allows you to set multiple requirements in one if statement.
Example 2:
int x = 5;
int y = 2;
if(x == 5 || y == 5)
{
System.out.println("I <3 if statements");
}
What is happening in this example is the if statement is checking to see if either y or x is equal to 5. Since one of them is (x) it runs the code inside the if statement printing out the sentence. I <3 if statements.
With the use of the or operate only if neither of the requirements are met will it not operate the code inside. Having both the requirements be met is fine because at least one of them are.
Also when using || you are not limited to only 2 requirements you can go on to make as many as you desire.
Example 3:
int x = 5;
int y = 2;
if(x == 5 && y == 2)
{
System.out.println("Coding is fun");
}
With the and operator, the if statement checks to see if both the requirements are met. In this example since x is equal to 5 and y is equal to 2 the code in the if statement will run printing the text. Coding is fun.
If you look to get more in depth you can also use else if and else statements. How the work is simply if the requirements of the previous if statements were not met than it will either run the code if it is an else statement or check to see if the next set of requirements are met in the else if statement.
Example 4:
int x = 5;
if(x == 1)
{
System.out.println("X is 1");
}
else if(x == 3)
{
System.out.println("X is 3");
}
else
{
System.out.println("X is unknown");
}
What is happening is that the original if statement is checking to see if x is equal to 1. Since it is not the code inside the if statement is not run and it moves on to the else if statement. The else if statement is checking to see if x is equal to 3. Once again since it is not it skips over the code inside the else if statement and moves the the else statement. With the else statement since there is no requirements it runs the code inside no matter what and finally prints out the sentence. X is unknown.
In the event that the requirements in one of the previous statements(if, or else if) is met it will run the code inside the given one and terminate there. In other words it won't run the else regardless, only if everything else fails.
I hope I was able to help with your problem. Enjoy your coding experiences! :)
I'm not sure what you mean by "thorough research on If statements", but the principle is simple.
There's always some kind of expression that might turn out to be true or false. It's written in parentheses. Then there's a bunch of statements that are usually (but not always) written between curly braces. Some naughty developers sometimes omit the braces, if there's only one statement, but it's arguably best not to do this.
The computer starts by working out whether the expression in parentheses is true or false. If it's true, the statements in the braces are run. If it's false, the statements in the braces are ignored.
For example,
if (today.equals("Friday")) {
developers.goHome("early");
managers.stay("late");
}
Here, if today.equals("Friday") turns out to be true, the two statements inside the braces are run. Otherwise, they are not.
Let's say you have a value x that you want to check if it's bigger or smaller than five for example you can do this :
int x ;
if(x>5) { // you're checking if x is bigger than 5
// If true print it's bigger...
System.out.print("It's bigger than five");
}else{ // anything else (if not bigger) print it's not bigger...
System.out.print("It's not bigger than five");
}
So if x was 6 for example output would be
It's bigger than five

if conditionals : boolean expression variables placing order [duplicate]

This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 5 months ago.
When we're using an if-conditional, we specify the condition in a boolean expression such as following :
if(boolean expression).
If I have two variables in a boolean expression, such as (bagWeight > WEIGHT_LIMIT), does the order of the two variables in which they appear matter? In other words, can I swap those two variables' places such as following? (WEIGHT_LIMIT < bagWeight). Notice it would still be bag weight is less than weight limit, but I just switch the order of which one appears first in the boolean expression. AND Does it depend on which one becomes a subject, like one that gets focused on and evaluated? (In this case, we're trying to figure out if the bag weight is heavier than the limit or not. So the bag weight gets evaluated according to something.. I would call it a subject.)
Eclipse doesn't scream at me that it's wrong, and intuitively it makes sense, but somehow it just bothers me whether there's a more common programming practice or not. So my questions were, can I swap the two variables' places and would not matter? and does it depend on the context of which being a subject? and which is a more common programming practice?
You can freely change the order of the two variables as you prefer. Eclipse (or the compiler) doesn't care, it just evaluates the expression and returns a value, either true of false.
can I swap those two variables' places such as following? (WEIGHT_LIMIT < bagWeight)
Yes, it will still work exactly the same.
Order only comes in to play when using short circuit operates such as || or &&.
examples:
if (boolean1 || boolean2)
In this case, boolean1 will be evaluated first. If it evaluates to true, then boolean2 will not be evaluated, since the first one meets the criteria of the if statement.
if (boolean1 && boolean2)
In this case if boolean1 is evaluates to false, then boolean2 will never be evaluated because the fact that boolean1 is false means that even if boolean2 was true, the condition of the if statement would never be satisfied.
Hope that helps.
The order that Java evaluates && and || is not so important if everything is already evaluated into variables as in your example. If these where method calls instead then the second part of the "if" will not be called unless necessary. Examples of when the myMethod() would not be evaluated at all.
if (true || myMethod())
or
if (false && myMethod())
That's why you might see statements similar to this in actual code.
String myStr = null;
if (myStr != null && myStr.trim().size() > 0)
If Java were to evaluate the second part then you would get a NullPointerException when myStr is null. The fact that Java will bypass the second part keeps that from happening.
The order of the operands doesn't matter in your specific case. Since the if statement is comparing two values, the two values must be evaluated. However, there are some cases when order does matter:
|| and &&
|| and && are shorthand logic operators. The second operand of || will not be evaluated if the first is true. The second operand of && will not be evaluated if the first is false.
++ and --
These can yield different results:
if (i++ > i)
if (i < i++)
In the first line, i is evaluated after the increment is done, so the first operand is 1 less than the second.
In the second line, i is evaluated first, which evaluates to i, then i++, which evaluates to i as well.

Deciding the order in which operators will operate

While deciding the order in which operators will operate, I am confused between following two statement.
Statement will be executed from left to right.
It will be executed according to precedence order of operators.
Following code executes from left to right
int i=5;
boolean b = i<5 && ++i<5;//line2
System.out.println(i);//prints 5
//left to right execution in line2.
//< is executed and ++ is not.Even though ++ has higher precedence.
But this code below seems to follow precedence order:
int a=1,b=1,c=1;
boolean b = a==b&&b==c;//line2: (a==b)&&(b==c)
/* In line2 code would not run from left to right.
First a==b is evaluated then b==c and then && operator.*/
I have asked partially this question here but did't get good enough explanation.
Can someone please clarify?
Assignment works from right to left. In your case, the boolean b will be assigned to whatever the expression on the right evaluates to:
a==b&&b==c
Note that assignment operators have different rules than logical/bitwise operators in terms of precedence (i.e. = doesn't have the same precedence as == or &&).
I think you need to know about logical AND and OR.
something && somethingElse - imagine that expression. It's gonna return true ONLY if both values are true. If both are false, or one of them is false - returns false. So, let's say that the first part is actually false (something=false). Like I said, if anything in this expression is false then there is no need to go further, because no matter what is the second one it's gonna return false anyway. That's why in your first example it doesn't go any further - there is no need, i is already not less than 5 so there is no reason to check the second part, because it's already gonna be false.
In your second example a==b is true, BUT we can't return true already, we need to check the second one, because like I said, if the second one is false then it has to return false. So the expression needs to go further to check the second part. Not like in first example where we could stop, here we need to keep checking.
When it comes to OR (||) rules are different. Only one of the parts needs to be true (that's why it's called or, this or that, doesn't matter, one truth is enough). So with || if the first part is true the we can return no matter what, but if the first part is false then we need to keep going no matter what, because the second one may be true.
i<5 && ++i<5;//line2
&&
[&&] eval LHS: i<5 to false
[&&] skip RHS: ++i<5 and yield false
And
//line2: (a==b)&&(b==c)
a==b&&b==c;
&&
[&&] eval LHS: a==b to true
[&&] eval RHS: b==c to true, yield true
The && is a short-cut operator that does not evaluate the right hand side.
The precedences are important for binary operators. The precedence of unary operators cannot reorder anything, but traditionally it has higher precedence, as it is tighter bound to the final value, and especially for postfix operators.
The prefix operator ++ has the important characteristic, that it is called before the evaluation of the term to which it is applied.
It goes without say, that the usage above is something to be get shot for, hung on the nearest AVL tree, tiered and feathered and chased out of town.

Why is order of expressions in if statement important

Suppose I have an IF condition :
if (A || B)
∧
|
|
left
{
// do something
}
Now suppose that A is more likely to receive a true value then B , why do I care which one is on the left ?
If I put both of them in the IF brackets , then I know (as the programmer of the code) that both parties are needed .
The thing is , that my professor wrote on his lecture notes that I should put the "more likely variable to receive a true" on the left .
Can someone please explain the benefit ? okay , I put it on the left ... what am I gaining ? run time ?
Its not just about choosing the most likely condition on the left. You can also have a safe guard on the left meaning you can only have one order. Consider
if (s == null || s.length() == 0) // if the String is null or empty.
You can't swap the order here as the first condition protects the second from throwing an NPE.
Similarly you can have
if (s != null && s.length() > 0) // if the String is not empty
The reason for choosing the most likely to be true for || or false for && is a micro-optimisation, to avoid the cost of evaluated in the second expression. Whether this translates to a measurable performance difference is debatable.
I put it on the left ... what am I gaining ? run time ?
Because || operator in C++ uses short-circuit evaluation.
i.e: B is evaulated only if A is evaluated to a false.
However, note that in C++ short-circuit evaluation is guaranteed for "built in" data types and not custom data types.
As per javadoc
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
So, if true statement comes first in the order, it short-circuits the second operand at runtime.
If the expression on the left is true, there is no need to evaluate the expression on the right, and so it can be optimized out at run time. This is a technique called short-circuiting. So by placing the expression more likely to be true on the left, we can expect our program to perform better than if it were the other way around.
You should place the condition that is more likely to be true first because that will cause the if statement to short-circuit. Meaning it will not evaluate the rest of the if statement because it will already know the answer is true. This makes code more efficient.
This is especially useful when your if statement is evaluating expensive things:
if(doExpensiveCheck1() || doExpensiveCheck2()) { }
In this case cause the checks are expensive it is in your benefit to place the most likely check first.
In many cases there is no practical difference apart from a tiny performance improvement. Where this becomes useful is if your checks are very expensive function calls (unlikely) or you need to check things in order. Say for example you want to check a property on something and to check if that something is nil first, you might do something like:
If (a != nil && a.attribute == valid)
{}
Yes exactly, you're gaining runtime, it won't seem much for one operation, but you have to keep in mind that operations will get repeated millions of times
Why perform two evaluations when one is enough is the logic
At runtime if(a||b) will test a first, if a is true it will not waste time testing b therefor the compiler will be 1 execution ahead. Therefore if a is more likely to be true than b this test is also likely to cut 1 line. The total number of lines not executed is tiny on a single line but it’s huge if the statement is nested in a loop of some sort(for,while ,recession or database related queries ). Eg per say we have 1million mins to test data in a database at 1 minute per record (30sec for condition A and 30 sec for condition B). Let A have 80% chances to be true and B have 20% chances to be true. The total time needed if you put A first is 600-000hrs yet it’s 900-000hrs if you put B first.if A is tested first[(0,8*1millions hours)*0,5mins+(0,2*1million hours)*1min]===6000-000hrs : if B is tested first [(0,2*1million hours)*0,5mins+(0,2*1million hours)*1min]===9000-000hrs. However you will notice the difference is less significant if the probability of A becoming true is closer to that of B.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Integer a = null;
Integer b = 3;
Integer c = 5;
if(a != null && a == 2){
System.out.println("both");
}else{
System.out.println("false");
}
}
}
Hello World
false

Strings don't seem to be equal in Java on Android, even though they print the same

I've got a problem that I'm rather confused about. I have the following lines of code in my android application:
System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
System.out.println("Yes it does!");
} else {
System.out.println("No it doesnt");
}
When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".
I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.
Has anyone got any idea what's going on here?
Use String's equals method to compare Strings. The == operator will just compare object references.
if ( CurrentNode.getNodeName().toString().equals("start") ) {
...
Use CurrentNode.getNodeName().toString().equals("start").
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.
You need to use .equals
if ("start".equals(CurrentNode.getNodeName().toString()) { ... }

Categories

Resources