Why does the main function in Java reside in a class? - java

I just started studying Java. And the main function of the program always resides in a class.
public class t{
public static void main(String[] args){
// do stuff
}
}
I have studied C++, and in there the main function doesn't need to be in a class. Why in Java we have to do that?
Why can't the main function exist in Java without a class, like it does in C++?

Probably for the same reason you put question marks at the end of a question: that's just how they decided it's done.
The main method is the result of a convention that says "this is how the entry point's method signature should look" which doesn't exempt it from language semantics.
Java does not support methods outside of classes/interfaces and as such it has to be contained in one.

The "every method in Java must be in a class because the spec says so" answer is only part of the story. By having main() inside a class it is possible to have multiple entry points within a project. i.e. multiple classes with main() methods. This allows you to select a different main class at runtime rather than compile time. e.g.
java -cp program.jar com.example.Class1
or then if you want to run a different main from the same jar
java -cp program.jar com.example.Class2

Because that is how the language was designed. The JVM first loads the class containing the main function and then calls the main() method. Without loading the class, main() cannot be called, i.e, main() doesn't exist without its enclosing class.

All methods must reside in a class in Java.
main is a method.
Therefore, main must reside in a class.
Furthermore, a class is not just a blueprint of an object. It is by itself a chunk of code that does something. One of the things it does is providing the entry point of the application by containing a main method.

Because everything is inside a class in Java. Java code consists only of classes. They may be nested in themselves or in a packagehierarchy, but nothing is allowed to appear outside of a class.
The only exceptions are the package and import statements.

since java is oop language , u cant do anything unless u create a class. this makes java object oriented language. and java was designed like that to first to load the public class and call main method

Let's consider that following is allowed in java
void main (){
f1();
f2();
}
int f1(){
f2();
return 1;
}
int f2(){
return 3;
}
since there are no prototypes in java how would main call f1 or f2 or how would f1 call f2?
i Think that this is one of the reasons

Related

Java classes written outside of class brackets

I'm confused as to what this is called in Java and what this does:
public class MainFrame(){
public static void main(String[] args{
//etc.
}
}//end class
class SampleMenuListener implements MenuListener(){
}//end SampleMenuListener
I researched inner classes and know how to use anonymous inner classes however I know this is not one and after some googling I couldn't figure out what this is called in Java. So my questions are what is this called? And in Eclipse the Class C shows up next to class SampleMenuListener. So is this essentially the same thing as making a new class in the same project folder called SampleMenuListener and making an instance of it in MainFrame? And if so is this simply just a shorthand way of writing another class without making it separate in eclipse? Or does it some how differ and how does it differ? Definitely feel free to post links as this may be a stupid question but like I said I couldn't seem to google the right keywords to get results on what this is called in Java.
Normally, we like to say that Java can only have one class per code file, and that the source file must be named for the class. This isn't entirely true. The actual rule is that you can only have one public class per code file. You can have as many as you want (but please don't...), so long as no more than one of them is public.
The others must be package access (no access specifier). See the relevant documentation.
In your example SampleMenuListener is simply a class like any other.
This is a normal class , it is just written in same .java file.
only difference is there is only one public class allowed(as file name need to be same as of public class )

Just started learning Java. Why is the main() inside of a class?

I'm learning Java and I noticed that the main() is put inside of a class. Why? I don't consider my main() to be a member of any object. So please tell me how I can get around this.
I don't consider my main() to be a member of any object.
It's not since it's a static method. It does not belong to any object but to the class itself.
Aside from that, all methods, including main must be defined in classes.
More generally, a class is the smallest unit in compiled Java code and contains both information on instances of the class and behavioral code that runs by itself (e.g. the main method).
By nature, Java is highly object oriented. So everything must be encapsulated within a class. All methods must be placed inside of a class. However, the main() is different. There can only be one main function in a class and it must always be static, meaning it is not part of an object and there is only one instance of it. When a java application is executed, the JRE will look for the main class (i.e. the class containing the main function). main() is where the execution starts. But due to the very nature of OO, it must be placed in a class. You can say that this is simply because of the skeletal structure of java. No other reason in particular.
You must put the main() in a class. And, it must be static (which means it is not a member of any Object). When you launch the Java Runtime Environment (JRE) it will load that class and invoke the main().
This is covered by JLS-12.1 - Java Virtual Machine Startup which says in part,
The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings. In the examples in this specification, this first class is typically called Test.

Why main method is marked as public?

