how does jvm enter in public static void main? - java

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.

Related

static block execution before interpretation of bytecode.how?

When we say java Test, class loaders will load .class files into method area and static variables if any are initialized to corresponding values assigned and static blocks will be executed.
In java execution means code has to be interpreted by java interpreter. But how static block executes here without interpretation? It is still in a class loading phase, isn’t it?
But in most of the blogs and videos they say once after class loading completes, new thread will be created and it will look for main method and starts executing it. Interpreter comes to picture once main method starts execution in all blogs I saw.
class Test {
static int x = 10;
static {
int y = 10;
System.out.println(x);
}
public static void main(String[] args) {
}
}
The existence of an interpreter is an implementation detail that is irrelevant for describing the behavior of a program. In principle, it is possible to have a JVM without an interpreter at all, as it could have only a compiler that translates all byte code to native code before executing, and still implement the correct behavior. Current desktop and server JVMs have both, executing the code in a mixed mode.
So, it is also irrelevant at which point blogs and videos mention the existence of an interpreter as a way to execute the code, the execution of code always implies the existence of technical means to execute the code, like an interpreter or compiler.
The actual behavior has been specified in The Java Language Specification, §12.4.1:
§12.4.1. When Initialization Occurs
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
A static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6) and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.¹
When a class is initialized, its superclasses are initialized (if they have not been previously initialized), as well as any superinterfaces (§8.1.5) that declare any default methods (§9.4.3) (if they have not been previously initialized). Initialization of an interface does not, of itself, cause initialization of any of its superinterfaces.
¹ this last bullet has been removed from newer specifications
Since the invocation of the main method is an invocation of “a static method declared by” your class, it implies the initialization of that class before the invocation. As you can derive from the last section, if the class containing the main method has uninitialized superclasses, they are initialized even before that class.
For the standard Java launcher, the order of events is
The main thread is created
The main thread loads the specified application class
The super classes of the application class are initialized, if not already initialized
The application class is initialized
The method static void main(String[]) is invoked on the application class
The terms “application class” and “main class” are interchangeable.
Note that this list is only meant to bring these events into the right order. There are far more events happening behind the scenes. Obviously, for asking the application class loader to load the application class, given by name, the classes String, Class, and ClassLoader must have been loaded and initialized, which also implies that their super class, Object has been initialized even before that. The existence of the main thread implies the loading and initialization of the class Thread. And all these classes use other classes behind the scenes.
You may run your application with the -verbose:class option to see which classes are already loaded before your application class.

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.

Java Understanding Java main method on logic

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.

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.

What's the meaning of System.out.println in Java?

