9. 7
CHAPTER 1
About this document
This document describes the specific Java defects that can be detected by
Klocwork. It also describes defect parameters.
10.
11. 9
CHAPTER 2
Code problems detected by Klocwork
In This Chapter
Code problems: Java ..........................................................9
Code problems: Java
ARRAY
This error is reported when the index of array access can be less than zero or
greater than the size of the array.
Defect Attributes
Name Value
Defect Code ARRAY
Category Code Quality/ Reliability/ Exceptions
Title Array index is out of range
Message Array {0} index {1} is out of range {2}
Enabled (default) true
Severity (default) Critical (1)
Applicable language Java
Customizable false
12. 10 Detected Java Defects
Vulnerability and risk
If this situation occurs in Java, it will throw an IndexArrayOutOfBounds
runtime exception. Rather than try to catch this exception, use index
checking. Index checking can work up to 100 times faster than catching the
exception. Also, an uncaught exception can cause a thread to finish, which
can lead to deadlock in multi-thread environments or the death of an
application. If a general exception is caught, an application may be restored,
but it may be missing functionality or diagnostics, or it may have a logic
flaw.
Mitigation and prevention
Check for array boundaries. Make sure the check is correct, that is, that
upperIndex string is less than array.length. Novice programmers usually
make mistakes using array.length as index.
Example_001:
Java Code Sample:
...
15: /**
16: * This method prints file number j from directory dir or
17: * error message if index is out of bounds
18: */
19: public static void getNthFile(File dir, int j) {
20: System.err.println("Info: getting file number " + j
21: + " from directory " + dir);
22: File results[] = dir.listFiles();
23: if (results != null && results.length >= j && j >= 0) {
24: System.out.println(j + " file is " + results[j]);
25: } else {
26: System.err.println("Error: not enough files");
27: }
28: }
...
Output:
com/klocwork/examples/Example_001.java:24:Critical(1):
ARRAY: Array results index j is out of range upper bound:
j(j<results.length) from j(j<=results.length)
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_001.java
13. Chapter 2 Code problems detected by Klocwork 11
Example_002:
Java Code Sample:
...
15: /**
16: * This method validates input string. String has field
17: * separated by :, original string, result string and
18: * extra info First field sould be equal second field to
19: * match
20: */
21: static boolean validate(String text) {
22: StringTokenizer tok = new StringTokenizer(text, ":");
23: String[] result = new String[tok.countTokens()];
24: int count = 0;
25: while (tok.hasMoreTokens()) {
26: result[count] = tok.nextToken();
27: count++;
28: }
29: if ((result == null) || (result.length < 2)
30: || (result[2] == null)) { return false; }
31: String toCompare = result[1];
32: if (toCompare.equalsIgnoreCase(result[0])) return true;
33: return false;
34: }
...
Output:
com/klocwork/examples/Example_002.java:29:Critical(1):
ARRAY: Array result index 2 is out of range upper bound:
result.length(2<result.length) from
result.length(2<=result.length)
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_002.java
CMP.OBJ
This warning appears if object references are compared rather than objects
themselves. Error produced only if compared object has different types and
none of them has explicit Object type.
14. 12 Detected Java Defects
Defect Attributes
Name Value
Defect Code CMP.OBJ
Category Code Quality/ Reliability/ Suspicious
practices
Title Comparing objects with ==
Message Comparing objects {0} and {1} with ==
Enabled (default) false
Severity (default) Review (9)
Applicable language Java
Customizable false
Vulnerability and risk
This problem can cause unexpected application behavior. Comparing objects
using == usually produces deceptive results, since the == operator compares
object references rather than values. To use == on a string, the programmer
has to make sure that these objects are unique in the program, that is, that
they don't have the equals method defined or have a static factory that
produces unique objects.
Mitigation and prevention
Use the equals() method to compare objects instead of the == operator. If
using ==, it is important for performance reasons that your objects are created
by a static factory, not by a constructor.
Example_010:
Java Code Sample:
...
14: /**
15: * Check that person is John 25 miner
16: */
17: Proffesional john = new Proffesional("John", 25,
"miner");
18: public boolean checkJohn(Person p) {
19: return p == john;
20: }
...
15. Chapter 2 Code problems detected by Klocwork 13
Output:
com/klocwork/examples/Example_010.java:19:Review(9):
CMP.OBJ: Comparing objects this.john and p with ==
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_010.java
CMP.STR
This warning appears if string references are compared rather than strings
themselves for String type.
Defect Attributes
Name Value
Defect Code CMP.STR
Category Code Quality/ Reliability/ Suspicious
practices
Title Comparing strings with ==
Message Comparing strings {0} and {1} with ==
Enabled (default) true
Severity (default) Investigate (5)
Applicable language Java
Customizable false
Vulnerability and risk
This problem can cause unexpected application behavior. Comparing objects
using == usually produces deceptive results, since the == operator compares
object references rather than values. To use == on a string, the programmer
has to make sure that these are constant strings, statically created in the same
class or "interned" prior to comparison using the intern() method.
Mitigation and prevention
Use the equals() method to compare objects instead of the == operator.
16. 14 Detected Java Defects
Example_009:
Java Code Sample:
...
14: /**
15: * Return symbolic name of operation
16: */
17: public String nameOperation(String key) {
18: if (key == "++") return "PLUS";
19: if (key == "--") return "MINUS";
20: return "UNKNOWN";
21: }
22:
23: // test start
24: public static void main(String[] args) {
25: Example_009 ex = new Example_009();
26: ex.test("++");
27: ex.test("+++");
28: String one = "+";
29: ex.test("+" + one);
30: ex.test(new String("++"));
31: }
32: private void test(String str) {
33: System.err.println("Name of " + str + "="
34: + nameOperation(str));
35: }
36: //test end
...
Output:
com/klocwork/examples/Example_009.java:18:Investigate(5):
CMP.STR: "Comparing strings "++" and key with =="
com/klocwork/examples/Example_009.java:19:Investigate(5):
CMP.STR: "Comparing strings "--" and key with =="
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_009.java
CMPF.FLOAT
Error printed when two float or double value compared using equals operator
(==).
17. Chapter 2 Code problems detected by Klocwork 15
Defect Attributes
Name Value
Defect Code CMPF.FLOAT
Category Code Quality/ Reliability/ Suspicious practices
Title Equality checks on floating point types should
be avoided
Message Equality checks on floating point types should
be avoided
Enabled (default) true
Severity (default) Warning (6)
Applicable language Java
Customizable false
Vulnerability and risk
Avoid equality checks on floating point types because of possible inaccuracy
of floating point calculations. The example below can lead to an infinite loop
because x1 + 700 times ((x2 - x1) / 700) does not equal to x2, due to
inaccuracy.
Mitigation and prevention
Use check great or equals, less or equals or abs different less than something,
for example (Math.abs(x1-x2) < MIN_DIFF).
18. 16 Detected Java Defects
Example_023:
Java Code Sample:
...
14: /**
15: * Calculates define integral
16: */
17: public static double integral(MyFunction f, double x1,
18: double x2) {
19: double x = x1;
20: double result = 0;
21: double step = (x2 - x1) / 700;
22: while (x != x2) { // should use (x <= x2)
23: result = result + f.valueFor(x) * step;
24: x = x + step;
25: }
26: return result;
27: }
...
Output:
com/klocwork/examples/Example_023.java:22:Warning(6):
CMPF.FLOAT: Equality checks on floating point types should be
avoided
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_023.java
COV.CMP
Error exists when method compareTo declared with signature different than
int compareTo(Object).
19. Chapter 2 Code problems detected by Klocwork 17
Defect Attributes
Name Value
Defect Code COV.CMP
Category Code Quality/ Reliability/ Suspicious practices
Title Method compareTo() should have signature int
compareTo(Object)
Message Method compareTo() should have signature int
compareTo(Object)
Enabled (default) true
Severity (default) Warning (6)
Applicable language Java
Customizable false
Vulnerability and risk
Intent was probably to implement interface method of Comarible interface,
but since this method has different signature it is not same method and will
not be called when comparator is used.
Mitigation and prevention
Declare that class implements Cloneable, declare int compareTo(Object)
method.
Example_024:
Java Code Sample:
...
18: String name;
19: int compareTo(MyClass a) {
20: return name.compareTo(a.name);
21: }
...
Output:
com/klocwork/examples/Example_024.java:20:Warning(6):
COV.CMP: Method compareTo() should have signature int
compareTo(Object)
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_024.java
20. 18 Detected Java Defects
ECC.EMPTY
An Empty Catch Clause (ECC.EMPTY) warning appears if nothing is
written in a catch block. If you catch an exception, it would be better to
process it rather than to ignore it.
Defect Attributes
Name Value
Defect Code ECC.EMPTY
Category Code Quality/ Reliability/ Error Handling
Title Empty catch clause
Message Empty catch clause
Enabled (default) true
Severity (default) Investigate (5)
Applicable language Java
Customizable false
Example_305:
Java Code Sample:
...
20: public void openFile(String name) {
21: try {
22: FileInputStream is = new FileInputStream(name);
23: // read file ...
24: } catch (FileNotFoundException e) {
25: // TODO Auto-generated catch block
26: }
27: }
...
Output:
com/klocwork/examples/Example_305.java:24:Investigate(5):
ECC.EMPTY: Empty catch clause
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_305.java
21. Chapter 2 Code problems detected by Klocwork 19
EHC.EQ
EHC Class should implement both equals(Object) and hashCode() methods.
EHC warnings appear if an equals() method was specified without a
hashCode() method or vice versa. This warning appears if a hashCode() is
specified without a equals(). This may cause a problem with some collections
that expect that equal objects to have equal hashcodes.
Defect Attributes
Name Value
Defect Code EHC.EQ
Category Code Quality/ Reliability/ Suspicious practices
Title Class defines hashCode() but does not define
equals()
Message Class defines hashCode() but does not define
equals()
Enabled (default) true
Severity (default) Warning (6)
Applicable language Java
Customizable false
Example_307:
Java Code Sample:
...
17: public class MyClass {
18: private int seed;
19: public MyClass(int seed) {
20: this.seed = seed;
21: }
22: public int hashCode() {
23: return seed;
24: }
25: // no equals(Object o) method defined
26: }
...
22. 20 Detected Java Defects
Output:
com/klocwork/examples/Example_307.java:23:Warning(6):
EHC.EQ: Class defines hashCode() but does not define equals()
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_307.java
EHC.HASH
EHC Class should implement both equals(Object) and hashCode() methods.
EHC warnings appear if an equals() method was specified without a
hashCode() method or vice versa. This may cause a problem with some
collections that expect equal objects to have equal hashcodes.
Defect Attributes
Name Value
Defect Code EHC.HASH
Category Code Quality/ Reliability/ Suspicious practices
Title Class defines equals() but does not define
hashCode()
Message Class defines equals() but does not define
hashCode()
Enabled (default) true
Severity (default) Warning (6)
Applicable language Java
Customizable false
23. Chapter 2 Code problems detected by Klocwork 21
Example_306:
Java Code Sample:
...
17: public class MyClass {
18: private int seed;
19: public MyClass(int seed) {
20: this.seed = seed;
21: }
22: public boolean equals(Object o) {
23: return (o instanceof MyClass)
24: && ((MyClass) o).seed == seed;
25: }
26: // no hashCode method defined
27: }
...
Output:
com/klocwork/examples/Example_306.java:23:Warning(6):
EHC.HASH: Class defines equals() but does not define
hashCode()
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_306.java
ESCMP.EMPTYSTR
ESCMP Compare string with an empty string using equals().
It is not necessary to call equals() to compare a string with an empty string.
s.length() works twice as fast. The following expressions:
s.equals("") or "".equals(s)
can be easily replaced with
(s.length() == 0) and (s != null && s.length() == 0)
Performance measurements (done using Java 2 Runtime Environment,
Standard Edition, build 1.4.1_02-b06) showed that code with "equals"
executed in 147 units of time while the same code with "length" executed in
71 units of time.
24. 22 Detected Java Defects
Defect Attributes
Name Value
Defect Code ESCMP.EMPTYSTR
Category Code Quality/ Efficiency
Title Inefficient empty string comparison
Message Comparing strings {0} and {1} using equals(),
instead of length() == 0
Enabled (default) false
Severity (default) Suggestion (7)
Applicable language Java
Customizable false
Example_003:
Java Code Sample:
...
16: public boolean emptyCheck1() {
17: if (s.equals("")) return true;
18: return false;
19: }
20: public boolean emptyCheck2() {
21: if ("".equals(s)) return true;
22: return false;
23: }
24: // fixed code
25: public boolean emptyCheck3() {
26: if (s.length() == 0) return true;
27: return false;
28: }
...
Output:
com/klocwork/examples/Example_003.java:17:Suggestion(7):
ESCMP.EMPTYSTR: "Comparing strings "" and this.s using
equals(),
instead of length() == 0"
com/klocwork/examples/Example_003.java:21:Suggestion(7):
ESCMP.EMPTYSTR: "Comparing strings this.s and "" using
equals(),
instead of length() == 0"
25. Chapter 2 Code problems detected by Klocwork 23
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_003.java
EXC.BROADTHROWS
A method should throw exceptions appropriate to the abstraction level. When
a method throws exceptions that are too general, like Exception and
Throwable, it is difficult for callers to handle errors correctly and do good
error recovery.
Defect Attributes
Name Value
Defect Code EXC.BROADTHROWS
Category Code Quality/ Reliability/ Error Handling
Title Method has an overly broad throws declaration
Message The {0} method throws a generic exception {1}
Enabled (default) false
Severity (default) Style (8)
Applicable language Java
Customizable true
Vulnerability and risk
When method throws exceptions that are too general, callers have to
investigate what kind of problem happened so that they can handle it
appropriately. It raises the risk of improperly handled problems. Also, when a
method code is changed and a new kind of exception is introduced, it's harder
to force all callers to handle it properly.
Mitigation and prevention
A method should throw exceptions appropriate to the abstraction level. When
necessary, low-level exceptions can be wrapped with higher-level exceptions.
26. 24 Detected Java Defects
Example_300:
Java Code Sample:
...
23: public void processFile(String fileName) throws Exception
{
24: InputStream is = new FileInputStream(fileName);
25: // do something
26: }
27: public int calculateSum(Collection data) throws Throwable
{
28: int sum = 0;
29: for (Iterator it = data.iterator(); it.hasNext();) {
30: String element = (String) it.next();
31: int i = Integer.parseInt(element);
32: sum += i;
33: }
34: return sum;
35: }
...
Output:
com/klocwork/examples/Example_300.java:24:Style(8):
EXC.BROADTHROWS: The processFile method throws a generic
exception
java.lang.Exception
com/klocwork/examples/Example_300.java:28:Style(8):
EXC.BROADTHROWS: The calculateSum method throws a generic
exception
java.lang.Throwable
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_300.java
FIN.EMPTY
Empty finalize() method.
FIN code problems have a questionable implementation of finalize method().
In this case, there is an empty finalize() method.
27. Chapter 2 Code problems detected by Klocwork 25
Defect Attributes
Name Value
Defect Code FIN.EMPTY
Category Code Quality/ Efficiency
Title Empty finalize() method should be removed
Message Empty finalize() method should be removed
Enabled (default) true
Severity (default) Suggestion (7)
Applicable language Java
Customizable false
Example_004:
Java Code Sample:
...
15:
16: public void test3() {
17: new Example_004() {
18: protected void finalize() throws Throwable {
19:
20: }
21: };
22: }
23: // fixed code
24: public void test1() {
25: new Example_004() {
26: };
27: }
...
Output:
com/klocwork/examples/Example_004.java:20:Suggestion(7):
FIN.EMPTY: Empty finalize() method should be removed
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_004.java
28. 26 Detected Java Defects
FIN.NOSUPER
Implementation of the finalize() method should call super.finalize().
FIN code problems have a questionable implementation of finalize method().
In this case there is a finalize() method implementation that does not call
super.finalize().
Defect Attributes
Name Value
Defect Code FIN.NOSUPER
Category Code Quality/ Reliability/ Suspicious practices
Title Implementation of the finalize() method should
call super.finalize()
Message Implementation of the finalize() method should
call super.finalize()
Enabled (default) true
Severity (default) Unexpected (4)
Applicable language Java
Customizable false
Vulnerability and risk
If a superclass implementor overrides a superclass finalizer but forgets to
invoke the superclass finalizer manually, the superclass finalizer will never
be invoked. This means resource cleanup for the superclass will never be
performed leading to resource leaks. Example_308:
Java Code Sample:
...
16: public class Example_308 {
17: /*
18: * no super.finalize() was called
19: */
20: public void finalize() {
21: System.err.println("finalized");
22: }
23: }
...
29. Chapter 2 Code problems detected by Klocwork 27
Output:
com/klocwork/examples/Example_308.java:21:Unexpected(4):
FIN.NOSUPER: Implementation of the finalize() method should
call
super.finalize()
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_308.java
FSC.PRT
This warning is reported for protected fields. It appears if some field in a
subclass shadows (has the same name, type and modifier) as some field in the
superclass. This can cause confusion.
Defect Attributes
Name Value
Defect Code FSC.PRT
Category Code Quality/ Maintainability
Title Class and its superclass have protected fields
with the same name
Message Class {0} hides field {2} of superclass {1} by
declaring a protected or package-private field
with the same name
Enabled (default) false
Severity (default) Review (9)
Applicable language Java
Customizable false
30. 28 Detected Java Defects
Example_309:
Java Code Sample:
...
17: public class SuperClass {
18: protected int index;
19: // ...
20: }
21: public class SubClass extends SuperClass {
22: protected int index;
23: // ...
24: }
...
Output:
com/klocwork/examples/Example_309.java:21:Review(9):
FSC.PRT: Class com.klocwork.examples.Example_309$SubClass and
its
superclass com.klocwork.examples.Example_309$SuperClass have
protected
fields with the same name: index
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_309.java
FSC.PRV
This warning is reported for private fields. It appears if some field in a
subclass shadows (has the same name, type and modifier) as some field in the
superclass. This can cause confusion.
31. Chapter 2 Code problems detected by Klocwork 29
Defect Attributes
Name Value
Defect Code FSC.PRV
Category Code Quality/ Maintainability
Title Class and its superclass have private fields with
the same name
Message Class {0} hides field {2} of superclass {1} by
declaring a private field with the same name
Enabled (default) false
Severity (default) Review (9)
Applicable language Java
Customizable false
Example_310:
Java Code Sample:
...
17: public class SuperClass {
18: private int index;
19: // ...
20: }
21: public class SubClass extends SuperClass {
22: private int index;
23: // ...
24: }
...
Output:
com/klocwork/examples/Example_310.java:21:Review(9):
FSC.PRV: Class com.klocwork.examples.Example_310$SubClass and
its
superclass com.klocwork.examples.Example_310$SuperClass have
private
fields with the same name: index
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_310.java
32. 30 Detected Java Defects
FSC.PUB
This warning is reported for public fields. It appears if some field in a
subclass shadows (has the same name, type and modifier) as some field in the
superclass. This can cause confusion.
Defect Attributes
Name Value
Defect Code FSC.PUB
Category Code Quality/ Maintainability
Title Class and its superclass have public fields with
the same name
Message Class {0} hides field {2} of superclass {1} by
declaring a public field with the same name
Enabled (default) false
Severity (default) Warning (6)
Applicable language Java
Customizable false
Example_311:
Java Code Sample:
...
17: public class SuperClass {
18: public int index;
19: // ...
20: }
21: public class SubClass extends SuperClass {
22: public int index;
23: // ...
24: }
...
Output:
com/klocwork/examples/Example_311.java:21:Warning(6):
FSC.PUB: Class com.klocwork.examples.Example_311$SubClass and
its
superclass com.klocwork.examples.Example_311$SuperClass have
public
fields with the same name: index
33. Chapter 2 Code problems detected by Klocwork 31
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_311.java
JD.BITCMP
JD.BITCMP happens when an if check contains binary such as & or | instead
of short-circuit, such as && or ||. It is better to use short-circuit operation for
performance. Also, if you use binary, both sides of the expression are
evaluated, and this can cause other unexpected problems, such as a null
pointer exception being thrown. as in the example below.
Defect attributes
Name Value
Defect Code JD.BITCMP
Category Code Quality/ Reliability/ Suspicious practices
Title Using non short-circuit logic in expression
Message Questionable use of bit operation '{0}' in
expression. Did you mean '{1}'?
Enabled (default) true
Severity (default) Severe (2)
Applicable language Java
Vulnerability and risk
A JD.BITCMP defect can cause a performance impact or unexpected
behavior, such as a RuntimeException being thrown.
Mitigation and prevention
Replace bit operation with short-circuit operation.
34. 32 Detected Java Defects
Example_043:
Java Code Sample:
...
14: static void check(int arr[]) {
15: if (arr!=null & arr.length!=0) {
16: foo();
17: }
18: return;
19: }
...
Output:
com/klocwork/examples/Example_043.java:15:Severe(2):
JD.BITCMP: Questionable use of bit operation '&' in
expression. Did
you mean '&&'?
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_04
3.java
See also:
JD.BITMASK (on page 32)
JD.BITR (on page 35)
JD.BITMASK
JD.BITMASK happens when int or a long variable is used with bit operation
& or | and is then compared to a constant, while the result of the evaluation is
known in advance. For example ((a & 0x0f) == 0xf0) is always false because
bitmasks are incompatible.
35. Chapter 2 Code problems detected by Klocwork 33
Defect attributes
Name Value
Defect Code JD.BITMASK
Category Code Quality/ Reliability/ Suspicious practices
Title Possible error in bit operations
Message Incompatible bitmasks '{0}' and '{1}' cause the
expression to always be constant.
Enabled (default) true
Severity (default) Severe (2)
Applicable language Java
Vulnerability and risk
It is unlikely that the code was intentional, so the error can cause unexpected
behavior.
Mitigation and prevention
Fix the bit operator (if it was the cause), or fix the bitmask.
Example_041:
Java Code Sample:
...
16: final static int FLAG = 0x01;
17: static boolean checkMask(int a) {
18: // mistyped, should be &
19: if ((a |FLAG) == 0) return true;
20: return false;
21: }
...
Output:
com/klocwork/examples/Example_041.java:19:Severe(2):
JD.BITMASK: Incompatible bitmasks '0x1' and '0x0' cause the
expression to always be constant.
36. 34 Detected Java Defects
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_04
1.java
See also:
JD.BITCMP (on page 31)
JD.BITR (on page 35)
JD.BTO.SBS
The JD.BTO.SBS checker triggers an error if a byte type is used with shift
operations or with an OR bit operator. Usually, it is an error, because usually,
the byte is perceived as unsigned and, if it contains a number greater than
128, it will be negative and the OR operator will produce unexpected results.
Defect attributes
Name Value
Defect Code JD.BTO.SBS
Category Code Quality/ Reliability/ Suspicious practices
Title Bit operation used with signed value
Message Bit operation '{1}' used with signed byte value
of '{0}'
Enabled (default) true
Severity (default) Warning (6)
Applicable language Java
Vulnerability and risk
JD.BTO.SBS defects result in incorrect program behavior.
Mitigation and prevention
Manually convert the unsigned value to signed and cast to the int, that is, if
you want to store '160', make sure the int contains '160', not -96, as would be
the case with an implicit cast.
37. Chapter 2 Code problems detected by Klocwork 35
Example_040:
Java Code Sample:
...
16: static int ipToInt(byte[] inet) {
17: int l = 0;
18: for (int i = 0; i < inet.length; i++) {
19: final byte b = inet[i];
20: l=l<<8 | b;
21: }
22: return l;
23: }
24: // fixed
25: static int ipToInt2(byte[] inet) {
26: int l = 0;
27: for (int i = 0; i < inet.length; i++) {
28: final byte b = inet[i];
29: int x = b<0?256+b:b;
30: l=l<<8 | x;
31: }
32: return l;
33: }
...
Output:
com/klocwork/examples/Example_040.java:20:Warning(6):
JD.BTO.SBS: Bit operation '|' used with signed byte value of
'b'
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_04
0.java
JD.BITR
JD.BITR happens when an if check contains only constants on both sides. It
can be the result of a programming error followed by compiler optimization
which replaces expressions with constants. As a sub-case, this checker will
trigger accidental assignments in conditions such as those in the example
below.
Note: Whether or not this error occurs depends on how the Java compiler
optimizes the code. For some compilers, JD.BITR never occurs and either
JD.RC.EXPR.DEAD or JD.RC.EXPR.CHECK occurs instead.
38. 36 Detected Java Defects
Defect attributes
Name Value
Defect Code JD.BITR
Category Code Quality/ Reliability/ Suspicious practices
Title Redundant expression
Message Expression '{0}' is always '{1}'. Is there a typo?
Enabled (default) true
Severity (default) Severe (2)
Applicable language Java
Vulnerability and risk
A statically evaluatable expression in an 'if' statement is most likely an error
in logic.
Mitigation and prevention
Fix the 'if' statement.
Example_042:
Java Code Sample:
...
14: static void check(boolean hasFields) {
15: if (hasFields = true) {
16: foo();
17: }
18: return;
19: }
...
Output:
com/klocwork/examples/Example_042.java:15:Severe(2):
JD.BITR: Expression '(...)' is always '1'. Is it a typo?
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_04
2.java
39. Chapter 2 Code problems detected by Klocwork 37
See also:
JD.BITCMP (on page 31)
JD.BITMASK (on page 32)
JD.RC.EXPR.CHECK (on page 70)
JD.RC.EXPR.DEAD (on page 71)
JD.CAST.COL
JD.CAST.COL is found when an object is retrieved from a collection (map
or list) and is cast immediately as type A, although it was put into the
collection as type B, where types A and B are unrelated. That is, Klocwork
cannot find that A is a subtype of B or B is a subtype of A. The
JD.CAST.COL checker checks only class fields.
Defect attributes
Name Value
Defect Code JD.CAST.COL
Category Code Quality/ Reliability/ Exceptions
Title Possible ClassCastException for collection
Message Suspicious cast to '{0}' of collection element. Put
the object into the collection as '{1}'.
Enabled (default) true
Severity (default) Error (3)
Applicable language Java
Vulnerability and risk
This usually causes a ClassCastException, because objects in the collection
have different types.
Mitigation and prevention
Choose which type you actually want to use--A or B--and, either put objects
of type A, or get objects of type B. The other option is to allow both of these
types to use an instanceof check before casting the object.
40. 38 Detected Java Defects
Example_071:
Java Code Sample:
...
19: class Filter {
20: HashMap len=new HashMap();
21: void fill(File dir){
22: File[] list = dir.listFiles();
23: for (int i = 0; i < list.length; i++) {
24: File file = list[i];
25: len.put(file,new Long(file.length()));
26: }
27: }
28: int getLength(String file){
29: Long l = (Long) len.get(file);
30: if (l!=null) return l.intValue();
31: return 0;
32: }
33: }
...
Output:
com/klocwork/examples/Example_071.java:29:Error(3):
JD.CAST.COL: Suspicious cast to 'java.lang.String' of
collection
element. Put the object into the collection as
'java.io.File'.
-> get at
com/klocwork/examples/Example_071.java:29
-> put at
com/klocwork/examples/Example_071.java:25
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_07
1.java
See also:
JD.CAST.UPCAST (on page 40)
JD.CATCH (on page 41)
41. Chapter 2 Code problems detected by Klocwork 39
JD.CAST.SUSP
JD.CAST.SUSP is triggered when an object is checked with an instance of
operator for type A and than cast to type B, where types A and B are
unrelated. (That is Klocwork cannot find that A is a subtype of B or B is a
subtype of A.)
Defect attributes
Name Value
Defect Code JD.CAST.SUSP
Category Code Quality/ Reliability/ Exceptions
Title Possible ClassCastException for different types
Message Suspicious cast of '{0}' from '{1}' to '{2}', {3}.
Enabled (default) true
Severity (default) Unexpected (4)
Applicable language Java
Vulnerability and risk
This is usually an error, because cast is not safe; the object can actually be
another type than B. In some cases, this error can produce false positives
when the path from instanceof to cast is incompatible.
Mitigation and prevention
Choose which type you actually want to use--A or B--and either change the
typecast to A, or check the instanceof to B.
Example_069:
Java Code Sample:
...
15: void setValue(Object a, Object value) {
16: if (a instanceof String) {
17: StringBuffer b = (StringBuffer) a;
18: b.append("=");
19: b.append(value);
20: }
21: }
...
42. 40 Detected Java Defects
Output:
com/klocwork/examples/Example_069.java:17:Unexpected(4):
JD.CAST.SUSP: Suspicious cast of 'a' from 'java.lang.String'
to
'java.lang.StringBuffer', where types are unrelated.
on trace 16 17
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_06
9.java
See also:
JD.CAST.UPCAST (on page 40)
JD.CAST.UPCAST
JD.CAST.UPCAST is triggered when an object is checked with an instance
of operator for type A and than cast to type B, where B is a subtype of type
A.
Defect attributes
Name Value
Defect Code JD.CAST.UPCAST
Category Code Quality/ Reliability/ Exceptions
Title Possible ClassCastException for subtypes
Message Suspicious cast of '{0}' to '{2}', where '{2}' is a
subtype of '{1}'. This object can hold other
subtypes of '{1}' which can cause a
ClassCastException.
Enabled (default) true
Severity (default) Warning (6)
Applicable language Java
Vulnerability and risk
This is usually an error, because the cast is not safe, the object can actually be
another subtype of A. In some cases, this error can produce false positives
when the path from the instanceof to the cast is incompatible.
43. Chapter 2 Code problems detected by Klocwork 41
Example_070:
Java Code Sample:
...
19: void setValue(Object a, Object value) {
20: if (a instanceof Map) {
21: HashMap b = (HashMap) a;
22: b.put(value, "");
23: } else if (a instanceof List) {
24: List b = (List) a;
25: b.add(value);
26: }
27: }
...
Output:
com/klocwork/examples/Example_070.java:21:Warning(6):
JD.CAST.UPCAST: Suspicious cast of 'a' to 'java.util.HashMap',
where
'java.util.HashMap' is subtype of 'java.util.Map'. This
object can
hold other subtypes of 'java.util.Map' which can cause
ClassCastException.
on trace 20 21
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_07
0.java
See also:
JD.CAST.SUSP (on page 39)
JD.CATCH
Klocwork reports a JD.CATCH defect when it finds a catch block with an
unwanted exception such as java.lang.NullPointerException. A list of
possible exceptions is in the Parameters section.
44. 42 Detected Java Defects
Defect attributes
Name Value
Defect Code JD.CATCH
Category Code Quality/ Reliability/ Error Handling
Title Catching runtime exception
Message Catching '{0}' explicitly is usually a bad
practice. Use preventive checks on data instead.
Enabled (default) true
Severity (default) Investigate (5)
Applicable language Java
Vulnerability and risk
Exceptions, as their names implies, should be used only for exceptional
conditions; they should never be used for ordinary control flow. Using
exceptions for control flow dramatically reduces performance,
maintainability, and readability of the code.
Mitigation and prevention
Change the code to code that does a preventive check (full null, array index,
and so on).
Example_058:
Java Code Sample:
...
16: // horrible abuse of exceptions. Don't ever do this!
17: void foo(int arr[]) {
18: try {
19: int i = 0;
20: while (true) {
21: arr[i++]--;
22: }
23: } catch (ArrayIndexOutOfBoundsException e) {
24: return;
25: }
26:
27: }
...
45. Chapter 2 Code problems detected by Klocwork 43
Output:
com/klocwork/examples/Example_058.java:23:Investigate(5):
JD.CATCH: Catching 'java.lang.ArrayIndexOutOfBoundsException'
explicitly is usually a bad practice. Use preventive checks
on data
instead.
See complete code sample:
<Klocwork installation
directory>/samples/inforcejava/com/klocwork/examples/Example_05
8.java
References
Effective Java, Item 39.
JD.CONCUR
JD.CONCUR is found when an iterator is created for collection A, then
something is removed from the collection, but the loop is not stopped.
Defect attributes
Name Value
Defect Code JD.CONCUR
Category Code Quality/ Reliability/ Exceptions
Title Possible ConcurrentModificationException
Message Possible 'ConcurrentModificationException' can be
thrown by method '{0}' while iterating over '{1}'.
You cannot remove a collection element while
iterating over the same collection.
Enabled (default) true
Severity (default) Critical (1)
Applicable Java
language
Vulnerability and risk
On the following invocation of the "next" method, the code will throw a
ConcurrentModificationException.