I have a question that why main method is marked as public?
According to an answer on stackoverflow, It is declared as static
"The method is static because otherwise there would be ambiguity: which constructor should be called?"
But, can anyone can explain why it is declared public always?
Because the JLS, Section 12.1.4, says so:
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.
If it's not public, then it won't be found; you'll get
Error: Main method not found in class Main, please define the main method as:
public static void main(String[] args)
I believe, the rational behind enforcing main as public is more to do with the language specification – rather than whether something could be achieved or not.
Refer:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.1.4
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. Therefore, either of the following declarations is acceptable:
Java uses JNI launch java application will never have any issue in calling a private main – but this is more like jail-brake (like another jail-brake, where reflection API let you access private method) and definitely not in spirit of java specification.
If I remember till JDK 1.3 – it was not mandatory from developer’s perspective. i.e. even a private main was being accepted by JRE. Though, it was not inline with JLS 1.3.
I tried searching JLS 1.3 for a reference, but could not get a link. But I found that it was reported as a bug by developers across world:
Please refer: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4155575
So, a fix was made in subsequent version to enforce rule stated by JLS.
Now, the point is why JLS writer enforced this rule at first place – I really have no idea. The only thing I can think of is that – to keep it “obvious” and non-confusing for developers.
The initialization software that starts your program must be able to see main so that it can call it.
Because that is what is known as the "entry point" and if it is private, your program will not be able to run.
Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application.
From coderanch
When the code is executed, a JVM will be created and that will act as a container for the code we are trying to execute. Declaring this method as public allows the JVM to start the code execution. If method is private, JVM wont be able to call it.
There are ways to call a private method as well (eg by using Reflection), but that is not a standard way to do things.
In Java a function or variable in class in unaccessible untill an Object is created from the class, but the 'main' function is supposed to run at startup(without Object initiation) by JVM. So the 'main' is declared public as well as static so that it can be accessed outside class & without even an Object is created.
Yes the standards say so that main method should be public in Java. But it's not only for Java. However even for C#, main must be public.
So just think about it in real world scenarios.
E.g. you want to enter your room, but you should enter your home main door first (given room is inside the house...and no other means to enter the house)
Main door is the only publicly available access point.
Because the main method should be accessed by JVM without any restrictions from any where. I think you can find more info here: Why main method is public

Java methods flow

I'm trying to learn how to program on android which of course uses Java. I understand Java vaugely, but this confuses me.
A method which I view as a function (PHP being my native programming language) can seemingly be declared anywhere in a java file and still be pulled out at any other point is this so? What I mean is in PHP you have to define a function(method) to then be able to call it. So everything has to be in order.
Also is calling a function like including that section of code in your method calling it. Example being:
method 1 contains opendb command
method 2 contains closedb command
oncreate method calls method 1 then 2 does it act accordingly.
Sorry may sound dumb but I like concrete answers and not assumptions of mine.
The order in which methods are declared in java is of no importance.
Methods have no relationship to each other. You could invoke a method1 any number of times regardless of another method method2.
A sample could look like:
public DatabaseManager {
public void openConnection() {
// ...
}
public void closeConnection() {
// ...
}
}
Which you can invoke using:
DatabaseManager db = new DatabaseManager();
db.openConnection();
// do something
db.closeConnection();
A method which I view as a function
(PHP being my native programming
language) can seemingly be declared
anywhere in a java file and still be
pulled out at any other point is this
so?
Well, partially true :-). Java (like many other languages) has the concept of "visibility" of a method (functions are usually called "methods" in Java). If a method is private, it is only visible (and usable) inside the same class, if it is public is can be called from anywhere. See e.g. the excellent Java tutorial, which covers this: http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
However, unlike PHP, the order in which methods are declared inside a single class is irrelevant. You can call a method from the same class before the point/line of its definition.
Also is calling a function like
including that section of code in your
method calling it. Example being:
Yes, in the simplest case calling a method behaves like including that code in the place where the method is called. But there are important differences:
If you call a method, it cannot access local variables from the calling method, and class fields only if both methods are in the same class.
Java (being object-oriented) has polymorphism: You call a method on an object instance, and the method that is actually executed depends on the runtime type of the object instance, which may be different for different code paths. In that case calling a method is more complicated than just replacing it with the method's code.
Java methods can recursively call themselves; that wouldn't work if the compiler just included them where they are called.
So it's probably not really helpful to think of method calls as "like including the code"...
Your problem is not Java at all. It sounds like you have never programed the object oriented way. You should learn what a class is, what a method is.
I strongly recommend the basics for OOP itself: http://download.oracle.com/javase/tutorial/java/concepts/
In Java, your methods can be declared in any order in the class, for example
class A {
void C() { }
void B() { C() }
}
Could be equivalently declared as
class A {
void B() { C() }
void C() { }
}
Your second question is not very clear. But just to clarify - there is nothing like including in Java to execute another script - generally you will create new objects or run static methods of a class to accomplish things.
Max... I have not coded in PHP, but I have done a lot of scripting. According to the online docs that I found, PHP does not natively support events. So you are right, everything has to be "in order" in PHP. So you may need to get your head around moving from the sequential model of programming that I grew up with, and move to the event driven model used in Android Java.
You can divide your program into three parts. A view or presentation (main.xml). The controller or event handler (MyApp.java) and the algorithms, say model.java. MyApp.java has "event handlers" that basically sit around waiting to receive events so that you cannot absolutely know the order in which methods will be called. Do the heavy work in Model.java and write it so that it knows nothing of the view and is reusable.
So in UNIX model is the ENGINE and the view and controller is the INTERFACE. INTERFACE-ENGINE vs model-Controller-view.
Hope that helps,
JAL