Is this static println function in out class from System namespace?
namespace System {
class out {
static println ...
}
How can I interpret this name? And where in JRE this function is defined? In java.lang.System/java.lang.Object?
No. Actually out is a static member in the System class (not as in .NET), being an instance of PrintStream. And println is a normal (overloaded) method of the PrintStream class.
See http://download.oracle.com/javase/6/docs/api/java/lang/System.html#out.
Actually, if out/err/in were classes, they would be named with capital character (Out/Err/In) due to the naming convention (ignoring grammar).
System is a class, that has a public static field out. So it's more like
class System
{
public static PrintStream out;
}
class PrintStream
{
public void println ...
}
This is a slight oversimplification, as the PrintStream class is actually in the java.io package, but it's good enough to show the relationship of stuff.
System.out.println()
High level Understanding
For understanding this we need to recall few basics of java:
dot (.) operator in java: In java . (dot operator) is used only to call methods or variables.
So we can say out is either method or variable.
Methods in java : we know methods always have parenthesis ‘( )’ after method name, So out cannot be a method in java. So out its a variable and println() is a method.
Class name in java: Class name should start with Capital letter ideally in java, So System is a class.
Now with basic knowledge of java we know :
System is a Class
out is a Variable
println() is a method
Lets get more in details:
out variable: static or instance?
called using class name, so we know its static variable of System class.
but its calling a method println() method so ‘out’ is an object of the reference type PrintStream.
the System class belongs to java.lang package
class System {
public static final PrintStream out;
//...
}
the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}
Explained answer on my youtube what is System.out.println
Check following link:
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/System.html
You will clearly see that:
System is a class in the java.lang package.
out is a static member of the System class, and is an instance of java.io.PrintStream.
println is a method of java.io.PrintStream. This method is overloaded to print message to output destination, which is typically a console or file.
println and print are the two overloaded methods which belong to the PrintStream class.
To access them we need an instance of this class.
A static property called out of type PrintStream is created on the System class.
Hence to access the above methods we use the following statements:
System.out.println("foo");
System.out.print("foo");
System.out.println("Hello World");
System: It is the name of standard class that contains objects
that encapsulates the standard I/O devices of your system.
It is contained in the package java.lang. Since java.lang package is imported in every java program by default,therefore java.lang package is the only package in Java API which does not require an import declaration.
out:The object out represents output stream(i.e Command
window)and is the static data member of the class
System.
So note here System.out (System -Class & out- static object i.e why its simply referred to by classname and we need not create any object).
println:The println() is method of out object that
takes the text string as an argument and displays it to the standard
output i.e on monitor screen.
Note
System -Class
out -static Object
println() -method
Remember a function (in java function is called method) always has the format function()
• System is a class in java.lang package
• out is a static object of PrintStream class in java.io package
• println() is a method in the PrintStream class
System is a class of java.lang package, out is an object of PrintStream class and also static data member of System class, print() and println() is an instance method of PrintStream class.
it is provide soft output on console.
It is quite simple to understand the question, but to answer it we need to dig deeper in to Java native code.
System is static class and cannot be instantiated
out is a reference variable defined in System
println() is the method used to print on standard output.
A brief and nice explanation is always welcome on this as we can learn much from this single line of statement itself!
Because out is being called with the System class name itself, not an instance of a class (an object), So out must be a static variable belonging to the class System. out must be instance of a class, because it is invoking the method println().
// the System class belongs to java.lang package
class System {
public static final PrintStream out;
}
class PrintStream {
public void println();
}
System is a class in java.lang package. And out is a PrintStream object. Nice explanation # http://lazy-geeks.blogspot.in/2015/01/what-is-systemoutprintln.html
System.out.println();
System is the class
out is a variable in the System class and it is a static and variable type is PrintStream.
Here is the out variable in System class:
public final static PrintStream out = null;
You can see implementation of System here.
println() is a overloaded method in PrintStream class.
PrintStream includes three overloaded printing methods, those are:
print()
println()
printf()
You can see implementation of PrintStream here.
You cannot instantiate System class and it is child class of Object and the Object is the father(superclass) of every classes including classes that you defined.
Here is what the oracle docs says:
public final class System extends Object
The System class contains several useful class fields and methods. It
cannot be instantiated.
Among the facilities provided by the System class are standard input,
standard output, and error output streams; access to externally
defined properties and environment variables; a means of loading files
and libraries; and a utility method for quickly copying a portion of
an array.
Since:
JDK1.0
If you donot know what is meant by instantiate, read this questioh. It is C# question but the concept is same.
Also, What is the difference between an Instance and an Object?
If you donot know what is meant by overload read this quesiotn.
System is a class in java.lang package.
out is the static data member in System class and reference variable of PrintStream class.
Println() is a normal (overloaded) method of PrintStream class.
From the javadoc about System, here's what the doc says:
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
JDK1.0
Regarding System.out
public static final PrintStream out
The "standard" output stream class Prinstream belongs to java.io package. This stream is already open and ready to accept output data.
When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().
Typically this stream corresponds to display output or another output destination specified by the host environment or user.
Regarding println();
class PrintStream{
public void println();
}
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data);
System is the java class.
out is the instance and also static member of PrintStream.
println is the method of PrintStream.
System.out.println("...") in Java code is translated into JVM. Looking into the JVM gave me better understanding what is going on behind the hood.
From the book Programming form the Java Virtual Machine.
This code is copied from https://github.com/ymasory/programming-for-the-jvm/blob/master/examples/HelloWorld.j.
This is the JVM source code.
.class public HelloWorld
.super java/lang/Object
.method public static main([Ljava/lang/String;)V
.limit stack 2
.limit locals 1
getstatic java/lang/System/out Ljava/io/PrintStream;
ldc "Hello, world"
invokevirtual java/io/PrintStream/println
(Ljava/lang/String;)V
return
.end method
.end class
As "The JVM doesn't permit byte-level access to memory" the out object in type Ljava/io/PrintSteram; is stored in a stack with getstatic JVM command.
Then the argument is pushed on the stack before called a method println of the java/io/PrintStream class from an instance named out. The method's parameter is (Ljava/lang/String;) and output type is void (V).
System: is predefined class of java.lang package.
out: is a static member of printStream class and its connect with console.
Println: is a method of printstream class and its not a static.
System.out.println
System is a class in the java.lang package.
out is a static data member of the System class and references a variable of the PrintStream class.
System - class which is final in nature. public final class System{}. Belongs to java.lang package
out - static reference variable of type PrintStream
println() - non static method in PrintStream class.
PrintStream belongs to java.io package.
To understand it better you can visit : How System.out.println() Works In Java

Categories

Resources