Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Hello World to pass CheckStyle

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?

like image 914
idude Avatar asked Mar 09 '23 11:03

idude


2 Answers

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).

like image 130
jeanr Avatar answered Mar 11 '23 01:03

jeanr


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

like image 29
Ivan Pronin Avatar answered Mar 10 '23 23:03

Ivan Pronin