Java Beginner question about String[] args in the main method

So I just tried excluding String[] args from the main method
It compiled alright !
But JVM is showing an exception
Why did it compile when String[] args HAS to be included every time ?
What is going on here ? Why won't it show a compilation error ?
typing this made me think that may be compiler did not see it as THE main method ..is that so ?
If that is the case..why not ? I mean isn't there supposed to be just one main method that MUST have String[] args as the argument ?
typing this made me think that may be
compiler did not see it as THE main
method ..is that so ?
Correct. There is no compile error because you're perfectly free to have all kinds of methods named main. But when you start the JVM and give it a "main class", then it will look for a method static public void main(String[]) in that class, and if it does not find such a method, it aborts with an exception.
This allows you to have multiple main methods in your program and is really the only thing that makes sense if you think about it: Applications can be composed from classes and JAR files from lots of different sources, written by different people at different times, so in many cases you can't really have a single, designated "main class" right from the start.
The JVM is looking for a very special main method to run. Only the signature
public static void main( String[] args )
is found. All other methods with name main are just "normal" methods.
Not every class has to have a public static void main(String[] args) method, only the one you want to run from the JVM. The result is that your class will compile with no error if it finds public static void main() but will throw an exception if you try and run it with the JVM because it can not find the entry point of the program.
Bottom line the entry point of your program must be public static void main(String[] args) which must be located in at least one of your .java files.
Note you can have multiple public static void main(String[] args) methods in your code (one per class) the advantage is you can use these to test and debug your classes individually.
To try to answer "why is it legal to compile without a proper main method" it's because not every java project is a stand alone application that can be run. Some are just libraries, where other programs will include them as jar files and use their code, but they don't "run" themselves. Others may be web applications, where they are deployed onto a web server that has already been started, only the server itself actually has a proper "main" method. The web application project is opened up and executed by it.
The compiler didn't really know at compile time that you were intending to try to run your code as a stand along application.
Java supports method overloading. This means you can have several methods with the same name, but different arguments.
Having said that, when you run java ClassName, Java looks in ClassName.class for a method with the signature public static void main (String[]) (it doesn't care what the String[] variable is named) and runs it. If it doesn't find one, Java will bomb out with the following exception:
Exception in thread "main"
java.lang.NoSuchMethodError: main
You are correct. The runtime is looking for a main method that takes a string array as a parameter, and isn't finding it.
The fact that you have a main method that doesn't take a string array is irrelevant. just like any other method, you can create multiple versions of main() that take different parameters - the runtime will just ignore them.
Isn't that overloading? It's fully legal to define a method
static void main() {
}
It's just not the entry point the JVM will be looking for.
Overloading is the ability to have multiple methods with the same name but different arguments. The compiler in fact creates a name based on the method name and the arguments.
So a main(String[]) would be called, to the compiler, something like main_String_arr, and main() would be called something like main.
You can have many methods named main, but only one can be THE main one - entry point to the program. It is the one with String[] args.
It's still a valid method. For example, you could have a static method called "main" with an int parameter if you wanted:
public static void main(int foo){}
The compiler doesn't complain because it's a valid method! It's just that, in order to run a Java program, Java looks for a static method called "main" with a single String array argument.
Yes..
The Java compiler will look for the same method signature to consider it a main
Writing any function that has the same name but another parameters will result in overloading functions..
Overloaded functions are not the same..!!
The case in C# is somehow different..
At last, you must make sure that your main is like that:
public static void main(String[] args)
You can use the compiler to compile part of an application: e.g. to make a jar file which you will call from another part of the app; or an applet that is started in a different way. Therefore the compiler cannot complain about the lack of a main(String[]) method. But trying to run the results of such a compile.
When you try to run the results of such a compile java is always looking for a specific main(String[]); if it can't find it it will throw a runtime exception. The main used to start an app must have exactly that signature.
Here's a quote from Java Tutorials/Getting Started:
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
So to be precise, the main method is defined by Java as an application entry point. Not everything is an application, and not every main method is an application entry point. Applets, for example, don't need a main, because it's started with a different mechanism.
Note also that since the introduction of varargs, you can actually declare your application entry point as follows:
public static void main(String... args)
This works because underneath the syntactic sugar, varargs in Java is implemented as arrays.
See also
Java Tutorials/Getting Started/Hello World
Java Tutorials/Command Line Arguments
Java Language Guide/Varargs
Related questions
Why is the Java main method static?
is possible to overload a main method?
Why main() in java is void?
Why do applets not need a main()?
Entry point for Java applications: main(), init(), or run()?
Important points:
Following is the signature of the main method:
public static void main(String[] args)
main method can be overloaded.
Multiple classes can contain the main method inside a single compilation unit (and so all of them will be called executable classes)
The class containing the main method may or may not be public.
By mistake, if you were to omit the static keyword (or the signature differs in any way), compilation would be done but a runtime error will occur.
From my blog:
Java: Important points about the main method

Categories

Resources