Sunteți pe pagina 1din 19

Q1. Explain PSVM or main method?

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.

e.g. class GeeksforGeeks {


private static void main(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

2. Static: It is a keyword which is when associated with a method, makes it a class


related method. The main() method is static so that JVM can invoke it without
instantiating the class. This also saves the unnecessary wastage of memory which
would have been used by the object declared only for calling the main() method by
the JVM.

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. Command line argument

Q3. Can we overload and over ride the main method?


Q4. What is class loader?

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.

Types of ClassLoaders in Java


Not all classes are loaded by a single ClassLoader. Depending on the type of class
and the path of class, the ClassLoader that loads that particular class is decided. To
know the ClassLoader that loads a class the getClassLoader() method is used. All
classes are loaded based on their names and if any of these classes are not found
then it returns a NoClassDefFoundError or ClassNotFoundException.
A Java Classloader is of three types:
1. BootStrap ClassLoader: A Bootstrap Classloader is a Machine code which
kickstarts the operation when the JVM calls it. It is not a java class. Its job is to
load the first pure Java ClassLoader. Bootstrap ClassLoader loads classes from
the location rt.jar. Bootstrap ClassLoader doesn’t have any parent
ClassLoaders. It is also called as the Primodial ClassLoader.
2. Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap
ClassLoader and loads the extensions of core java classes from the respective
JDK Extension library. It loads files from jre/lib/ext directory or any other
directory pointed by the system property java.ext.dirs.
3. System ClassLoader: An Application ClassLoader is also known as a System
ClassLoader. It loads the Application type classes found in the environment
variable CLASSPATH, -classpath or -cp command line option. The
Application ClassLoader is a child class of Extension ClassLoader.
Note: The ClassLoader Delegation Hierarchy Model always functions in the order
Application ClassLoader->Extension ClassLoader->Bootstrap ClassLoader. The
Bootstrap ClassLoader is always given the higher priority, next is Extension
ClassLoader and then Application ClassLoader.
Principles of functionality of a Java ClassLoader
Principles of functionality are the set of rules or features on which a Java
ClassLoader works. There are three principles of functionality, they are:

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:

protected synchronized Class<?>


loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
Class c = findLoadedClass(name);
try {
if (c == NULL) {
if (parent != NULL) {
c = parent.loadClass(name, false);
}
else {
c = findBootstrapClass0(name);
}
}
catch (ClassNotFoundException e)
{
System.out.println(e);
}
}
}
Note: If a class has already been loaded, it returns it. Otherwise, it delegates the
search for the new class to the parent class loader. If the parent class loader doesn’t
find the class, loadClass() calls the method findClass() to find and load the class.
The finalClass() method searches for the class in the current ClassLoader if the
class wasn’t found by the parent ClassLoader.

Q5. JVM architecture?

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;

// Java code to demonstrate use of Class object


// created by JVM
public class Test
{
public static void main(String[] args)
{
Student s1 = new Student();

// Getting hold of Class object created


// by JVM.
Class c1 = s1.getClass();

// Printing type of object using c1.


System.out.println(c1.getName());

// getting all methods in an array


Method m[] = c1.getDeclaredMethods();
for (Method method : m)
System.out.println(method.getName());

// getting all fields in an array


Field f[] = c1.getDeclaredFields();
for (Field field : f)
System.out.println(field.getName());
}
}

// A sample class whose information is fetched above using


// its Class object.
class Student
{
private String name;
private int roll_No;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getRoll_no() { return roll_No; }
public void setRoll_no(int roll_no) {
this.roll_No = roll_no;
}
}
Output:
Student
getName
setName
getRoll_no
setRoll_no
name
roll_No
Note : For every loaded .class file, only one object of Class is created.
Student s2 = new Student();
// c2 will point to same object where
// c1 is pointing
Class c2 = s2.getClass();
System.out.println(c1==c2); // true
Linking : Performs verification, preparation, and (optionally) resolution.
 Verification : It ensures the correctness of .class file i.e. it check whether this file
is properly formatted and generated by valid compiler or not. If verification fails,
we get run-time exception java.lang.VerifyError.
 Preparation : JVM allocates memory for class variables and initializing the
memory to default values.
 Resolution : It is the process of replacing symbolic references from the type with
direct references. It is done by searching into method area to locate the
referenced entity.
Initialization : In this phase, all static variables are assigned with their values
defined in the code and static block(if any). This is executed from top to bottom in a
class and from parent to child in class hierarchy.
In general, there are three class loaders :
 Bootstrap class loader : Every JVM implementation must have a bootstrap class
loader, capable of loading trusted classes. It loads core java API classes
present in JAVA_HOME/jre/lib directory. This path is popularly known as
bootstrap path. It is implemented in native languages like C, C++.
 Extension class loader : It is child of bootstrap class loader. It loads the classes
present in the extensions directories JAVA_HOME/jre/lib/ext(Extension path) or
any other directory specified by the java.ext.dirs system property. It is
implemented in java by the sun.misc.Launcher$ExtClassLoader class.
 System/Application class loader : It is child of extension class loader. It is
responsible to load classes from application class path. It internally uses
Environment Variable which mapped to java.class.path. It is also implemented
in Java by the sun.misc.Launcher$AppClassLoader class.
// Java code to demonstrate Class Loader subsystem
public class Test
{
public static void main(String[] args)
{
// String class is loaded by bootstrap loader, and
// bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());

// Test class is loaded by Application loader


System.out.println(Test.class.getClassLoader());
}
}
Output:
null
sun.misc.Launcher$AppClassLoader@73d16e93
Note : JVM follow Delegation-Hierarchy principle to load classes. System class loader
delegate load request to extension class loader and extension class loader delegate request
to boot-strap class loader. If class found in boot-strap path, class is loaded otherwise request
again transfers to extension class loader and then to system class loader. At last if system
class loader fails to load class, then we get run-time
exception java.lang.ClassNotFoundException.

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.

Q6. What is static?


Sol. static is a non-access modifier in Java which is applicable for the following:
1. blocks
2. variables
3. methods
4. nested classes
To create a static member(block,variable,method,nested class), precede its
declaration with the keyword static. When a member is declared static, it can be
accessed before any objects of its class are created, and without reference to any
object. For example, in below java program, we are accessing static
method m1() without creating any object of Test class.

// Java program to demonstrate that a static member


// can be accessed before instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}
Output:

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 {

System.out.println("Static block initialized.");

b = a * 4;

public static void main(String[] args)

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;
}

// static method(main !!)


public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}

}
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");

