what is the standard guideline to declare the "==" condition? [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
please see the below code:-
if(myVariable==5)
{
//some logic
}
one of my friends says that this is not a good way to write the code as its not per guidelines, however he dont have any reason to it. Is there is a chance of exception with above code or accidental modification?? According to him the better way would have been
if(5==myVariable)
{
//some logic
}
please let me know which is a better way and why??? Do provide links if u have any.

The only reason to write:
5 == variable
instead of
variable == 5
is that in the former case if you incorrectly put an assignment (single =) in place you will get a compile time error because you are trying to overwrite a constant.
However any decent compiler will give you a warning if you do:
if (variable = 5)
so IMHO it's not worth worrying about. I always use the latter if (var == num) form.
However in Java there is a common pattern that is worth using. When testing a string for equality, one should use:
if ("constant".equals(variable)) { ... }
instead of:
if (variable.equals("constant")) { ... }
since the latter can trigger a null pointer exception, and the former cannot.

The reversal is preferable in some languages like C, where
if (x = 5) {
...
}
would accidentally assign x to the value 5 if you mistype = instead of ==. By reversing the two arguments the compiler would rightfully object to you reassigning the value 5.
Unlike C/C++, for languages such as Java it's not such an issue since
if (x = 5) {
...
}
isn't a valid statement. I still follow the above practise however. I don't have to rethink when swapping between Java and C/C++.

Both are same. select which ever you find more readable.. I would go with first

For that specific case, it's technically safer to do 5 == variable because then if you accidentally say 5 = variable the compiler will complain. On the other hand, variable = 5 is perfectly legal.

This convention is to prevent you from accidentally writing if (myVariable=5) when you mean if (myVariable==5).

For ==, it doesn't matter a bit what order you do it in.
Your friend mentioned "guidelines"-- perhaps it's a business rule? Albeit an arbitrary and semi-pointless one...

It's immaterial. I prefer the first one, because it's more readable.
I hope you're aware that using == is not always correct for reference types. In those cases you should prefer equals. THEN it matters, because you want to avoid null pointer exceptions. It's best to dereference the instance that cannot be null in that case.

There is no such guildline I found.
First approach should be followed because it is more readable.

i think if you what to know if they are equals it's fine then.
but if you want to know about string, then i more appropriated use '.equals'.
e.g:
object.equals("something");

The only thing I can think of is to avoid possible syntax errors of the kind constant = expression, or to avoid mangled operator overload in C++. In Java both expressions are syntatically valid and picking one over the other is a matter of choice.

Related

why use null != anything instead of anything!=null? [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 7 years ago.
I have seen various codes of my seniors and they have used this at many places.What effect does it have? why cant they include anything != null. This is true for below thing too
"true".equals(x).
Why is this so?
anything != null is exactly equivalent to null != anything.
On the other hand, "true".equals(x) avoids the need to check if x is null when doing x.equals("true").
The reason for including constants on the left hand side of an equals expression is to avoid NullPointerException even when the variable is null. This also improves the readability of the expression.
That being said, null!=something is a personal choice and I would prefer using something!=null.
These are two separate practices.
Using null on the left side when comparing to null ensures that you won't, by mistake, use = instead of ==. However, this is a practice taken from languages other than Java, as in Java the expression
if ( something = null )
is going to fail as it does not resolve to a boolean value. In other languages it may be permissible to use a condition whose value is actually a pointer.
Thus this practice has no meaning in Java.
The second practice, as you were told, has to do with preventing a NullPointerException. It should be noted that this practice is controversial, because it allows a null to propagate to a later point in the program, and that usually means that it will be harder to find when it causes a bug.
This is called a Yoda condition. Among other things, it helps prevent an accidental assignment due to a missing = or !, as in foo = null. The reverse, null = foo, would not even compile.
That said, it is purely a stylistic preference. foo != null is logically equivalent to null != foo.
That check is so the program ensures the variable in question has been initialized before reading it. If a program tries to access a null variable, it will crash (specifically in Java it will throw a NullPointerException). It is a critical aspect of defensive programming.
As far as ordering, the evaluation of whether something is null or not is commutative. Meaning:
something != null
Is the same as
null != something
It is all a matter of personal preference. And as #manouti explains above, "true".equals(x) avoids the need to check if x is null when doing x.equals("true"), so you save a line of code.
Seems that some people prefer null != anything, because anything might be quite long expression, so writing null first makes it visible in the narrow window and simplifies code reading ("ok, we just check if something is not null"). But it's totally a matter of style.
As for "true".equals(x), it's well explained by #manouti.

Comparing Boolean Value

I have a checkBox named as testCheck. When user check this the value becomes TRUE. I am able to implement the compare of the TRUE/FALSE with the following ways
1.
if (testCheck.getValue() == Boolean.TRUE) {
// Respective Code
}
2.
if (testCheck.getValue().equals(Boolean.TRUE)) {
//Respective Code
}
3.
if (testCheck.getValue()) {
//Respective Code
}
My questions:
Is there any difference ?
If yes, Which one is the best way of implementation ?
It depends....
if the return type of testCheck.getValue() is boolean, the 3rd one is ok.
But if it was Boolean (Big B), I would do:
Boolean.TRUE.equals(testCheck.getValue())
to avoid the NPE during autoboxing.
The answers:
There's no difference for compiler: a good optimizer will generate the same code. But there's difference for human beings (developers, testers, supporters etc): it's readability.
The 3d option is far more natural and that's why easier to read.
So the expected code (least surprise principle) is
if (testCheck.getValue()) {
...
//Respective Code
}
I prefer 3rd option. It's elegant. Since the testCheck.getValue() evaluated to boolean, you can use it inside the if condition
In java, with == operator, we are checking two reference are referring same object in memory.
To check two object are meaningfully equal, use .equals() method.
Is there any difference ?
There is only a difference in readability.
If yes, Which one is the best way of implementation ?
The last one is probably the way to go if you want your code to be read and understood fast.
Is there any difference ?
Yes, there is.
If yes, Which one is the best way of implementation ?
3rd one.

Ternary Operators Java [duplicate]

This question already has answers here:
Ternary Operator
(4 answers)
Closed 5 months ago.
Is there a way to implement this in a ternary operation. I'm very new to that ternary stuff, maybe you could guide me.
if(selection.toLowerCase().equals("produkt"))
cmdCse.setVisible(true);
else
cmdCse.setVisible(false);
This one doesn't seem to work.
selection.toLowerCase().equals("produkt")?cmdCse.setVisible(true):cmdCse.setVisible(false);
In this case, you don't even need a ternary operator:
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
Or, cleaner:
cmdCse.setVisible(selection.equalsIgnoreCase("produkt"));
Your version:
selection.toLowerCase().equals("produkt")? cmdCse.setVisible(true): cmdCse.setVisible(false);
is semantically incorrect: ternary operator should represent alternative assignments, it's not a full replacement for if statements. This is ok:
double wow = x > y? Math.sqrt(y): x;
because you are assigning either x or Math.sqrt(y) to wow, depending on a condition.
My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.
Perhaps
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
The ternary operator isn't exactly like an if statement. A ternary operator has to "return" something from both sides, so putting void method calls like setVisible() there won't work.
Instead, you could do something like this without ternary operators at all:
cmdCse.setVisible(selection.toLowerCase().equals("product"));
But just to demonstrate the point, the ternary equivalent would look something like this:
cmdCse.setVisible(selection.toLowerCase().equals("product") ? true : false);
Notice how now the ternary operator "returns" true or false on both sides instead of simply calling a void method.
I think this will work for you
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
Directly from the docs
Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).
In your case cmdCse.setVisible(true / false); doesn't return anything, and the operation also has side effects (it changes state of cmdCse), so the conditional operator cannot be used here (when you do use the operator, both of the ? and : branches must have the same return type).
As an aside, please note that .. ? .. : .. should be referred to as the conditional operator
On the issue of using exceptions
I want to answer the issue of the exceptions here as this question is a duplicate for another question concerning throwing exceptions from a ternary expression, but this is not addressed in the above answers.
The general consensus is that it cannot be done directly as in:
public Character next() {
return hasNext() ? s.charAt(cur++) : throw new NoSuchElementException(); // compilation error
}
will give you a compilation error, but as Clement pointed out it can be done via a declared extra function. It can also be done via (ab-)using lambda expressions.
public Character next() {
return hasNext() ? s.charAt(cur++) : ((Function<Integer, Character>) x -> {throw new NoSuchElementException();}).apply(1);
}
for sure this is not that pretty (it is pretty ugly) and I would not recommend to do that for readability purposes, but sometimes there are circumstances which might warrant exceptionally doing that. If someones figures out a way to do it without the cast it would be a bit more readable.
If you had a function throwNoSuchElementException() defined somewhere that you use more than once, it would look a bit more readable:
public Character next() {
return hasNext() ? s.charAt(cur++) : throwNoSuchElementException();
}
(P.S.: I included this answer for completeness sake, as I asked myself can it really be not done?)
(P.S.S.: If the exception to be thrown is not a runtime exception this will not work so easily and would require even more handstands - not really worth it)
Here are my tips, if you need to set things to booleans, then simple use setBoolean(condition), else, if you need to set a variable to a non boolean value, then use var=condition?result1:result2(or the variable itself if you don't want to change if condition is false), otherwise, use if else.

Null check coding standard [duplicate]

This question already has answers here:
Which has better performance: test != null or null != test [duplicate]
(8 answers)
Closed 9 years ago.
I have a doubt regarding coding standard of a null check.
I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?
Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use null != a.
The null != a is an old practice in programming languages like Java,C++ (called as Yoda Conditions).
As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.
There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".
Once I was working in a project where the coding guideline was to use if (null != a) because they thought it is easier for the developer to understand that the constant value has to come first always (as in CONSTANT_VALUE.equals(variable). That was pretty annoying to me.
They're both the same. It depends on your coding style.
From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.
No difference betwwen them if statement works based on result of expression
so u write either if(a!=null) or if(null!=a) will produce true or false then result is evaluated.
So it doesnt matter you write which you like
They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null
Example "some value".equals(your_variable) , some value can be any value you know is not null. This will avoid NPE when your_variable is null.
String str = "somevalue";
if(str != null && str.equals("somevalue")) { }
if("somevalue".equals(str)) { }
Both the conditions will be same if str is null or not.

Which has better performance: test != null or null != test [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 2 years ago.
Consider the following two lines of code
if (test ! = null)
and
if (null != test)
Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error.
So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.
They are exactly the same. The second one can make sense when using equals:
if("bla".equals(test))
can never throw a NullPointerException whereas:
if(test.equals("bla"))
can.
There is no performance difference but I personally find the second one being confusing.
Second one looks for me like "Yoda condition", i.e. if(2 == x) ... and is much less readable.
It's best practice to avoid some basic typo's that most modern IDE's will pick up, because sometimes you want to do comparisons between more complex types that are not null and end up doing accidental assignments. So the pattern remains the same, but I've never seen this linked to performance and have never seen it generate special byte code.
The idea is to have the static, known value first, so you can't throw any kind of weird exception when you perform the comparison.
Neither of the two methods are "more correct" though, so it's entirely up to you to decide what you wish to use.
there is no difference. But in second way you avoid the typo like test = null. Beacause in second way you'll get compiler error.
It's not a best practice to use the latter one. Both are equivalent, but the former is easier to read.
This "best practice" comes from C where boolean don't exist. Integers are used instead, and if (foo = 1) is not a syntax error, but is completely different from if (foo == 1).
In Java, only boolean expressions can be inside an if, and this practice doesn't make much sense.
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read codes Left-To-Right.
Second form is better for code writer, because in java = operator is for assignment and == operator is for test equivalent, but people usually using in if statement = instead of ==, by second approch developer getting Compile-Time-Error because null can't use in Left-Side of a assignment statement.

Categories

Resources