It is said that a java program itself is a class, but I just don't get the logic behind this.
The java program itself starts of by the definition of a class (after importing the packages...etc) and the main method itself is defined inside a class.
Why is it this way?
Why does a main method have to be included within a class rather than outside as a separate method/function like in the languages such as c, c++...etc.
For example a simple hello world program in java:-
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello world!"+"Hello again");
}
}
Why is it necessary that a program should start with a class and the main method included within it?
The JVM doesn't understand the concept methods outside of a class. Fundamentally any method called by the JVM will have to be in a class. The main method is static as at the start of a java application nothing will have been initialised, so making it static allows the JVM to call it as a starting point.
Because the Java language specification says so! See here for example. Or more precisely:
The Java Virtual Machine starts up by loading a specified class and then invoking the method main in this specified class.
(to be found right in the beginning of chapter 12, Execution).
Sometimes there isn't a "big" reason behind things.The fathers of the java language probably had a look around what other languages did at that time when they started Java. They decided to go for this approach - and there was never a hard, pressing reason to come back and change that.
Beyond that: you have to understand that the JVM doesn't care about Java source code. It only cares about the Java bytecode specification - and complete classes coming in as compiled .class files.
In other words: there is simply no other "unit" that could wrap around single methods/functions but classes.
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.
Related
This may seem like a stupid queestion to most of you, but I have been learning Java using BlueJ, and BlueJ is created for learning, and as such Main Methods are not necessary given the BlueJ extensions provided by my University.
Therefore, now that I am playing around in both NetBeans and IntelliJ - I really want to get a good idea of when to declare a Main Method.
I know the Main method is the entry point of a package when it is compiled and run. But that is the extent of my knowledge.
If I am to build some apps in a full blown IDE, should I place all of my Class methods within a Main Method? Should the Main method be seperate from all others? Do I declare instance Variables within the Main Method?
Are there any good sites, or tutorial materials available that can help me structure my BlueJ Java knowledge into an IDE that requires a Main Method?
Thanks
Ok.
Main method is an entry point to your application.
If you watch any Java related tutorial, you'll probably see something like this.
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
System.out.println("Hello, World");
}
}
This has been taken from Oracle's website.
When working with IntelliJ, you'll be presented with a package main on the top, or something else.
You see. Java unlike some other languages distinguish between namespaces using those packages. Think of them as a little packages full of Java classes that you can reuse.
For example, if you look at Log4J's repo => here, all these folders are essentially packages.
That way you can have many packages, and a single file that will trigger your main method, and start everything else.
That's how it's usually done.
But if you really want to learn Java from scratch. My suggestion is go to YouTube. Derek has done some marvelous job with his tutorials.
Best of luck.
While technically you can have more than one main method, for most use cases you only need one.
You should define it where it makes sense to do so in some "central" class responsible for bootstrapping your application and getting everything going.
The main method is static though so it can't access your class' instance. Typically this is how you'd get around this.
class TicTacToe {
public void theEntryPointToYourApplication() {
// ...
}
public static void main(String[] args) {
// This doesn't necessarily have to be the same class where you
// defined your main method
TicTacToe ticTacToe = new TicTacToe();
ticTacToe.theEntryPointToYourApplication();
}
}
This is just a small example though there are many ways and different approaches depending on your specific use case and needs.
Personally I have never used BlueJ.I've always been a netbeans fan.But the answer to your question is a general rule that most of the Object Oriented Programming Languages follow.You know that main method is the entry point of a package when it is compiled and run.Let me explain it in simple language.
Consider a soccer game.Assume that the field is the main method.The players are different functions.You are free to define any number of functions, but only 22 functions are called in the field.The whole game is controlled and played by these 22 functions only.So what do you learn from this?
We learn that java is only concerned with what is present in its main method just like the fans sitting in the stadium are only concerned with the 22 players who are currently playing.So if a programmer is writing a small program,normally the whole logic goes into the main method.But if its a large program,the program is distributed into various modules/functions and then these functions are called in the main method so that they get executed.
I know that I'll need a main method, but can that main method be in a different class other than the Main class?
Not all Java applications require a main method.
Java can also be used to create web applications, for instance, which don't require main methods to run.
The answer to your question depends on what exactly you mean. Do you mean a class with the name 'Main'? Then, no, there is no requirement for this at all.
The only requirement that Java has, is that the signature of the method is correct. the main method must:
be public
be main
be static
have returntype void
accept an array of Strings as (only) parameter
It's easier to add it in the public class in a file, but not mandatory. The name of the class it is in, is entirely up to you, though many will choose a name like 'Main' or 'Open', simply to more easily find it.
If you want to be able to run your application, by simple double-clicking the .jar file, you'll need to point to the class that contains the main method (to use: your application might contain a lot of main classes, used for internal testing, but only one can be used to start the actual application) in the manifest file: Manifest files
Prior to Java 7, it was possible to run a desktop application without a main method, by (ab)using an instantiation block, but this was removed as of Java 7, because this is not what the instantiation block was intended for.
It's not necessary to define yout main method in a main class. You can place your main method wherever you want, as long the syntax i correct :
public static void main (String[] args){
//...
}
You absolutely don't.
The method itself can be placed whereever you want it to be, there is no limitation.
However, I personally would recommend putting it in a class which at least contains something like "Main", because when others look at your code, and they are not using an IDE which supports jumping to the main method, people usually have an easier time finding your starting point.
However, that is just for sake of readability, and as I said, jumping to main is/should be usually a widespread supported feature
Yes, the Main method is required to run a function although a java class can be without the Main method. Though, it won't run...
Beginner just starting out
.can i write entirety of code outside of main and still run? generally i'm asking what is "main" used for?
In theory you can just code everything in main and in will work. However to make your code structured you probably want to code outside of main and call it from main.
The main Method is the start point for the VM of Java. So if you want to run your application, there has to be a main method. Not only Java has this concept, also other OOP-Programminglanguages like C,C++,C#. You can write code outside the main. but remember that the code can only be accessed if there is a way to it from the main Method, example functions.
The main method is where your system is able to call and start the program up. The main method is needed if you wish to run your program and make use of your other classes.
You can create your program inside the main method if you wish, but as your programs become more sophisticated, you are going to want to create other classes that are initialized and used in your main method.
For example, if you make two classes called "Suv" "Sedan", and make one more class called "Mechanic" - the class that will hold your main - you can initialize Suv and Sedan and you can call the methods you made in Suv and Sedan to do things like change the engine, or to change the color, etc.
If you are just learning java, then don't worry about it too much and just write your code in your main method.
Main is the entry point of any java application. The Java Virtual Machine starts up by loading a specified class and then invoking the method main in this specified class.
You can write your code in main method, or somewhere else and call that in the main method in the order in which you want to execute it.
The method main must be declared public, static, and void. Following is the reason for it:
public:- main is marked public so that it can be accessed from anywhere outside the scope of the class or broadly we can say outside the scope of project.
static:- It is marked static so that it can be called without any instance of the class. Without declaring main method static, your program will compile successfully but throw an error at run time.
void:- The keyword void is used with main to tell the JVM that the main method does not return any value. It is solely for the initiation of the application not for returning anything.
Following is the valid declaration of the main method:
public static void main(String[] args)
public static void main(String... args)
I am new to java programming and i just came across to a java program composed of many files and only one of the file had a main function while others did not. I didn't really understood that why don't we have a main function in every java file.
Not every file needs a "main" function. For example, you may want to import a file with specific function or class. In this case (a java file without a "main" function), the java file simply represents a chunk of code, which is added to your program. So it doesn't need a separate "main" function, if you already have one.
In java, main() is an entry point to a program/application. Sometimes in a application we just need only one entry point to start the program and from this point other necessary code are used.
But not all application necessarily need an main() method - like web application or java applet where a container initiate the application/program.
Every Java program must have an entry point, and that entry point must have a certain signature. Which, as you have noticed, is public static void main(String[] args)
After that, the class that is the entry point can create instances of other classes and/or invoke their methods, or invoke static class-level methods. It is not necessary for those classes to have an entry point, because the program is already running (executing your code) in the Java Virtual Machine (JVM).
You'll notice that a common error novice (and sometimes even seasoned) programmers make is trying to run a program for which the runtime environment cannot find an entry point. E.g., Eclipse: Java, no main method found (in this example, the problem was that the OP had the wrong method signature). The runtime has to find something to, well, RUN.
If your code is going to be run by some other code (e.g., you are developing a library or an API that contains functionality that will be used as part of another application) it may not be necessary for you to have a main method. If you look through the .jar files of some of the standard libraries using your IDE, you should discover that very few of them have classes with a main method - this is because they are not intended to be run alone, but rather in the context of another application.
The public void main(String args[]) method in java is the entry point to the program. If it is run directly, it will start from the main method. However, not every class that you might make in Java is an acceptable entry point. In fact, in many applications, you should have exactly one main method. There is generally not too much need for more. Some java libraries has no main method anywhere at all. This code is generally designed so that it can be used by other java code, and often has no sensible way to run itself. It's not designed to do that. It is designed to help other programs that do.
What classes without a main method are used for, is a) to provide functionality for other java programs (dependancies for instance), b) to provide additional functionality to the program that is invoked through the main method.
Here is a couple example files that illustrate the second.
MainExample.java
public class MainExample{
public static void main(String args[]){
OtherClass other = new OtherClass()
other.doExpensiveComputation1();
other.doExpensiveComputation2();
}
}
OtherClass.java
public class OtherClass{
public void doExpensiveComputation1(){
//do stuff here
}
public void doExpensiveComputation2(){
//do other stuff here
}
}
Now, you might be asking, "couldn't I just write those methods inside the main class?". In some cases the answer might be yes, but for more complex code, it generally isn't. In some cases it will be impractical simply because it clutters up the main class too much to keep track of. It is much easier to keep track of code that keeps its classes in different files.
Execution of Java program always starts from Main method.Class having main method is the entry point for the program and further from there you can get the rest of the desired functionality.
If You want you can have main method in each java file, which will behave as multiple entry points for your program.
I have a Java project(running in Eclipse) without main method and need to debug and see which is the caller class and the flow of the program. How do I start?
It is a simple project and does not contain any web/tomcat related data.
Thank you for your responses. I am new to StackOverflow and so pardon my writing and asking questions.
I am including packages and trying to create objects of a class, but it is not recognizing the classes. All the classes are public.
There is no way to run a Java SE application without starting with public static void main. If you want to debug the code of a library or framework you need to create a main method and call the code from there.
Take a look to JUnit. If you just want to debug your code is what you normally have to do.
Since Java requires all methods and variables to be within classes, the JVM needs a starting point that exists before any objects are initialized. Therefore, main must be static and public for the JVM to find it. Unlike C++, the main method does not return a status code, so it is of return type void rather than int.