Java one line if statement [duplicate] - java

This question already has answers here:
Is it ok if I omit curly braces in Java? [closed]
(16 answers)
Closed 9 years ago.
I am using if condition without braces in java something like
if(somecondition)
//Only one line Business logic
but some told use braces always even one line statement something like this
if(somecondition){
//Only one line Business logic
}
What is the better way according to java sandard?

there's no real "standard". i prefer always using braces because if you dont you risk someone adding an innocent looking logging statement turning your code from
if(somecondition)
//Only one line Business logic
into
if(somecondition)
log.debug("condition was true");
//Only one line Business logic
and then things stop working :-)

That's a matter of taste. I would use braces or else no braces but write all code in one line to improve readability.
Also you might consider using a ternary operator
booleanExpression ? value1 : value2

In addition to #radai answer, if you are a real evil mind, when you see a if with no braces you can do something that will make you ennemies by adding a semi-colon on the same line of the if but at the 800th column of the line(or something).
like
if(condition) /*a loooot of whitespace*/ ;
//Only one line Business logic that will get executed whatever is the condition
This is why i prefer to use braces and recommend people to use them

No naked if statements. You're just asking for trouble. Always use { }

it is better to use braces when checking for errors or updating the code.
imagine.
if(answer.equals("add"))
addedValue += Scanner.readInt();
but you have a new requirement to add only the absolute value, so you change to.
if(answer.equals("add2))
valueToBeAdded = Scanner.readInt();
if(valueToBeAdded < 0) valueToBeAdded = - valueToBeAdded;
addedValue += valueToBeAdded;
this is not a really correct algorithm, is just an example of what can happens.

Using if statement with braces is better way to java standard, because it increase the readability and reduce unwanted error.

The two statements have exactly the same effect but I have suffered so often from the lack of braces that I also always comment that there should be braces even around 1 line statements. This makes the code easier to maintain and can save a lot of headache. My experience shows that one line if statements often turn into multi-line statements on later iterations so what you save by not writing two { the first time, you will give later on.

According to java standard braces are better because if they are not there compiler has to work around more and also would be performance issue.

Related

What does the colon mean in Java (Part 2)?

This question has already been asked, but the answers seem to be incomplete. What does the first colon in the following context mean?
import hudson.model.SCMS;
(...)
SCMS: for (SCM scm : scmTriggerItem.getSCMs()) {
(...)
Additionally, the colon has some new uses in Java 8.
This question (which has originally been asked two years ago) is different from loop-in-java-code, because it is wider. While the answers of the original question do not mention the use of the colon as label, which is answered in question "loop-in-java-code", the latter question doesn't ask for the use of the colon within for loops nor in Java 8.
As the answer from biziclop shows, there are colon usages in the Java syntax that are easily forgotten and not mentioned in the other two questions.
There are four six uses of the : character in the Java language.
To denote a label. Labels can be used to break or continue to in loops.
In an enhanced for statement (also called for-each statement), which allows easy iteration across collections and arrays.
As one half of the ?: conditional operator.
And since Java 8, as part of the :: method reference operator.
In a switch statement, after case or default.
And you can also use it in an assert statement to specify an error message when the assertion fails.
In your case, SCMS: is a label, while for (SCM scm : scmTriggerItem.getSCMs()) is an enhanced for statement.
You can always look up the full syntax reference of Java here. It is amazingly dull but without it I easily missed two of the six cases.

How do you go back to a specific line in Java?

I am trying to make a Math Calculator Application. However I am wondering if there is a statement that allows you to go back to a certain line?
Let me clarify:
I am not referring to a loop. Here's a possibly scenerio: Let's say that the user has run the program and reached let's say line 54. If I have an if-else statement there, if there a way that I could make it so that "if (input = 0){go back to line 23}
Is there anything that may allow me to do this, not including a loop?
Java does not have a goto (goto is a reserved word but not used). Consider how your approach and language choice fit together. There is likely a better way to do this. Consider extracting a method or using a flag inside of a loop. Without more information, guidance will be limited.
Nope.
The goto statement exists in C and C++, which Java is vaguely similar to, but it's generally considered very bad practice to use. It makes code difficult to read and debug. Here are some correct ways to solve this problem with more structured programming:
do {
...
} while (input == 0);
private void doTheThing() { // please use a better name!
...
if (input == 0) doTheThing(); // recursion not recommended; see alternate
// method below
}
// alternate method:
do {
doTheThing();
} while (input == 0);
Why can't you use a loop?
Put your code in a function, then put in a loop that runs while input = 0.

Empty if-statements [duplicate]

This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 9 years ago.
By "empty if-statement", I mean something like this (note the semicolon):
if (condition);
I'm having trouble thinking of an application for this. With a while loop you can do this:
while (callUntilReturnsFalse());
But there's no such application for an if-statement. What's more, the Java compiler doesn't issue an error or a warning when confronted with such a statement. This can lead to large and silent problems, especially with a long and convoluted statement:
if ((functionA() && functionB(getFoo()) ||
checkForComplexCondition(arg1, arg2, getBar(getFoo())));
{
doStuff();
}
My question is: why is this allowed in Java? And, more importantly, can I enable an option to cause a warning when this happens?
(This question was asked before with regards to C#, which does issue a warning, but I was hoping to find a way to cause a warning with Java.)
why is this allowed in Java?
See Java Language Specification (14.6. The Empty Statement):
An empty statement does nothing.
It's simply allowed and it's equivalent to (and will be translated to):
if (condition) { }
Which means, if the condition is true, do nothing.
If you're using eclipse, you can look here, you might find something useful (I'm not sure there exists such an option for semicolon terminator):
Window → Preferences → Java → Compiler → Error/Warnings
EDIT
As #nullptr pointed out in his answer, there exist an IDE warning for this, you need to set warning on Empty statement.
I don't think this is truly relevant to the intent of the question but I think it should be stated as it is relevant to the essence of the question.
There is an effect of an:
if(variable);
if the variable is volatile. It''s effect is to cause a memory barrier to be honoured between the current thread and any other threads accessing the variable.
public volatile variable;
....
if(variable);
See here for a more detailed discussion.
I cannot imagine any real value to putting this kind of statement in your code but I felt it important to note that there is a real effect to this statement in this very specific situation.
There's one construct that I use fairly frequently which the "null statement" makes clearer and easier to understand. Here's an example:
for (int i=0; i < argc; i++)
{
if (argv[i]=="left")
hpos++;
else if (argv[i]=="right")
hpos--;
else if (argv[i]=="up")
;
else if (arv[i]=="down")
;
else fprintf(stderr, "Unknown option \"%s\\n".", argv[i]);
}
In this case, I still want to check for the existence of certain options, while only executing code for some of them. In this case, using the null statement, as above, makes the function and structure of the code more readable and comprehensible to the next guy who has to come along and maintain it.
There are certainly ways to restructure this code to not require the null statement. But I don't believe that its intention will be as clear as in the code snippet.
I found a warning for this in Eclipse as Empty statement:
Thanks to Maroun Maroun for putting me on the right track.
I don't see so much danger in the possibility of an if with an empty statement. The rationale behind it resides in the grammar of the Java language, which allows the empty statement ;:
Block:
{ BlockStatements }
BlockStatements:
{ BlockStatement }
BlockStatement:
LocalVariableDeclarationStatement
ClassOrInterfaceDeclaration
[Identifier :] Statement
LocalVariableDeclarationStatement:
{ VariableModifier } Type VariableDeclarators ;
Statement:
Block
;
Identifier : Statement
StatementExpression ;
if ParExpression Statement [else Statement]
assert Expression [: Expression] ;
switch ParExpression { SwitchBlockStatementGroups }
while ParExpression Statement
do Statement while ParExpression ;
for ( ForControl ) Statement
break [Identifier] ;
continue [Identifier] ;
return [Expression] ;
throw Expression ;
synchronized ParExpression Block
try Block (Catches | [Catches] Finally)
try ResourceSpecification Block [Catches] [Finally]
Mind that this is true for almost all imperative languages.
I mean it can be dangerous and difficult to find as every other empty body in case you forgot any implementation, certainly nothing I would lose the sleep for. In a long and convoluted statement you could get problems because of a ( ) closing the wrong pair of expressions or even for thinking your condition wrong (especially with many && and ||).
I'm mostly a C# developer, although I have a little Java background. But I think my answer applies to both. I suspect it's not an intentional feature, but more of an emergent feature. The grammar of the language goes (roughly)
if (*condition*)
*statement*
Unfortunately the below are both valid statements (I checked, you can drop as many into C# as you like and the compiler doesn't complain):
;
{
}
Therefore the construct that you highlighted is allowed.
The condition could be a function call with side effects. It wouldn't be correct to treat it as an error or warning.
In the statement
if (eval) { //pseudo-code
}
Sometimes data is actually changed in evaluation of (eval). For example, in
while (someIterator.next()) {
}
Calling next() actually changes the state of the someIterator object.
And of course there is the classic example that usually happens from a typo (and is not recommended)
int x;
if (x = getNumberOfWidgets() > 5) {
}
Conventional wisdom advises against coding this way, as it is harder to tell what is going on. However, the statements are legal and so that is one reason why such an 'if' statement is allowed.
I believe that they left it in because it can increase code readability. Even if nothing should be done for a case you may still want to let people know that the case is important.

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

How to find nested conditons count in java

I have to read java file by java code and to determine the greatest nested count of if statements in it.
for example:
if (someCondition)
{
if (someCondition)
{
// Expression
}
}
In this case program should display greatest nested if depth is 2.
Now the problem is that position of curly brace after if is uncertain.
for example it can be like :
Curly brace start and end comes in same line
if (someCondition){}
OR
Curly brace start in next line
if (someCondition)
{
}
OR
Conditions without curly brace
if (someCondition)
if (someCondition) // Single line without curly brace
Can anybody suggest what will be the best way to get the required nested count?
You'll need to parse the Abstract Syntax Tree (AST) of the Java source code. See Java library for code analysis. Once you have the AST, you can do a search to find the longest path of nested conditionals.
As the answer already said, you should rely on the AST rather than viewing code manually for this. The AST will never be wrong, your own reading abilities most often will.
I don't know a complete solution right now, but I suggest you spend some time looking at existing tools for computing software metrics. Nesting depth is a typical metric and there should be tools around.
If you can't find anything, you can at least fall back to writing something like an Eclipse plugin. In that case, you could simply load the Java file in the Eclipse editor, and Eclipse performs all the hard work for you and gives you the AST for free. Determining the nesting depth of a given AST is then rendered a simple task. Developing a prototype for that shouldn't take more than a few hours. And it's easy to extend it to cover your whole project and have it answer questions like "which java file in our project has the maximum nesting depth and what depth is that?". But then again.. someone else will surely point out an existing tool that already does this and much more.
I82Much's answer will certainly get you there, but feels a little like cheating.
Knowing little about your project, I would think that a simple stack mechanism with a max value record would do the trick push on { and pop on }. Once you have that basic model working, simply add the special case of control statements with one line bodies (this is valid for if, for, while ...). In those cases, you'll be looking for those keywords, followed by ( and a ). Once you've encountered that combination, if the scan encounters either another control statement or a semi-colon before it encounters a { then this is one of those special cases and you should push (using a special marker indicating to pop on ; rather than }).

Categories