Why the main program in Java is put into a class? - java

Why does the main method have to be put into a class? I understand the main ideas of OOP but I cannot get why the main program is defined within a class. Will such a class instantiated somewhere? I mean there is no code outside the class. What is a reason to define a class and never use objects of this class?

The Java Virtual Machine (JVM) has to start the application somewhere. As Java does not have a concept of “things outside of a class” the method that is called by the JVM has to be in a class. And because it is static, no instance of that class is created yet.

While it's true that java has no concept of methods outside of classes, it would be pretty easy to allow developers to skip all the broilerplate of actually writing out the class definition and simply let people write the main function directly, if they wanted too.
But back when people were developing java, people were more dogmatic about OO then they are now, and that probably played a big part. Think of it as an example of Opinionated software
It has one useful feature though, which that you can main functions to any class and launch them as programs. It's handy for testing specific features of those classes when you're working on them. If main() had to be in a separate file, and not part of a class, that would make things difficult. What if you want more then one main() function? What if you wanted to write functions to be called by main outside of the class? Would they go in a global namespace? Would multiple main() functions collide?
Not like those problems are impossible to solve, but other then a little extra typing, which can be especially annoying for newbies the current solution isn't too bad, especially since IDEs will generate the basic class structure when you create a new file.

It does simplify the design of the virtual machine. Since virtual machine already knows how to run a static method of a class then it can treat the main method just as any other static method.
If you put the main method in any other construct other than a class then the VM has to be modified to know about another construct complicating things even more.

When the Java language was designed, the notion that everything must be an object was a point of dogmatism. (though they left in a few primitive types). These days you could perhaps design a language that uses a closure -- even one outside any class -- instead.

What #Bombe said. I would add that to OO purists, the fact that the entry class is not instantiated is a misstep. The reason is the static main prevents someone from writing a family of main classes that share the same main() method written using a template method pattern.
If Java had been written to instantiate the main class and invoke the main method, users would have enjoyed the benefits of inheritance and interfaces.

As we know main is the entry point for the JVM to start. And in java there is nothing except classes and interfaces. So we have to have a main method in the class that too it should be a public class. and the main should always be public static, because it should be accessible for JVM to start and static because it starts without creating any objects

The main reason is so that multiple classes can have a main method. So a codebase can have many "entry points" and one just uses the class to specify which one is called. Also, this is inline with the OO design where (almost) everything is an object.

Main in java is a static method, therefore the class it's in doesn't need to be instantiated into an object, the class simply needs to be loaded.

That's simply how Java was designed: (almost) everything is an object, and code can only exist as part of a class.
Since the main() is static, it being called does not automatically lead to an instantiation of the class. However, it's perfectly possible (and quite common, at least in small Swing programs and Applets) to have the class that contains the main() be an otherwise normal class that is instantiated and used like any other class.

Related

Is there any convention to store methods not particularly related to any class? [java]

I am currently learning Java and, while making a project, I created some methods that do not suit logically in any given class but are useful in the whole context of the project.
The best example I have is a method that splits camelCase worlds like this:
splitCamelCase -> Split Camel Case.
I have thought about creating a new abstract class called Toolbox and storing those methods there, but I wonder if there is any convention or best practice regarding this topic.
It's not uncommon to have utility classes (commonly named SomethingUtils) when it just doesn't make sense to put a method in an existing class.
There's nothing inherently wrong with it, but if you find yourself having a lot of methods or utility classes, then your design might be a bit off and you're programming in a more procedural than object oriented way.
As mentioned in comments, you don't make it an abstract class. It's a class filled with static methods working entirely on the parameters passed to them.
As kayaman sir has said if you are having too many utility classes and method it means that you code is more procedural rather than object oriented.
Nut if you still want to have a class which is just used to provide some utility then you can have such a class in java , just put some static method in them.
One of the best example of such a class is java.lang.Math.
for example following code will work
class MyUtilityClass
{
private MyUtilityClass()
{
// no object creation will be allowed
}
// make as many static methods you want
}
You can create your ToolBox Class and then you declare it as a package. After that you can import your ToolBox at the beginning of classes you want to use the methods from that ToolBox.

Does Java have regular-old functions?

