Java pdf
Java pdf
1)What is Java?
Java is a object oriented, platform independent, case sensitive, strongly typed checking ,
high level , open source programming language developed by James Gosling in the
year of 1995.
2)Features of Java?
1)Simple
2)Object oriented
3)Platform independent
4)Portable
5)Architecture Neutral
6)Highly secured
7)Robust
8)Multithreaded
9)Distributed
10)Dynamic
Java virtual machine (JVM), archiever (.jar) , document generator (javadoc) and
JRE
JRE stands for Java Runtime Environment.
1
It provides very good environment to run java applications only.
JVM
JVM stands for Java Virtual Machine.
2)Extension classloader (loads all the jar files from ext folder)
using static block. But from 1.7 version onwards it is not possible to execute
ex: class A
static
System.out.println("Hello World");
System.exit(0);
6)What is typecasting?
Process of converting from one datatype to another datatype is called
typecasting.
2
i)Implicit typecasting
If we want to store small value into a bigger variable then we need to use
implicit typecasting.
ii)Explicit typecasting
If we want to store bigger value into a smaller variable then we need to use
explicit typecasting.
class Test
out.println("Hello World");
3
10)How many memories are there in java?
We have five memories in java.
1) Method area
2) Heap
3) JAva Stack
4) PC Register
1) System.gc()
2) Runtime.getRuntime().gc()
It can be class name, variable name, method name and label name.
1) default
2) public
4
3) private
4) protected
1) Instance variable
2) Static variable
3) Local variable
1) Instance block
2) Static block
3) Local block
static:
JVM wants to call this method without using object reference.
void:
Main method does not return anything to JVM.
main:
It is an identifier given to a main method.
String[] args:
It is a command line argument.
5
20)Is java purely object oriented or not?
No, java will not consider as purely object oriented because
it does not support many OOPS concepts like multiple inheritance, operator overloading
and more ever we depends upon primitive datatypes which are non-objects.
============OOPS==================
1) What is class?
A class is a blue print of an object.
ex:
syntax:
optional
<implements> Interface_name
6
ex: class A
public class
We can access public class within the package and outside of the package.
If we declare any class as final then extending some other class is not possible.
ex:
final class A
3) What is object ?
It is a outcome of a blue print.
7
It is a instance of a class.
Object class
Object class present in java.lang package.
toString()
It is a method present in Object class.
Whenever we are trying to display any object reference directly or indirectly toString()
Data Hiding
It is used to hide the data from the outsider.
4)Types of objects?
We have two types of objects.
1)Immutable object
After object creation if we perform any changes then for every change a new object
ex: String
Wrapper classes.
8
2)Mutable object
After object creation if we perform any changes then all the changes will reflect to single
ex: StringBuffer
StringBuilder
private Singleton()
if(singleton==null)
singleton=new Singletone();
return singleton;
6)What is hashcode?
For every object , JVM will create a unique identifier number i.e hash code.
9
In order to read hash code we need to use hashCode() method of Object class.
ex:
System.out.println(t.hashCode());
7) What is Interfaces?
Interface is a collection of zero or more abstract methods.
Abstract method is a incomplete method which ends with semicolon and does not have any body.
ex:
To write the implementation of abstract methods of an interface we will use implementation class.
It is possible to create object for implementation class because it contains method with body.
- //constants
- //abstract method
A "abstract" keyword is applicable only for class and method but not for variable.
10
To write the implementation of abstract methods of an abstract class we will use sub classes.
syntax:
{ - //instance variables
- //abstract methods
- //concrete methods
9)What is Abstraction?
Hiding the internal implementation and high lighting the set of services is called abstraction.
Best example of abstraction is ATM machine, coffee machine,calcular, phone and etc.
1)It gives security because it will hide internal implementation from the outsider.
2)Enhancement becomes more easy without effecting enduser they can perform any
10)What is Encapsulation?
The process of encapsulating or grouping variables and it's associate methods in a
In encapsulation for every variable we need to declare setter and getter methods.
11
2)Enhancement becomes more easy.
The main disadvantage of encpasulation is ,it will increase the length of our code and
//setter
this.empId=empId;
//getter
return empId;}
11)What is the difference between POJO class and Java Bean class?
POJO class
A class is said to be pojo class if it supports following two properties.
12
2)A class must have constructor.
Note:
Every Java bean class is a pojo class.
CONSTRUCTORS
1)What is Constructor?
Constructor is a special method which is used to initialize an object.
ex:class A
A()
System.out.println("0-arg const");
ex: class A
A(int i)
13
{
System.out.println("parameterized const");
1)Userdefined constructor
A constructor which is created by the user based on the application requirement
2) Parameterized constructor
Suppose if we are passing atleast one argument to userdefined constructor is
14
4) What is Method Overloading?
Having same method name with different parameters in a single class is called
method overloading.
ex: class A
System.out.println("0-arg method");
System.out.println("int-arg method");
method overriding.
Methods which are present in parent class are called overridden methods.
Methods which are present in child class are called overriding methods.
15
ex: class A
System.out.println("ITALENT");
class B extends A
System.out.println("IIHUB TALENT");
Method resolution will taken care by JVM Method resolution will taken care
16
9)Can we override static methods in java?
No , we can't override static methods in java.
object reference.
reference.
1)Predefined API:
Built-In API is called predefined API.
17
2)Userdefined API:
API which is created by the user based on the requirement is
methods.
implementation class.
15)What is polymorphism?
Polymorphism has taken from Greek Word.
18
Here poly means many and morphism means forms.
Method Hiding
another class.
3) Multiple inheritance
4) Hierarchical inheritance
5) Hybrid inheritance
19
Ex:
P1.m1() p2.m1()
|-----------------------------|
C.m1();
But from java 1.8 version onwards java supports multiple inheritance through
There is no specific keyword to implement Has-A relationship but mostly we will use new operator.
ex:
class Engine
class Car
Composition
Without existing container object there is a no chance of having contained object then the relationship
between
container object and contained object is called composition which is strongly association.
20
Aggregation
Without existing container object there is a chance of having contained object then the relationship
between container object and contained object is called aggregation which is loosely association.
Marker interfaces are empty interfaces but by using those interfaces we get some ability to do.
ex: Serializable
Remote
ex:class Outer_Class
class Inner_Class
- //code to be execute
But because of powerful features and benefits of inner classes, Programmers started
Inner class does not accept static members i.e static variable, static method and
static block.
21
22)What is package?
Package is a collection of classes, interfaces, enums ,Annotations, Exceptions and Errors.
All package names we need to declare under lower case letters only.
1)Predefined packages:
Built-In packages are called predefined packages.
2)Userdefined package:
Packages which are created by ther user are called userdefined packages.
ex: com.ihubtalent.www
Arrays
1)what is Array?
In a normal variable we can store only one value at a time.
To store more then one value in a single variable then we need to use arrays.
Definition:
Array is a collection of homogeneous data elements.
1)Arrays are fixed in size.Once if we create an array there is no chance of increasing and decreasing the
size of an array.
22
2)To use array concept in advanced we should know what is the size of an array which is always not
possible.
It will return size of an array. It will return number of character present in String.
Ex: ex:
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
System.out.println(arr.length);//3 System.out.println(str.length());//5
} }
} }
3)What is Recursion?
A method is called self for many number of times is called Recursion.
23
In Recursion post Increment and Decrement are used.
4) What is Enum?
Enum is a group of named constants.
Using enum we can create our own datatype called enumerated datatype.
Syntax:
enum enum_type_name
val1,val2,....,valN
Ex:
enum Months
JAN,FEB,MAR
byte Byte
short Short
24
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
constructors
Every wrapper contains following two constructors.One will take corresponding primitive as an
argument and another will take corresponding String as an argument.
Character char
STRINGS
1) What is Strings?
String is a collection/set of characters.
case1:
Once if we create a String object we can't perform any changes.If we perform any changes then for
every change a new object will be created such behaviour is called immutability of an object.
25
2)Difference between == and .equals() method
==
It is a equality operator or comparision operator.
.equals()
It is a method present in String class.
It is a case sensitive.
StringBuffer StringBuilder
All the methods present in All the methods present in StringBuilder are
performance is low.
26
EXCEPTION HANDILING
1)What is the difference between Exception and Error?
Exception
Exception is a problem for which we can provide solution programmatically.
ex:
ArithmeticException
FileNotFoundException
IllegalArgumentException
Error:
Error is a problem for which we can't provide solution programmatically.
ex:
OutOfMemoryError
StackOverFlowErrr
2)Abnormal termination
1)Smooth termination
During the program execution suppose if we are not getting any interruption in the middle of the
program such type of termination is called smooth termination.
ex:
class Test
27
{
System.out.println("Hello World");
2)Abnormal termination
During the program execution suppose if we are getting any interruption in the middle of the program
such type of termination is called abnormal termination.
ex:
class Test
System.out.println(10/0);
2) What is Exception?
It is a unwanted, unexpected event which disturbs normal flow of our program.
Exception always raised at runtime so they are also known as runtime events.
1)Predefined exceptions
2)Userdefined exceptions
1)Predefined exceptions
Built-In exceptions are called predefined exceptions.
28
It is categories into two types.
i)Checked exception:
Exceptions which are checked by a compiler at the time of compilation
ex: IOException
InterruptedException
ii)Unchecked exceptions:
Exceptions which are checked by a JVM at the time of runtime is called
unchecked exceptions.
ex: ArithmeticException
IllegalArgumentException
If any checked exception raised in our program we must and should handle that exception by
using try and catch block.
2)Userdefined exceptions
Exceptions which are created by the user based on the application requirement are called customized
exceptions.
ex: StudentsNotPracticingException
NoInterestInJavaException
InsufficientFeeException
If any exception raised in try block then try block won't be executed.
If any exception raised in the middle of the try block then reset of code won't be executed.
29
4) what is catch block?
It is a block which contains Error handling code.
A catch block is used to catch the exception which is thrown by try block
A catch block will take exception name as a parameter and that name must match with exception class
name.
Syntax:
try
- //Risky code
catch(ArithmeticException ae)
1)printStackTrace()
It will display name of the exception, description of the exception and line number of the exception.
2)toString()
It will display name of the exception and description of the exception.
3)getMessage()
It will display description of the exception.
30
It is never recommanded to maintain cleanup code inside catch block because if no exception raised in
try block then catch won't be executed.
But we need a place where we can maintain cleanup code and it should execute irrespective of
exception raised or not.Such block is called finally block.
syntax
try
- // Risky Code
catch(Exception e)
- // Errorhandling code
finally
- //cleanup code
If we declare any variable as final then reassignment of that variable is not possible.
If we declare any method as final then overriding of that method is not possible.
If we declare any class as final then creating child class is not possible.
finally
It is a block which contains cleanup code and it will execute irrespective of exception raised or not.
finalized method
It is a method called by garbage collector just before destroying an object for cleanup activity.
31
6) What is throw statement?
Sometimes we will create exception object explicitly and handover to JVM manually by using throw
statement.
8) what is Generics?
Array is a typesafe.
We can provide guarantee that what type of elements are present in array.
ex:
str[0]="hi";
str[2]=10; // invalid
At the time of retrieving the data from array , we don't need to perform any typecasting
ex:
str[0]="hi";
COLLECTIONS
1)Difference between Arrays and Collections?
Arrays Collections
It is a collection of homogenous data It is a collection of homogenous and
32
recommanded to use. recommanded to use.
explicitly.
2) What is Collection?
Collection is an interface which is present in java.util package.
If we want to represent group of individual objects in a single entity then we need to use Collections.
interface.
33
4) What is the Difference between ArrayList vs LinkedList?
ArrayList LinkedList
The underlying data structure is The underlying data structure is
interface.
If we want to represent group of individual objects If we want to represent group of individual objects
in a single entity where duplicates are allowed. where duplicates are not allowed and order is not
preserved then we need
34
bcoz objects are arrange based on
hashcode of an oject.
Duplicate objects are not allowed. Duplicate objects are not allowed.
It implements Serializable
Duplicate objects are not allowed. Duplicate objects are not allowed.
Map
It is not a child interface of Collection interface.
If we want to represent group of individual objects in a key-value pair then we need to use Map
interface.
35
Duplicate keys are not allowed but values can be duplicated.
class.
keys.
(any number).
and it is based on hashcode of the All entries will store in the sorting
36
Duplicate keys are not allowed. Duplicate keys are not allowed but values
can be duplicated.
(any number).
11)What is TreeMap?
The underlying data structure is RED BLACK TREE.
Insertion order is not preserved. All entries will store in the sorting order of keys.
and Comparable.
If we depends upon customized sorting order then keys can be hetrogeneous and
non-comparable.
For empty TreeMap if we insert NULL as key then we will get NullPointerException.
After insertion elements if we are trying to insert NULL as key the we will
get NullPointerException.
Duplicate keys are not allowed Duplicate keys are not allowed but values are allowed.
37
but values can be duplicated.
NullPointerException.
13)Comparable vs Comparator?
OR
If we depend upon default natural sorting(ascending order) order then we need to use Comparable
interface.
Comparator
Comparator interface present in java.util package.
Implementation for equals() method is optional because equals() method is available by default by
Object class throw inheritence.
If we depend upon customized sorting order then we need to use Comparator interface.
38
15)Explain Enumeration vs Iterator vs ListIterator
Types of Cursors in java
Cursors are used to retrieve the objects one by one from Collection.
1)Enumeration
2)Iterator
3)ListIterator
1)Enumeration
Enumeration interface present in java.util package.
2)Iterator
It is used to retrieve the objects one by one from any Collection object.Hence it is known as universal
cursor.
39
public Object next();
3)ListIterator
It is a child interface of Iterator interface.
Using ListIterator we can read objects in forward direction and backward direction.Hence it is a bi-
directional cursor.
Using ListIterator we can perform read, remove ,adding and replacement of new objects.
MULTI-THREADING
1) What is the difference between Thread and Process?
Thread
Thread is a light weight sub process.
PROCESS
Process is a collection of threads.
One process can't communicate with another process.They are independent to each other.
40
Downloading a file from internet is one process.
2)What is Multi-tasking?
Executing several task simultenously such concept is called multi-tasking.
3)What is Multi-Threading
Executing several threads simultenously such concept is called multi-threading.
In multi-threading only 10% of work must be done by a programmer and 90% work will be done by JAVA
API.
Once if we call t.start() method then our thread will goes to ready/runnable state.
If thread schedular allocates the CPU then our thread will enters to running state.
41
Once the run() method execution is completed then our thread will goes to dead state.
The valid range for thread priority is 1 to 10.1 is a least priority and 10 is a highest priority.
ex:
Thread.MAX_PRIORITY -- 10
Thread.NORM_PRIORITY -- 5
Thread.MIN_PRIORITY -- 1
1)yield()
2)join()
3)sleep()
1)yield()
It will pause the current execution thread and gives chance to other threads having same priority.
If multiple threads having same priority then we can't expect any execution order.
If there is no waiting threads then same thread will continue the execution.
42
2)join()
If a thread wants to wait untill the completion of some other thread then we need to use join() method.
A join() method throws one checked exception called InterruptedException so we must and should
handle that exception by using try and catch block or by using throws statement
3)SLEEP():
If a thread don't want to perform any operation on perticular amount of time then we need to use
sleep() method.
A sleep() method will throw one checked exception called InterruptedException so must and should
handle that exception by using try and catch block or by using throws statement.
Whenever a thread wants to access any object. First it has to acquire the lock of it and release the lock
once thread complete its task.
The life of deamon thread is same as user threads. Once threads executed deamon thread will terminate
automatically.
43
Problems without synchronization:
If we won't have synchronization then we will face following problems.
1) Thread interference.
8)What is Synchronization?
A synchronized keyword is applicable for methods and blocks.
A synchronization is allowed one thread to execute given object.Hence we achieve thread safety.
The main disadvantage of synchronization is ,it will increase waiting time of a thread which reduce the
performance of the system.
Whenever a thread wants to access object , first it has to acquire lock of an object and thread will
release the lock when it completes it's task.
When a thread wants to execute synchronized method.It automatically gets the lock of an object.
When one thread is executing synchronized method then other threads are not allowed to execute
other synchronized methods in a same object concurently.But other threads are allowed to execute
non-synchronized method concurently.
synchronization.
ex: If we have 100 lines of code and if we want to perform synchronization only for
If we keep all the logic in synchronized block then it will act as a synchronized method.
3)Static Synchronization:
In static synchronization the lock will be on class but not on object.
If we declare any static method as synchronized then it is called static synchronization method.
44
11)What is DeadLock in java?
DeadLock will occur in a suitation when one thread is waiting to access
object lock which is acquired by another thread and that thread is waiting
Here both the threads are waiting release the thread but no body will
2)Thread Starvation
ex:
Function interface is also known as Single Abstract Method Interface or SAM interface.
ex:
a=f1(){}
f1(f2(){}){}
45
@FunctionalInterface is a annotation which is used to declare functional interface and it is optional.
2)Lamda Expression
Lamda Expression introduced in java 1.8v.
Lamda expression does not support modifier,return type and method name.
3)Stream API
If we want to process the objects from Collections then we need to use Stream API.
Syntax:
Stream s=c.stream();
JDBC QUESTIONS
46
1)What is JDBC ?
JDBC is a persistence technology which is used to develop persistence logic having the capability to
perform persistence operations on persistence data of a persistence store.
1)Simple Statement
2)PreparedStatement
3)CallableStatement
5)What is DatabaseMetaData?
DatabaseMetaData is an interface which is present in java.sql package.
47
DatabaseMetaData gives information about database product name, database product version,
database driver name, database driver version, database username and etc.
ex:
DatabaseMetaData dbmd=con.getMetaData();
5)What is ResultSetMetaData?
ResultSetMetaData is an interface which is present in java.sql package.
ResultSetMetaData gives information about number of columns, datatype of a columns, size of a column
and etc.
ex:
ResultSetMetaData rsmd=rs.getMetaData();
1)Select query
It will give bunch of records from database table.
2)Non-Select query
It will give numeric value represent number of records effected in a
database table.
48
JDBC Connection pool represent connectivity with same database software.
A programmer is not responsible to create, manage or destroy JDBC connection objects in jdbc
connection pool. A jdbc connection pool is responsible to create,manage and destroy jdbc connection
objects in jdbc connection pool.
It allows us to read the records sequentially or uni-directionally such type of ResultSet object is called
non-scrollable ResultSet object.
class CreateTableApp
Class.forName("oracle.jdbc.driver.OracleDriver");
Connecton con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
49
sname varchar2(10),sadd varchar2(12))";
PreparedStatement ps=con.prepareStatement(qry)
int result=ps.executeUpdate();
if(result==0)
else
System.out.println("Table created");
ps.close();
con.close();
import java.util.*;
class CreateTableApp
int no=sc.nextInt();
String name=sc.next();
50
String add=sc.next();
Class.forName("oracle.jdbc.driver.OracleDriver");
Connecton con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
PreparedStatement ps=con.prepareStatement(qry);
ps.setInt(1,no);
ps.setString(2,name);
ps.setString(3,add);
int result=ps.executeUpdate();
if(result==0)
else
System.out.println("Table created");
ps.close();
con.close();
51
Servlet Questions
1)What is Servlet ?
Servlet is a dynamic web resource program which enhanced the functionality of
or
Servlet is a java based dynamic web resource program which is used to generate
or
Servlet is a single instance multi-thread java based web resource program which is used
CSS program
Bootstrap program
52
2)Dynamic web resource program
It is responsible to generate dynamic web pages.
Some part of industry considers servlet container and jsp container are web containers.
5)ServletConfig object
ServletConfig is an interface which is present in javax.servlet package.
ServletConfig object will be created by the web container for every servlet.
ex:
ServletConfig config=getServletConfig();
6)ServletContext object
ServletContext is an interface which is present in javax.servlet package.
ServletContext object is created by the web container for every web application i.e it is one per web
application.
ServletContext object is used to read configuration information from web.xml file and it is for all
servlets.
Or ServletConfig config=getServletConfig();
53
ServletContext context=config.getServletContext();
2) To perform validation
and etc.
1)Filter
2)FilterChain
3)FilterConfig
It will carry limited amount of data. It will carry unlimited amount of data.
54
9)Explain Servlet Life cycle methods?
We have three life cycle methods in Servlets
(Object which can be used directly without any configuration is called implicit object).
JSP QUESTIONS
1)Advantages of JSP
> To work with JSP strong java knowledge is not required.
55
> It supports tag based language.
2)What is jsp?
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content.
This helps developers insert java code in HTML pages by making use of special JSP tags,
Implicit objects are created by the web container that is available for every jsp program.
Object which can be used directly without any configuration is called implicit object.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletRespons
config ServletConfig
application ServletContext
session HttpSession
pageContext pageContext
page Object
56
exception Throwable
i)Scriptlet tag
ex: <% code %
ii)Expression tag
ex: <%= code %>
iii)Declaration tag
ex: <%! code %>
2)Directive Tags
3)Standard Tags
<jsp:include>
<jsp:forward>
<jsp:setProperty>
<jsp:getProperty>
<jsp:useBean>
and etc.
4)JSP comment
<%-- jsp comment --%>
i)Scriptlet tag
It is used to declare java code.
57
1)_jspInit()
It is used for instantiation event
This method will execute just before JES class object creation.
2)_jspService()
It is used for request arrival event
3)_jspDestroy()
It is used for destruction event.
This method will execute just before JES class object destruction
6)Phases in JSP?
In JSP , we have two phases.
1)Translation phase
In this phase, our JSP program converts to JES class
8)MVC in JSP?
MVC stands for Model View Controller.
It is a design partern which seperates business logic , persistence logic and data.
58
59
60