I was wondering what the effect of creating extra main methods would do to your code.
For example,
public class TestClass {
public static void main (String[] args){
TestClass foo = new TestClass();
}
}
After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?
It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like
>java TestClass
However, doing something like:
public class TestClass
{
public static void main (String[] args)
{
TestClass foo = new TestClass();
foo.main(args);
}
}
Or
public class TestClass
{
public TestClass()
{
//This gets executed when you create an instance of TestClass
main(null);
}
public static void main (String[] args)
{
TestClass foo = new TestClass();
}
}
That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....
When in doubt, just test it out :-)
The main method is static, which means it belongs to the class rather than the object. So the object won't have another main method inside it at all.
You could call the main method on instances of the object, but if you do that it's literally just another way of calling TestClass.main() (and it's frowned upon by many, including me, to call a static method on an instance of an object anyway.)
If you're referring to multiple main methods in the same program, then this isn't a problem either. The main class is simply specified and its main method is executed to start the program (in the case of a jar file this is the main-class attribute in the manifest file.)
It won't have an additional main-method, as main is static. So it's once per class.
If you have multiple main-methods in your project, you will specify which one to launch when starting your application.
This is perfectly fine. Having multiple main methods doesn't cause any problems. When you first start a Java program, execution begins in some function called main in a class specified by the user or by the .jar file. Once the program has started running, all the other functions called main are essentially ignored or treated like other functions.
After searching for a Java Class with multiple main() methods or in plain words, overloaded main() methods, I came up with an example of my own. Please have a look
public class MultipleMain{
public static void main(String args[]){
main(1);
main('c');
main("MyString");
}
public static void main(int i){
System.out.println("Inside Overloaded main()");
}
public static void main(char i){
System.out.println("Inside Overloaded main()");
}
public static void main(String str){
System.out.println("Inside Overloaded main()");
}
}
I tested this Java Code on JDK 1.7 and works like a charm !
You need "public static void main(String args[])" to start with and then you can call overloaded main methods inside this main and it should work for sure.
Any comments and suggestion are highly appreciated. I am just a novice Java Developer willing to develop my Java skills.
Thanks,
PK
No, you can have any number of main-methods in a project. Since you specify which one you want to use when you launch the program it doesn't cause any conflicts.
You can have only one main method in one class, But you can call one main method to the another explicitly
class Expmain
{
public static void main(String[] ar)
{
System.out.println("main 1");
}
}
class Expmain1
{
public static void main(String[] ar)
{
System.out.println("main 2");
Expmain.main(ar);
}
}
when you run your Java class it will always look for the signature public static void main(String args[]) in the class. So suppose if you invoking by command line argument, it will look for the method Signature in the class and will not invoke other until if u explicitly inoke it by its class name.
class MainMethod1{
public static void main(String[] ags){
System.out.println("Hi main 1");
testig2 y = new testig2();
//in this case MainMethod1 is invoked/.......
// String[] a = new String[10];
// testig2.main(a);
}
}
class MainMethod2{
public static void main(String[] ags){
System.out.println("Hi main 2");
}
}
But when you try the same from eclipse it will ask for which class to compile. Means MainMethod1 or Mainmethod2. So if te class has the exact signature they can be used as individual entry point to start the application.
Coming to your question, If you remove the signature as u did above by changing the argument if main method. It will act as a normal method.
It is all about the execution engine of JVM. Remember, you write >java com.abc.MainClass on cmd prompt.
It explains everything. If main method is not found here it throws a run time Error:Main Method Not Found in class MainClass.
Now if main method is found here, it acts as the first point when Program Counters have to map and start executing the instructions. Referred classes are loaded then, referred methods may be called using the instances created inside. So, main is class specific though one class can have only one main method.
Please note, main method's signature never changes. You can have two overloaded main methods in same class, like
public static void main(String[] args) {}
public static void main() {} //overloaded in same class.
During Static binding, the original main is resolved and identified by execution engine.
Another interesting point to consider is a case where you have two different classes in of java file.
For example, you have Java file with two classes:
public class FirstClassMultiply {
public static void main (String args[]){
System.out.println("Using FirstClassMultiply");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiple is :" + mult.multiply(2, 4));
}
public static void main (int i){
System.out.println("Using FirstClassMultiply with integer argument");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 5));
}
int multiply(int a, int b) {
return (a * b);
}
}
class SecondClass {
public static void main(String args[]) {
System.out.println("Using SecondClass");
FirstClassMultiply mult = new FirstClassMultiply();
System.out.println("Multiply is :" + mult.multiply(2, 3));
FirstClassMultiply.main(null);
FirstClassMultiply.main(1);
}
}
Compiling it with javac FirstClassMultiply.java will generate two .class files, first one is FirstClassMultiply.class and second one is SecondClass.class
And in order to run it you will need to do it for the generated .class files: java FirstClassMultiply and java SecondClass, not the original filename file.
Please note a couple of additional points:
You will be able to run SecondClass.class although it's class wasn't public in the original file!
FirstClassMultiply overloading of the main method
of is totally fine, but, the only entry point to your prog
will be the main method with String args[] argument.
Related
Can we call main() function inside any other function? I tried but did not come up with it.
If we can't call it then why?
Why main() is not like ordinary methods?
Yes why not try something like:
public class Main {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
public class NewMain {
public static void main(String args[]) {
Main.main(args);
}
}
If you run:
java NewMain
the output is:
Hello World
Why main() is not like ordinary methods
Not like ordinary methods in what sense? It is like any other method. I'll try to explain why main looks like this, maybe it'll help you to understand what's going on.
It's void because when it finishes, it doesn't mean that the program finished. If it spawns a new thread it might be that these threads are still running.
It's public because it's called by the JVM, which is outside the scope of the project.
And of course it has to be static because when the JVM calls it, there's no object existing for the class being called.
Nothing special about it when you understand it, so yes.. it can be called like any other static method.
Sure you can, main() is like nay other method in that area.
public class A {
public static void main(String[] args) {
System.out.println("a's main()");
B.main(new String[0]);
}
}
public class B {
public static void main(String[] args) {
System.out.println("B's main()");
}
}
Running A's main() will produce:
a's main()
B's main()
All the actions that you do one other methods can also be done on the main method
The only difference between main method and other methods is that the main method servers as the starting point for running a class
The java command launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
Except for this reason, there is nothing else.
I have a doubt regarding static methods. In the program written below, output will be: main. I understand this because main is a static method, so when class loads, it executes. If so, the same principle should apply for met() also, right? As it is also static. Why does only main executes whereas met() doesn't when the class loads?
public class Test {
static void met() {
System.out.println("method");
}
public static void main(String[] args) {
System.out.println("main");
}
}
No, this isn't correct.
Neither of these methods are called when the class is loaded.
main() is called when you execute the class Test.
Only static initialisers are called when the class is loaded. A static initialiser looks like this:
static
{
//code here
}
A class is loaded before the main() method is executed, and therefore its static initialiser is run before the main() method. The following snippet will make that clear.
public class TestA
{
static
{
System.out.println( "hello" );
}
public static void main( String[] args )
{
System.out.println( "bye" );
}
}
Let me explain it in detail
Types of methods There are basically two types of methods,
Instance methods
Class Methods
Instance Methods Belong to objects and you will always need an object/instance to call such methods.
static methods are the class methods and they can be called directly by class name, there is no need to have an instance of class to call them.
For example,
class Demo{
public void sayHello(){
System.out.println("Hello");
}
public static void sayHi(){
System.out.println("Hi")
}
public static void main(String args[]){
Demo.sayHi(); //Call to static/class method
Demo.sayHello(); //It will not work
Demo d = new Demo();
d.sayHello(); //It will work.
}
}
**But NONE of them gets called automatically when class loads.**
Main Difference between the two
In memory there is ONLY ONE copy of static methods which will be available for all the objects. But whenever an object is created a new copy of instance method is created for the object, so each object has its own instance method. Similar to instance & class variables.
Static methods are not meant to be run automatically, instead they are shared by all objects. Why main() method is called, because it is the entry point of the program.
Apart from them, there is static block which is called automatically only once when the class is loaded.
Example
class Main{
static{
System.out.println("static block");
}
public static void main(String args[]){
System.out.println("main");
}
}
Output will be
static block
main
main() method is not executed because it's static, it executes because it is the Entry Point for any Java program. If you want something to run, you'll need to call it from the main method. No other methods are automatically called when the class is executed.
Not at all. The main method will only run if that particular class is ran as entry point.
That met() method will not run until it has been called. The main difference it has with instance methods, is that you do not need to create an instance of the class in order to run it, you can simply run it through the class itself: Test.met();
What you mean is a static block:
private static String description;
static{
description = "this runs on loading the class";
}
You can use static block instead of static method, to print it before main method like this -
public class Test
{
static{
System.out.println("method");
}
public static void main(String[] args){
System.out.println("main");
}
}
met() is a static method, it will be in memory when the class is loaded, you need to call it.. You could use a static block to print "method".
If you want to execute on load , just intialise it as static block,
static{
System.out.println("method");
}
Because static blocks are executed once the class loads . And among other static methods main() has the high priority
No static method will get called when you call it only, you are mixing static initializer and static method
it prints main because when you run Java application it invokes main() method
there is a difference between static methods, static blocks and static variables. As you do not call the static method, it will not print
To make it print you will need to call Test.met ();
Alternatively you could have it set as a static block
as in
static {
System.out.println("static block");
}
This will be called as soon as Test is loaded.
Not all static method will be called by default when a program runs.
From Docs
The java tool launches a Java application. It does this by starting a Java runtime environment, loading a
specified class, and invoking that class's main method. The method declaration must look like the following:
**public static void main(String args[])**
So, main will be called by JVM and someone should call met() so that it is executed.
What you understood is wrong. Because whenever class loads JVM creates Class class object and int that class class object all static methods resides. main method is entry point for JVM thats why it is executing, JVM internally calling Main method. Whenever Class loads that time it only executes Static internalization blocks.
Main() is only executed because it is the entry point.
For more information you can read the documentation.
I have a doubt about Java.
In a Java project (handled by Eclipse for example), can I have more classes that contain the main() method and consequently can I chose to execute one class or another class?
Tnx
Andrea
You can have as many Classes as you want as long as each class have single main method.
You'll have to be opening a Specific Class in Eclipse if you wanna run main in that class or you can choose previously run classes from Eclipse Run Menuitem.
main means public static void main(String[] args) which is entry point in java programs.
Yes, you can have more classes that contain the main() method, but at least one class which contain main() should be public so that JMV will start that class as Main thread
as the code written by aUserHimself represent
Yes, you can have as many public static void main(String args[]) methods as classes.
You can also have more of them in the same file. For example, inside Class2.java you can have:
class Class1 {
public static void main(String args[]) {
}
}
public class Class2 {
public static void main(String args[]) {
}
}
Let me sum up the points regarding main method in JAVA (which is confusing at the beginning).
1. can we have more than one main() method in a class?
Ans: Yes. You can have more than one method with the name main but different signature. These methods will be overloaded. BUT the main method with following sigature will be treated as app entry point.
public static void main(String args[]) which is same as public static void main(String... args) or public static void main(String[] args)
2. can we have more than one main method in a java program?
Ans: Yes. We can have different classes having the main methods.
Then which one will be treated as app entry point?
While running a program with such classes, the user will be asked to choose among the classes to act as entry point.
Yes you can have more classes that contain public static void main(String[] args). And you can chose to execute one class or another class. However, you can't have more than one main method within same class.
I typed this code into Eclipse
public class Hello
{
public static void main()
{
System.out.println("Doesn't execute");
}
// .....
}
When I press run it says that it does not contain a main type.
I don't know what I'm doing wrong , and I am new to java.
It should be:
public static void main(String[] args)
This is what your code should look like:
public class Hello {
public static void main(String[] args) {
System.out.println("Doesn't execute");
}
}
Notice the closing parenthesis, also I have properly changed your main method.
Here's another hint:
When you create a new Java class in Eclipse, there is an option to auto-generate the main method stub for you (this option would have fixed your error without you even knowing).
It is the first checked checkbox in the following screenshot.
main method without the string array arguments is not the method that JVM looks for to start the execution of a class.
After completion of the initialization for a class (during which other consequential loading, linking, and initializing may have occurred), the method main of class is invoked.
The method main must be declared public, static, and void. It must specify a formal parameter whose declared type is array of String. Therefore, either of the following declarations is acceptable:
public static void main(String[] args)
public static void main(String... args)
Read more about JVM startup, loading, linking and intilization of class here:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.4
I went through an interview recently and they ask me two questions in core Java.
Q 1.
Can we write a java class with:
public static int main(String[] args){
System.out.println("Hello");
I answered: No. The compiler won't compile it as it is expecting the return type of main to be int, though we can overload it.
Q 2: The next question I was unable to answer.
Write a program so that your Java main method could return something.
I.e. how can you make public static void main([] args) to return something?
Can any body help me to answer this?
Q 1. Can we write a java class with : public static int main(String[] args){
Yes, you can but you can't run that Java class.
Example class:
class MainTest {
public static int main(String[] args) {
return 1;
}
}
You will receive an error message when trying to run it:
Error: Main method must return a value of type void in class MainTest, please
define the main method as:
public static void main(String[] args)
Q 2: Next question I unable to answer. He asked write a program so
that your java main method could return something.
You can use System#exit(int) to quit your program with a specific exit code which can be interpreted by the operating system.
Typically, in languages where main returns int (such as C and C++) the return code of main becomes the exit code of the process, which is often used by command interpreters and other external programs to determine whether the process completed successfully. To achieve the same effect in Java, use the System.exit method (analogous to the standard C function exit), like so:
public static void main(String[] args) {
System.exit(42);
}
Quoting the Java documentation linked above:
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
One can not return a value from a Java main function. Programs can however return a status code.
Try the following to exit with an int status in Java System.exit(45)
One way of doing such thing is by modifying the values of args[i] for i smaller than args.length, at the interior of method main.
Example:
public class Test{
//
public static void main(String[] args){
args[0] = "a value";
args[1] = "another value";
}
}
From another class:
public class Other{
public static void main(String[] args){
String[] result={"",""};
Test.main(result);
System.out.println(result[0]);
System.out.println(result[1]);
}
}
Then the output is:
value
another value
Yes, we can write main method with a return type other than void. This simply means that we can overload our main method. Some examples are
public static void main(String ... x){ }
public static int main(String []args){ }
public static void main(string array[]){ }
But, note here that the compiler will only know
public static void main(String []args){ }
If above method is not present it will not compile.
Yes You can return of type void.But the value will go to JVM and no more code after return will be executed because The control will return to JVM which calls main()