"If" statement, constant equality [duplicate] - java

This question already has answers here:
Which is more effective: if (null == variable) or if (variable == null)? [duplicate]
(9 answers)
Closed 4 years ago.
Possible Duplicate:
Order of condition checking?
When i read some source codes, the if statement is coded in this way,
if (1 == a) {
...
}
instead of
if (a == 1){
...
}
I read a programming book about the advantage of this way, but cannot remember exactly what it is about. Any one know about this ?
(Sorry if this question disturbs you :-) )

The advantage is compiler will tell you that error right away. For example, a = 1 will compile but will produce an error at run time whereas 1 = a will produce an error at compile time since 1 is not a valid lvalue.
Example: this will produce an error right away:
int a = 0;
if(1 = a) {
print("test");
}
Whereas this will compile (warnings may be produced depending on the compiler) but it will cause issues at run time.
int a = 0;
if(a = 1) {
print("test");
}
The main idea here is to make certain that you are using == in a condition instead of =.
That being said every modern compiler (ie. Eclipse) will treat the above as an error now. So it's not as big of a deal as it used to back in the notepad and vi days (in my opinion). I personally prefer the a == 1 since that seems more readable to me.

In classic C, where a condition is an integral expression, it's very easy to write
if (a = 1)
by mistake. The problem is that if you do it, the compiler won't complain, since the assignment evaluates to an integer, too. Writing the expression backward makes it such that if you make this typo, the code won't compile. It's not a bad idea to do this in C; it makes much less sense in other languages.

If you leave out an =, 1 = a is a compiler error, whereas a = 1 is a subtle mistake.

Related

