Core Java Interview QSTN
Core Java Interview QSTN
What is API ?
Java support more than 18 international languages so java take 2 byte for characters, because
for 18 international language 1 byte of memory is not sufficient for storing all characters and
symbols present in 18 languages. Java supports Unicode but c support ascii code. In ascii
code only English language are present, so for storing all English latter and symbols 1 byte is
sufficient.
Java and javac are tools or application programs or exe files developed by sun micro system
and supply as a part of jdk 1.5/1.6/1.7/1.8 in bin folder. Java tool are used for rur the java
program and javac tool are used for compile the java program.
Different Java programmers can have different styles and approaches to write program. By
using standard Java naming conventions they make their code easier to read for themselves
and for other programmers. Readability of Java code is important because it means less time
is spent trying to figure out what the code does, and leaving more time to fix or modify it.
Java follows camelcase syntax for naming the class, interface, method and variable.
What is JVM ?
What is classloader ?
Class loader subsystem will load the .class file into java stack and later sufficient memory
will be allocated for all the properties of the java program into following five memory
locations.
Heap area
Method area
Java stack
PC register
Native stack
The main aim of JIT compiler is to speed up the execution of java program.
Boolean data type takes zero bytes of main memory space because Boolean data type of java
implemented by Sun Micro System with a concept of flip - flop. A flip - flop is a general
purpose register which stores one bit of information (one true and zero false).
Java is free from pointer due to this execution time of application is improve.
[whenever we write a Java program we write without pointers and internally it is
converted into the equivalent pointer program].
Java have garbage collector which is always used to collect un-Referenced (unused)
Memory location for improving performance of a Java program.
Garbage collector, collect the unused memory space and improve the performance of
java application.
Java have no pointers so that using java program we can develop an application very
easily.
Java is a platform independent programming language, Because when you install jdk
software on your system then automatically jvm are install on your system. For every
operating system separate jvm is available which is capable to read .class file or byte code.
When we compile your java code then .class file is generated by javac compiler these code
are readable by jvm and every operating system have its own jvm so jvm is platform
dependent but due to jvm java language is become platform independent.
Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.
A class has to be loaded in main memory before we start using it. Static block is executed
during class loading. This is the reason why a static block executes before the main method.
because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.
The dot operator(.) is used to access the instance variables and methods of class objects.It is
also used to access classes and sub-packages from a package.
The main purpose of using this keyword is to differentiate the formal parameter and data
members of class, whenever the formal parameter and data members of the class are similar
then jvm get ambiguity (no clarity between formal parameter and member of the class)
To differentiate between formal parameter and data member of the class, the data member of
the class must be preceded by "this".
Whenever the derived class is inherits the base class features, there is a possibility that base
class features are similar to derived class features and JVM gets an ambiguity. In order to
differentiate between base class features and derived class features must be preceded by super
keyword.
What is the difference between this. (this dot) and this() (this off).
this. can be used to differentiate variable of class and formal parameters of method or
constructor.
this() can be used to call one constructor within the another constructor without creation of
objects multiple time for the same class.
static keyword always fixed the memory that means that will be located only once in the
program where as final keyword always fixed the value that means it makes variable values
constant.
Because object is not required to call static method if main() is non-static method, then jvm
create object first then call main() method due to that face the problem of extra memory
allocation.
Yes, We can overload main() method. A Java class can have any number of main() methods.
But run the java program, which class should have main() method with signature as "public
static void main(String[] args). If you do any modification to this signature, compilation
will be successful. But, not run the java program. we will get the run time error as main
method not found.
Can we override java main method ?
Path variable is set for use all the tools like java, javac, javap, javah, jar, appletviewer etc.
Classpath variable is used for set the path for all classes which is used in our program so we
set classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed
rt.jar file we get all .class files.
If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, Pascal are treated as non-portable language. JAVA is a
portable language.
Import is a keyword in java language used to import the predefined properties of java API
into current working java program. Read more......
For each and every fundamental data type there exist a pre-defined class, Such predefined
class is known as wrapper class.
The main purpose of wrapper class is to convert numeric string data into numerical or
fundamental data. We know that in java whenever we get input form user, it is in the form of
string value so here we need to convert these string values in different different datatype
(numerical or fundamental data), for this conversion we use wrapper classes. Read more......
Access Specifier
Which access specifier are called universal access specifier ?
Public
Default
Default
Scope of protected specifier ?
protected members of class is accessible within the same class and other class of same
package and also accessible in inherited class of other package.
private members of class in not accessible any where in program these are only accessible
within the class. private are also called class level access specifier.
JVM Architecture
JVM (Java Virtual Machine) is a software. It is a specification that provides Runtime
environment in which java bytecode can be executed.
Operation of JVM
JVM mainly performs following operations.
Note: Java is platform Independent but JVM is platform dependent because every Operating
system have different-different JVM which is install along with JDK Software.
Heap area
Method area
Java stack
PC register
Native stack
Heap area:
Method area
Java Stack
In which all the non-static variable of class will be stored and whose address referred by
object reference.
Pc Register
Which holds the address of next executable instruction that means that use the priority for the
method in the execution process?
Native Stack
Native stack holds the instruction of native code (other than java code) native stack depends
on native library. Native interface will access interface between native stack and native
library.
Execution Engine
Which contains Interpreter and JIT compiler whenever any java program is executing at
the first time interpreter will comes into picture and it converts one by one byte code
instruction into machine level instruction JIT compiler (just in time compiler) will comes into
picture from the second time onward if the same java program is executing and it gives the
machine level instruction to the process which are available in the buffer memory.
Note: The main aim of JIT compiler is to speed up the execution of java program.
JIT is the set of programs developed by SUN Micro System and added as a part of JVM, to
speed up the interpretation phase.
In the older version of java compilation phase is so faster than interpretation phase. Industry
has complained to the SUN Micro System saying that compilation phase is very faster and
interpretation phase is very slow.
So solve this issue, SUN Micro System has developed a program called JIT (just in time
compiler) and added as a part of JVM to speed up the interpretation phase. In the current
version of java interpretation phase is so faster than compilation phase. Hence java is one of
the highly interpreted programming languages.
Constructor
Why use constructor ?
The main purpose of create a constructor is, for placing user defined values in place of
default values.
Constructor will never return any value even void, because the basic aim constructor is to
place value in the object
Constructor definition should not be static because constructor will be called each and every
time when object is created. If you made constructor is static then the constructor before
object creation same like main method.
Constructor will not be inherited from one class to another class because every class
constructor is created for initialize its own data members.
The purpose of default constructor is to create multiple object with respect to same class for
placing same value.
What is purpose of parameterized constructor ?
The purpose of parametrized constructor is to create multiple object with respect to same
class for placing different value of same type or different type or both.
Is constructor inherited?
The default constructor provides the default values to the objects. The java compiler creates a
default constructor only if there is no constructor in the class.
yes, that is current instance (You cannot use return type yet it returns a value).
Constructor are calling from bottom to top and executing from top to bottom.
The scope of constructor is within the class so that it is not possible to achieved overriding at
constructor level.
Method Constructor
1 Method can be any user defined name Constructor must be class name
2 Method should have return type It should not have any return type (even void)
Method should be called explicitly either It will be called automatically whenever object
3
with object reference or class reference is created
Method is not provided by compiler in any The java compiler provides a default
1
case. constructor if we do not have any constructor.
String Handling
Why use string handling in Java
The basic aim of String Handling concept is storing the string data in the main memory
(RAM), manipulating the data of the String, retrieving the part of the String etc. String
Handling provides a lot of concepts that can be performed on a string such as concatenation
of string, comparison of string, find sub string etc.
equals() method always used to comparing contents of both source and destination String. It
return true if both string are same in meaning and case otherwise it returns false.
== Operator is always used for comparing references of both source and destination objects
but not their contents.
String StringBuffer
The data which enclosed within double The data which enclosed within double quote
1 quote (" ") is by default treated as String (" ") is not by default treated as StringBuffer
class. class
2 String class object is immutable StringBuffer class object is mutable
When we create an object of String class by When we create an object of StringBuffer class
3 default no additional character memory by default we get 16 additional character
space is created. memory space.
If the content is fixed and would not change frequently then we use String.
If content is not fixed and keep on changing but thread safety is required then we use
StringBuffer
If content is not fixed and keep on changing and thread safety is not required then we
use StringBuilder
Both of them are belongs to public final. so that they never participates in inheritance
that is is-A relationship is not possible but they can always participates in As-A and
Uses-A relationship.
All the things between StringBuffer and StringBuilder are same only difference is
StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one
thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow
at a time so it not thread safe.
StringBuffer StringBuilder
1 It is thread safe. It is not thread safe.
Its methods are synchronized and provide Its methods are not synchronized and unable to
2
thread safety. provide thread safety.
Relatively performance is low because Relatively performance is high because no
3 thread need to wait until previous process need to wait any thread it allows multiple
is complete. thread at a time.
1 Introduced in 1.0 version. Introduced in 1.5 version.
What is StringTokenizer ?
It is a pre defined class in java.util package can be used to split the given string into tokens
(parts) based on delimiters (any special symbols or spaces). Read more......
Exception Handling
What is Exception Handling ?
The process of converting system error messages into user friendly error message is known as
Exception handling.
What is Exception ?
An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's Instructions.
Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
Yes, One try block can contains another try block that is nested or inner try block can be
possible.
The ArithmeticException is thrown when integer is divided by zero or taking the remainder
of a number by zero. It is never thrown in floating-point operations.
throw throws
throws is a keyword which gives an indication to
throw is a keyword used for hitting and
the specific method to place the common
1 generating the exception which are
exception methods as a part of try and catch
occurring as a part of method body
block for generating user friendly error messages
The place of using throw keyword is The place of using throws is a keyword is always
2
always as a part of method body. as a part of method heading
When we use throw keyword as a part of When we write throws keyword as a part of
method body, it is mandatory to the java method heading, it is optional to the java
3
programmer to write throws keyword as programmer to write throw keyword as a part of
a part of method heading method body.
Error Exception
1 Can be handle. Can not be handle.
Example: Example:
2 NoSuchMethodError ClassNotFoundException
OutOfMemoryError NumberFormateException
Multithreading
What is thread ?
New State
Ready State
Running State
Waiting State
Read more.........
If the thread is in new or dead state no memory is available but sufficient memory is available
if that is in ready or running or waiting state.
Sleep() can be used to convert running state to waiting state and automatically thread convert
from waiting state to running state once the given time period is completed. Where as
suspend() can be used to convert running state thread to waiting state but it will never return
back to running state automatically.
Allowing only one thread at a time to utilized the same resource out of multiple threads is
known as thread synchronization or thread safe.
Synchronized block
Synchronized method
A class has to be loaded in main memory before we start using it. Static block is executed
during class loading. This is the reason why a static block executes before the main method.
because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.
The main purpose of using this keyword is to differenciate the formal parameter and data
members of class, whenever the formal parameter and data members of the class are similar
then jvm get ambiguty (no clearity between formal parameter and member of the class)
To differenciate between formal parameter and data member of the class, the data member of
the class must be preceded by "this".
Whenever the derived class is inherits the base class features, there is a possibility that base
class features are similar to derived class features and JVM gets an ambiguity. In order to
differentiate between base class features and derived class features must be preceded by super
keyword.
What is the difference between this. (this dot) and this() (this off).
this. can be used to differentiate variable of class and formal parameters of method or
constructor.
this() can be used to call one constructor within the another constructor without creation of
objects multiple time for the same class.
Difference between static and final keyword
static keyword always fixed the memory that means that will be located only once in the
program where as final keyword always fixed the value that means it makes variable values
constant.
Because object is not required to call static method if main() is non-static method, then jvm
create object first then call main() method due to that face the problem of extra memory
allocation.
These methods always access with These property always access with class
object reference reference
4 Syntax: Syntax:
Objref.methodname(); className.methodname();
Super class is always pointing to base class features and this keyword is always pointing to
current class features.
super() and super(..) are used for establishing the communication between base class and
derived class constructor.
this() and this(...) are used for establishing the communication between current class
constructor.
Which access specifiers is known as package access specifiers.
Abstract classes definitions should not be made as final because abstract classes always
participate in inheritance classes.
These methods always access with These property always access with class
object reference reference
4 Syntax: Syntax:
Objref.methodname(); className.methodname();
A new keyword is used to allocate memory at runtime, new keyword is used for create an
object of class
If the variable keep on changing such type of variables we have to declare with volatile
modifier. Read more......
The main advantage of Volatile keyword is we can resolve data inconsistency problems.
Synchronized Keyword is used for when we want to allowed only one thread at a time then
use Synchronized modifier. If a method or block declared as a Synchronized then at a time
only one thread is allowed to operate on the given object.
The main advantage of Synchronized keyword is we can resolve data inconsistency problem.
The main dis-advantage of Synchronized keyword is it increased the waiting time of thread
and effect performance of the system, Hence if there is no specific requirement it is never
recommended to use synchronized keyword.
Inheritance
What is Inheritance ?
The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented programming.
If we develop any application using concept of Inheritance than that application have
following advantages,
It's main uses are to enable polymorphism and to be able to reuse code for different
classes by putting it in a common super class
For code Re-usability
No, In Inheritance the scope of access modifier increasing is allow but decreasing is not
allow. Suppose in parent class method access modifier is default then it's present in child
class with default or public or protected access modifier but not private(it decreased scope).
Single inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
Due to ambiguity problem java does not support mutiple inheritance at class level.
Java can not support multiple inheritance at class level but you can achieve multiple
inheritance in java by using Interface concept.
Package keyword is always used for creating the undefined package and placing
common classes and interfaces.
import is a keyword which is used for referring or using the classes and interfaces of a
specific package.
The real life example of inheritance is child and parents, all the properties of father are
inherited by his son.
In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height,
age as well as behaviors:- barking, eating, and sleeping.
Interface
What is interface ?
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
Whenever we compile any Interface program it generate .class file. That means the bytecode
of an interface appears in a .class file.
An interface cannot contain instance fields. Interface only contains public static final
variables.
Because, constructor are used for eliminate the default values by user defined values, but in
case of interface all the data members are public static final that means all are constant so no
need to eliminate these values.
Other reason because constructor is like a method and it is concrete method and interface
does not have concrete method it have only abstract methods that's why interface have no
constructor.
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity.
Because, constructor are used for eliminate the default values by user defined values, but in
case of interface all the data members are public static final that means all are constant so no
need to eliminate these values.
Other reason because constructor is like a method and it is concrete method and interface
does not have concrete method it have only abstract methods that's why interface have no
constructor.
In java, abstract and final both modifiers are not allowed for a class at a time the reason is
abstract and final are opposite keywords. If a class is an abstract, then that class must be
extended (inherited). If a class is final then that class can not be extended. So both keyword
can not be use at a time
Abstract class are used for fulfill common requirement. If we use concrete classes for fulfill
common requirements than such application will get the following limitations.
Encapsulation is not provides fully security because we can access private member of the
class using reflation API, but in case of Abstraction we can't access static, abstract data
member of class.
Abstract Interface
It is collection of abstract method and
1 It is collection of abstract method.
concrete methods.
There properties can be reused commonly There properties commonly usable in any
2
in a specific application. application of java environment.
3 It does not support multiple inheritance. It support multiple inheritance.
Abstract class is preceded by abstract
4 It is preceded by Interface keyword.
keyword.
Which may contain either variable or
5 Which should contains only constants.
constants.
The default access specifier of abstract There default access specifier of interface
6
class methods are default. method are public.
These class properties can be reused in These properties can be reused in any other
7
other class using extend keyword. class using implements keyword.
Inside abstract class we can take Inside interface we can not take any
8
constructor. constructor.
For the abstract class there is no restriction For the interface it should be compulsory to
9 like initialization of variable at the time of initialization of variable at the time of
variable declaration. variable declaration.
Inside interface we can take instance and Inside interface we can not take instance and
10
static block. static block.
For the interface variable can not declare
There are no any restriction for abstract
11 variable as private, protected, transient,
class variable.
volatile.
There are no any restriction for abstract For the interface method can not declare
12 class method modifier that means we can method as strictfp, protected, static, native,
use any modifiers. private, final, synchronized.
Abstraction shows only important things to the user and hides the internal details for example
when we ride a bike, we only know about how to ride bike but can not know about how it
work ? and also we do not know internal functionality of bike.
The common example of encapsulation is capsule. In capsule all medicine are encapsulated in
side capsule.
Encapsulation is not provides fully security because we can access private member of the
class using reflation API, but in case of Abstraction we can't access static, abstract data
member of class.
polymorphism
Give Real life example of polymorphism
Suppose if you are in class room that time you behave like a student, when you are in market
at that time you behave like a customer, when you at your home at that time you behave like
a son or daughter, Here one person present in different-different behaviors.
Overloading Overriding
Whenever same method or Constructor is Whenever same method name is existing
existing multiple times within a class either multiple time in both base and derived
1 with different number of parameter or with class with same number of parameter or
different type of parameter or with different same type of parameter or same order of
order of parameter is known as Overloading. parameters is known as Overriding.
Arguments of method must be different at Argument of method must be same
2
least arguments. including order.
3 Method signature must be different. Method signature must be same.
Private, static and final methods can be Private, static and final methods can not be
4
overloaded. overrided.
5 Access modifiers point of view no restriction. Access modifiers point of view not
reduced scope of Access modifiers but
increased.
Also known as compile time polymorphism or Also known as run time polymorphism or
6
static polymorphism or early binding. dynamic polymorphism or late binding.
Overloading can be exhibited both are method Overriding can be exhibited only at
7
and constructor level. method leve.
The scope of Overriding is base class and
8 The scope of overloading is within the class.
derived class.
Overloading can be done at both static and Overriding can be done only at non-static
9
non-static methods. method.
For overloading methods return type may or For overriding method return type should
10
may not be same. be same.
Collection Framework
Main advantage of Collection Framework ?
Collections are grow-able in nature and hence based on our requirement we can increase or
decrease the size and it store homogeneous data type. The basic aim of collection framework
is to improve the performance of java based application.
Array Collection
Arrays are fixed in size and hence once we Collections are grow-able in nature and
1 created an array we are not allowed to increase hence based on our requirement we can
or decrease the size based on our requirement. increase or decrease the size.
Arrays can hold both primitives as well as Collections can hold only objects but not
2
objects. primitive.
Performance point of view arrays faster than Performance point of view collections are
3
collection slower than array
Collections can hold both homogeneous
4 Arrays can hold only homogeneous elements.
and heterogeneous elements.
Memory point of view arrays are not Memory point of view collections are
5
recommended to use. recommended to use.
For any requirement, there is no ready method For every requirement ready made
6
available. method support is available.
Note: Above difference is same for difference between Array and any Collection object (like
Vector, ArrayList, LinkedList).
Java support following technique to retrieve the elements from any collection object.
foreach loop
Iterator interface
ListIterator interface
Enumeration interface
Vector ArrayList
Vector is legacy Collection Framework (old
1 ArrayList is new Collection Framework.
class).
2 Vector is Synchronized by default. ArrayList is not Synchronized.
For retrieving elements from Vector class can For retrieving elements from ArrayList
3 be use foreach loop, Iterator, ListIterator and class can be use foreach loop, Iterator and
Enumaration. ListIterator.
HashMap HashTable
1 HashMap is a new class in java API. HashTable is a legacy class in java API.
2 HashMap is not Synchronized. HashTable is Synchronized.
HashMap allows maximum one null key and HashTable does not allows any null key
3
multiple null value. and null values.
HashMap TreeMap
HashMap class object organizes the data in TreeMap class object organized the data in
1 the form of key, value pair by following the form of key, value pair by following
hasing mechanism. binary tree concept.
2 HashMap store data in undermined form. TreeMap store data in sorted order.
In HashMap the operation like insertion, In TreeMap the operation like insertion,
3
deletion and modification takes less time. deletion and modification takes more time.
Elements retrieving time of HashMap is
3 Elements retrieving time of TreeMap is less.
more.
HashSet TreeSet
HashSet class object organizes the data in the
TreeSet class object organized the data by
1 form HashTable by following Hashing
following binary tree concept.
mechanism.
2 HashSet display data in undermined form. TreeSet display data in sorted order.
In HashSet the operation like insertion, deletion In TreeSet the operation like insertion,
3
and modification takes more time. deletion and modification takes less time.
Elements retrieving time of TreeSet is
3 Elements retrieving time of HashSet is more.
less.
A property file is one type of the file which organizing the date in the form of (key, value)
pair. A property file is a text file which is to be created in any editors like-notepad, Editpuls
and etc. Property file should be saved on same file name with on extension .prop or .rbf.
Why Legacy Collection Framework are not use for web based applications. ?
Legacy Collection Framework are Synchronized because of this we can not use Legacy
Collection Framework for web based applications.