Documente Academic
Documente Profesional
Documente Cultură
Sol. In Java programs, the point from where the program starts its execution or simply the
entry point of Java programs is the main() method. Hence, it is one of the most important
methods of Java and having proper understanding of it is very important.
Explanation:
Every word in the public static void main statement has got a meaning to the JVM.
1. Public: It is an Access modifier, which specifies from where and who can access the
method. Making the main() method public makes it globally available. It is made public
so that JVM can invoke it from outside the class as it is not present in the current class.
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
class GeeksforGeeks {
public void main(String[] args)
{
System.out.println("I am a Geek");
}
}
Error: Main method is not static in class test, please define the main method as:
public static void main(String[] args)
3. Void: It is a keyword and used to specify that a method doesn’t return anything.
As main() method doesn’t return anything, its return type is void. As soon as
the main() method terminates, the java program terminates too. Hence, it doesn’t
make any sense to return from main() method as JVM can’t do anything with the
return value of it.
class GeeksforGeeks {
public static int main(String[] args)
{
System.out.println("I am a Geek");
return 1;
}
}
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
main: It is the name of Java main method. It is the identifier that the JVM looks for as the
starting point of the java program. It’s not a keyword.
class GeeksforGeeks {
public static void myMain(String[] args)
{
System.out.println("I am a Geek");
}
}
Error: Main method not found in class, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
String[] args: It stores Java command line arguments and is an array of
type java.lang.String class. Here, the name of the String array is args but it is not fixed and
user can use any name in place of it.
class GeeksforGeeks {
// javac GeeksforGeeks.java
// java GeeksforGeeks 1 2 3
public static void main(String[] args)
{
for (String elem : args)
System.out.println(elem);
}
}
1
2
3
Q2. From where the main method takes the value as parameter?
Sol. The Java ClassLoader is a part of the Java Runtime Environment that
dynamically loads Java classes into the Java Virtual Machine. The Java run time
system does not need to know about files and file systems because of classloaders.
Java classes aren’t loaded into memory all at once, but when required by an
application. At this point, the Java ClassLoader is called by the JRE and these
ClassLoaders load classes into memory dynamically.
1. Delegation Model: The Java Virtual Machine and the Java ClassLoader use an
algorithm called the Delegation Hierarchy Algorithm to Load the classes into
the Java file.
The ClassLoader works based on a set of operations given by the delegation
model. They are:
ClassLoader always follows the Delegation Hierarchy Principle.
Whenever JVM comes across a class, it checks whether that class is
already loaded or not.
If the Class is already loaded in the method area then the JVM proceeds
with execution.
If the class is not present in the method area then the JVM asks the Java
ClassLoader Sub-System to load that particular class, then ClassLoader
sub-system hands over the control to Application ClassLoader.
Application ClassLoader then delegates the request to Extension
ClassLoader and the Extension ClassLoader in turn delegates the
request to Bootstrap ClassLoader.
Bootstrap ClassLoader will search in the Bootstrap
classpath(JDK/JRE/LIB). If the class is available then it is loaded, if not the
request is delegated to Extension ClassLoader.
Extension ClassLoader searches for the class in the Extension
Classpath(JDK/JRE/LIB/EXT). If the class is available then it is loaded, if
not the request is delegated to the Application ClassLoader.
Application ClassLoader searches for the class in the Application
Classpath. If the class is available then it is loaded, if not then
a ClassNotFoundException exception is generated.
2. Visibility Principle: The Visibility Principle states that a class loaded by a
parent ClassLoader is visible to the child ClassLoaders but a class loaded by a
child ClassLoader is not visible to the parent ClassLoaders. Suppose a class
GEEKS.class has been loaded by the Extension ClassLoader, then that class is
only visible to the Extension ClassLoader and Application ClassLoader but not
to the Bootstrap ClassLoader. If that class is again tried to load using Bootstrap
ClassLoader it gives an exception java.lang.ClassNotFoundException.
3. Uniqueness Property: The Uniquesness Property ensures that the classes
are unique and there is no repetition of classes. This also ensures that the
classes loaded by parent classloaders are not loaded by the child classloaders.
If the parent class loader isn’t able to find the class, only then the current
instance would attempt to do so itself.
Methods of Java.lang.ClassLoader
After the JVM requests for the class, a few steps are to be followed in order to load a
class. The Classes are loaded as per the delegation model but there are a few
important Methods or Functions that play a vital role in loading a Class.
1. loadClass(String name, boolean resolve): This method is used to load the
classes which are referenced by the JVM. It takes the name of the class as a
parameter. This is of type loadClass(String, boolean).
2. defineClass(): The defineClass() method is a final method and cannot be
overriden. This method is used to define a array of bytes as an instance of
class. If the class is invalid then it throws ClassFormatError.
3. findClass(String name): This method is used to find a specified class. This
method only finds but doesn’t load the class.
4. findLoadedClass(String name): This method is used to verify whether the
Class referenced by the JVM was previously loaded or not.
5. Class.forName(String name, boolean initialize, ClassLoader loader): This
method is used to load the class as well as initialize the class. This method also
gives the option to choose any one of the ClassLoaders. If the ClassLoader
parameter is NULL then Bootstrap ClassLoader is used.
Example: The following code is executed before a class is loaded:
Sol. JVM(Java Virtual Machine) acts as a run-time engine to run Java applications.
JVM is the one that actually calls the main method present in a java code. JVM is a
part of JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any
other Java enabled system without any adjustment. This is all possible because of
JVM.
When we compile a .java file, .class files(contains byte-code) with the same class
names present in .java file are generated by the Java compiler. This .class file goes
into various steps when we run it. These steps together describe the whole JVM.
Class Loader Subsystem
It is mainly responsible for three activities.
Loading
Linking
Initialization
Loading : The Class loader reads the .class file, generate the corresponding binary
data and save it in method area. For each .class file, JVM stores following
information in method area.
Fully qualified name of the loaded class and its immediate parent class.
Whether .class file is related to Class or Interface or Enum
Modifier, Variables and Method information etc.
After loading .class file, JVM creates an object of type Class to represent this file in
the heap memory. Please note that this object is of type Class predefined
in java.lang package. This Class object can be used by the programmer for getting
class level information like name of class, parent name, methods and variable
information etc. To get this object reference we can use getClass() method
of Object class.
// A Java program to demonstrate working of a Class type
// object created by JVM to represent .class file in
// memory.
import java.lang.reflect.Field;
import java.lang.reflect.Method;
JVM Memory
Method area :In method area, all class level information like class name, immediate
parent class name, methods and variables information etc. are stored, including
static variables. There is only one method area per JVM, and it is a shared resource.
Heap area :Information of all objects is stored in heap area. There is also one Heap
Area per JVM. It is also a shared resource.
Stack area :For every thread, JVM create one run-time stack which is stored here.
Every block of this stack is called activation record/stack frame which store methods
calls. All local variables of that method are stored in their corresponding frame. After
a thread terminate, it’s run-time stack will be destroyed by JVM. It is not a shared
resource.
PC Registers :Store address of current execution instruction of a thread. Obviously
each thread has separate PC Registers.
Native method stacks :For every thread, separate native stack is created. It stores
native method information.
Execution Engine
Execution engine execute the .class (bytecode). It reads the byte-code line by line,
use data and information present in various memory area and execute instructions. It
can be classified in three parts :-
Interpreter : It interprets the bytecode line by line and then executes. The
disadvantage here is that when one method is called multiple times, every time
interpretation is required.
Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It
compiles the entire bytecode and changes it to native code so whenever
interpreter see repeated method calls,JIT provide direct native code for that part
so re-interpretation is not required,thus efficiency is improved.
Garbage Collector : It destroy un-referenced objects.For more on Garbage
Collector,refer Garbage Collector.
Java Native Interface (JNI) :
It is an interface which interacts with the Native Method Libraries and provides the
native libraries(C, C++) required for the execution. It enables JVM to call C/C++
libraries and to be called by C/C++ libraries which may be specific to hardware.
Native Method Libraries :
It is a collection of the Native Libraries(C, C++) which are required by the Execution
Engine.
from m1
Static blocks
If you need to do computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating use of static blocks.
// Java program to demonstrate use of static blocks
class Test
// static variable
static int a = 10;
static int b;
// static block
static {
b = a * 4;
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40
Static variables
When a variable is declared as static, then a single copy of variable is created and
shared among all objects at class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables :-
We can create static variables at class-level only. See here
static block and static variables are executed in order they are present in a program.
Below is the java program to demonstrate that static block and static variables are
executed in order they are present in a program.
// java program to demonstrate execution
// of static blocks and variables
class Test
{
// static variable
static int a = m1();
// static block
static {
System.out.println("Inside static block");
}
// static method
static int m1() {
System.out.println("from m1");
return 20;
}
}
Output:
from m1
Inside static block
Value of a : 20
from main
Static methods
When a method is declared with static keyword, it is known as static method. The
most common example of a static method is main( ) method.As discussed above,
Any static member can be accessed before any objects of its class are created, and
without reference to any object.Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
Below is the java program to demonstrate restrictions on static methods.
// java program to demonstrate restriction on static methods
class Test
{
// static variable
static int a = 10;
// instance variable
int b = 20;
// static method
static void m1()
{
a = 20;
System.out.println("from m1");
// instance method
void m2()
{
System.out.println("from m2");
}
// Student class
class Student
{
String name;
int rollNo;
// static variable
static String cllgName;
this.rollNo = setRollNo();
}
// static method
static void setCllg(String name){
cllgName = name ;
}
// instance method
void getStudentInfo(){
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);
//Driver class
public class StaticDemo
{
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");
s1.getStudentInfo();
s2.getStudentInfo();
}
}
Output:
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ
Static nested classes : We can not declare top-level class with a static modifier, but can
declare nested classes as static. Such type of classes are called Nested static classes. For
static nested class, see static nested class in java
A static method cannot reference the “this” object, and cannot reference any other non-
static members.
However, it can be called without reference to an object, (by qualifying it with the class
name if you’re outside of the class).
A static field has only one value, which is shared across the entire application. This can
be a source of confusion, when the value seems to change magically. (because it’s being
changed by another instance!)
It can also be the source of memory leaks; static fields are allocated as long as the class
is loaded, which could be forever. Be sure you know what you’re doing with a static field.
In Java, a nested class that is declared static is just an ordinary class that happens to be
declared inside another class. If it’s public you can instantiate it and use it just like any
other class.
The interesting part is that a non-static nested class (sometimes called an “inner” class) is
contained within an instance of the outer class, and can reference instance members of
the containing object.
Among other things, this means you cannot even create an instance of the inner class
without qualifying it with an instance of the outer class.
(In .NET languages, all nested classes are automatically static, and you cannot change
this.)
1. Static members are always part of memory weather they are in use or not, but it
hardly impact.
2. Static members are created with a particular intention (Creating at class level
instead of object level), so it requires a clear vision of your requirement.
3. To synchronize a static method you need some extra efforts.
4. Above all points are design approaches not disadvantages.
5. The tag line will be you must know “static “before using it :D.
Q22 JVM has its own garbage collector so why we explicitly use system.gc?
Q25 If we have abstract class so why we use interface if both are working as same?
Q36 Find no of vowel in any string and how many times it's repeated?
Q52 What is array list and linked list and difference between then and which we have to prefer?