JAVA.MAGIC.STRING
Magic number used: string.
Magic numbers are used. This checker flags the use of magic numbers in binary operations.
Vulnerability and risk
Use of magic numbers impairs maintainability.
Mitigation and prevention
Declare constant variables using the final qualifier.
Example 1
Copy
public class C11 {
double d314 = 3.14; //NG
int i0 = 0;//OK 0 is exception
int i1 = 1;//OK 1 is exception
int i2 = 2;//NG
final int final_i2 = 2;//OK
int assign_final_i2 = final_i2;//OK
int assign_final_i2_and_magicnum = final_i2 + 3;//NG
char c1 = '1';//NG
final char final_c1 = '1';//OK
String s1 = "string1";//NG
final String sf1 = "string1";//OK
final double fDB314 = 3.14;//OK
double var_init_with_const = fDB314;
public void somefunc_number(double a, int b) {
}
public void somefunc_char(char str) {
}
public void somefunc_string(String str) {
}
public void test_number(int v, String strVar) {
double local_var = 3.14;//NG
if (v < 3) {//NG
somefunc_number(v, 2);//NG
somefunc_number(3.1, v);//NG
somefunc_number(v, v);//OK
}
if (0 != v) {//NG
}
}
public void test_char(char v) {
char local_var = 'a';//NG
final char final_local_var = 'a';//OK
if (v != '3') {//NG
somefunc_char('a');//NG
somefunc_char(v);//OK
}
if ('0' != v) {//NG
}
}
public void test_string(String v) {
String local_var = "a";//NG
final String final_local_var = "fix";//OK
if (v.length() != "3".length()) {//NG
somefunc_string("a");//NG
somefunc_string(v);//OK
}
if ("0".length() != v.length()) {//NG
}
}
}