So I'm new to using checkstyle and for my simple HelloWorld java program, I'm receiving a lot of errors I don't understand.
My code:
package <package_name>;
/**
* A simple class to compile.
*/
public class HelloWorld {
/**
* @param args standard main parameters
*/
public static void main(String[] args) {
System.out.println("hello world");
}
}
I'm receiving the errors:
Line 6: Utility classes should not have a public or default constructor
Line 10: Parameter args should be final
Why is this occurring? Is it necessary for me to create a private constructor for my main
class and make the default arguments final?
For Utility classes like your Main class, it is better to create a private constructor in order to don't let java compiler write itself the default no args constructor Main()
.
Java always makes a copy of parameters before sending them to methods. The final keyword here only means that inside the method the variables can not be reassigned. (note that if you have a final object like in your case String[]
, you can still change the attributes of the object).
1st issue is answered here and is documented here. Short answer is that you're not providing any instance members to HelloWorld
class, so why allow them to create instances? That's why it's recommended to create a private
constructor.
2nd issue - is stated here. Short answer - Changing the value of parameters during the execution of the method's algorithm can be confusing and should be avoided. That's why it's recommended to declare them final
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With