In tutorials on the internet I usually see pieces of code within public static void main(String[] args)
, whereas the lecturer for my programming course usually writes a method and calls that method within main.
For example, in tutorials I'd see:
class Person {
public static void main(String[] args) {
int age = 20;
System.out.println(age);
}
}
My lecturer would write:
class Person {
void run() {
int age = 20;
System.out.println(age);
}
public static void main(String[] args) {
new Person().run();
}
}
Is there a difference between these two, or is it just a matter of preference?
From output perspective there is no difference as both will display the same thing. and from the technical perspective first example is even faster than the second example. It's a standard coding practice which makes the difference here. As being a beginner, the first example might look better solution as it is easier, faster and straight forward compared to the second example (which has extra effort for writing new method, creating new object then calling the method to achieve same thing which you could achieve with single line of code in the first example.)
The technical difference is already mentioned by @adam-arold. I will emphasize on programming principle which is the major difference here.
The second Example follows the Standard coding principle called SoC (Separation of Concerns). SoC says each Class/Method
should be having codes only related to what they are supposed to do, for any extra functionality should be handled in separate Class/Method
. Main
method is an entry point and responsibility for Main
method is to configure the setup and initiate your program rather than handling any business logic (here business logic is to print a line).
Your lecturer is following the standard practice :) even with simple examples.
Sounds like your lecturer is pretty good programmer :)