Why can my Java code run? - java

In Java, if should have {} except when there is only one line under if.
But then, why can the following code run on my computer?
int x=1;
int y=1;
if(x<=4)
if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");
System.out.println("***");
Here is what it looks like on my IDE:
And everything runs good. Here is the result (under it loading other resources, don't care about that. I just modified some of my code to try out the code as soon as possible.)

Java will associate the else to the last candidate if.
Your code (with braces) is equal to
if(x<=4) {
if(y>=4) {
System.out.println("%%%");
} else {
System.out.println("+++");
}
}
System.out.println("***");
A candidate if is matched when there is exactly 1 statement (ending with semicolon) or block between the if and the else.

Thanks for you all and the problem solved.
The point is, if execute the next one statement or block.
Java considers the following code as a whole statement.
`if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");`
And it follows the first if.
The last print is not in the scope of consideration, it's just caused by bad indentation.

This is your code
if(x<=4)
if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");
System.out.println("***");
this is what java thinks
if(Boolean) go to next line
if(Boolean) ok this is false, go to else f

Related

Branching efficiency

The a couple weeks ago I submit a function for code review that looked like this.
Function{
If (condition)
Else If (condition)
Else if (condition)
Else
return value
}
My lead giving the code review said "I hate else if," but he didn't say why or what I should have done instead. He just gave me the go ahead to upload this function.
My question is what are some alternatives to a bunch of "else ifs" that would make the code look more elegant and maybe perform better?
I tried pulling up his code to get an idea of what he would have done and I noticed several times he did
If (condition)
If (condition)
If (condition)
Should I avoid writing "else"? I was going to ask him but he no longer works here.
Thank you
I try to avoid "else", "else if" and also "if" and "for". In my point of view, branching and looping add complexity to code. But it's everytime depends on what you want to do. Some examples:
If you do thing like:
if fruit.isBanana() then fruit.eatBanana()
else if fruit.isOrange() then fruit.eatOrange()
...
Instead of this, you can use inheritance:
class Banana extends Fruit {
function eat() {
... yum yum yum banana ...
}
}
class Orange extends Fruit {
function eat() {
... yum yum yum orange ...
}
}
And then, if you have an instance:
fruit.eat()
Another example: If you use "if" and "for" for filtering:
longFruits = []
for fruit in fruits {
if fruit.isBanana() then longFruits.add(fruit)
}
then you can work with collections instead:
longFruits = CollectionUtils.select(fruits, Precicate.isBanana)
This is just a couple examples and technics.
You can use switches.
switch (variable) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
default:
doSomething();
break;
}
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Oops, I misread your question, so you probably already know this, but anyway:
This is how it works:
Example 1
if your program looks like this:
if(condition1){ doThing1(); }
else if(condition2){ doThing2(); }
else if(condition3){ doThing3(); }
else{ doThing4() }
done();
Your program is first going to check if condition1 is true. if it is, it's going to run the method doThing1(). Afterwards it will not check condition2 or condition3, and will go directly to the done()-method.
If condition1 is false, the program will check if condition2 is true. If it is, it will run the method doThing2() and afterwards it will go directly to the done()-method.
If condition1 and condition2 is false, the program will check if condition3 is true and if it is, run the doThing3()-method.
If none of the conditions are true, it will run the method doThing4() and afterwards the done-method.
Example 2:
However, if your program looks like this:
if(condition1){ doThing1(); }
if(condition2){ doThing2(); }
if(condition3){ doThing3(); }
done();
Your program first checks if condition1 is true, if it is, it runs the method doThing1()
Then it checks if condition2 is true, if it is, it runs the doThing2()-method
Then it checks if condition3 is true, if it is, it runs the doThing3()-method
Lastly, it runs the done()-method.
The difference is that in example 1, the program doesn't check condition2 or condition3 if condition1 is true, whereas in example 2, it always checks all of the conditions. This means that in example 1, only one of the methods doThing1(), doThing2(), doThing3() and doThing4() is going to be run. In example 2 however, if more than one of the conditions are true, the program will run more than one of the methods.
Try writing a simple program where you use the two examples and change doThing1(); to System.out.println("1"); and so on, and try out different combinations of values (true or false) for the conditions if you didn't understand my answer.
I would use spacing to make sure the code looks neat without changing the actual meaning of the code. you can use switch, as explained in shinjw:s answer, but that isn't always practical since you have to use a byte, short, char or int to determine the outcome. Just write
if(condition1) //place1
else if(condition2) //place2
else if(condition3) //place3
else //place4
to make sure the conditions are nicely lined up if you want that, but only use that if the thing you are going to write at place 1,2,3 and 4 is one line. Otherwise it looks weird. If lining up the conditions isn't that important, I would write
if(condition1) //code1
else if(condition2) //code2
else if(condition3) //code3
else //code4
Since Java isn't space sensitive, any place you could use one space you could use any number of spaces and anytime you could use one new line, you could use any number of blank lines. It's not the tabbing, but the {} that divides code.
Right up front: I like else if. I think it makes for good clean code, unless one can design away the need for a series of comparisons. That said, ...
else if is not a first-class construct in Java. It's actually an if nested inside an else. From the JLS 7 (since OP indicates they use Java 6 and I don't have the JLS for that), an IfThenElseStatement is
if ( Expression ) StatementNoShortIf else Statement
where Expression is any Java Expression that evaluates to a boolean or Boolean, and StatementNoShortIf is any Java Statement that does not end in an if with no else.
We get an else if by substituting another if statement for Statement (following the else). So
// example 1
if (condition0) {
// body 0
} else if (condition1) {
// body 1
} else if (condition2) {
// body 2
} else {
// body 3
}
is, as far as Java is concerned, identical to:
// example 2
if (condition0) {
// body 0
} else {
if (condition1) {
// body 1
} else {
if (condition2) {
// body 2
} else {
// body 3
}
}
}
The only difference syntactically is that in example 2 no braces have been omitted (or, put another way, nested if statements have been enclosed in a Block). The else if construct is possible solely because those enclosing Blocks are unnecessary.
It is possible that your former lead prefers to use braces wherever they can be used, thinking that this is somehow safer or more readable. I disagree with this idea: as I said, else if makes for cleaner code IMO. But the only time a series of disconnected if statements better in any sense than if else is when the conditions and associated actions are truly independent of each other.

