Java Understanding Java main method on logic - java

The main method is the most significant method in your Java application with regards to launching your application as the entry point. What happens prior to this method being used is unclear. Please can someone help me understand/clarify what happens before the method is used by correcting my perception thereof based on the method signature as follows:
The JVM creates at least one Object that will access your main method. This (assumed) object attempts to access your Java application according to the API which obviously binds you to the known method signature public static void main (String[] args){}
public You can't restrict the (assumed) solitary object on the JVM from accessing your Object housing the main method completely looking at logic alone and not the API/signature?
static There are simply no objects up and running to create any other instances of objects up yet (other than the assumed JVM one) to instantiate or create objects out of yet. The static modifier implies the only possibility of accessing this method as it is not bound to an instance and can be accessed therefore 2ithout an instance. Yet again this is logic as without any objects up and running (apart from the assumed JVM one), there can't be any objects up yet to instantiate any other objects with?
args A standard across languages and applications/executables to provide ability to customize the application?|
Is this a correct and logical way to approach and understand the main method?

It's not entirely clear what you're really asking, but the JVM specification section 5.2 covers at least some of this:
The Java Virtual Machine starts up by creating an initial class, which is specified in an implementation-dependent manner, using the bootstrap class loader (ยง5.3.1). The Java Virtual Machine then links the initial class, initializes it, and invokes the public class method void main(String[]). The invocation of this method drives all further execution. Execution of the Java Virtual Machine instructions constituting the main method may cause linking (and consequently creation) of additional classes and interfaces, as well as invocation of additional methods.
In an implementation of the Java Virtual Machine, the initial class could be provided as a command line argument. Alternatively, the implementation could provide an initial class that sets up a class loader which in turn loads an application. Other choices of the initial class are possible so long as they are consistent with the specification given in the previous paragraph.
The JLS section 12.1 has some other descriptions too.
The JVM invokes the main method directly - it doesn't need to create a new object to do so. Although the main method itself has to be public, the class it's declared in doesn't. For example:
public class Test {
private static class EntryPoint {
public static void main(String[] args) {
System.out.println("Hi");
}
}
}
Then execute with:
java 'Test$EntryPoint'
It prints "Hi" as expected.
No code outside the Test class has access to EntryPoint.main() other than through privileged reflection - or direct access that the JVM is clearly capable of.

java first boots up its core - java.lang, classloaders, system properties, runtime etc and then looks at what it has to do. Before the JVM is initialized there is no "java" in that process. Its just a native process and so I think it would be wrong to think in Java terms before this happens.
Now the JVM launcher would first look at pre mains, call them in order (first calling respective static blocks) then look at the main method, call that classes static block(s) if there are any; finally call the main method, passing any command line arguments to the premain and main methods.
Simple Tests:
public class Test {
static{
System.out.println("Hi static 1");
}
public static void main(String[] args) {
System.out.println("Hi main");
}
static{
System.out.println("Hi static 2 better to have 1 static block per class but you can have N ");
}
}

