Reputation: 392
I was testing a program for CPU usage check and I got a null pointer exception, so I added null check. When I added null check I started getting series of errors. Here is the code:
double ideltime=Double.parseDouble(cpuIdle.trim());
**String idelTimeStr=formatter.format(ideltime);
if(idelTimeStr!=null)**
double usuage=temp - Double.parseDouble(idelTimeStr);
cpuUsage = formatter.format(usuage);
The Highlighted lines show the null check added. Compilation error after this null check is as follows:
CPUUsage.java:29: error: '.class' expected
double usuage=temp - Double.parseDouble(idelTimeStr);
^
CPUUsage.java:29: error: not a statement
double usuage=temp - Double.parseDouble(idelTimeStr);
^
CPUUsage.java:29: error: illegal start of expression
double usuage=temp - Double.parseDouble(idelTimeStr);
^
CPUUsage.java:29: error: ';' expected
double usuage=temp - Double.parseDouble(idelTimeStr);
Please help in resolving this.
Upvotes: 5
Views: 101
Reputation: 36630
You can ommit the curly braces when there is only one statement:
if (condition)
statement;
is identical to
if (condition) {
statement;
}
This is defined by the grammar in the JLS Chapter 14: Blocks and Statements. The relevant production terms are:
IfThenStatement:
if ( Expression ) Statement
...
Statement:
StatementWithoutTrailingSubstatement
...
StatementWithoutTrailingSubstatement:
Block
EmptyStatement
ExpressionStatement
...
Finally, an ExpressionStatement
is something like an assignment or a method invocation, but not a variable declaration. Variable declarations require a block.
A block is a sequence of statements, local class declarations, and local variable declaration statements within braces.
and JLS 14.4: Local Variable Declaration Statements:
Every local variable declaration statement is immediately contained by a block.
Since you are declaring double usuage = ...
you need the curly braces in this case:
if(idelTimeStr != null) {
double usuage=temp - Double.parseDouble(idelTimeStr);
}
is not identical to
if(idelTimeStr != null)
double usuage=temp - Double.parseDouble(idelTimeStr);
With the curly braces, your program is syntactically fine, but then you need to consider that the usuage
variable is only visible within the block, so you will need to add more of your code inside the curly braces (or declare and initialize usuage
with a default value outside of the if
block).
In any case, I suggest to always use braces even if there is only one statement.
Upvotes: 6