Java Possible Coding Errors
Rules available in this category:
- Use_proper_primitive_type_literals
- Do_not_instantiate_class_before_initializing_static_final_fields
- Do_not_create_threads_using_the_default_empty_run_method
- Avoid_calling_wait_on_Condition_object
- Possible_bug_in_method_invocation_on_an_immutable_object
- Possible_NPE_due_to_earlier_check_against_null
- Possible_overflow_in_average_computation_for_large_numbers
- Avoid_comparing_with_one_to_check_if_number_is_odd
- Possible_bug_in_control_flow_statement
- Remainder_of_32-bit_signed_random_integer_could_be_negative
- Remainder_of_hashCode_could_be_negative
- Possible_ConcurrentModificationException
- Possible_bug_in_the_usage_of_loop_variables
- Avoid_more_than_one_getter_or_setter_per_field
- Possible_null_pointer_exception_during_constructor_execution
- Ensure_boxing_unboxing_correct_behaviour
- Possible_typos_in_wrapper_class
- Always_compare_chars_with_values_within_their_range
- Avoid_using_put_putAll_and_get_methods_for_java.util.Properties_objects
- Avoid_dangling_else_statements
- Avoid_calling_equals_on_unrelated_types
- Avoid_unconditional_wait
- Avoid_waiting_with_two_locks_held
- Avoid_calling_notify_on_unlocked_objects
- Interface_method_conflicts_with_protected_Object_method
- Avoid_using_char_array_in_string_concatenation
- Avoid_calling_wait_on_unlocked_objects
- Avoid_calling_Thread_sleep_with_lock_held
- Avoid_declaring_variables_of_type_ThreadGroup
- Possible_bug_in_assigning_value_to_boolean
- Questionable_Octate_Escape_In_String
- Switch_case_does_not_cover_all_enums
- Invalid_regular_expression_syntax
- Possibly_incorrect_regular_expression_pattern
- Avoid_adding_collection_to_itself
- Always_rethrow_ThreadDeath
- Avoid_possible_typos_in_switch_statement
- Use_System_dot_exit_with_care
- Avoid_wrong_increment_in_for
- Never_call_overridable_method_from_constructor
- Avoid_assigning_values_to_method_parameter
- Avoid_non_Serializable_field_inside_Serializable_Class
- Avoid_serializable_class_extending_a_class_without_a_zero_arg_constructor
- Always_null_pointer_exception
- Possible_null_pointer_exception_passing_null_value_as_method_parameter
- Always_class_cast_exception
- Avoid_calling_applet_methods_relying_on_stubs_in_constructor
- Avoid_double_checked_locking
- Avoid_immediate_dereference_of_readLine
- Result_of_readLine_not_used
- Declare_Runnable_run_as_synchronized
- Avoid_TODO_comments
- Avoid_using_spin_locks
- Avoid_down_casting_to_concrete_collection
- Bad_cast_to_another_abstract_collection
- Avoid_empty_statement
- Avoid_fields_with_closely_similar_names
- Avoid_mutable_exception
- Do_not_cast_to_lower_precision
- Avoid_casting_without_check
- Do_not_cast_integer_division_to_double
- Do_not_cast_integer_multiplication_to_long
- Use_random_nextInt
- Avoid_casting_random_value_to_integer
- Overwritten_increment
- Overwritten_decrement
- Invalid_month_argument
- Do_not_call_run_explicitly
- Avoid_catching_IllegalMonitorStateException
- Always_call_swing_methods_in_swing_event_thread
- Erroneous_use_of_binary_AND_with_ZERO
- Erroneous_use_of_binary_AND
- Declare_Object_as_parameter_for_compareTo_method
- Always_explicitly_initialize_all_fields_in_a_constructor
- Avoid_passing_decimal_literals_to_BigDecimal_constructor
- Use_string_equals_method
- Avoid_circular_initialization_for_static_fields
- Always_ensure_get_set_methods_access_correct_fields
- Declare_fields_of_user-defined_Exception_as_final_or_private
- Avoid_overloading_methods_on_argument_types
- Private_field_is_never_written
- Do_not_call_synchronized_method_from_synchronized_method
- Always_place_literals_first_in_string_comparison
- Avoid_equals_operator_for_decimal_point_values
- Avoid_returning_java_lang_Object
- Avoid_invoking_runFinalizersOnExit
- Avoid_contiguous_non_String_values_during_concatenation
- Conditional_expression_always_evaluates_to_constant_value
- Avoid_accessing_uninitialized_fields_in_constructors
- Avoid_accessing_uninitialized_fields
- Avoid_Serializable_class_having_non_Serializable_parent
- Avoid_comparison_with_float_NaN
- Declare_get_method_synchronized
- Avoid_using_float_or_double
- Avoid_assigning_variable_to_same_variable
- Erroneous_use_of_binary_OR
- Avoid_unsynchronized_lazy_initialization_of_static_field
- Avoid_using_volatile_modifier_for_array
- Avoid_synchronization_on_mutable_field
- Avoid_methods_with_closely_similar_names
- Use_serializable_objects_as_argument
- Do_not_call_methods_that_use_AppletStub
- readResolve_method_should_have_java_lang_Object_as_its_return_type
- Avoid_setSize_in_componentResized
- Avoid_unnecessary_call_to_Math_ceil
- Avoid_unnecessary_call_to_Math_class_method
- Always_use_method_return_values
- Always_check_return_value_of_input_stream_read
- Always_check_return_value_of_input_stream_skip
- Erroneous_indexOf_check
- Calling_equals_of_final_classes
- Possible_infinite_recursion
- Possible_infinite_loop
- instanceOf_will_always_return_false
- Avoid_classes_that_are_not_accessible
- Avoid_rethrowing_an_exception_in_a_catch_clause
- Avoid_initializing_array_dimensions_with_negative_values
- Use_Equals_Instead_Equality_Operator
- Possible_spelling_mistake_while_overriding_method
- Do_not_use_zero_as_index_with_resuset
- Do_not_use_zero_as_index_with_PreparedStatement
- Always_call_wait_inside_while_or_doWhile_loop
- Always_call_Condition_await_inside_a_loop
- Avoid_public_semaphores
- Do_not_call_interrupted_method_on_thread_object
- Avoid_unnecessary_comparison_of_two_null_references
- Avoid_unnecessary_comparison_of_non_null_reference_with_null_reference
- Avoid_unnecessary_comparison_with_int
- Do_not_start_Thread_in_constructor
- Classes_or_interfaces_having_same_name_as_java_file_should_be_public
- Always_ensure_only_one_class_or_interface_has_same_name_as_java_file
- Avoid_returning_this
- Avoid_calling_getResource_on_getClass
- Non_instantiable_class_should_contain_non_private_static_method
- Do_not_override_synchronized_method_with_unsynchronized_method
Severity:
Medium
Rule:
Use proper primitive type literals where ever available.
Reason:
Use proper primitive type literals where ever available.
Usage Example:
package com.rule;
public class Use_proper_primitive_type_literals_violation
{
public void method()
{
float f2 = 0; // VIOLATION
}
}
Should be written as:
package com.rule;
public class Use_proper_primitive_type_literals_correction
{
public void method()
{
float f2 = 0.0f; // CORRECTION
}
}
Reference:
Reference Not Available.
Severity:
Medium
Rule:
Creating an instance of the class before initializing static final fields can cause errors.
Reason:
Creating an instance of the class before initializing static final fields can cause errors.
Usage Example:
package com.rule;
public class Do_not_instantiate_class_before_initializing_static_final_fields_violation
{
private static final long MAX_VALUE;
private static Do_not_instantiate_class_before_initializing_static_final_fields_violation instance;
static
{
instance = new Do_not_instantiate_class_before_initializing_static_final_fields_violation(); // VIOLATION
MAX_VALUE = 1000;
}
}
Should be written as:
package com.rule;
public class Do_not_instantiate_class_before_initializing_static_final_fields_correction
{
private static final long MAX_VALUE;
private static Do_not_instantiate_class_before_initializing_static_final_fields_correction instance;
static
{
MAX_VALUE = 1000;
instance = new Do_not_instantiate_class_before_initializing_static_final_fields_correction(); // CORRECTION
}
}
Reference:
No reference available.
Severity:
High
Rule:
Since the thread has no task to execute, it simply wastes time and degrades performance.
Reason:
Since the thread has no task to execute, it simply wastes time and degrades performance.
Usage Example:
class NoopThread extends Thread
{
public NoopThread()
{
}
public NoopThread(String s, ThreadGroup tg)
{
super(tg, s);
}
public NoopThread(Runnable r)
{
super(r);
}
public void test1() {
Thread t = new NoopThread();
t.start();
}
public void test2() {
Thread t = new Thread("Cool Thread"); // VIOLATION
t.start();
}
public void test3() {
ThreadGroup tg = new ThreadGroup("My Cool ThreadGroup");
Thread t = new Thread(tg, "Cool Thread"); // VIOLATION
t.start();
}
public void run()
{
super.run();
//...
}
}
Should be written as:
class NoopThread extends Thread
{
private Runnable r = null;
public NoopThread()
{
}
public NoopThread(String s, ThreadGroup tg)
{
super(tg, s);
}
public NoopThread(Runnable r)
{
super(r);
this.r = r;
}
public void test1() {
Thread t = new NoopThread();
t.start();
}
public void test2() {
Thread t = new Thread(r, "Cool Thread"); // FIXED
t.start();
}
public void test3() {
ThreadGroup tg = new ThreadGroup("My Cool ThreadGroup");
Thread t = new Thread(tg, r, "Cool Thread"); // FIXED
t.start();
}
public void run()
{
super.run();
//...
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
Waiting for a Condition should be done using one of the await methods defined by the Condition interface.
Reason:
Waiting for a Condition should be done using one of the await methods defined by the Condition interface.
Usage Example:
import java.util.concurrent.locks.*;
public class Test
{
int x;
void waitOnCondition(Condition cond) throws InterruptedException
{
while (x == 0)
{
cond.wait(); // VIOLATION
}
}
}
Should be written as:
import java.util.concurrent.locks.*;
public class Test
{
int x;
void waitOnCondition(Condition cond) throws InterruptedException
{
while (x == 0)
{
cond.await(); // FIXED
}
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
An operation on an immutable object won't change the object itself.
Reason:
An operation on an immutable object won't change the object itself.
Usage Example:
import java.math.*;
public class Test
{
void fubar()
{
BigDecimal bd=new BigDecimal(10);
bd.add(new BigDecimal(5)); // VIOLATION
}
}
Should be written as:
import java.math.*;id="rule6"> Rule 6: Possible_NPE_due_to_earlier_check_against_null >
public class Test
{
void fubar()
{
BigDecimal bd=new BigDecimal(10);
bd = bd.add(new BigDecimal(5)); // FIXED
}
}
Severity:
Medium
Rule:
The variable referenced at this point is known to be null due to an earlier check against null.
Reason:
The variable referenced at this point is known to be null due to an earlier check against null.
Usage Example:
public class Test
{
public void fubar()
{
Object nullObject = null;
if (nullObject == null)
{
try
{
System.out.println("hello");
nullObject = "notnull";
}
catch (RuntimeException ex)
{
System.out.println(nullObject.getClass()); // VIOLATION
}
}
}
}
Should be written as:
public class Test
{
public void fubar()
{
Object nullObject = null;
if (nullObject != null) // FIXED
{
try
{
System.out.println("hello");
nullObject = "notnull";
}
catch (RuntimeException ex)
{
System.out.println(nullObject.getClass());
}
}
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
If the sum of the two numbers is greater than the maximum positive int value, then it overflows to a negative value, and the value stays negative when divided by two.
Reason:
If the sum of the two numbers is greater than the maximum positive int value, then it overflows to a negative value, and the value stays negative when divided by two.
Usage Example:
public class Test
{
public static int binarySearch(int[] a, int key)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) / 2; // VIOLATION
int midVal = a[mid];
if (midVal < key)
{
low = mid + 1;
}
else if (midVal > key)
{
high = mid - 1;
}
else
{
return mid; // key found
}
}
return -(low + 1); // key not found.
}
}
Should be written as:
public class Test
{
public static int binarySearch(int[] a, int key)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) >>> 1; // FIXED
int midVal = a[mid];
if (midVal < key)
{
low = mid + 1;
}
else if (midVal > key)
{
high = mid - 1;
}
else
{
return mid; // key found
}
}
return -(low + 1); // key not found.
}
}
Reference:
http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html
Severity:
Medium
Rule:
It wont work for negative numbers.
Reason:
It wont work for negative numbers.
Usage Example:
public class Test
{
public boolean isOdd(int x)
{
return x % 2 == 1; // VIOLATION
}
}
Should be written as:
public class Test
{
public boolean isOdd(int x)
{
return x % 2 != 0; // FIXED
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
Having an empty statement as the body might have not been intended.
Reason:
Having an empty statement as the body might have not been intended.
Usage Example:
public class Test
{
public static void main(String[] args)
{
if(args.length ==1); // VIOLATION
System.out.println(args[0]);
}
}
Should be written as:
public class Test
{
public static void main(String[] args)
{
if(args.length ==1) // FIXED
System.out.println(args[0]);
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
Please ensure that the possibility of the result of the remainder operation being negative is handled.
Reason:
Please ensure that the possibility of the result of the remainder operation being negative is handled.
Usage Example:
import java.security.SecureRandom;
import java.util.Random;
class Test
{
Random r = new Random();
SecureRandom sr = new SecureRandom();
public int getRandomElement(int a[])
{
return a[r.nextInt() % a.length]; // VIOLATION
}
public int getSecureRandomElement(int a[])
{
return a[sr.nextInt() % a.length]; // VIOLATION
}
}
Should be written as:
import java.security.SecureRandom;
import java.util.Random;
class Test
{
Random r = new Random();
SecureRandom sr = new SecureRandom();
public int getRandomElement(int a[])
{
int index = r.nextInt() % a.length;
if(index != -1)
{
return a[index]; // FIXED
}
}
public int getSecureRandomElement(int a[])
{
int index = sr.nextInt() % a.length;
if(index != -1)
{
return a[sr.nextInt() % a.length]; // FIXED
}
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
Please ensure that the possibility of the result of the remainder operation being negative is handled.
Reason:
Please ensure that the possibility of the result of the remainder operation being negative is handled.
Usage Example:
public class Test
{
public static Object getHashBucket(Object a[], Object x)
{
return a[x.hashCode() % a.length]; // VIOLATION
}
public static Object getHashBucket2(Object a[], Object x)
{
int i = x.hashCode() % a.length; // VIOLATION
return a[i];
}
}
Should be written as:
public class Test
{
public static Object getHashBucket(Object a[], Object x)
{
return a[Math.abs(x.hashCode() % a.length)]; // FIXED
}
public static Object getHashBucket2(Object a[], Object x)
{
int i = Math.abs(x.hashCode() % a.length); // FIXED
return a[i];
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
Possibility of a ConcurrentModificationException to be thrown at runtime.
Reason:
Possibility of a ConcurrentModificationException to be thrown at runtime.
Usage Example:
import java.util.*;
public class Test
{
public void someMethod(Collection collection)
{
Iterator iter = collection.iterator();
while (iter.hasNext())
{
Object element = iter.next();
collection.remove(element); // VIOLATION
}
}
}
Should be written as:
import java.util.*;
public class Test
{
public void someMethod(Collection collection)
{
Iterator iter = collection.iterator();
while (iter.hasNext())
{
iter.remove(); // FIXED
}
}
}
Reference:
Not Available.
Severity:
High
Rule:
There is a high probability that the wrong variable was used in the loop.
Reason:
There is a high probability that the wrong variable was used in the loop.
Usage Example:
public class Test
{
public void myMethod()
{
int[] a= new int[5];
for(int i=0; i<a.length; i++)
{
int[] b= new int[5];
for(int j=0; j<b.length; j++)
{
b[i]= 1;// VIOLATION
}
}
for (int j = 0; j < a.length; i++)// VIOLATION
{
System.out.println("The index is:" + j);
}
}
}
Should be written as:
public class Test
{
public void myMethod()
{
int[] a= new int[5];
for(int i=0; i<a.length; i++)
{
int[] b= new int[5];
for(int j=0; j<b.length; j++)
{
b[j]= 1;// FIXED
}
}
for (int j = 0; j < a.length; j++)// FIXED
{
System.out.println("The index is:" + j);
}
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
It is possible that the second getter or setter was meant to access or set another field.
Reason:
It is possible that the second getter or setter was meant to access or set another field.
Usage Example:
public class Test
{
private Object _obj, _obj1;
public Object getObj()
{
return _obj;
}
public Object getObj1(int num) //VIOLATION
{
return _obj;
}
}
Should be written as:
public class Test
{
private Object _obj, _obj1;
public Object getObj()
{
return _obj;
}
public Object getObj1(int num)
{
return _obj1; //FIXED
}
}
Reference:
Not Available.
Severity:
High
Rule:
Violates on possible cases of method invocations from constructors which throw a null pointer exception.
Reason:
Violates on possible cases of method invocations from constructors which throw a null pointer exception.
Usage Example:
public class Test
{
public Test()
{
methodThrowingNPE(); // VIOLATION
}
protected void methodThrowingNPE()
{
// ...
}
}
class Sub extends Test
{
Sub()
{
//...
}
protected void methodThrowingNPE()
{
Object s = null;
int i = 2;
if(i == 3)
{
s = new Object();
}
System.out.println(s.toString());
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
Autoboxing capability can lead to unexpected behavior especially when passing arguments.
Reason:
Autoboxing capability can lead to unexpected behavior especially when passing arguments.
Usage Example:
public class Test
{
public static void main(String[] args)
{
Integer number = new Integer(10);
new Test().foo(number/10); // VIOLATION
}
private void foo(int i)
{
System.out.println("primitive = " + i);
}
private void foo(Integer i)
{
System.out.println("wrapper = " + i);
}
}
Should be written as:
In the above code foo(int) method will be called and not foo(Integer); please ensure if this is expected behaviour.
Reference:
No references Available.
Severity:
Medium
Rule:
Possible typos in arguments to wrapper classes.
Reason:
Possible typos in arguments to wrapper classes.
Usage Example:
public class Typos
{
Integer i = new Integer("15A"); //VIOLATION
public Boolean myMethod()
{
return Boolean.valueOf(" true"); //VIOLATION, would return "false"
}
}
Should be written as:
public class Typos
{
Integer i = new Integer("10"); // CORRECTION
public Boolean myMethod()
{
return Boolean.valueOf("true"); // CORRECTION
}
}
Reference:
No references available.
Severity:
Medium
Rule:
If the constant is not within the range of possible "char" value, the boolean would always result to true or false.
Reason:
If the constant is not within the range of possible "char" value, the boolean would always result to true or false.
Usage Example:
public class AlwaysCompareCharsWithValuesWithinTheirRange
{
public static String getAsciiString(String inString)
{
StringBuffer outStringBuffer= new StringBuffer();
for (int i= 0; i< inString.length(); i++)
{
char currentChar= inString.charAt(i);
if (currentChar> -1 && currentChar< 256) // VIOLATION
{
outStringBuffer.append(currentChar);
}
}
return outStringBuffer.toString();
}
}
Should be written as:
public class AlwaysCompareCharsWithValuesWithinTheirRange
{
public static String getAsciiString(String inString)
{
StringBuffer outStringBuffer= new StringBuffer();
for (int i= 0; i< inString.length(); i++)
{
char currentChar= inString.charAt(i);
if (currentChar< 256) // CORRECTION
{
outStringBuffer.append(currentChar);
}
}
return outStringBuffer.toString();
}
}
Reference:
id="rule19"> Rule 19: Avoid_using_put_putAll_and_get_methods_for_java.util.Properties_objects >
Severity:
Medium
Rule:
Using 'put' and 'putAll' might allow non-string entries, which should be avoided and getProperty directly returns a string as a return value.
Reason:
Using 'put' and 'putAll' might allow non-string entries, which should be avoided and getProperty directly returns a string as a return value.
Usage Example:
public class PropClass
{
java.util.Properties properties= new java.util.Properties();
public String someMethod()
{
properties.put("A", "someString"); // VIOLATION
return (String)properties.get("A"); // VIOLATION
}
}
Should be written as:
public class PropClass
{
java.util.Properties properties= new java.util.Properties();
public String someMethod()
{
properties.setProperty("A", "someString"); // CORRECTION
return properties.getProperty("A"); // CORRECTION
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html
Severity:
Medium
Rule:
Dangling else statement lead to ambiguity and possible error in logic.
Reason:
Dangling else statement lead to ambiguity and possible error in logic.
Usage Example:
public class AvoidDanglingElseStatements
{
void method ()
{
int num = 23;
if (num < 24) // VIOLATION: should have "{ }" braces
if (num < 5)
num++;
else
num--;
}
}
Should be written as:
public class AvoidDanglingElseStatements
{
void method ()
{
int num = 23;
if (num < 24)
{ // CORRECTION
if (num < 5)
num++;
}
else
{
num--;
}
}
}
Reference:
No references available.
Severity:
Medium
Rule:
This equals comparison will always return false.
Reason:
This equals comparison will always return false.
Usage Example:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
public class Test
{
public void aMethod()
{
Collection al = new ArrayList();
Collection v = new Vector();
if (al.equals(v)) // VIOLATION
{
System.out.println("Never here");
}
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
The call to java.lang.Object.wait() is not within a conditional control flow.
Reason:
The call to java.lang.Object.wait() is not within a conditional control flow.
Usage Example:
public class Test
{
void clueless() throws Exception
{
synchronized(this)
{
this.wait(); // VIOLATION
}
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
Avoid waiting on a monitor while two locks are held.
Reason:
Avoid waiting on a monitor while two locks are held.
Usage Example:
public class Test
{
Object lock = new Object();
Object value;
public synchronized void notifyMethod(Object v)
{
synchronized(lock)
{
value = v;
lock.notifyAll();
}
}
public synchronized Object waitMethod() throws InterruptedException
{
synchronized(lock)
{
while (value == null)
{
lock.wait(); // VIOLATION
}
return value;
}
}
public void someMethod(Object a, Object b)
{
try
{
synchronized (a)
{
synchronized (b)
{
a.wait(); // VIOLATION
}
}
} catch (InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
Should be written as:
Reference:
No references available.
Severity:
Critical
Rule:
This method calls notify() or notifyAll() without obviously holding a lock on the object.
Reason:
This method calls notify() or notifyAll() without obviously holding a lock on the object.
Usage Example:
public class Test
{
public void bar(Object a, Object b) throws InterruptedException {
synchronized (a) {
b.notify(); // VIOLATION
b.notifyAll(); // VIOLATION
}
}
}
Should be written as:
public class Test
{
public void bar(Object a, Object b) throws InterruptedException {
synchronized (b) {
b.notify();
b.notifyAll();
}
}
}
Reference:
No references available.
Severity:
Critical
Rule:
This interface has a method which is incompatible with the protected Object method.
Reason:
This interface has a method which is incompatible with the protected Object method.
Usage Example:
interface someInterface
{
int clone(); // VIOLATION
}
Should be written as:
Reference:
No references available.
Severity:
Critical
Rule:
The char array is not converted to an equivalent String.
Reason:
The char array is not converted to an equivalent String.
Usage Example:
public class Test
{
public void aMethod()
{
String h = "hello";
char[] arr = {'w','o','r','l','d'};
String msg = h + " " + arr; // VIOLATION
}
}
Should be written as:
public class Test
{
public void aMethod()
{
String h = "hello";
char[] arr = {'w','o','r','l','d'};
String world = String.valueOf(arr);
String msg = h + " " + world;
}
}
Reference:
No references available.
Severity:
Critical
Rule:
This method calls wait() without obviously holding a lock on the object.
Reason:
This method calls wait() without obviously holding a lock on the object.
Usage Example:
public class Test
{
public void foo(Object a, Object b) throws InterruptedException
{
synchronized (a)
{
b.wait(); // VIOLATION
}
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
Avoid calling Thread.sleep(), while lock held.
Reason:
Avoid calling Thread.sleep(), while lock held.
Usage Example:
package com.rule;
public class Avoid_calling_Thread_sleep_with_lock_held_violation
{
public synchronized void method()
{
long time = 100000;
try
{
Thread.sleep(time); //Violation.
}
catch (InterruptedException e)
{
// Handle Exception.
}
}
}
Should be written as:
package com.rule;
public class Avoid_calling_Thread_sleep_with_lock_held_correction
{
public synchronized void method()
{
try
{
wait(); // Correction.
}
catch (InterruptedException e)
{
// Handle Exception.
}
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid declaring variables of type ThreadGroup
Reason:
Avoid declaring variables of type ThreadGroup
Usage Example:
public class ThreadGroupTest
{
public static void main(String[] args)
{
ThreadGroup squares = new ThreadGroup("Squares"); // VIOLATION
Thread t1 = new Thread(squares, new T(), "t1");
Thread t2 = new Thread(squares, new T(), "t2");
t1.start();
t2.start();
System.out.println("ThreadGroup name is: " + squares.getName());
System.out.println("There are currently " + squares.activeCount() + " threads running");
System.out.println("The maximum priority of a Thread that can be contained
within " + squares.getName() + " is " + squares.getMaxPriority());
System.out.println("There are currently " + squares.activeGroupCount() + " active groups");
System.out.println(squares.getName() + " parent is " + squares.getParent());
}
}
class T implements Runnable
{
private int square;
public void run()
{
for(int i = 1; i < 5; i++)
{
square = i * i;
System.out.println("Thread " + Thread.currentThread().getName() +
" has a priority of " + Thread.currentThread().getPriority() +
": " + square);
}
}
}
Should be written as:
Avoid using ThreadGroup.
Reference:
Joshua Bloch: "Effective Java - Programming Language Guide"
Severity:
Low
Rule:
Most probably this was supposed to be a boolean comparison using ==, not an assignment using =
Reason:
Most probably this was supposed to be a boolean comparison using ==, not an assignment using =
Usage Example:
class Test
{
public void test1(boolean b)
{
if (b = true) // VIOLATION
{
System.out.println("Hi");
}
}
public void test2(int a, int b, int c, int d, boolean e)
{
if (e = false) // VIOLATION
{
System.out.println("Hi");
}
}
public void test3(boolean b)
{
while (b = true) // VIOLATION
{
System.out.println("Wow");
}
}
}
Should be written as:
class Test
{
public void test1(boolean b)
{
if (b) // FIXED
{
System.out.println("Hi");
}
}
public void test2(int a, int b, int c, int d, boolean e)
{
if (!e) // FIXED
{
System.out.println("Hi");
}
}
public void test3(boolean b)
{
while (b) // FIXED
{
System.out.println("Wow");
}
}
}
Reference:
Not Available.
Severity:
High
Rule:
Avoid questionable use of Octate Escape In String
Reason:
Avoid questionable use of Octate Escape In String
Usage Example:
package com.rule;
class Questionable_Octate_Escape_In_String_violation
{
public void method()
{
String str = "Allowed : \012";
String str1 = "Allowed : \377";
System.out.println("suspicious: \128"); // Violation.
String str2 = "suspicious: \318\013"; // Violation.
String str3 = "suspicious: \013 \318"; // Violation.
}
}
Should be written as:
Reference:
No reference available
Severity:
High
Rule:
The compiler can optionally flag incomplete enum switch statements.
Reason:
The compiler can optionally flag incomplete enum switch statements.
Usage Example:
public class BadSwitch
{
void fubar(Colors c)
{
switch(c) // VIOLATION
{
case BLUE:
case WHITE:
{
// ....
break;
}
}
}
}
enum Colors
{
BLUE, WHITE, RED;
}
Should be written as:
public class BadSwitch
{
void fubar(Colors c)
{
switch(c) // FIXED
{
case RED:
{
//..
break;
}
case BLUE:
case WHITE:
{
// ....
break;
}
}
}
}
enum Colors
{
BLUE, WHITE, RED;
}
Reference:
No reference available.
Severity:
High
Rule:
The syntax of the regular expression is invalid.
Reason:
The syntax of the regular expression is invalid.
Usage Example:
import java.util.regex.*;
public class WillThrowPatternSyntaxException
{
void x(String s) throws Exception
{
Pattern.matches("][", s); // VIOLATION
}
}
Should be written as:
Please verify the regex pattern.
Reference:
No references available.
Severity:
High
Rule:
A String function is being invoked and "." is being passed to a parameter that takes a regular expression as an argument.
Reason:
A String function is being invoked and "." is being passed to a parameter that takes a regular expression as an argument.
Usage Example:
public class Test
{
public void fubar(String s)
{
s.replaceAll(".", "/"); // VIOLATION
}
}
Should be written as:
Please ensure this is intended.
Reference:
Not Available.
Severity:
High
Rule:
Avoid adding a collection to itself.
Reason:
Avoid adding a collection to itself.
Usage Example:
package com.rule;
import java.util.ArrayList;
import java.util.Collection;
public class Avoid_adding_collection_to_itself_violation
{
public void method()
{
Collection c = new ArrayList();
c.add("Item 1");
c.add("Item 2");
c.addAll(c); // Violation.
}
}
Should be written as:
Reference:
Reference not available.
Severity:
Medium
Rule:
Always rethrow ThreadDeath Error.
Reason:
Always rethrow ThreadDeath Error.
Usage Example:
package com.rule;
/**
* @author Administrator
*
*/
public class Always_rethrow_ThreadDeath_violation
{
public static void main(String args[])
{
new Thread()
{
public void run()
{
run1();
}
private void run1()
{
for (int i = 0; i < 100; i++)
{
try
{
doStop(i);
}
catch (ThreadDeath th) // Violation
{
System.out.println("th.getClass()="+th.getClass());
th.printStackTrace();
}
System.out.println("i="+i);
}
}
private void doStop(int i)
{
if (i == 5)
stop();
}
}.start();
}
}
Should be written as:
package com.rule;
public class Always_rethrow_ThreadDeath_correction
{
public static void main(String args[])
{
new Thread()
{
public void run()
{
run1();
}
private void run1()
{
for (int i = 0; i < 100; i++)
{
try
{
doStop(i);
}
catch (ThreadDeath th)
{
System.out.println("th.getClass()="+th.getClass());
th.printStackTrace();
throw th; // Correction
}
System.out.println("i="+i);
}
}
private void doStop(int i)
{
if (i == 5)
stop();
}
}.start();
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadDeath.html
Severity:
Medium
Rule:
Labels should not appear in switch statements because they will not be used.
Reason:
Labels should not appear in switch statements because they will not be used.
Usage Example:
public class MyClass
{
static int method (int i) {
switch (i) {
case 4:
case3: // VIOLATION: label typo
i++;
break;
case 25:
unusedlabel: // VIOLATION: unused label.
break;
}
return i;
}
}
Should be written as:
public class MyClass
{
static int method (int i) {
switch (i) {
case 4:
case 3: // CORRECTION
i++;
break;
case 25:
// CORRECTION
break;
}
return i;
}
}
Reference:
No references available.
Severity:
High
Rule:
Use System.exit with care.
Reason:
Use System.exit with care.
Usage Example:
package com.rule;
public class Use_System_dot_exit_with_care_violation
{
public static void main(String[] s)
{
int ia[]={1,2,3,4,5,6,7, 8, 9, 10, 11, 12, 13};
(new ThreadDoSum(ia)).start();
System.exit(0); // Violation
}
}
class ThreadDoSum extends Thread
{
int[] ia = null;
public ThreadDoSum(int ia[])
{
this.ia = ia;
}
public void run()
{
int sum = 0;
for (int i = 0; i < ia.length; i++)
{
sum += ia[i];
}
System.out.println(sum);
}
}
Should be written as:
package com.rule;
public class Use_System_dot_exit_with_care_correction
{
public static void main(String[] s)
{
int ia[]={1,2,3,4,5,6,7, 8, 9, 10, 11, 12, 13};
(new ThreadDoSum(ia)).start();
return;// Correction
}
}
class ThreadDoSum extends Thread
{
int[] ia = null;
public ThreadDoSum(int ia[])
{
this.ia = ia;
}
public void run()
{
int sum = 0;
for (int i = 0; i < ia.length; i++)
{
sum += ia[i];
}
System.out.println(sum);
}
}
Reference:
http://www.javapractices.com/Topic86.cjp
http://www.devx.com/tips/Tip/14560
Severity:
Medium
Rule:
Avoid wrong increment in for loop.
Reason:
Avoid wrong increment in for loop.
Usage Example:
package com.rule;
class Avoid_wrong_increment_in_for_violation
{
public void method ()
{
int array[] = {10,20,30,40};
int length = array.length;
int j = 0;
for(int i = 0 ; i < length ;j++) // Violation.
{
// Some Code ...
}
}
}
Should be written as:
package com.rule;
class Avoid_wrong_increment_in_for_Correction
{
public void method ()
{
int array[] = {10,20,30,40};
int length = array.length;
for(int i = 0 ; i < length ;i++) // Correction.
{
// Some Code ...
}
}
}
Reference:
Reference not available.
Severity:
High
Rule:
Never call overridable method from constructor.
Reason:
Never call overridable method from constructor.
Usage Example:
public class Never_call_overridable_method_from_constructor_violation
{
public static void main(String[] a)
{
Child c = new Child();
System.out.println(c.type); //is null even though Child's inititlize() was executed.
}
public Never_call_overridable_method_from_constructor_violation()
{
inititlize(); //Violation
}
public void inititlize()
{
}
}
class Child extends Never_call_overridable_method_from_constructor_violation
{
public String type = null;
public Child()
{
super();
}
public void inititlize()
{
type = "CHART";
}
}
Should be written as:
Do not call overridable method inside constructor.
Reference:
http://www.javapractices.com/Topic11.cjp
Severity:
High
Rule:
It can lead to possible errors.
Reason:
It can lead to possible errors.
Usage Example:
public class Test
{
public void method (int[] a)
{
a[0] = 0; // VIOLATION
}
}
Should be written as:
public class Test
{
public void method (int[] a)
{
final int len = a.length;
int[] b = new int [len];
System.arraycopy (a, 0, b, 0, len);
b[0] = 0; // FIXED
}
}
Reference:
Not available.
Severity:
Critical
Rule:
Avoid non-Serializable and non primitive instance field inside Serializable class.
Reason:
Avoid non-Serializable and non primitive instance field inside Serializable class.
Usage Example:
package com.rule;
import java.io.*;
public class Avoid_non_Serializable_field_inside_Serializable_class_violation implements Serializable
{
MyClass mc = new MyClass(); // Violation
private int iNum = 90;
public static void main(String args[]) throws IOException
{
FileOutputStream out = new FileOutputStream("Test");
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(new Avoid_non_Serializable_field_inside_Serializable_class_violation());
oos.flush();
}
}
class MyClass
{
int j =89;
}
Should be written as:
Avoid non Serializable field inside Serializable class.
Reference:
Reference not available.
Severity:
Critical
Rule:
If any non-serializable superclasses don't have a zero-argument constructor, serialization will fail.
Reason:
If any non-serializable superclasses don't have a zero-argument constructor, serialization will fail.
Usage Example:
public class SomeClass implements java.io.Serializable
extends SuperClass //VIOLATION
{
SomeClass()
{
super(0);
}
}
class SuperClass
{
SuperClass(int i) { }
}
Should be written as:
public class SomeClass implements java.io.Serializable
extends SuperClass
{
SomeClass()
{
super(0);
}
}
class SuperClass
{
SuperClass(int i) { }
SuperClass() { } // CORRECTION
}
Reference:
No references available.
Severity:
Critical
Rule:
This code would definitely throw a java.lang.NullPointerException.
Reason:
This code would definitely throw a java.lang.NullPointerException.
Usage Example:
public class Erroneous_null_check_violation
{
public void aMethod()
{
Object x = new Object();
if (x == null)
{
System.out.println(x.toString()); // VIOLATION
}
}
}
Should be written as:
Reference:
Reference not available.
Severity:
Critical
Rule:
A possibly-null value is passed to a method which unconditionally dereferences it resulting in a null pointer exception.
Reason:
A possibly-null value is passed to a method which unconditionally dereferences it resulting in a null pointer exception.
Usage Example:
public class Test
{
public void fubar()
{
Object s = null;
//...
System.out.println(getStringRepresentation(s)); // VIOLATION
}
private String getStringRepresentation( Object s )
{
return s.toString();
}
}
Should be written as:
public class Test
{
public void fubar()
{
Object s = null;
//...
System.out.println(getStringRepresentation(s));
}
private String getStringRepresentation( Object s )
{
return s != null ? s.toString() : ""; // FIXED
}
}
Reference:
Not Available.
Severity:
Critical
Rule:
This code would definitely throw a java.lang.ClassCastException.
Reason:
This code would definitely throw a java.lang.ClassCastException.
Usage Example:
import java.util.Hashtable;
import java.util.Vector;
public class Test
{
Hashtable baz()
{
return new Hashtable();
}
Vector [] faz()
{
return new Vector[10];
}
int f2()
{
Object o = faz();
return ((Hashtable [])o).length; // VIOLATION
}
int hx()
{
Object o = baz();
return ((Vector)o).size(); // VIOLATION
}
}
Should be written as:
Reference:
No references available.
Severity:
Critical
Rule:
This code in the constructor calls methods in the parent Applet that rely on the Applet stub.
Reason:
This code in the constructor calls methods in the parent Applet that rely on the Applet stub.
Usage Example:
import java.applet.Applet;
import java.net.URL;
public class Test extends Applet
{
public Test()
{
URL u1 = getDocumentBase(); // VIOLATION
URL u2 = getCodeBase(); // VIOLATION
if (u1.equals(u2))
return;
if (getParameter("bad") != null) // VIOLATION
return;
if (getAppletContext() != null) // VIOLATION
return;
}
}
Should be written as:
Reference:
No references available.
Severity:
Critical
Rule:
Avoid double checked locking.
Reason:
Avoid double checked locking.
Usage Example:
package com.rule;
public class Avoid_double_checked_locking
{
Object objOne = null;
if(objOne == null)
{
synchronized(this)
{
if(objOne == null) // Violation.
{
objOne = null;
}
}
}
}
Should be written as:
Reference:
http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.
Severity:
Medium
Rule:
Avoid immediate dereference of result of readLine() method.
Reason:
Avoid immediate dereference of result of readLine() method.
Usage Example:
package com.rule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
class Avoid_immediate_dereference_of_readLine_violation
{
public void method ()
{
BufferedReader in = new BufferedReader(new FileReader("InputFile.txt"));
if(in.readLine().equals("AppPerfect")) // Violation
{
// Some Code ...
}
}
}
Should be written as:
package com.rule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
class Avoid_immediate_dereference_of_readLine_Correction
{
public void method ()
{
BufferedReader in = new BufferedReader(new FileReader("InputFile.txt"));
String str = in.readLine();
if(str != null )
{
if(str.equals("AppPerfect")) // Correction
{
// Some Code ...
}
}
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Result of readLine() is not used.
Reason:
Result of readLine() is not used.
Usage Example:
package com.rule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class Result_of_readLine_not_used_violation
{
public void method()
{
BufferedReader in = new BufferedReader(new FileReader("InputFile.txt"));
String str = null;
if(in.readLine() != null ) // Violation
{
str = in.readLine();
}
}
}
Should be written as:
package com.rule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
public class Result_of_readLine_not_used_correction
{
public void method()
{
BufferedReader in = new BufferedReader(new FileReader("InputFile.txt"));
String str = null;
if((str = in.readLine()) != null) //Correction.
{
str;
}
}
}
Reference:
Reference not available.
Severity:
Low
Rule:
The run method should be declared as synchronized.
Reason:
The run method should be declared as synchronized.
Usage Example:
package com.rule;
public class Declare_Runnable_run_as_synchronized_violation implements Runnable
{
public void run() // VIOLATION
{
System.out.println("Declare_Runnable_run_as_synchronized_violation.run()");
}
}
Should be written as:
package com.rule;
public class Declare_Runnable_run_as_synchronized_correction implements Runnable
{
public synchronized void run() // CORRECTION
{
System.out.println("Declare_Runnable_run_as_synchronized_correction.run()");
}
}
Reference:
No reference available.
Severity:
Low
Rule:
TODO comments left in the code could indicate that the implementation is incomplete or some bug needs to be fixed.
Reason:
TODO comments left in the code could indicate that the implementation is incomplete or some bug needs to be fixed.
Usage Example:
public class MyClass
{
public void myMethod()
{
// TODO Auto-generated method stub // VIOLATION
}
}
Should be written as:
public class MyClass
{
public void myMethod()
{
//...
// FIXED, TODO comment is removed
}
}
Reference:
Not available.
Severity:
Low
Rule:
Avoid using primitive spin locks.
Reason:
Avoid using primitive spin locks.
Usage Example:
public class Test
{
boolean flag;
void waitForTrue()
{
for(;flag;); // VIOLATION
}
Test foo;
Test bar;
void waitForNonNull()
{
while(foo == null); // VIOLATION
}
static void waitForNonNullIndirect(int x, Test baz)
{
while(baz.foo == null); // VIOLATION
while(baz.foo.bar == null); // VIOLATION
}
static boolean sflag;
static void waitForStatic()
{
do
{
}while(!sflag); // VIOLATION
}
}
Should be written as:
Reference:
No references available.
Severity:
High
Rule:
Avoid down casting to concrete collection.
Reason:
Avoid down casting to concrete collection.
Usage Example:
public class Test
{
List a;
public Vector swap(List b)
{
Vector v = (Vector) a;
a = (Vector) b; // VIOLATION
return v;
}
}
Should be written as:
Reference:
No references available.
Severity:
High
Rule:
Avoid casting java.util.Collection or java.util.Iterable to another abstract collection.
Reason:
Avoid casting java.util.Collection or java.util.Iterable to another abstract collection.
Usage Example:
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
public class Test
{
Map bar()
{
return new Hashtable();
}
int d()
{
Map m = bar();
Set s = (Set) m.values(); // VIOLATION
return s.size();
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
Do not use empty statements
Reason:
Do not use empty statements
Usage Example:
package com.rule;
public class Avoid_empty_statement
{
public void saveAndExit(boolean bExit)
{
for(i=0; i < fileCount; saveFile(i++)); //violation
if (bExit)
{
exitEditor();
}; //Violation
}
}
Should be written as:
package com.rule;
public class Avoid_empty_statement
{
public void saveAndExit()
{
for(i=0; i < fileCount; saveFile(i++))
{ //Correction
}
if (bExit)
{
exitEditor();
} //Correction
}
}
Reference:
http://www.faqs.org/docs/javap/c3/s6.html
Severity:
Low
Rule:
Avoid fields with closely similar names
Reason:
Avoid fields with closely similar names
Usage Example:
package com.rule;
public class Avoid_fields_with_closely_similar_names_violation
{
int field;
int Field; // VIOLATION
}
Should be written as:
package com.rule;
public class Avoid_fields_with_closely_similar_names_correction
{
int field1;
int field2; // CORRECTION
}
Reference:
Reference not available.
Severity:
Low
Rule:
Fields are mutable.
Reason:
Fields are mutable.
Usage Example:
public class someException extends Exception
{
private String message; // VIOLATION
public someException(String message)
{
//...
}
}
Should be written as:
public class someException extends Exception
{
private final String message;
public someException(String message)
{
//...
}
}
Reference:
No references available.
Severity:
Medium
Rule:
Avoid casting primitive types to lower precision data types.
Reason:
Avoid casting primitive types to lower precision data types.
Usage Example:
package com.rule;
public class Do_not_cast_to_lower_precision
{
void method(long l, double d, float f, String str)
{
short s = (short) l; // VIOLATION
int i = s;
i = (int) f; // VIOLATION
f = (float) d; // VIOLATION
method((byte) i);
Object obj = (Object) str;
}
void method(byte b)
{
}
}
Should be written as:
Try using data types of proper precision.
Reference:
Reference Not Available.
Severity:
Medium
Rule:
This code could possibly throw a java.lang.ClassCastException.
Reason:
This code could possibly throw a java.lang.ClassCastException.
Usage Example:
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
public class Test
{
public static void main(String[] args)
{
Collection h = new ArrayList();
int i = 2;
if (i == 3)
{
h = new Vector();
}
List j = (Vector)h; // VIOLATION
if (h instanceof ArrayList)
{
j = (ArrayList)h;
}
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
Do not cast result of integer division to a double.
Reason:
Do not cast result of integer division to a double.
Usage Example:
package com.rule;
class Do_not_cast_integer_division_to_double_violation
{
public void method ()
{
int x = 2;
int y = 5;
double value1 = x / y; // Violation.
}
}
Should be written as:
package com.rule;
class Do_not_cast_integer_division_to_double_Correction
{
public void method ()
{
int x = 2;
int y = 5;
double value1 = (double) x / y; // Correction.
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
If the multiplication is done using long arithmetic, you can avoid the possibility that the result will overflow.
Reason:
If the multiplication is done using long arithmetic, you can avoid the possibility that the result will overflow.
Usage Example:
public class Test
{
long convertDaysToMilliseconds(int days)
{
return 1000*3600*24*days; // VIOLATION
}
}
Should be written as:
public class Test
{
static final long MILLISECONDS_PER_DAY = 24L*3600*1000; // FIXED
long convertDaysToMilliseconds(int days)
{
return days * MILLISECONDS_PER_DAY;
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
Use random.nextInt() instead of (int)(random.nextDouble()).
Reason:
Use random.nextInt() instead of (int)(random.nextDouble()).
Usage Example:
package com.rule;
import java.util.Random;
public class Use_random_nextInt_violation
{
public void method()
{
Random r = new Random();
int i = (int)(r.nextDouble()*100); // Violation.
}
}
Should be written as:
package com.rule;
import java.util.Random;
public class Use_random_nextInt_correction
{
public void method()
{
Random r = new Random();
int i = r.nextInt(100); //Corection.
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid casting random value from 0 to 1 to integer before its use.
Reason:
Avoid casting random value from 0 to 1 to integer before its use.
Usage Example:
import java.util.Random;
public class Avoid_casting_random_value_to_integer_violation
{
public void method()
{
Random r = new Random(3);
int i = (int) r.nextFloat(); // Violation.
}
}
Should be written as:
import java.util.Random;
public class Avoid_casting_random_value_to_integer_violation
{
public void method()
{
Random r = new Random();
int i = r.nextInt(3);
}
}
Reference:
http://java.sun.com/developer/JDCTechTips/2001/tt0925.html#tip1
Severity:
Medium
Rule:
Avoid overwriting the increment of a variable.
Reason:
Avoid overwriting the increment of a variable.
Usage Example:
package com.rule;
public class Overwritten_increment_violation
{
public void method()
{
int i = 10;
i = i++; // Violation.
}
}
Should be written as:
package com.rule;
public class Overwritten_increment_correction
{
public void method()
{
int i = 10;
i++; //Correction.
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid overwriting the decrement of a variable.
Reason:
Avoid overwriting the decrement of a variable.
Usage Example:
package com.rule;
public class Overwritten_decrement_violation
{
public void method()
{
int i = 10;
i = i--; // Violation.
}
}
Should be written as:
package com.rule;
public class Overwritten_decrement_correction
{
public void method()
{
int i = 10;
i--; //Correction.
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid passing wrong month value.
Reason:
Avoid passing wrong month value.
Usage Example:
package com.rule;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Invalid_month_argument_violation
{
public void method()
{
Date date = new Date();
date.setMonth(12); // Violation.
Calendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH,14); // Violation.
}
}
Should be written as:
package com.rule;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Invalid_month_argument_correction
{
public void method()
{
Date date = new Date();
date.setMonth(0); // Correction
Calendar cal = new GregorianCalendar();
cal.set(Calendar.MONTH,2); // Correction
}
}
Reference:
Reference not available.
Severity:
High
Rule:
Calling run method of Runnable object directly will not create a new thread.
Reason:
Calling run method of Runnable object directly will not create a new thread.
Usage Example:
package com.rule;
public class Do_not_call_run_explicitly_violation
{
public void method(Do_not_call_run_explicitly_violation1 obj)
{
obj.run(); // VIOLATION
}
}
class Do_not_call_run_explicitly_violation1 implements Runnable
{
public void run()
{
}
}
Should be written as:
package com.rule;
public class Do_not_call_run_explicitly_correction
{
public void method(Do_not_call_run_explicitly_violation1 obj)
{
new Thread(obj).start(); // CORRECTION
}
}
class Do_not_call_run_explicitly_violation1 implements Runnable
{
public void run()
{
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runnable.html
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html
Severity:
Medium
Rule:
Catching IllegalMonitorStateException represents a logical error in the code.
Reason:
Catching IllegalMonitorStateException represents a logical error in the code.
Usage Example:
package com.rule;
public class Avoid_catching_IllegalMonitorStateException_violation
{
public void method(Object obj)
{
try
{
obj.wait(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (IllegalMonitorStateException e) // VIOLATION
{
e.printStackTrace();
}
}
}
Should be written as:
package com.rule;
public class Avoid_catching_IllegalMonitorStateException_correction
{
public void method(Object obj)
{
try
{
// use proper synchronization
synchronized(obj) // CORRECTION
{
obj.wait(1000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
Reference:
No Reference available.
Severity:
Medium
Rule:
Certain swing methods should only be called in swing event thread.
Reason:
Certain swing methods should only be called in swing event thread.
Usage Example:
package com.rule;
import javax.swing.JFrame;
public class Always_call_swing_methods_in_swing_event_thread_violation
{
public static void main(String args[])
{
JFrame frame = new JFrame();
frame.setTitle("Title");
frame.setSize(200, 100);
frame.show(); // Violation
frame.pack(); // Violation
frame.setVisible(true); // Violation
}
}
Should be written as:
package com.rule;
import javax.swing.JFrame;
public class Always_call_swing_methods_in_swing_event_thread_correction implements Runnable
{
final Frame frame;
public FrameShower(Frame frame)
{
this.frame = frame;
}
public void run()
{
frame.show(); //Correction
}
public static void main(String args[])
{
JFrame frame = new JFrame();
frame.setTitle("Title");
frame.setSize(200, 100);
Runnable runner = new FrameShower(frame);
}
}
Reference:
http://java.sun.com/developer/JDCTechTips/2003/tt1208.html#1
Severity:
Medium
Rule:
Avoid erroneous use of binary AND operator with zero.
Reason:
Avoid erroneous use of binary AND operator with zero.
Usage Example:
package com.rule;
public class Erroneous_use_of_binary_AND_with_ZERO_violation
{
public static final int HSCROLLBAR = 1;
public static final int VSCROLLBAR = 2;
public static final int NONE = 0;
public static final int BOTHSCROLLBARS = 3;
public boolean check(int attribs)
{
return ((attribs & NONE) == NONE);
}
}
Should be written as:
No correction available.
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid expression involing specific use of bitwise AND operator that always evaluate to false.
Reason:
Avoid expression involing specific use of bitwise AND operator that always evaluate to false.
Usage Example:
package com.rule;
public class Erroneous_use_of_BAND_violation
{
public static final int HSCROLLBAR = 1;
public static final int VSCROLLBAR = 2;
public static final int NONE = 0;
public static final int BOTHSCROLLBARS = 3;
public boolean check(int attribs)
{
return ((attribs & VSCROLLBAR) == BOTHSCROLLBARS);
}
}
Should be written as:
No correction available.
Reference:
Reference not available.
Severity:
Medium
Rule:
If compareTo method is declared, it should have the parameter of type java.lang.Object.
Reason:
If compareTo method is declared, it should have the parameter of type java.lang.Object.
Usage Example:
package com.rule;
public class Declare_Object_as_parameter_for_compareTo_method_violation
{
public int compareTo(Declare_Object_as_parameter_for_compareTo_method_violation o) // VIOLATION
{
return 0;
}
}
Should be written as:
package com.rule;
public class Declare_Object_as_parameter_for_compareTo_method_correction
{
public int compareTo(Object o) // CORRECTION
{
return 0;
}
}
Reference:
No reference available.
Severity:
Medium
Rule:
Explicitly intialize all fields constructor.
Reason:
Explicitly intialize all fields constructor.
Usage Example:
public class Init
{
private int i = 5;
private int j;
private int k;
public Init()
{
this (12);
k = 0;
}
public Init ( int val ) // VIOLATION : k is not initialized.
{
j = val;
}
}
Should be written as:
public class Init
{
private int i = 5;
private int j;
private int k;
public Init()
{
this (12);
}
public Init ( int val )
{
j = val;
k = 0; // CORRECTION
}
}
Reference:
No references available.
Severity:
Medium
Rule:
This should be avoided because decimal literals are not precisely equal to their desired values.
Reason:
This should be avoided because decimal literals are not precisely equal to their desired values.
Usage Example:
import java.math.*;
public class Test
{
public void method()
{
BigDecimal bd= new BigDecimal(.1); //VIOLATION
}
}
Should be written as:
Use the 'BigDecimal' constructor which takes a String as an argument instead
of the one which takes a double since this constructor will produce a precise
value.
import java.math.*;
public class Test
{
public void method()
{
BigDecimal bd= new BigDecimal(".1"); //FIXED
}
}
Reference:
Not available.
Severity:
Medium
Rule:
Use equals method for String comparison.
Reason:
Use equals method for String comparison.
Usage Example:
package com.rule;
public class Use_string_equals_method_violation
{
public void foo()
{
String str = "compare";
String temp = new String("compare");
if(str == temp) // Violation
{
//...
System.out.println("same content");
}
}
}
Should be written as:
package com.rule;
public class Use_string_equals_method_correction
{
public void foo()
{
String str = "compare";
String temp = new String("compare");
if(str.equals(temp)) // Correction
{
//...
System.out.println("same content");
}
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Initializations that depend on static fields from different classes or files should be avoided.
Reason:
Initializations that depend on static fields from different classes or files should be avoided.
Usage Example:
public class NoCirc
{
public static void main(String args[])
{
// If the order is switched, the result would be different
IC2 ref2= new IC2();
IC1 ref1= new IC1();
System.out.println(IC1.a + " "+ IC2.b);
}
}
class IC1
{
static int a= IC2.b+ 1; //VIOLATION
}
class IC2
{
static int b= IC1.a; //VIOLATION
}
Should be written as:
public class NoCirc
{
public static void main(String args[])
{
IC2 ref2= new IC2();
IC1 ref1= new IC1();
System.out.println(IC1.a + " "+ IC2.b);
}
}
class IC1
{
static int a= IC2.b+ 1; // CORRECTION
}
class IC2
{
static int b= 0; // CORRECTION
}
Reference:
No references available.
Severity:
High
Rule:
If the getter or setters are setting fields other than the one mentioned in it name, then it could be a possible bug.
Reason:
If the getter or setters are setting fields other than the one mentioned in it name, then it could be a possible bug.
Usage Example:
public class AlwaysEnsureGetSetMethodsAccessCorrectFields
{
private String _str1;
private String _str2;
public void setStr1(String str) //VIOLATION
{
_str2= str;
}
public String getStr2() //VIOLATION
{
return _str1;
}
}
Should be written as:
public class AlwaysEnsureGetSetMethodsAccessCorrectFields
{
private String _str1;
private String _str2;
public void setStr1(String str) // CORRECTION
{
_str1= str;
}
public String getStr2() // CORRECTION
{
return _str2;
}
}
Reference:
No references available.
Severity:
Medium
Rule:
Declare the fields as final or private so as to prevent them from unauthorized modifications.
Reason:
Declare the fields as final or private so as to prevent them from unauthorized modifications.
Usage Example:
public class MyException extends java.lang.Exception // VIOLATION
{
String extraMessage;
int severity;
//...
}
Should be written as:
public class MyException extends java.lang.Exception
{
final String extraMessage;
private severity;
//...
}
Reference:
id="rule80"> Rule 80: Avoid_overloading_methods_on_argument_types >
Severity:
Medium
Rule:
Method overloading based on the argument's datatype should be avoided.
Reason:
Method overloading based on the argument's datatype should be avoided.
Usage Example:
package com.rule;
public class Avoid_overloading_methods_on_argument_types_violation
{
void method(Integer intVal) // VIOLATION
{
// handle Integer
}
void method(String strVal)
{
// handle String
}
}
Should be written as:
package com.rule;
public class Avoid_overloading_methods_on_argument_types_correction
{
void method(Object val) // CORRECTION
{
if(val instanceof Integer)
{
// handle Integer
}
else if(val instanceof String)
{
// handle String
}
}
}
Reference:
No reference available.
Severity:
Medium
Rule:
No value was assigned to private field.
Reason:
No value was assigned to private field.
Usage Example:
package com.rule;
public class Private_field_is_never_written_violation
{
private String name; // VIOLATION
public void debug()
{
System.out.println("name = "+ name);
}
}
Should be written as:
package com.rule;
public class Private_field_is_never_written_correction
{
// private String name; // CORRECTION
public void debug()
{
// System.out.println("name = "+ name);
}
}
Reference:
No reference available
Severity:
Critical
Rule:
Do not call synchronized method from synchronized method.
Reason:
Do not call synchronized method from synchronized method.
Usage Example:
package com.rule;
public class Do_not_call_synchronized_method_from_synchronized_method_violation
{
public synchronized void meth()
{
Test tt = new Test();
//...
tt.foo(); // Violation
}
}
class Test
{
public synchronized void foo()
{
//...
}
}
Should be written as:
Avoid calling synchronized method from synchronized method.
Reference:
http://www.onjava.com/pub/a/onjava/2004/10/20/threads2.html
Severity:
High
Rule:
Always place literals first in string comparison.
Reason:
Always place literals first in string comparison.
Usage Example:
package com.rule;
public class Always_place_literals_first_in_string_comparison_violation
{
public void method()
{
String str = "AppPerfect";
if(str.equals("AppPerfect")) // Violation.
{
}
}
}
Should be written as:
package com.rule;
public class Always_place_literals_first_in_string_comparison_correction
{
public void method()
{
String str = "AppPerfect";
if("AppPerfect".equals(str)) //Correction.
{
}
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Do not use equals operator for decimal point values to avoid possible errors
Reason:
Do not use equals operator for decimal point values to avoid possible errors
Usage Example:
package com.rule;
class Avoid_equals_operator_for_decimal_point_values_violation
{
public boolean isEqual(float f1, float f2)
{
return f1 == f2;
}
}
Should be written as:
Instead of checking for exact equality, check for sufficient equality. That is find the difference of two values and see if its in the permissible limits.
package com.rule;
class Avoid_equals_operator_for_decimal_point_values_correction
{
public boolean isEqual(float f1, float f2)
{
return (Math.abs(f1 - f2) < 0.01);
}
}
Reference:
http://www-106.ibm.com/developerworks/java/library/j-jtp0114/
Severity:
Medium
Rule:
Avoid returning java.lang.Object.
Reason:
Avoid returning java.lang.Object.
Usage Example:
public class NoObject
{
private String str;
public NoObject(String str)
{
super();
this.str = str;
}
public Object getMyString() // VIOLATION
{
return str;
}
public static void main(String[] args) throws Exception
{
NoObject no = new NoObject("Test");
String str = (String) no.getMyString();
System.out.println ( str );
}
}
Should be written as:
public class NoObject
{
private String str;
public NoObject(String str)
{
super();
this.str = str;
}
public String getMyString() // CORRECTION
{
return str;
}
public static void main(String[] args) throws Exception
{
NoObject no = new NoObject("Test");
String str = no.getMyString();
System.out.println ( str );
}
}
Reference:
No references available.
Severity:
High
Rule:
Avoid invoking System.runFinalizersOnExit or Runtime.runFinalizersOnExit.
Reason:
Avoid invoking System.runFinalizersOnExit or Runtime.runFinalizersOnExit.
Usage Example:
package com.rule;
public class Avoid_invoking_runFinalizersOnExit_violation
{
public void method()
{
Object[] oa = getObjects();
process(oa);
System.runFinalizersOnExit(true); // Violation.
Runtime.runFinalizersOnExit(true); // Violation.
}
}
Should be written as:
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid contiguous non String values during String concatenation.
Reason:
Avoid contiguous non String values during String concatenation.
Usage Example:
package com.rule;
public class Avoid_contiguous_non_String_values_during_concatenation_violation
{
public void method()
{
int principle = 100;
int interest = 10;
System.out.println("Net payable = " + principle + interest + " rupees"); // VIOLATION
}
}
Should be written as:
package com.rule;
public class Avoid_contiguous_non_String_values_during_concatenation_correction
{
public void method()
{
int principle = 100;
int interest = 10;
int total = principle + interest
System.out.println("Net payable = " + total + " rupees"); // CORRECTION
}
}
Reference:
Reference Not Available.
Severity:
Medium
Rule:
A conditional expression that always evaluates to false is mostly likely a possible bug.
Reason:
A conditional expression that always evaluates to false is mostly likely a possible bug.
Usage Example:
public class MyClass
{
public void process (int array_size, boolean b1, boolean b2)
{
if (array_size < 0 && array_size > 100 ) // VIOLATION
throw new IllegalArgumentException("invalid array size");
}
}
Should be written as:
public class MyClass
{
public void process (int array_size, boolean b1, boolean b2)
{
if (array_size < 0 || array_size > 100 ) // CORRECTION
throw new IllegalArgumentException("invalid array size");
}
}
Reference:
No references available.
Severity:
Medium
Rule:
Do not use any class fields that have not assigned any value in constructors.
Reason:
Do not use any class fields that have not assigned any value in constructors.
Usage Example:
package com.rule;
public class Avoid_accessing_uninitialized_fields_in_constructors_violation
{
private String name;
private int id;
public Avoid_accessing_uninitialized_fields_in_constructors_violation(int ID)
{
name = "name" + id; // VIOLATION
id = ID;
}
}
Should be written as:
package com.rule;
public class Avoid_accessing_uninitialized_fields_in_constructors_correction
{
private String name;
private int id;
public Avoid_accessing_uninitialized_fields_in_constructors_correction(int ID)
{
name = "name" + ID; // CORRECTION
id = ID;
}
}
Reference:
No reference available.
Severity:
Medium
Rule:
Do not use any class fields that have not assigned any value in methods.
Reason:
Do not use any class fields that have not assigned any value in methods.
Usage Example:
package com.rule;
public class Avoid_accessing_uninitialized_fields_violation
{
private String name;
private int id;
public void method()
{
name = "name" + id; // VIOLATION
id = ID;
}
}
Should be written as:
package com.rule;
public class Avoid_accessing_uninitialized_fields_correction
{
private String name;
private int id;
public void method()
{
name = "name" + ID; // CORRECTION
id = ID;
}
}
Reference:
No reference available.
Severity:
Critical
Rule:
The error is detected at runtime.
Reason:
The error is detected at runtime.
Usage Example:
package com.rule;
public class Avoid_Serializable_class_having_non_Serializable_parent_violation extends Super implements java.io.Serializable // VIOLATION
{
Avoid_Serializable_class_having_non_Serializable_parent_violation()
{
super(0);
}
}
class Super
{
Super(int i)
{
}
}
Should be written as:
package com.rule;
public class Avoid_Serializable_class_having_non_Serializable_parent_correction extends Super implements java.io.Serializable
{
Avoid_Serializable_class_having_non_Serializable_parent_violation()
{
super();
}
}
class Super
{
Super()
{
}
}
Reference:
http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html
Severity:
Medium
Rule:
Avoid comparison with Float.NaN and Double.NaN.
Reason:
Avoid comparison with Float.NaN and Double.NaN.
Usage Example:
package com.rule;
public class Avoid_comparison_with_float_NaN_violation
{
public void method()
{
if(performDivision(0.0f, 0.0f) == Float.NaN) // Violation
{
System.out.println("Not a Number");
}
else
{
System.out.println(" a Number");
}
}
public float performDivision(float f1,float f2)
{
return f1/f2;
}
}
Should be written as:
package com.rule;
public class Avoid_comparison_with_float_NaN_correction
{
public void method()
{
if(Float.isNan(performDivision(0.0, 0.0))) // Correction
{
System.out.println("Not a Number");
}
else
{
System.out.println(" a Number");
}
}
public float performDivision(float f1,float f2)
{
return f1/f2;
}
}
Reference:
http://www.concentric.net/~Ttwang/tech/javafloat.htm
Severity:
High
Rule:
If the set method is synchronized, the get method should also be synchronized.
Reason:
If the set method is synchronized, the get method should also be synchronized.
Usage Example:
package com.rule;
public class Declare_get_method_synchronized_violation
{
private int value;
public int getValue() // VIOLATION
{
return value;
}
public synchronized void setValue(int val)
{
value = val;
}
}
Should be written as:
package com.rule;
public class Declare_get_method_synchronized_correction
{
private int value;
public synchronized int getValue() // CORRECTION
{
return value;
}
public synchronized void setValue(int val)
{
value = val;
}
}
Reference:
No reference available.
Severity:
High
Rule:
Float and double do not provide exact results and should not be used where exact results are required.
Reason:
Float and double do not provide exact results and should not be used where exact results are required.
Usage Example:
public class BadFloatAndDouble
{
public static void main(String[] args)
{
double funds = 1.0;
int itemsBought = 0;
for (double price = .10; funds >= price; price += .10) // VIOLATION
{
funds -= price; // VIOLATION
itemsBought++;
}
System.out.println(itemsBought + " items bought.");
System.out.println("Change : $" + funds); // VIOLATION
}
}
Should be written as:
public class BadFloatAndDouble
{
public static void main(String[] args)
{
final BigDecimal TEN_CENTS = new BigDecimal(".10");
int itemsBought = 0;
BigDecimal funds = new BigDecimal("1.00");
for (BigDecimal price = TEN_CENTS; funds.compareTo(price) >= 0;
price = price.add(TEN_CENTS))
{
itemsBought++;
funds = funds.subtract(price);
}
System.out.println(itemsBought + " items bought.");
System.out.println("Money left over: $" + funds);
}
}
Reference:
Joshua Bloch: "Effective Java - Programming Language Guide" Addison Wesley, 2001, pp. 149-151
Severity:
Critical
Rule:
Avoid assigning variable to same variable.
Reason:
Avoid assigning variable to same variable.
Usage Example:
package com.rule;
public class Avoid_assigning_variable_to_same_variable_violation
{
private int iVar;
Avoid_assigning_variable_to_same_variable_violation(int iVar)
{
iVar = iVar; // Violation
}
}
Should be written as:
package com.rule;
public class Avoid_assigning_variable_to_same_variable_correction
{
private int iVar;
Avoid_assigning_variable_to_same_variable_violation(int iVar)
{
this.iVar = iVar; // Correction
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid erroneous use of binary OR operator.
Reason:
Avoid erroneous use of binary OR operator.
Usage Example:
package com.rule;
public class Erroneous_use_of_binary_OR_violation
{
public static final int HSCROLLBAR = 1;
public static final int VSCROLLBAR = 2;
public static final int NONE = 0;
public static final int BOTHSCROLLBARS = 3;
public boolean check(int attribs)
{
return ((attribs | BOTHSCROLLBARS) == HSCROLLBAR);
}
}
Should be written as:
No correction available.
Reference:
Reference not available.
Severity:
Critical
Rule:
Avoid unsynchronized lazy initialization of non-volatile static field.
Reason:
Avoid unsynchronized lazy initialization of non-volatile static field.
Usage Example:
package com.rule;
public class Avoid_Lazy_initialization_of_unsynchronized_static_field_violation
{
private static Singleton instance = null;
public static Singleton getInstance ( )
{
if (instance == null )
instance = new Singleton ( ); // Violation
return instance;
}
}
Should be written as:
Reference:
http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html
Severity:
High
Rule:
Avoid using volatile modifier for array.
Reason:
Avoid using volatile modifier for array.
Usage Example:
package com.rule;
public class Avoid_using_volatile_modifier_for_array_violation
{
public static volatile int i = 10;
public static volatile int[] array = {10,20,30}; //Violation.
}
Should be written as:
Reference:
Reference not available.
Severity:
Critical
Rule:
Avoid synchronization on objects whose references are mutable.
Reason:
Avoid synchronization on objects whose references are mutable.
Usage Example:
package com.rule;
public class Avoid_synchronization_on_mutable_field_violation
{
MyClass myClass = new MyClass();
public void foo()
{
synchronized(myClass)// Violation
{
//...
}
}
}
Should be written as:
Avoid synchronization on objects whose references are mutable.
Reference:
Reference not available.
Severity:
Low
Rule:
Avoid methods in same class which differ only in case.
Reason:
Avoid methods in same class which differ only in case.
Usage Example:
package com.rule;
public class Avoid_methods_with_closely_similar_names_violation
{
public void method()
{
}
public void Method() // VIOLATION
{
}
}
Should be written as:
package com.rule;
public class Avoid_methods_with_closely_similar_names_correction
{
public void method1()
{
}
public void method2() // CORRECTION
{
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
The objects passed to some of the methods need to be Serializable.
Reason:
The objects passed to some of the methods need to be Serializable.
Usage Example:
package com.rule;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class Use_serializable_objects_as_argument_violation
{
public void method1(ObjectOutputStream oos) throws Exception
{
oos.writeObject(this); // VIOLATION
}
class USOAAV_ObjectOutputStream extends ObjectOutputStream
{
USOAAV_ObjectOutputStream(OutputStream os) throws IOException
{
super(os);
}
}
}
Should be written as:
package com.rule;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class Use_serializable_objects_as_argument_correction implements Serializable // Correction
{
public void method1(ObjectOutputStream oos) throws Exception
{
oos.writeObject(this);
}
class USOAAV_ObjectOutputStream extends ObjectOutputStream
{
USOAAV_ObjectOutputStream(OutputStream os) throws IOException
{
super(os);
}
}
}
Reference:
No reference available.
Severity:
High
Rule:
The methods of Applet that use AppletStub should not be called from constructor.
Reason:
The methods of Applet that use AppletStub should not be called from constructor.
Usage Example:
package com.rule;
import java.applet.Applet;
public class Do_not_call_methods_that_use_AppletStub_violation extends Applet
{
private String docBase;
public Do_not_call_methods_that_use_AppletStub_violation()
{
docBase = getDocumentBase().toString(); // VIOLATION
}
}
Should be written as:
package com.rule;
import java.applet.Applet;
public class Do_not_call_methods_that_use_AppletStub_correction extends Applet
{
private String docBase;
public void init() // CORRECTION
{
docBase = getDocumentBase().toString();
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/api/java/applet/AppletStub.html
Severity:
Critical
Rule:
This is the convention to be followed for the readResolve method to be recognized by the serialization mechanism.
Reason:
This is the convention to be followed for the readResolve method to be recognized by the serialization mechanism.
Usage Example:
import java.io.ObjectStreamException;
import java.io.Serializable;
public class Test implements Serializable
{
public Test readResolve () throws ObjectStreamException // VIOLATION
{
return null;
}
}
Should be written as:
import java.io.ObjectStreamException;
import java.io.Serializable;
public class Test implements Serializable
{
public Object readResolve () throws ObjectStreamException // VIOLATION
{
return null;
}
}
Reference:
Not Available.
Severity:
High
Rule:
Do not call setSize method inside the componentResized method
Reason:
Do not call setSize method inside the componentResized method
Usage Example:
package com.rule;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class Avoid_setSize_in_componentResized_violation extends Frame
{
public Avoid_setSize_in_componentResized_violation()
{
Panel pan = new Panel();
pan.setBackground(Color.blue);
this.add(pan, BorderLayout.CENTER);
pan.addComponentListener(new ComponentAdapter(){
public void componentResized(ComponentEvent e)
{
setSize();
Frame parent = Avoid_setSize_in_componentResized_violation.this;
parent.setSize(200, 200); // VIOLATION
parent.validate();
}
public void setSize()
{
}
});
this.addComponentListener(new ComponentAdapter(){
public void componentResized(ComponentEvent e)
{
e.getComponent().setSize(10, 10); // VIOLATION
((Component) e.getSource()).setSize(20, 20); // VIOLATION
setSize(100, 100); // VIOLATION
}
});
}
}
Should be written as:
Remove calls to setSize methods from componentResized method.
Reference:
Reference Not Available.
Severity:
Medium
Rule:
Avoid unnecessary call to Math.ceil().
Reason:
Avoid unnecessary call to Math.ceil().
Usage Example:
package com.rule;
public class Avoid_unnecessary_call_to_Math_ceil_violation
{
public void method()
{
int i = 10;
double result = Math.ceil((double)i); // Violation
}
}
Should be written as:
package com.rule;
public class Avoid_unnecessary_call_to_Math_ceil_correction
{
public void method()
{
double i = 10.2;
double result = Math.ceil(i); // Correction
}
}
Reference:
Reference not available.
Severity:
Medium
Rule:
Avoid unnecessary call to a method of Math class.
Reason:
Avoid unnecessary call to a method of Math class.
Usage Example:
package com.rule;
public class Avoid_unnecessary_call_to_Math_class_method_violation
{
public static final double NUMBER = -10.2;
public void method()
{
double d =Math.abs(NUMBER); // Violation.
}
}
Should be written as:
package com.rule;
public class Avoid_unnecessary_call_to_Math_class_method_correction
{
public static final double NUMBER = -10.2;
public static final double ABSNUMBER = 10.2;
public void method()
{
double d = ABSNUMBER; //Correction.
}
}
Reference:
Reference not available.
Severity:
Low
Rule:
The return value of the method call should not be ignored.
Reason:
The return value of the method call should not be ignored.
Usage Example:
package com.rule;
public class Always_use_method_return_values
{
public void fubar()
{
String someString = getString();
someString.trim();
}
private String getString()
{
return "hello";
}
}
Should be written as:
package com.rule;
public class Always_use_method_return_values
{
public void fubar()
{
String someString = getString();
someString = someString.trim();
}
private String getString()
{
return "hello";
}
}
Reference:
No reference available.
Severity:
Low
Rule:
The return value of the method call InputStream.read(byte[] b) and InputStream.read(byte[] b,int off,int len) should always be checked.
Reason:
The return value of the method call InputStream.read(byte[] b) and InputStream.read(byte[] b,int off,int len) should always be checked.
Usage Example:
package com.rule;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Always_check_return_value_of_input_stream_read_violation
{
public void method()
{
InputStream in = null;
try
{
in = new FileInputStream("Filename.txt");
in.read(b,3,10); //Violation.
}
catch(IOException ioe)
{
// Handle Exception.
}
finally
{
in.close();
}
}
}
Should be written as:
package com.rule;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Always_check_return_value_of_input_stream_read_correction
{
public void method()
{
InputStream in = null;
try
{
in = new FileInputStream("Filename.txt");
int i = in.read(b,3,10); //Correction
// Check value of i.
}
catch(IOException ioe)
{
// Handle Exception.
}
finally
{
in.close();
}
}
}
Reference:
Reference not available.
Severity:
Low
Rule:
The return value of the method call InputStream.skip(long n) should always be checked.
Reason:
The return value of the method call InputStream.skip(long n) should always be checked.
Usage Example:
package com.rule;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Always_check_return_value_of_input_stream_skip_violation
{
public void method()
{
InputStream in = null;
try
{
long count = 100000;
in = new FileInputStream("Filename.txt");
in.skip(count); //Violation.
}
catch(IOException ioe)
{
// Handle Exception.
}
finally
{
in.close();
}
}
}
Should be written as:
package com.rule;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Always_check_return_value_of_input_stream_skip_correction
{
public void method()
{
InputStream in = null;
try
{
long count = 100000;
in = new FileInputStream("Filename.txt");
int i = in.skip(count); //Correction
// Check value of i.
}
catch(IOException ioe)
{
// Handle Exception.
}
finally
{
in.close();
}
}
}
Reference:
Reference not available.
Severity:
Low
Rule:
The condition should check whether indexOf returns negative or non-negative value.
Reason:
The condition should check whether indexOf returns negative or non-negative value.
Usage Example:
public class SomeClass
{
public void aMethod()
{
String s = "hello";
if(s.indexOf("e") > 0) // VIOLATION
{
// ...
}
if(s.indexOf("s") < 1) // VIOLATION
{
// ...
}
if(s.indexOf("h") >=1) // VIOLATION
{
// ....
}
If(s.indexOf("o") <= 0) // VIOLATION
{
// ...
}
}
}
Should be written as:
public class SomeClass
{
public void aMethod()
{
String s = "hello";
if(s.indexOf("e") >= 0)
{
// ...
}
if(s.indexOf("s") == -1)
{
// ...
}
if(s.indexOf("h") != -1)
{
// ....
}
If(s.indexOf("o") == -1)
{
// ...
}
}
}
Reference:
Reference not available.
Severity:
Low
Rule:
This code calls equals on an object of a final class which doesn't have equals() method overriden.
Reason:
This code calls equals on an object of a final class which doesn't have equals() method overriden.
Usage Example:
public final class Test
{
public void check(Test ne)
{
if (ne.equals( this )) // VIOLATION
{
System.out.println( "it's equal" );
}
}
}
Should be written as:
Check if equals needs to be overriden in class Test or not.
Reference:
No references available.
Severity:
Critical
Rule:
Possible infinite recursion.
Reason:
Possible infinite recursion.
Usage Example:
package com.rule;
import com.appperfect.common.dstruct.Color;
import com.appperfect.common.dstruct.Font;
public class Possible_infinite_recursion_violation
{
public void showMessage(String s, Font f)
{
showMessage(s, f, null);
}
public void showMessage(String s, Font f, Color fg)
{
showMessage(s, f, fg); //Violation
}
public void showMessage(String s, Font f, Color fg, Color bg)
{
//..code that renders actually
}
}
Should be written as:
No correction available.
Reference:
Reference not available.
Severity:
Critical
Rule:
Possible infinite loop.
Reason:
Possible infinite loop.
Usage Example:
import java.util.List;
import java.util.Iterator;
public class Test
{
public void method(List l)
{
boolean bool = true;
do
{
//...
} while (bool); //VIOLATION
Iterator iter;
for (iter = l.iterator(); iter.hasNext();) //VIOLATION
{
//...
}
while (true) //VIOLATION
{
//...
}
}
}
Should be written as:
import java.util.List;
import java.util.Iterator;
public class Test
{
public void method(List l)
{
boolean bool = true;
do
{
//...
bool = false; //FIXED
} while (bool);
Iterator iter;
for (iter = l.iterator(); iter.hasNext();)
{
//...
System.err.println(iter.next()); //FIXED
}
while (true)
{
//...
break; //FIXED
}
}
}
Reference:
Not Available.
Severity:
Medium
Rule:
This instanceOf check will always return false.
Reason:
This instanceOf check will always return false.
Usage Example:
import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
public class Test
{
public static void main(String[] args)
{
Collection s = new ArrayList();
if (s instanceof Vector) // VIOLATION
{
// ...
}
else
{
// ...
}
}
}
Should be written as:
Reference:
No references available.
Severity:
Medium
Rule:
Fields, methods, and types that are not "private" and not "static" are useless if the only constructors available are private.
Reason:
Fields, methods, and types that are not "private" and not "static" are useless if the only constructors available are private.
Usage Example:
public class Test// VIOLATION
{
private static Test _test;
private Test()
{
}
public Test getInstance()
{
if (_test == null)
{
_test = new Test();
}
return _test;
}
}
Should be written as:
public class Test // FIXED
{
private Test _test;
private Test()
{
}
public static Test getInstance()
{
if (_test == null)
{
_test = new Test();
}
return _test;
}
}
Reference:
Not Available.
Severity:
Low
Rule:
Removing it improves code readability and makes code less error-prone.
Reason:
Removing it improves code readability and makes code less error-prone.
Usage Example:
public class Test
{
public void method() throws Exception
{
try
{
// ...
}
catch (Exception e)// VIOLATION
{
throw e;
}
}
}
Should be written as:
public Test
{
public void method() throws Exception
{
// FIXED : try-catch statement is removed
// ...
}
}
Reference:
Not Available.
Severity:
Critical
Rule:
When an array is declared with a negative dimenson, a NegativeArraySizeException would be thrown.
Reason:
When an array is declared with a negative dimenson, a NegativeArraySizeException would be thrown.
Usage Example:
public class Test
{
private static final int A_SIZE= 10;
private static final int B_SIZE= 15;
private static int[] diffSet= new int[A_SIZE- B_SIZE]; // VIOLATION
}
Should be written as:
public class Test
{
private static final int A_SIZE= 10;
private static final int B_SIZE= 15;
private static int[] diffSet= new int[A_SIZE- B_SIZE>= 0 ? A_SIZE- B_SIZE : 0]; // FIXED
}
Reference:
Not Available.
Severity:
Medium
Rule:
Use equals() instead of '==' operator.
Reason:
Use equals() instead of '==' operator.
Usage Example:
package com.rule;
public class UseEqualsInsteadEqualityOperator_Violation
{
private void foo()
{
String str = "compare";
String temp = new String("compare");
if(str == temp) // Violation
{
//...
}
}
}
Should be written as:
package com.rule;
public class UseEqualsInsteadEqualityOperator_Correction
{
private void foo()
{
String str = "compare";
String temp = new String("compare");
if(str.equals(temp)) // Correction
{
//...
}
}
}
Reference:
http://www.devx.com/tips/Tip/14219
Severity:
Medium
Rule:
Possible spelling mistake while overriding method.
Reason:
Possible spelling mistake while overriding method.
Usage Example:
package com.rule;
public class Possible_spelling_mistake_while_overriding_method_violation
{
public String ToString() // VIOLATION
{
return super.toString();
}
}
Should be written as:
package com.rule;
public class Possible_spelling_mistake_while_overriding_method_correction
{
public String toString() // CORRECTION
{
return super.toString();
}
}
Reference:
Reference Not Available.
Severity:
Critical
Rule:
The index for get and update methods of ResultSet starts from 1.
Reason:
The index for get and update methods of ResultSet starts from 1.
Usage Example:
package com.rule;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Do_not_use_zero_as_index_with_ResultSet_violation
{
public String getName(ResultSet rs) throws SQLException
{
return rs.getString(0); // VIOLATION
}
public void setName(ResultSet rs, String name) throws SQLException
{
rs.updateString(0, name); // VIOLATION
}
}
Should be written as:
package com.rule;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Do_not_use_zero_as_index_with_ResultSet_correction
{
public String getName(ResultSet rs) throws SQLException
{
return rs.getString(1); // CORRECTION
}
public void setName(ResultSet rs, String name) throws SQLException
{
rs.updateString(1, name); // CORRECTION
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/resultset.html
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html
Severity:
Critical
Rule:
The index for the setters of PreparedStatement start from 1.
Reason:
The index for the setters of PreparedStatement start from 1.
Usage Example:
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Test
{
public void setName(PreparedStatement ps, String name) throws SQLException
{
ps.setObject(0, name); // VIOLATION
}
}
Should be written as:
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Test
{
public void setName(PreparedStatement ps, String name) throws SQLException
{
ps.setObject(1, name); // FIXED
}
}
Reference:
Not Available.
Severity:
High
Rule:
Always call wait from within a while or do-while loop.
Reason:
Always call wait from within a while or do-while loop.
Usage Example:
package com.rule;
public class AlwaysCall_wait_inside_while_or_doWhile_loop_Violation
{
int available = 0;
synchronized public void consume()
{
try
{
if (available < 0)
{
wait (); // VIOLATION
}
}
catch (InterruptedException e)
{
//consume
}
}
}
Should be written as:
package com.rule;
public class AlwaysCall_wait_inside_while_or_doWhile_loop_Correction
{
int available = 0;
synchronized public void consume()
{
try
{
while (available < 0)
{
wait (); // CORRECTION
}
}
catch (InterruptedException e)
{
//consume
}
}
}
Reference:
http://today.java.net/cs/user/create/cs_msg?x-lr=cs_msg/7296&x-lr2=a/131
Severity:
High
Rule:
If the object is used for multiple conditions, the condition the caller intended to wait for might not be the one that actually occurred.
Reason:
If the object is used for multiple conditions, the condition the caller intended to wait for might not be the one that actually occurred.
Usage Example:
public class Test
{
void fubar(Condition cond) throws InterruptedException // VIOLATION
{
cond.await();
}
}
Should be written as:
public class Test
{
int x;
void fubar(Condition cond) throws InterruptedException
{
while (x == 0)
{
cond.wait(); // FIXED
}
}
}
Reference:
Not Available.
Severity:
High
Rule:
Avoid using wait(), notify() or notifyAll() on the "this" reference.
Reason:
Avoid using wait(), notify() or notifyAll() on the "this" reference.
Usage Example:
import java.util.*;
public class Test extends Thread
{
ArrayList objects = new ArrayList();
public static void main(String[] args)
{
final Test test = new Test();
Thread t1 = new Thread()
{
public void run()
{
try
{
test.add(new Object());
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
};
t1.start();
Thread t2 = new Thread()
{
public void run()
{
try
{
test.add(new Object());
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
};
t2.start();
}
public synchronized void add(Object obj) throws InterruptedException
{
while (objects.size() == 10)
{
wait(); // VIOLATION
}
objects.add(obj);
if(objects.size() == 1)
{
notify();
}
}
}
Should be written as:
Consider using a private member variable to control synchronization.
Reference:
No reference available.
Severity:
High
Rule:
The static method interrupted in Thread class should not be called on a thread object.
Reason:
The static method interrupted in Thread class should not be called on a thread object.
Usage Example:
package com.rule;
public class Do_not_call_interrupted_method_on_thread_object_violation
{
public void method(Thread th)
{
boolean b = th.interrupted(); // VIOLATION
}
}
Should be written as:
package com.rule;
public class Do_not_call_interrupted_method_on_thread_object_correction
{
public void method(Thread th)
{
boolean b = th.isInterrupted(); // CORRECTION
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#interrupted()
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#isInterrupted()
Severity:
Low
Rule:
Avoid unnecessary comparison of two references which are definitely null.
Reason:
Avoid unnecessary comparison of two references which are definitely null.
Usage Example:
public class Test
{
public void fubar()
{
Object ob1 = null;
Object ob2 = null;
//...
if(ob1 != ob2) // VIOLATION
{
//...
}
}
}
Should be written as:
Check if the ob1 and ob2 are to always remain null, then the condition can be removed.
Reference:
Not Available.
Severity:
Low
Rule:
Avoid unnecessary comparison of two references where one is definitely non null and the other is definitely null.
Reason:
Avoid unnecessary comparison of two references where one is definitely non null and the other is definitely null.
Usage Example:
public class Test
{
public void fubar()
{
Object ob1 = null;
Object ob2 = null;
//...
ob2 = new Object();
//...
if(ob1 == ob2) // VIOLATION
{
//...
}
}
}
Should be written as:
If one value is always going to be null and the other always non-null, then the condition can be removed.
Reference:
Not Available.
Severity:
Medium
Rule:
This will return a constant value.
Reason:
This will return a constant value.
Usage Example:
public class Test
{
int method(int x)
{
for(int i = 0; i <= Integer.MAX_VALUE; i++) // VIOLATION
{
if (i*i == x)
{
return i;
}
}
return 0;
}
int method2(int x)
{
if (x < 0 || x > Integer.MAX_VALUE) // VIOLATION
{
return -1;
}
return x;
}
}
Should be written as:
Please recheck condition.
Reference:
Not Available.
Severity:
Low
Rule:
The start() method of a thread should not be called in it's constructor.
Reason:
The start() method of a thread should not be called in it's constructor.
Usage Example:
package com.rule;
public class Do_not_start_Thread_in_constructor_violation
{
void method()
{
new Thread_sub();
}
class Thread_sub extends Thread
{
public Thread_sub()
{
start(); // VIOLATION
}
}
}
Should be written as:
package com.rule;
public class Do_not_start_Thread_in_constructor_correction
{
void method()
{
new Thread_sub().start(); // CORRECTION : call to start() moved here
}
class Thread_sub extends Thread
{
public Thread_sub()
{
// CORRECTION : call to start() is moved to where object is created
}
}
}
Reference:
https://lists.xcf.berkeley.edu/lists/advanced-java/2001-April/016440.html
Severity:
Low
Rule:
Classes or interfaces having same name as java file should be declared as public.
Reason:
Classes or interfaces having same name as java file should be declared as public.
Usage Example:
file name: MyFile.java
class MyFile // VIOLATION
{}
Should be written as:
file name: MyFile.java
public class MyFile // CORRECTION
{}
Reference:
No references available.
Severity:
Low
Rule:
Atleast one class or interface should have the same name as the java file in which it is declared.
Reason:
Atleast one class or interface should have the same name as the java file in which it is declared.
Usage Example:
file name: MyClass.java
class MyClass_ // VIOLATION
{
}
Should be written as:
file name: MyClass.java
class MyClass // CORRECTION
{
}
Reference:
No refrerences available.
Severity:
Medium
Rule:
Avoid returning this from a method.
Reason:
Avoid returning this from a method.
Usage Example:
package com.rule;
public class Avoid_returning_this_violation
{
public Avoid_returning_this_violation method1()
{
return this; // VIOLATION
}
public void method2()
{
// something synchronized
}
public static void main(String[] args)
{
Avoid_returning_this_violation a = new Avoid_returning_this_violation();
a.method1().method2();
}
}
Should be written as:
package com.rule;
public class Avoid_returning_this_correction
{
public void method1()
{
return; // CORRECTION
}
public void method2()
{
// something synchronized
}
public static void main(String[] args)
{
Avoid_returning_this_correction a = new Avoid_returning_this_correction();
a.method1();
a.method2();
}
}
Reference:
http://gee.cs.oswego.edu/dl/html/javaCodingStd.html#secRec
Severity:
Medium
Rule:
Calling getResource() on the class returned by getClass() might cause unexpected results.
Reason:
Calling getResource() on the class returned by getClass() might cause unexpected results.
Usage Example:
package com.rule;
import java.net.URL;
public class Avoid_calling_getResource_on_getClass_violation
{
public URL loadResource(String str)
{
return this.getClass().getResource(str); // VIOLATION
}
}
Should be written as:
package com.rule;
import java.net.URL;
public class Avoid_calling_getResource_on_getClass_correction
{
public URL loadResource(String str)
{
return Avoid_calling_getResource_on_getClass_correction.class.getResource(str); // CORRECTION
}
}
Reference:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getResource(java.lang.String)
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
Severity:
Critical
Rule:
There should be atleast one non-private, static method in the class having only private constructors
Reason:
There should be atleast one non-private, static method in the class having only private constructors
Usage Example:
package com.rule;
class Non_instantiable_class_should_contain_non_private_static_member_violation
{
private Non_instantiable_class_should_contain_non_private_static_member_violation()
{
}
private static int getValue() // VIOLATION
{
return 1;
}
}
Should be written as:
package com.rule;
class Non_instantiable_class_should_contain_non_private_static_member_correction
{
private Non_instantiable_class_should_contain_non_private_static_member_correction()
{
}
static int getValue() // CORRECTION
{
return 1;
}
}
Reference:
Reference Not Available.
Severity:
High
Rule:
Do not override synchronized method with unsynchronized method.
Reason:
Do not override synchronized method with unsynchronized method.
Usage Example:
package com.rule;
public class Do_not_override_synchronized_method_with_unsynchronized_method_violation
{
public synchronized void foo() {}
}
class child
{
public void foo(){} // Violation
}
Should be written as:
package com.rule;
public class Do_not_override_synchronized_method_with_unsynchronized_method_correction
{
public synchronized void foo() {}
}
class child
{
public synchronized void foo() {} // Correction
}
Reference:
Reference not available.