Adding Null Checks Throws Some Compilation Errors

I tested the program to check CPU usage, and I got a null pointer exception, so I added a null check. When I added null check, I started getting a number 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 display a null check. A 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 issue.

+5
source share
1 answer

You can omit curly braces when there is only one statement:

 if (condition) statement; 

coincides with

 if (condition) { statement; } 

This is determined by grammar in JLS Chapter 14: Blocks and Statementments . Appropriate production conditions:

 IfThenStatement: if ( Expression ) Statement ... Statement: StatementWithoutTrailingSubstatement ... StatementWithoutTrailingSubstatement: Block EmptyStatement ExpressionStatement ... 

Lastly, an ExpressionStatement is something like a destination or method call, but not a variable declaration. Variable declarations require a block .

JLS 14.2: Blocks :

A block is a sequence of operators, local class declarations, and local variable operators in braces .

and JLS 14.4: Local variable declaration statements :

Each local variable declaration statement is immediately contained in a block.

Since you are declaring double usuage = ... , you need curly braces in this case:

 if(idelTimeStr != null) { double usuage=temp - Double.parseDouble(idelTimeStr); } 

not identical

 if(idelTimeStr != null) double usuage=temp - Double.parseDouble(idelTimeStr); 

With curly braces, your program is syntactically thin, but then you need to consider that the usuage variable is visible only inside 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 the if block).

In any case, I suggest always using curly braces, even if there is only one statement .

+6
source

Source: https://habr.com/ru/post/1236401/


All Articles