What is the best way to check null in Java [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 5 years ago.
When checking for nulls I use this:
String str;
if(str == null){
//...
}
but I've seen this as well:
if(null == str){
//...
}
Is there any advantage of using one over the other? Or is it just to improve readability?
The second version ( null == str ) is called a yoda condition.
They both result in the same behavior, but the second one has one advantage: It prevents you from accidentally changing a variable, when you forget one =. In that case the compiler returns an error at that row and you're not left with some weird behavior of your code and the resulting debugging.
The null == x convention is usually found in code written by people familiar with C, where an assignment can also be an expression. Some C programmers write code like this so that if they miss an = in
if (NULL == ptr)...
the code will not compile, since NULL = ptr is not a valid assignment. This prevents a rather sneaky error from being introduced in the code-base, although modern C compilers make make such conventions obsolete, as long as one takes care to enable and read the generated warnings...
This coding style has never had any usefulness in Java, where reference assignments cannot be used as boolean expressions. It could even be considered counter-intuitive; in their natural language most people will say "if X is null...", or "if X is equal to 17...", rather than "if null is equal to X...".
There's no difference between the two other than readability. Use whichever makes more sense to you.
As you stated readability is the most important reason. Reading it out loud, the (null == str) does not read well. It's almost like reading right to left. (str == null) reads much better.
In addition, I think the following needs to be taken into consideration:
if (str != null)
if (str == null)
vs.
if (null != str)
if (null == str)
I would expect the positive (str == null) and the negative to be written in the same manner, which is another reason I would favor the top set.
if (null == str) {
}
is a programming idiom from c/c++, where the assignment operator = can be used to resolve to a true/false statement. For example in c if you want to check if I can open a stream in c/c++, you can
if (myStream = openStream())
which sets opens and assigns in one line. However, this means that people often type = when they mean ==, and it would be valid syntax in c: for example if (x = 5) will always resolve to true, when they really mean if (x ==5). So people write if (5 == x) so if you leave out a = your code won't compile.
This doesn't apply to java.
There is no real difference. However the second is considered less error prone. In the first case you would not get an error if you tried to do
String str;
if(str = null){
}
which is something you usually don't do in conditionals.
Also, you get to think about the actual condition first, which is a good practice.
if(a==b) {} is the same as if(b==a) {} , and the same is true if b was null. It's just a style/order difference as far as functionality, at least in java.
Some developers argue that var == null is more error-prone than null == var. Their argument is that you might accidentally assign the variable instead of doing a null-check.
But only when the variable you test against null is a Boolean you can accidentally use the = instead of == and it will compile.
Boolean checked = Boolean.TRUE;
if(checked = null){ // accidentally assigned null and compiles
}
Only in this case the assignment compiles, because the conditional expression must evaluate to a boolean value. See JLS-14.9. Since the assignment expression itself evaluates to a boolean type, it compiles. But you will get a NullPointerException at runtume, because java will try to unbox the checked variable which is null.
If you use any other type then Boolean you will get a compiler error. E.g.
String str = "hello";
if(str = null){ // compiler error, because str = null doesn't evaluate to a boolean
}
My conclusion is that error situations are extremly rare and you can easily write unit tests that detect such errors.
So write the if-statement it in the way it is more readable.
I think "if name is null" makes more sense then "if null is name".

Is it appropiate the statement. if (0 != expression or variable) {} in java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm working on a java source code that has the style:
if (0 == var) {}
and
if (null == someObj) {}
or
if (0 != var) {}
and
if (null != someObj) {}
Should I rewrite it to:
if (var == 0) {}
and
if (someObj == null) {}
?
Thanks in advance!.
It's perfectly valid to have:
if (0 == var) {}
and
if (null == someObj) {}
It's famously called yoda condition to prevent accidental use single = in place of ==.
I personally never used it. But some people like it. It's really a matter of taste.
However, it's of no use in Java. Because, such an accidental typo is caught at compile time.
The following would give a compile time error in Java.
if( var = 0 )
{
//Some code
}
Because assignment operation doesn't yield Boolean value in Java.
However, in languages like C/C++, the above is valid and compiler would give no errors if warnings are not enabled. The above if condition will always evaluate to false (0) in C/C++. So it may go unnoticed and give unexpected results at run time.
In GCC, with all warnings enabled, it would give the warning for the above in C or C++:
warning: suggest parentheses around assignment used as truth value
So this may not of much use in C/C++ too as one is expected to compile with all warnings and fix all warnings. As I said before it's a personal choice and makes no difference.
So if ( 0 == var){} is a valid syntax and is same as if (var == 0) {} and if you prefer Yoda conditions it, go for it!
In general to write 0 == n is called a yoda condition. Because if you say it loud you say if zero equals my var.
It is better to write n == 0. But it is exactly the same. But it is read better.
Some of the pros of the condition does not apply to java.
if (value = 42)
yields a compile error. value = 42 yields an int which is not a valid input in an if in java. But perfectly legal in C.
To compare using the constant on the left side is a common best practice. But only if using Object equals method.
if ("CONSTANT".equals(myString))
if myString is null or you are comparing primitives since there is no .equals() access to the variable theres no point in checking null.
if ( "CONSTANT" == null )
Although is only my opinion, the benefit is legibility only.
This type of terms is known as "Yoda expressions", because they are "backwards" compared to English natural language.
I don't think it pays of with assignments - good code audit tools catch these types of errors, and most should already be caught by the more strict Java compiler (using = instead of == was a common typo in C!)
However, when you are using compareTo methods, you need to consider null values.
if ("example".equals(input))
cannot run into a NullPointerException, while the more "natural"
if (input.equals("example"))
can, and needs extra checking for null values.
The first style is preferred by some because saying var = null instead of var == null by accident would be a bug that would be hard to catch in languages like C and C++, but null = var would be easy to catch, as it wouldn't compile. As noted in the comments, this doesn't apply for Java because null = var isn't a boolean expression.

Multiple && Statements - Efficiency [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does Java evaluate remaining conditions after boolean result is known?
When executing code with multiple && statements in java, does the compiler continue to resolve additional boolean comparisons if the first one resolves to false?
if (1==2 && 3==4 && 4==5) { Do Something }
Once determining 1==2 is false, will the compiler immediately break out of the if statement or will it continue to resolve 3==4 and 4==5 after?
In the case of && it'll stop evaluating the moment it detects that one of the conditions is false. This is called short circuit evaluation.
"SHORT CIRCUIT EVALUATION IN PROGRAMMING LANGUAGES"
In the case of any logical expression most compiler stop evaluation expression as soon as result evaluated. its not only in Java but in almost in every language. (but not all e.g. VB6)
You can also check it as follows:
i = 0 , j =1;
i && ++j;
system.out.print(" j=" + j);
The value of j will be 1, it means ++j was not executed.
does the compiler continue to resolve additional boolean comparisons if the first one resolves to false
The short answer. No! The compiler javac and the JIT analyses statically all the code. It doesn't take short cuts like this. e.g. if the second condition doesn't compile, you will always get a compilation error regardless of the first condition.
What you may have intended to ask is; will the program execute the other conditions if the first or second one is false In this case, it will not.
This doesn't make a difference for the compiler -- all it does is resolve the boolean comparisons into machine code, represented by one or more .class files.
As far as the actual runtime... If I remember correctly from Computer Science class, both Tarun's and Lews's answers are correct -- the comparison will short-circuit as soon as it gets to an expression that isn't true.
IF "1==2" is false than the compiler will immediately break out the if statement.
&&
- The above is a short-circuit AND operator. If the 1st condition results in false the 2nd condition is not evaluated.
Eg:
if ((a==false) && (b==true)){
}
The above will stop after the first evaluation.
- If you want to force the evaluation of both the conditions, then try Non-Short Circuit AND (&)
A sidenote to the keyword 'Efficiency' in your title :- as stated by other answers your basic question is easily answered, so it's not a question of efficiency, but a question if you need for some reason all expressions to be evaluated, for example when executing code which changes state (which would be by the way not good coding at all).
But if you think of 'Efficiency' in terms of executing speed, then you almost never have to optimize on that level, either the compiler will do it for you or you wouldn't notice the difference. It may be important in some time critical operation or in operations which run in very big loops, but in nearly every other case, it's much more important to write clean code, so that another human can read it well.

Checking for null - what order? [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 5 years ago.
When checking for nulls I use this:
String str;
if(str == null){
//...
}
but I've seen this as well:
if(null == str){
//...
}
Is there any advantage of using one over the other? Or is it just to improve readability?
The second version ( null == str ) is called a yoda condition.
They both result in the same behavior, but the second one has one advantage: It prevents you from accidentally changing a variable, when you forget one =. In that case the compiler returns an error at that row and you're not left with some weird behavior of your code and the resulting debugging.
The null == x convention is usually found in code written by people familiar with C, where an assignment can also be an expression. Some C programmers write code like this so that if they miss an = in
if (NULL == ptr)...
the code will not compile, since NULL = ptr is not a valid assignment. This prevents a rather sneaky error from being introduced in the code-base, although modern C compilers make make such conventions obsolete, as long as one takes care to enable and read the generated warnings...
This coding style has never had any usefulness in Java, where reference assignments cannot be used as boolean expressions. It could even be considered counter-intuitive; in their natural language most people will say "if X is null...", or "if X is equal to 17...", rather than "if null is equal to X...".
There's no difference between the two other than readability. Use whichever makes more sense to you.
As you stated readability is the most important reason. Reading it out loud, the (null == str) does not read well. It's almost like reading right to left. (str == null) reads much better.
In addition, I think the following needs to be taken into consideration:
if (str != null)
if (str == null)
vs.
if (null != str)
if (null == str)
I would expect the positive (str == null) and the negative to be written in the same manner, which is another reason I would favor the top set.
if (null == str) {
}
is a programming idiom from c/c++, where the assignment operator = can be used to resolve to a true/false statement. For example in c if you want to check if I can open a stream in c/c++, you can
if (myStream = openStream())
which sets opens and assigns in one line. However, this means that people often type = when they mean ==, and it would be valid syntax in c: for example if (x = 5) will always resolve to true, when they really mean if (x ==5). So people write if (5 == x) so if you leave out a = your code won't compile.
This doesn't apply to java.
There is no real difference. However the second is considered less error prone. In the first case you would not get an error if you tried to do
String str;
if(str = null){
}
which is something you usually don't do in conditionals.
Also, you get to think about the actual condition first, which is a good practice.
if(a==b) {} is the same as if(b==a) {} , and the same is true if b was null. It's just a style/order difference as far as functionality, at least in java.
Some developers argue that var == null is more error-prone than null == var. Their argument is that you might accidentally assign the variable instead of doing a null-check.
But only when the variable you test against null is a Boolean you can accidentally use the = instead of == and it will compile.
Boolean checked = Boolean.TRUE;
if(checked = null){ // accidentally assigned null and compiles
}
Only in this case the assignment compiles, because the conditional expression must evaluate to a boolean value. See JLS-14.9. Since the assignment expression itself evaluates to a boolean type, it compiles. But you will get a NullPointerException at runtume, because java will try to unbox the checked variable which is null.
If you use any other type then Boolean you will get a compiler error. E.g.
String str = "hello";
if(str = null){ // compiler error, because str = null doesn't evaluate to a boolean
}
My conclusion is that error situations are extremly rare and you can easily write unit tests that detect such errors.
So write the if-statement it in the way it is more readable.
I think "if name is null" makes more sense then "if null is name".

Troubleshooting Java code that refuses to cooperate

The string called "code" doesn't seem to read. Why is that and how do I fix it?
My code (the snippet that causes problems):
String code;
for(int z = 0; z<x;z= z+0) // Repeat once for every character in the input string remaining
{
for(int y=0;y<2;y++) //Repeat twice
{
c = (char)(r.nextInt(26) + 'a'); //Generate a random character (lowercase)
ca = Character.toString(c);
temp = code;
code = temp + ca; //Add a random character to the encoded string
}
My error report:
--------------------Configuration: <Default>--------------------
H:\Java\Compiler.java:66: variable code might not have been initialized
temp = code;
^
1 error
Process completed.
(I am using JCreator 5.00, Java 7.)
(Yes, the error report looks stupid, but it Stack Overflow reads it as coding.)
What value would code have if x is zero? The answer is it would have no value at all (not even null). You could just initialize it to an empty string if you like:
String code = "";
Java requires that every variable is initialized before its value is used. In this example, there is a fairly obvious case in which the variable is used before it is assigned. The Java Language Spec (JLS) doesn't allow this. (If it did, the behaviour of programs would be unpredictable, including ... potentially ... JVM crashes.)
In other cases, the compiler complains when in fact the variable in question is always initialized (or so it seems). Rather than "understanding" your code, or trying to derive a logical proof of initialization, the compiler follows a specified procedure for deciding if the variable is definitely assigned. This procedure is conservative in nature, and the answer it gives is either "it is initialized" or "it might not be initialized". Hence the wording of the compilation error message.
Here is an example in which the compiler will complain, even though it is "obvious" that the variable is initialized before use:
boolean panic;
for (int i = 0; i < 10; i += 2) {
if (i % 2 == 1 && panic) { // compilation error here
System.out.println("Panic!!");
}
}
The definite assignment rules (specified in the JLS) say that panic is NOT definitely initialized at the point indicated. It is a simple matter for a person who understands the basics of formal methods to prove that i % 2 == 1 will always be false. However, the compiler can't. (And even if it could, the code is still in error given JLS rules.)
You've created a reference, but you've never initialized it. Initialize code by changing the first line to
String code = ""
Edit: Zavior pointed out that you can pull an initialized string from the cache rather than allocate space for a new one.
But why are you assigning temp to code and then code to temp plus something else? It can be set to code = code + ca.

Categories