It seems that string comparison cannot simply be done by "==" operator as I read from explanation that in java and c#:
In Java I saw this explanation:
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically "equal").
In c# I saw this code:
if (parametrii[0].Equals("teach"))// to check the equality of values
It makes sense to me that "==" is checking of addresses and .equal() is just checking values.
However I have been using "==" in python and c++ all the time and I have never encounter such errors for examples
In python:
string1 = "helloworld"
string2 = "helloworld"
print(string1 == string2)// result true
In c++:
while(getline(ifs, line2)){
stringstream ssm(line2);
string from_stop;
string to_stop;
getline(ssm, from_stop, ',');
getline(ssm, to_stop, ',');
if(from_stop == to_stop){
adjList[from_stop].push_back(to_stop);
}
}
or
bool stop124 = false;
bool stopA24 = false;
bool stop126 = false;
for (int i = 0; i < adjVec.size(); i++) {
if (adjVec[i] == "124") stop124 = true;
else if (adjVec[i] == "A24") stopA24 = true;
else if (adjVec[i] == "126") stop126 = true;
}
Those code will successfully compile and get the correct results of comparing value. I know there is a strcmp() function in c++ but I rarely use it and don't quite know when to use it rather than == in checking whether two strings are equal in value.
So my question is that is this because there is a difference among those programming languages or it is just for me to be lucky that I did not run into those errors?
Since Java does not allow operator overloading, they had to resort to creating a function (Equals) to compare for 'true' objects equality - and leave operator == to perform pointer comparison. This choice can not be really justified by any other reason, as it warrants for illogical code, more typing in generalized case (people usually compare for true equality, not pointer equality) and steeper learning curve.
C++ with a clear distinction between pointer and an object is not constraint by Java limitations, and thus allows proper value-semantics for classes and intuitive forms of comparison.
Python compares string lexicographically i.e using ASCII value of the characters, so you can use the == operator. Java creates a string object, and thus you have to use the .equals() method to check the value.
So to answer you questions it's the language that are different. If you are trying to compare 2 strings in C++ I'd use the compare method.
If x and y are int variables. Are the following two segments of Java code behaviourally equivalent for all values of x and y? Explain why, or why not.
Version 1:
if (x > 10)
{
if (y < 20)
{System.out.print("hi");
}
}
Version 2:
if (x > 10 && y < 20)
{
System.out.print("hi");
}
I think it is equivalent but I just want to make sure I'm not missing anything. I don't see how they cannot be equivalent. Thanks.
Yes, they are completely equivalent. In situations like these it comes down to picking the one you think is clearest.
Yes, they are.
The important point which might not be so obvious is that in both versions the second comparison is only evaluated if the first one results in 'true'.
Yes, they are equivalent, but the second one is shorter, and you can add a single else clause, which you cannot do in the first, because you'd have to write two independent else clauses there.
Whether one or two else clauses should be used depends on what your logic requires, so both forms may be appropriate.
I would generally recommend the second one, but if you don't need a single else clause, and the expressions are large, the first one may end up being more readable.
Yes they are equivalent also from the semantic point of view.
if ((one.option != two.option) && (one.side == two.side))
I need to check the followng Business Logic above
so i written this way
if((data[0].getData.value()!=data[1].getData.value())
&&(data[0].getAction().value()==data[1].getAction().value()))
Is this correct ??
Assuming data[0] in place of one
getData.value() in place of option shown in the top if condition .
I am concerned about the brackets inside the if condition
It's correct, but personally I wouldn't bother with the brackets in this particular case. I would, however, use more whitespace. I'd write that as:
if (data[0].getData.value() != data[1].getData.value()
&& data[0].getAction().value() == data[1].getAction().value())
If you really want the brackets, I'd write it as:
if ((data[0].getData.value() != data[1].getData.value())
&& (data[0].getAction().value() == data[1].getAction().value()))
I'd normally only include the brackets if I wanted to differentiate between, say,
if ((x && y) || z)
and
if (x && (y || z))
Of course, this is assuming that the values are ones which are appropriate to compare with == and !=. If they're strings or other objects, you should potentially be using equals instead.
Two general comments.
First, consider using tests for this kind of thing, specifically test driven development, where you write the test first, fail it and then only write enough of a test to pass it. Then there will be no mystery whether the code is correct.
This is an exercise that will help you learn that approach.
Second, based on that snippet, it looks like your code could use some refactoring to make the intention clear, for example by putting them into a method with a clear name (in your case probably two) that gets called there. TDD tends to result in that kind of clean code, as long as you take the time to refactor once your tests pass.
Your parentheses are correct.
Your if statement is valid but it is difficult to read. I'd recommend following the advice of others about white-space and assigning the values to variables to improve readability. Well written code shouldn't require comments, it should be self evident what data your working with!
Is it bad to write:
if (b == false) //...
while (b != true) //...
Is it always better to instead write:
if (!b) //...
while (!b) //...
Presumably there is no difference in performance (or is there?), but how do you weigh the explicitness, the conciseness, the clarity, the readability, etc between the two?
Update
To limit the subjectivity, I'd also appreciate any quotes from authoritative coding style guidelines over which is always preferable or which to use when.
Note: the variable name b is just used as an example, ala foo and bar.
It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) over if (b) or even worse if (flag).
As to the performance concern, the compiler optimizes it away at any way.
As to the authoritative sources, I can't find something explicitly in the Java Code Conventions as originally written by Sun, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.
You should not use the first style. I have seen people use:
if ( b == true )
if ( b == false )
I personally find it hard to read but it is passable. However, a big problem I have with that style is that it leads to the incredibly counter-intuitive examples you showed:
if ( b != true )
if ( b != false )
That takes more effort on the part of the reader to determine the authors intent. Personally, I find including an explicit comparison to true or false to be redundant and thus harder to read, but that's me.
This is strongly a matter of taste.
Personally I've found that if (!a) { is a lot less readable (EDIT: to me) than if (a == false) { and hence more error prone when maintaining the code later, and I've converted to use the latter form.
Basically I dislike the choice of symbols for logic operations instead of words (C versus Pascal), because to me a = 10 and not b = 20 reads easier than a == 10 && !(b==20), but that is the way it is in Java.
Anybody who puts the "== false" approach down in favour of "!" clearly never had stared at code for too long and missed that exclamation mark. Yes you can get code-blind.
The overriding reason why you shouldn't use the first style is because both of these are valid:
if (b = false) //...
while (b = true) //...
That is, if you accidentally leave out one character, you create an assignment instead of a comparison. An assignment expression evaluates to the value that was assigned, so the first statement above assigns the value false to b and evaluates to false. The second assigns true to b, so it always evaluates to true, no matter what you do with b inside the loop.
I've never seen the former except in code written by beginners; it's always the latter, and I don't think anyone is really confused by it. On the other hand, I think
int x;
...
if(x) //...
vs
if(x != 0) //...
is much more debatable, and in that case I do prefer the second
IMHO, I think if you just make the bool variable names prepended with "Is", it will be self evident and more meaningful and then, you can remove the explicit comparison with true or false
Example:
isEdited // use IsEdited in case of property names
isAuthorized // use IsAuthorized in case of property names
etc
I prefer the first, because it's clearer. The machine can read either equally well, but I try to write code for other people to read, not just the machine.
In my opinion it is simply annoying. Not something I would cause a ruckus over though.
The normal guideline is to never test against boolean. Some argue that the additional verbosity adds to clarity. The added code may help some people, but every reader will need to read more code.
This morning, I have lost 1/2 hour to find a bug. The code was
if ( !strcmp(runway_in_use,"CLOSED") == IPAS_FALSE)
printf(" ACTIVE FALSE \n"); else
printf(" ACTIVE TRUE \n");
If it was coded with normal convention, I would have seen a lot faster that it was wrong:
if (strcmp(runway_in_use, "CLOSED"))
printf(" ACTIVE FALSE \n"); else
printf(" ACTIVE TRUE \n");
I prefer the long approach, but I compare using == instead of != 99% of time.
I know this question is about Java, but I often switch between languages, and in C#, for instance, comparing with (for isntance) == false can help when dealing with nullable bool types. So I got this habbit of comparing with true or false but using the == operator.
I do these:
if(isSomething == false) or if(isSomething == true)
but I hate these:
if(isSomething != false) or if(isSomething != true)
for obvious readability reasons!
As long as you keep your code readable, it will not matter.
Personally, I would refactor the code so I am not using a negative test. for example.
if (b == false) {
// false
} else {
// true
}
or
boolean b = false;
while(b == false) {
if (condition)
b = true;
}
IMHO, In 90% of cases, code can be refactored so the negative test is not required.
This is my first answer on StackOverflow so be nice...
Recently while refactoring I noticed that 2 blocks of code had almost the exact same code but one used had
for (Alert alert : alerts) {
Long currentId = alert.getUserId();
if (vipList.contains(currentId)) {
customersToNotify.add(alert);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
and the other had
for (Alert alert : alerts) {
Long currentId = alert.getUserId();
if (!vipList.contains(currentId)) {
customersToNotify.add(alert);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
so in this case it made sense to create a method which worked for both conditions like this using boolean == condition to flip the meaning
private void appendCustomersToNotify(List<Alert> alerts
List<Alert> customersToNotify, List<Long> vipList, boolean vip){
for (Alert alert : alerts) {
Long currentId = alertItem.getUserId();
if (vip == vipList.contains(currentId)) {
customersToNotify.add(alertItem);
if (customersToNotify.size() == maxAlerts) {
break;
}
}
}
}
I would say it is bad.
while (!b) {
// do something
}
reads much better than
while (b != true) {
// do something
}
One of the reasons the first one (b==false) is frowned upon is that beginners often do not realize that the second alternative (!b) is possible at all. So using the first form may point at a misconception with boolean expressions and boolean variables. This way, using the second form has become some kind of a sjiboleth: when someone writes this, he/she probably understands what's going on.
I believe that this has caused the difference to be considered more important than it really is.
While both are valid, to me the first feels like a type error.
To me b == false looks as wrong as (i == 0) == false. It is like: huh?
Booleans are not an enum with 2 possible values. You don't compare them. Boolean are predicates and represent some truth. They have specific operators like &, |, ^, !.
To reverse the truth of an expression use the operator '!', pronounch it as "not".
With proper naming, it becomes natural: !isEmpty reads "not is empty", quite readable to me.
While isEmpty == false reads something like "it is false that it is empty", which I need more time to process.
I won't go into all of the details at length because many people have already answered correctly.
Functionality-wise, it gives the same result.
As far as styling goes, it's a matter of preference, but I do believe !condition to be more readable.
For the performance argument, I have seen many say that it makes no difference, but they have nothing to justify their claims. Let's go just a bit deeper into that one. So what happens when you compare them?
First, logically:
if(condition == false)
In this case, if is comparing its desired value to execute with the value between the parentheses, which has to be computed.
if(!condition)
In this case, if is directly compared to the opposite(NOT) of the condition. So instead of 2 comparisons, it is one comparison and 1 NOT operation, which is faster.
I wouldn't just say this without having tested it of course. Here is a quick screenshot of the test I did. !condition is nearly twice as fast over 10 million iterations.
https://imgur.com/a/jrPVKMw
EDIT: I tested this in C#, compiled with visual studio. Some compilers may be smarter and optimize it properly, which would make the performance 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()) { ... }