When you put the command like java someClassName then the flowing thing happen.
1.It load the class someClassName and execute the static block(if any)
During class loading an Object class Class will be created which will represent your class.
2.It invoke the main method using the the class name(It won't create any object of your class)
that why main method is static.

Say, file Demo.java contains source code as
public class Demo{
}
when this code is compiled as it's compile successfully as
$javac Demo.java
but when it's executed as
$java Demo
then it shows an exceptional error
Main method not found in class Demo, please define the main method as: public static void main(String[] args)
so compiler is not responsible to check whether main() method is present or not. JVM is responsible for it. JVM check for main() method with prottoype as
public static void main(Strings[] args)
Why JVM search main() method? Is it possible to change main() method into any other method main_hero()?
JVM is instructed to find main() method from inside JVM. Yes, it's possible to change main() method into main_hero() method but inside JVM you must have to instruct to search main_hero() method.
JVM{
public static void main(String[] args)
}
to
JVM{
public static void main_hero(String[] args)
}
Why public?
JVM is installed either in C or D drive so to call from anywhere public is used.
Why static?
main() method is no related to object so without existing object also JVM has to call this method. main method no way related to object.
Why void?
JVM is going to call main() method but what can JVM do with return value if main() method return. So it's meant to be void.

Related

non-static main method in eclipse

I just started learning java using eclipse IDE. I noticed that main method has to be static else it throws error. Because of this I have to declare many Scanner class' objects for each user-given input. Is there a way to make the main method non-static or defining main method without the static keyword in eclipse??
Is there a way to make the main method non-static or defining main method without the static keyword [...]?
No, this is part of how java works.
There is no way around it.
But it shouldn't impact your application since you can always create an instance of your main class and call another method on it:
public class X {
public static void main(String args[]) {
new X().nonStaticMain();
}
public void nonStaticMain() {
// just pretend this is your main
}
}
The main method is the first method that JVM looks for during compilation. This main method has to be executed even before the instantiation of any object of the class. so that later these instantiated objects will invoke other required methods. And hence, static will help the main to run before object instantiation. It is not possible to run the main method without the static keyword.
The answer is no.
You can have a look at these links too:
[A Closer Look at the "Hello World!" Application]
(https://docs.oracle.com/javase/tutorial/getStarted/application/index.html)
Why is the Java main method static?

What does `public static void main args` mean?

I am not sure what this means, whenever before you write a code, people say this
public static void main(String[] args) {
What does that mean?
Here is a little bit detailed explanation on why main method is declared as
public static void main(String[] args)
Main method is the entry point of a Java program for the Java Virtual Machine(JVM). Let's say we have a class called Sample
class Sample {
static void fun()
{
System.out.println("Hello");
}
}
class Test {
public static void main(String[] args)
{
Sample.fun();
}
}
This program will be executed after compilation as java Test. The java command will start the JVM and it will load our Test.java class into the memory. As main is the entry point for our program, JVM will search for main method which is declared as public, static and void.
Why main must be declared public?
main() must be declared public because as we know it is invoked by JVM whenever the program execution starts and JVM does not belong to our program package.
In order to access main outside the package we have to declare it as public. If we declare it as anything other than public it shows a Run time Error but not Compilation time error.
Why main must be declared static?
main() must be declared as static because JVM does not know how to create an object of a class, so it needs a standard way to access the main method which is possible by declaring main() as static.
If a method is declared as static then we can call that method outside the class without creating an object using the syntax ClassName.methodName();.
So in this way JVM can call our main method as <ClassName>.<Main-Method>
Why main must be declared void?
main() must be declared void because JVM is not expecting any value from main(). So,it must be declared as void.
If other return type is provided,the it is a RunTimeError i.e., NoSuchMethodFoundError.
Why main must have String Array Arguments?
main() must have String arguments as arrays because JVM calls main method by passing command line argument. As they are stored in string array object it is passed as an argument to main().
According to the Java language specification, a Java program's execution starts from main() method. A main() method should follow the specific syntax, it can be explained as:
public static void main(String[] args)
public - Access specifier, shows that main() is accessible to all other classes.
void - return type, main() returns nothing.
String args[] - arguments to the main() method, which should an array of type string.
static - Access modifier. A main method should always be static, because the `main()' method can be called without creating an instance of the class.
Let us assume, we are executing a Helloworld java program.
While executing the program, we use the command
java Helloworld.
Internally, this command is converted into
Helloworld.main()
By making main() method static, JVM calls the main() method without creating an object first.
In Java your main method must always be:
public static void main(String args[])
The program execution starts with main() function, hence the main() function.
It must be public so that it is accessible to the outside environment.
The main() method is always static because, as you know that the program execution starts at main() method and there is no instance of the class containing main() method is initiated. Hence as the static method can run without need of any instance it is declared of static.
Java is platform independent, hence you may try to compile the java file on one system and try to execute the class file on another. Each machines' bit architecture may be different hence the return type of the main function must always be main().
Hope this helps.
Public = This method is visible to all other classes.
static = This method doesn't need an instance to be ran.
void = This method doesn't return anything.
main() = Main method (First method to run).
String[] = Array of strings.
args = Array name.
public --> Access specifier. Any other class can access this method.
static --> The method is bound to the class, not to an instance of the class.
void --> Return type. The method doesn't return anything.
main(String[] args) --> method name is main(). It takes an array of String's as argument. The String[] args are command line arguments.
Note: The main() method defined above is the entry point of a program, if you change the signature, then your program might not run.
Please go through this video link ->
https://youtu.be/ggsRGcA8hnQVery for a clear and to the point explanation of public static void main(String args[]) method.

We cant access non static instance from a static method, but can initiate a class. how?

We cant access non static instance from a static method. But main() method is static and runs first. During initialization of any other class in main method, it will call the constructor. Is that constructor static ? what is the basic flow for JVM ?
The main method is called by the JVM to run the method which is outside the scope of project.
When the JVM calls the main method, there is no object existing for the class being called. So it has to have static method to allow this from class.
During initialization of any other class in main method, it will call the constructor.
If you mean instantiation, then Yes it will. Creating an instance of a class calls the constructor, whether the new call is made in main or anywhere else.
If you really do mean class initialization (which typically happens implicitly), then No it won't. The initialization of a class does no involve the classes constructors.
For example
public class Example {
private static int foo = OtherClass.someMethod();
static {
// do something
}
public Example() {
// do something
}
}
Class initialization executes the initializer for foo and the static initializer block, but is doesn't execute the constructor. Creating an instance of Example calls the Example() constructor.
Is that constructor static ?
Constructors are always static ... in the sense that new doesn't require an existing instance.
Yes, we can't access non-static variables from static block because, non-static variable are instance variables & can only be accessed by creating an object of class with new operator or using reflection like Class.newInstance(). Whereas, static variables are class level & it's value is constant for every single object. It means no need to create an object of a class to access those variables. You can access static variable by using class name (different class) or directly (within same class) like :-
public class HelloWorld {
private static String message = "Hello";
public static void main(String[] args) {
System.out.println(message);
System.out.println(HelloWorld1.sayHello);
}
}
public class HelloWorld1 {
public static String sayHello = "Hello1";
}
main() method :
public static void main(String[] args) {}
In Java, main() method is static & it's the entry point of JVM. Since, main() method doesn't belong to any class in Java. When we define main() method in any user-defined class, then it will belong to that class. And since it's static & within the same class, no need to access it using class name. The main method is directly available to JVM.
How JVM works :
When there is need to execute to any Java class ClassLoader comes into picture. The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.
Image taken from : Understanding JVM Internals
When JVM starts to execute a Java file, it'll
First compile .java file & convert it into .class file which contains bytecode i.e, machine language or assembly language. Each time the same bytecodes are processed, JVM works with JIT (Just-In-Time) compiler to convert byte code into native code.
Loads the .java file & necessary packages using System Class Loader & BoostrapperClassLoader resp.
After loading, JVM will look into .class file & store all information like variables, packages, methods, etc & save them into a memory & initialize all the field variables.
The JVM then starts interpreting bytecode & displays the result of that in human readable form.

how does jvm enter in public static void main?

How can jvm enter in default class:
class try1
{
public static void main(String args[])
{
...
}
}
In it how does JVM access this method?
In packages, if a class is 'default' its public methods cant be accessed from outside the package, so how does jvm enter this class?
It is not JVM itself who invokes main method. This is rather a job of Java launcher, i.e. java.exe.
Java launcher is a small program written in C that uses regular JNI functions:
JNI_CreateJavaVM to create a new instance of JVM and to obtain an instance of JNIEnv;
JNIEnv::FindClass to locate the main class specified in the command line;
JNIEnv::GetStaticMethodID to find public static void main(String[]) method in class #2.
JNIEnv::CallStaticVoidMethod to invoke the method found in #3.
In fact, JNI allows you to work with all classes, methods and fields, even with private modifier.
First of all the JVM does not enter the method, it invokes (calls) it (yes, it matters). The keyword public declares that the method can be accessed from anywhere (different packages); the static keyword declares that you can call the method without instatiating the class (among other things) and as far as I know the class that contains the main method is always public.
You explicitly told java what class to load on the command line or in a .jar's Manifest if you're running an executable jar.
The Java Specification Chapter 12 goes briefly into what happens when the JVM starts up. (The JVM Specification Chapter 5 covers it in more detail.)
In short:
java try1 will load the try1 class, then link, verify, resolve, and initialize it.
Once that's done, it will look for a main method that is public, static, and void that accepts an array of Strings, then it will execute that method.
The JVM doesn't care that your class wasn't public. As the first class loaded, it is the current compilation unit and initial access control is calculated from it.

can we access public method defined in a default class outside the package in java?

The main method in java is defined as a public method, and this method is defined in a default class. lets say
class test{
public static void main(String args[]){
System.out.println("Hi");
}
}
can you please explain how the JVM is able to access this main method as the class is default and it can be accessed only with in the package.
You're thinking of the JVM as a bunch of Java code in some other package, which therefore couldn't access the main method hidden in your class with default accessibility. But it's not. The JVM is the virtual machine on which Java code is run; it decides what is and is not accessible to other Java code. In particular, it can run whichever methods it likes, regardless of their accessibility.

Categories

Resources