Trouble with .equals() and ==

I'm having trouble with these if statements and can't figure out the problem:
If I try changing them to a nested if, else if format I get a compiler error saying "else" with no if statement.
The if statements don't even work, as you can see from the ouput below they all run even when the strings aren't equal.
Any help would be great. Thanks!
if (labelArray[0] == e.getSource() && myAppliance.size() >= 1) {
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("CLOCK")); {
System.out.println(options[0]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("LAMP")); //"Clock", "Lamp", "Television"
{
System.out.println(options[1]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("TELEVISION")); {
System.out.println(options[2]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
}
Output:
Clock
Clock
Lamp
Clock
Television
Clock
Remove the ; at the end of the lines with the ifs.
remove the ; from immediate after if statements, compilers take them as statements and it defeats the purpose of using if itself.
Ifs work on the next statement they can take, so they'll run on the next line or treat a block enclosed on curly braces as a statement. By writing ; after the if, it's basically using an empty statement, then just proceeding to execute your block of code regardless.
Just remove the ; and it should work.

Java - Very basic syntax

Basically I'm quite new to Java and just been given some code which reads:
if (n > 1)
l--;
m = l;
Although I'm wondering whether this would be equivalent to either one of these, and if so which and why?
#1
if (n > 1) {
l--;
m = l;
}
OR
#2
if (n > 1) {
l--;
}
m = l;
It's equivalent to the second one. The if statement executes the next statement if its expression evaluates to true. It doesn't matter to the compiler if the next statement is a single statement (as it is in your original code sample) or a block (as it is in your second revision).
It's the same as the second block of code.
When you don't see braces following a "grouping" statement (the if statement, in your example), it means that only the next line falls within the scope of that grouping statement.
Going beyond what the question asks, languages such as Java, C/C++, and C# use braces to declare blocks of code, whereas languages such as Python use whitespace. You can think of line of code is a block by itself. Blocks can be incrementally built by combining more blocks. This is done by grouping blocks; in Java, this is done through curly braces. When the if statement is evaluated (or a for loop, or a while loop, etc), the next outermost block falls under that statement.
the 2nd option.
If there's no { }, only the following statement is part of the If case
Obviously #2, because a if statement only takes the first expression after it into account. That is why it is always important to use brackets around your statements, both for clarity and fewer bugs. There is nothing more frustrating than spending hours wondering why code doesn't work because you forgot to add a bracket somewhere

Why there is no compile time error? Strange - Java

I had an if statement checking some value, And encountered a weird bug(Not sure!). My code was incorrect syntactically and in result it produced a wrong result, however eclipse didn't raised any error while compiling. Why My below code worked?
if((this.trackPointList.get(point).getTurnOutId().equals(seg.getSegRef().getTurnOut())) && seg.getSegRef().getKind().equals("arc")); // <---- See here I have semicolon
{
... code to run ...
}
Above code check only first condition and ignores seg.getSegRef().getKind().equals("arc") but I guess this should raised an issue at compile time, Am I right? My logic worked once I debugged it by skimming line by line and found this semicolon. I will appreciate if someone could explain, if it is a valid syntax.
Enlighten Me, Please!
The ; makes Java think that the body of the if conditional is complete, even if there is no other code preceding it. In effect, the code in the if statement is executed, but no body exists because the ; is there.
The { ...code to run...} is just a code block that executes, and anything declared inside that block is not visible outside the block. It will always run here because it's not part of the if block.
edit: here's another stack overflow question about the { } blocks: What do curly braces in Java mean by themselves?
The code is syntactically correct. You can write ifs without braces, like:
if(condition) statement;
Having empty statements is also valid. For instance this code is valid:
int a = 0;;
;;;
So an empty if is valid as well, although it doesn't make much sense :)
if(condition);
An if statement followed by a semicolon is called an "empty if statement".
It rarely is of any use, but it's syntactically legal.
You can write something like this
if ( doSomethingThatReturnsABoolean() )
; // Empty statement
else
doSomeOtherThing()
but it would be better to write
if ( !doSomethingThatReturnsABoolean() )
doSomeOtherThing()
Regarding your observation that only the first condition gets checked:
If the first condition returns false the second condition will not get checked, because
(false && secondCondition)
always equals to false, so the value of secondCondition is irrelevant.
The ; after the if(..) statement represents an empty statement that is executed conditionally when the if(..) evaluates to true. The { .. } represents a code block that always executes with it's own scope.
The second condition may be ignored if the first condition is false due to short-circuit evaluation.
if(condition); is equivalent to if(condition){}
same thing with for loop & while loop:
for(;condition;); is equivalent to for(;condition;){}
while(condition); is equivalent to while(condition){}

While Loop Weirdness in Java

I noticed that java (hence probably C) has no problem with this:
while(condition1) {
//do somethin'
} while(condition2);
Is this the same as:
while(condition1 && condition2) {
//do somethin'
}
No, you have two loops.
while(condition1) {
// do something
}
while(condition2); // second loop which does nothing.
The second loop is the same as
while(condition2) { }
EDIT: My suggestion is to use the automatic formatter in your IDE regularly. Otherwise you can create formatting which suggests the code does things it doesn't.
example 1
if (condition)
statement1;
statement2;
statement3;
In this example, it appears that the first two statements are part of the if condition, but only the first is.
example 2
http://www.google.com/
statement;
Doesn't look like legal Java, but it is, not for the reasons the formatting suggests ;)
No, they are different.
The first while(condition1) will run first.
Then comes while(condition2), which has nothing after it except a single ; which means it's just some empty statement.
Remember that in control blocks like if, for, while, if you don't use the {} braces, then only the first immediate statement after it will be considered part of it.
Example:
if (condition)
System.out.println("hello"); // prints only if condition is true.
System.out.println("no"); // not bound to the 'if'. Prints regardless.
while (condition)
; // do nothing!
System.out.println("something"); // not bound to the while
Edit The empty while loop is mentioned in the Java code conventions
7.6 while Statements
A while statement should have the following form:
while (condition) {
statements;
}
An empty while statement should have the following form:
while (condition);
There is no construct is java as shown in the first form. You have probably seen
do {
} while (cond)
EDIT : You are misreading the first form. There should have been a line break after the }. This confused me as well.

Categories