// Cannot make a static reference to the non-static field b


b = 10; // compilation error
// Cannot make a static reference to the
// non-static method m2() from the type Test
m2(); // compilation error

// Cannot use super in a static context


System.out.println(super.a); // compiler error
}

// instance method
void m2()
{
System.out.println("from m2");
}

public static void main(String[] args)


{
// main method
}
}
When to use static variables and methods?
Use the static variable for the property that is common to all objects. For example, in
class Student, all students shares the same college name. Use static methods for
changing static variables.
Consider the following java program, that illustrate the use of static keyword with
variables and methods.
// A java program to demonstrate use of
// static keyword with methods and variables

// Student class
class Student
{
String name;
int rollNo;

// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;

public Student(String name)


{
this.name = name;

this.rollNo = setRollNo();
}

// getting unique rollNo


// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// 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);

// accessing static variable


System.out.println("cllgName : " + cllgName);
}
}

//Driver class
public class StaticDemo
{
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");

Student s1 = new Student("Alice");


Student s2 = new Student("Bob");

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

Q7.why we make static?


Sol. “static” in Object Oriented languages means that the member is not tied to a
particular instance.

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).

Static methods are essentially the same as procedures in non-object-oriented languages


like Pascal or Fortran.

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.

Static classes are interesting.

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.)

Q8 what is the advantage of making static?


First advantages ...
1. Globally accessible
2. One instance per JVM
3. Can be accessed by using class name (No object require)
4. Contains a single value applicable to all instances.
5. Load up on JVM startup.

Q9 what is the disadvantage of making static?


A few words about Disadvantages.

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.

Q10 effect on performance when we make things as static?

Q11 what is object class and explain it's methods?

Q12 what is turnary operator?

Q13 what is upcasting and downcasting?

Q14 difference between super and super()?

Q15 major difference between interface and abstract class?

Q16 can we override a static method?


Q17 how you can prevent the overriding?

Q18 what is typecasting?

Q19 what is narrowing and widining?

Q20 what is class cast exception

Q21 is this a better approach to make all data member as static?

Q22 JVM has its own garbage collector so why we explicitly use system.gc?

Q21 Types of memory in java?

Q23 Output of all four conditions?

Q24 What is polymorphism?

Q25 If we have abstract class so why we use interface if both are working as same?

Q26 How this keyword works?

Q27 Is string mutable or immutable?

Q28 Difference between string builder or string buffer?

Q29 Which is better string builder or string buffer?

Q30 What will be the output?

Q31 How to fetch all vowels from "Iloveindia"?

Q32 How to reverse by its 2nd position? Eg . My name is khan

Q33 Pallendrome string?

Q34 Convert array to arraylist

Q35 Arraylist to array

Q36 Find no of vowel in any string and how many times it's repeated?

Q37 Fibonacci series program and algo both?

Q38 What is exception?

Q39 What is a hierarchy of exception?

Q40 What is error?

Q41 Tell me some type of java exception?

Q42 Tell me some checked and un checked exception?

Q43 Can you write try with in catch?

Q44 Can we have a multiple catch with single try

Q45 What will the the print output?

Q46 What is thow throws and throwable


Q47 What is final finally and finalize

Q48 Why we use finally block?

Q49 What is collection

Q50 Can you sort an array with collections?

Q51 Hierarchy of collections?

Q52 What is array list and linked list and difference between then and which we have to prefer?

Q53 What is hashmap and linked hashmap

Q54 What is set and hashset?

Q55 How can you sort a hashmap?

S-ar putea să vă placă și