What I mean is, does Java have functions that exist outside of classes that I can declare? (Like, before the main class)
This is something I can do in C++ and JS, etc.
Static method
Declaring a method to be static makes it non-object-oriented. Its scope is outside that of any instances of that class. Invoked via the class name, Person.doSomething rather than by an instance.
Often called a "class method" though that seems like something of a misnomer to my mind. That name suggests object-orientation where it does not exist. Java simply has no other place to store "just a function", so such functions are bolted onto a class. I think of them as orphaned code with no where else to live. Some folks consider this arrangement to be a poor design choice in Java, where an explicit holder of non-object-oriented code would have been better.
You can think of class methods as "just a function" since it is not behavior on an object.
Lambda
Java 8 and later supports lambda expressions, where you pass a chunk of executable in the same way we pass data. This is known as functional programming, distinct from object-oriented programming.
This is something like "just a function" but its scope includes elements inside its defining class.

Best coding (layout) practice for the "main() class" file?

Currently, my "main() class" file looks a bit like the following code. Rather than clutter up this example code with //comments for discussion, I have simply labelled four code lines with numbers (1 to 4), and these numbers refer to questions that appear after the code. Thank you.
// package myPackage; // **1**
import myOtherPackage.*;
class mainProject{ // **2**
// **3**
private int myVar;
mainProject(){
myVar = 0;
}
public static void main(String args[]){
// Keep main() looking fairly simple?
// Perhaps just have some "essentials" here, such as error handling?
new mainProject().start(); // **4**
}
private void start(){
// The project gets going here..
}
}
1 Unlike other class files in my project, I have not assigned a package name for my "main() class" file. Is this a bad design choice?
2 Is there a good naming convention for the "main class"? Is it helpful to incorporate the word "main" in to this class name? Would something roughly like "mainProject" be a good idea?
3 Various coding constructs can appear inside the main class file. For example, local variables, constructors, the main() method, and local methods. Do they have a "best order" in which they appear in this file?
4 Is it worthwhile to keep the main() method looking fairly "lean and simple"? In this example, I have just called a local private method called start(), which is intended to get the project started.
Ok, here is how I do it in my professional projects.
For 1. every class should have a package. Main or no main makes no difference. Package is the way java organizes your classes at runtime in form of namespaces. So if you stop giving packages then you may end up with two class files with same name in the same folder or jar and when that happens, JVM picks the first class it finds by the name on the classpath. That may not exactly be the one you want.
For 2. main (speciallypublic static void main(String[] args) is a specific and standard signature that Java needs. Any runnable program, a program that produces an output and can be executed needs a main method with this signature. I will try to explain the signature and that maybe will help you understand why it's like that.
It's public because you want the JVM runtime code to execute the method. Using private or protected won't allow the JVM code to see your method.
It's static because without static the JVM code would need an instance of your class to actually access the method. Remember that static methods and fields can be accessed by just using the class name. However non static members need a valid live object to reach them.
It's void because main does not return anything to its caller. It's like any method having a void return type.
And it's called main because the Java creators thought to give it that name. JVM runtime code which executes this method needs to know about the name of your method which will kick off the execution. Now, if I name it anything then it's impossible for the JVM code to make a wild guess. So name standardization called for a standard name and Java creators stuck to main.
String[] is actually a string array containing the command line arguments that you pass to your program. args is the name of the argument and ironically this is the only thing that you can change to any name you want.
For naming the main class, I usually prefer the names like MyProjectLauncher or MyProjectBootstrap where myProject is the name of your project like tomcat or bigben or anything you like.
For 3. standard convention is:
public class MyClass{
//private members
//protected members
//constructors
//private methods
//protected methods
//public methods
//hashcode and equals
//toString overrides
}
You can pick what you need and drop what you need. Public methods also include the getters and setter for your variables if you use them.
For 4. When designing classes you need to keep in mind scalability and manageability of code. It's very common to have a main class and a few classes at start of the project and then when they grow into oversized kangaroos of thousands of lines then refactor code to adjust it. What you should do is create classes based on functionality, service helpers or actions. Keep main separate in a different class. Just use main to initialize a few things, parse command line options and delegate to start or initialize method which does the remaining things to kick off your program.
Hope this helps.
1 yes you should always use packages. But dont use camelcase in them... So myotherpackage rather than myOtherpackage.
2 yes, it is good convention to incorporate the word main, e.g. MyApplicationMain. Remember class names start with a caps letter.
3 yes, the common order would be statics, members, constructors, methods, much like you have already
4 yes! This enables better testing and you should not use a static context for any longer than you need to.
If you add a package and take on board my tips for caps letters, i think what you have above is absolutely fine.
Usually, it is good to define your own packages in order to avoid naming clashes with any other classes on your classpath. This also applies to the main class. Imagine what would happen if somewhere else in your dependencies there is a class whose creator used the same approach of leaving it in the default package. So yes, put iinto a package.
The naming is left at your latitude, but Java coding conventions definitely urge you to capitalize the name of the class. So, Main or MainProject or EntryPoint would be better choices.
I think you refer to fields and methods as members of the class. Please note that local variables and local methods have a totally different meaning (they're not members of the class itself). The usual ordering is static fields, instance fields, static methods constructors, instance methods. I don't think there is a strong convention, but these are the habits.
It is worthwhile keeping any method clean and simple ;)
ALWAYS use a package. No matter what. This is your namespace!
Don't use camelCase in your package names.
Avoid to import whole packages.*, better import a single package.Clazz.
Class names should ALWAYS be UpperCaseAndCamelCase.
Leave a space between the class or method name and the opening braket {, it improves readability.
The rest seems to be ok. It is more or less a matter of pragmatism. Your code has to fulfill the purpose it was written for and also needs to be testable and readable (by others).
All these criteria will form a ruleset for you or your team.
What if someone else has a main class with the same name? Its better to place it in a package for all but the simplest test programs.
Incorporating "Main" in the class name is a good idea because it quickly tells the reader the purpose of the class, but "mainClass" should be "MainClass" according to java language conventions
The usual order is variables, constructors, and methods in whatever order is reasonable
Yes, keep the main method small and easily readable. The logic in it should mostly just be related to parameters passed to the program, and even that should be factored out when it gets to be too large.
1 packages should definitely be used. It is better for maintenance purposes, if your project gets larger with time then there could be exact same syntax for main used. the package name should be meaningful as well and provide concise containment for relevant functionality classes.
2 yes, it is good to include the word main in the class name and should start with capital letter.
3 commonly the order is variables, constructors, methods.
4 keep the main concise and simple. the lesser code it has the better as you already have done.

Possible to have a function thats not a method in java?

In this Java program I'm writing I’m finding that I’m clogging up the main() method with a lot of code that would make it hard to quickly understand/read. Specifically due to a lot of error checking that I’m doing. As a result I want to write a quick function that is only going to be used by this one method to improve readability.
Is writing another method within the class my only option or are there other alternatives?
Is writing another method within the class my only option or are there other alternatives?
It depends:
If the methods should belong only to this class, they should be declared as private or protected methods in the class, depending if the class can be inherited or not.
If the methods should be reused in other classes, it would be better to move it to utility classes as public. For example, check if a String is empty and also validating if is not null. Note that for this example there are methods covering these validations in utility classes from Apache Common Langs, explicitely StringUtils#isEmpty(String).
By the way, Java has methods, no functions.
Answer is yes, generally private methods in the classes hold the code which is not used by outside world. But havig private methods help to reduce the cyclomatic complexity of your public methods. Smaller methods lead to more readable and understandable methods.
Since Java was designed that way, you can only have methods. So, yes, that's the only way. Usually you would use class methods (static) for instance independent methods. These can also be within another class, for example a utility or helper class.

Why main method needs to be static? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is the Java main method static?
JAVA supports reflection still JAVA needs main method to be static why?
Using reflection we can create the object of class and even call methods of that class so why JAVA need main method to be static.
Appreciate your comments on this.
The only answer that can be reliably given is "because the JLS says so". Quote:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
Well, reflections have been introduced since Java 1.1 only so the initial Java 1.0 standard could not be based on them. They probably had some reflection-like code just to bootstrap and it is not known how complete it was at times when Java was still called Oak.
Also, this may be inherited from C++ and further inherited from C. While C++ could also construct an application object first and call the virtual main() on it, this probably looked too complex and the choice is to use a simple main, familiar to C developers.
Because when you run a program, the runtime environment looks for a method with the signature public static void main (String[] args). Even if reflexion is supported, the runtime still needs to call a class' main method first.
Public: In order for the JVM to gain access to the main method it has to be public.
Static: As it would be really complex or maybe impossible to foresee your instantiation criteria of the class hosting the main method, it is mandated to be static, enabling the JVM to call it without the need to create an object from the class.
After all, you need a clear contract when defining a language, without such mandated constraints, things might get messy for the JVM designers.
Explanation of every keyword in public static void main(String []args)
1.public:
It must be public because JVM is not part of the class, where you define main method.So, It should not be private
2.static:
JVM is not going to construct any object to call themain. And main is not depending upon the class.
3.void:
mainis not going to return any useful information to JVM. The program execution starts from main() and if there is normal exit ends with the last statement in main.In between the lot takes place.
4.main:
It's just a proper noun used to show the importance of the method.
5.Array of Strings:
The args passed to the main is one or more words, they may be an int, float, char, or String. Everything above can be represented as Strings.
Hope it helps

Categories