0% found this document useful (0 votes)
8 views

Java pdf

Java is an object-oriented, platform-independent programming language with features like simplicity, security, and robustness. Key concepts include the differences between JDK, JRE, and JVM, typecasting, class loaders, and the use of constructors and methods. The document also covers OOP principles such as encapsulation, inheritance, polymorphism, and the distinctions between interfaces and abstract classes.

Uploaded by

alatheiri123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java pdf

Java is an object-oriented, platform-independent programming language with features like simplicity, security, and robustness. Key concepts include the differences between JDK, JRE, and JVM, typecasting, class loaders, and the use of constructors and methods. The document also covers OOP principles such as encapsulation, inheritance, polymorphism, and the distinctions between interfaces and abstract classes.

Uploaded by

alatheiri123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

COREJAVA

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

3)Differences betweend JDK , JRE and JVM ?


JDK
JDK stands for Java Development Kit.

It is a installable software which contains compiler (javac) , interpreter (java),

Java virtual machine (JVM), archiever (.jar) , document generator (javadoc) and

other tools needed for java application development.

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.

It is an interpreter which is used to execute our program line by line procedure.

4)Types of classloaders in java?


We have three types of predefined classloaders.

1)Bootstrap classloader (loads rt.jar file)

2)Extension classloader (loads all the jar files from ext folder)

3)System/Application classloader(it loads .class file from classpath).

5)Is it possible to execute java program without main methods?


Till 1.6 version it is possible to execute java program without main method

using static block. But from 1.7 version onwards it is not possible to execute

java program without main method.

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.

Typecasting can be performed in two ways.

2
i)Implicit typecasting
If we want to store small value into a bigger variable then we need to use

implicit typecasting.

A compiler is responsible to perform implicit typecasting.

Implicit typecasting is also known as Widening/upcasting.

ii)Explicit typecasting
If we want to store bigger value into a smaller variable then we need to use

explicit typecasting.

A programmer is responsible to perform explicit typecasting.

Explicit typecasting is also known as Norrowing/Downcasting.

7)What is static import in java?


Using static import we can access static members directly.

Ex: import static java.lang.System.*;

class Test

public static void main(String[] args)

out.println("Hello World");

8)Which is a default package in java?


java.lang package

9) What is JIT compiler?


IT is a part of a JVM which is used to increase the execution speed of our program.

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

5) Native method stack

11) What is native method in java?


A Method which is developed by using some other language is called native method.

12) What is Garbage Collector ?


Garbage collector is responsible to destroy unused or useless objects in java.

There are two ways to call garbage collector in java.

1) System.gc()

2) Runtime.getRuntime().gc()

13) What is identifier?


A name in java is called identifier.

It can be class name, variable name, method name and label name.

14) What .class file contains ?


A .class file contains byte code instructions.

15) Is java support access specifiers?


Java does not support access specifiers.

Java support access modifiers.

1) default

2) public

4
3) private

4) protected

16) What is program?


Program is a collection of instructions (or) Program is a set of instructions.

17)Types of variables in java?


we have three types of variables in java.

1) Instance variable

2) Static variable

3) Local variable

18) Types of blocks in java?


We have three types of blocks in java.

1) Instance block

2) Static block

3) Local block

19)Explain main method ?


public:
JVM wants to call this method from any where that's why main method is public.

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.

A class is a collection of variables and methods.

A class is a reusable component.

A class will accept following modifiers.

ex:

default, public, final, abstract

We can declare a class as follow.

syntax:

optional

modifier class class_name <extends> Parent_classname

<implements> Interface_name

- // variables and methods

2)What is the difference between default class and public class?


default class
We can access default class within the package.

6
ex: class A

public class
We can access public class within the package and outside of the package.

ex: public class A

What is final class?


If we declare any class as final then creating child class is not possible.

If we declare any class as final then extending some other class is not possible.

ex:

final class A

class B extends A // invalid

What is abstract class ?


If we declare any class as abstract then creating object of that class is not possible.

ex: abstract class A

3) What is object ?
It is a outcome of a blue print.

7
It is a instance of a class.

Instance means allocating memory for our data members.

Object class
Object class present in java.lang package.

Object class consider as a parent class for every java program.

Object class contains following methods.

toString()
It is a method present in Object class.

Whenever we are trying to display any object reference directly or indirectly toString()

method will be executed.

Data Hiding
It is used to hide the data from the outsider.

It means outside person must not access our data directly.

Using private modifier we can implement data hiding concept.

ex: class Account

private double balance;

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

will be created such behaviour is called immutable 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

object such behaviour is called mutable object.

ex: StringBuffer

StringBuilder

5)What is singleton class?


A class which allows us to create only one object is called singleton class.

To declare a singleton class we required private constructor and static method.

ex: class Singleton

private static Singleton singleton=null;

private Singleton()

public static Singleton getInstance()

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:

Test t=new Test();

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:

public abstract void m1();

It is not possible to create object for interfaces.

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.

By default , every abstract method is a public and abstract.

Interface contains only constants i.e public static final.

Syntax: interface interface_name

- //constants

- //abstract method

In java, a class can't extends more then one class.

But interface can extends more then one interface.

8) What is Abstract class?


Abstract class is a collection of zero or more abstract methods and zero or more concrete methods.

A "abstract" keyword is applicable only for class and method but not for variable.

It is not possible to create object for abstract class.

10
To write the implementation of abstract methods of an abstract class we will use sub classes.

By default every abstract method is a public and abstract.

Abstract class contains only instance variables.

syntax:

abstract class class_name

{ - //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.

The main advantages of abstraction are.

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

changes in our internal system.

3)It provides flexibility to the enduser to use the system.

4)It improves maintainability of an application.

10)What is Encapsulation?
The process of encapsulating or grouping variables and it's associate methods in a

single entity is called encapsulation.

In encapsulation for every variable we need to declare setter and getter methods.

A class is said to be encapsulated class if it supports data hiding + abstraction.

The main advantages of encapsulation are.


1)It gives security.

11
2)Enhancement becomes more easy.

3)It provides flexibility to the enduser to use the system.

4)It improves maintainability of an application.

The main disadvantage of encpasulation is ,it will increase the length of our code and

slow down the execution process.

ex: class Employee

private int empId;

//setter

public void setEmpId(int empId)

this.empId=empId;

//getter

public int getEmpId()

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.

1)All variables must be private.

2)All variables must have setter and getter method.

Java Bean class:


A class is said to be java bean class if it supports following four properties.

1)A class must be public.

12
2)A class must have constructor.

3)All variables should be private.

4)All variables should have setter and getter method.

Note:
Every Java bean class is a pojo class.

But every pojo class is not a java bean class.

CONSTRUCTORS
1)What is Constructor?
Constructor is a special method which is used to initialize an object.

ex: Test t=new Test();

Having same name as class name is called constructor.

A constructor will execute when we create an object.

A constructor does not allowed any returntype.

A constructor will accept following modifiers.

ex:default, public, private , protected

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

is called userdefined constructor.

It is categories into two types.

i)Zero Argument constructor

ii) Parameterized constructor

i)Zero Argument constructor

Suppose if we are not passing atleast one argument to userdefined constructor is

called zero argument constructor.

2) Parameterized constructor
Suppose if we are passing atleast one argument to userdefined constructor is

called parameterized argument constructor.

2)What is default constructor?


It is a compiler generated constructor for every java program where we are not

defining any constructor.

Default constructor is a empty implementation.

To see the default constructor we need to use below command.

ex: javap -c Test

3)What is Constructor Overloading:


Having same constructor name with difference parameters in a single class is

called constructor overloading.

14
4) What is Method Overloading?
Having same method name with different parameters in a single class is called

method overloading.

All the methods present in a class are called overloaded methods.

Method resolution will taken care by compiler based on reference type.

ex: class A

public void m1()

System.out.println("0-arg method");

public void m1(int i)

System.out.println("int-arg method");

5) Can we overload main method in java?


Yes, we can overload main method in java.But JVM always execute main method

with String[] parameter only.

6) What is Method Overriding?


Having same method name with same parameters in two different classes is called

method overriding.

Methods which are present in parent class are called overridden methods.

Methods which are present in child class are called overriding methods.

Method resolution will taken care by JVM based on runtime objects.

15
ex: class A

public void m1()

System.out.println("ITALENT");

class B extends A

public void m1()

System.out.println("IIHUB TALENT");

7)Can we override final methods in java?


ans) No , we can't override final methods in java.

8)What is Method Hiding?


Method hiding is exactly the same as method overriding with following differences.

Method overriding Method hiding


All the methods present in method overriding All the methods present in method

must be non-static. hiding must be static.

Method resolution will taken care by JVM Method resolution will taken care

based on runtime object. by compiler based on reference type.

It is also known as runtime polymorphism, It is also known as compile time

dynamic polymorphism, late binding. polymorphism, static polymorphism,early binding.

16
9)Can we override static methods in java?
No , we can't override static methods in java.

10)Can we override main method in java?


No , we can't override main method because it is static.

11)What is this keyword?


A "this" keyword is a java keyword which is used to refer current class

object reference.

We can utility this keyword in following ways.

i)To refer current class variables

ii)To refer current class methods

iii)To refer current class constructors

12)what is Super Keyword?


A "super" keyword is a java keyword which is used to refer super class object

reference.

We can utility super keyword in following ways.

i)To refer super class variables

ii)To refer super class methods

iii)To refer super class constructors

13) What is API?


API stands for application programming interface.

It is a base for the programmer to develop software applications.

API is a collection of packages.

We have three types of API's.

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

called userdefined API.

3)Third party API:


API which is given by third party vendor.

ex: JAVAZOOM API , Text API and etc.

14)Differences between interface and abstract class?

Interface Abstract class


To declare interface we will use To declare abstract class we will use

interface keyword. abstract keyword.

Interface is a collection of abstract Abstract class is a collection of abstract

methods,default methods and static methods and concrete methods.

methods.

Interface contains constants. Abstract class contains instance variables.

We can achieve multiple inheritance. We can't achieve multiple inheritence.

It does not support constructor. It supports constructor.

It does not support blocks. It supports blocks.

To write the implementation of To write the implementation of abstract

abstract methods we need to use methods we need to use sub class.

implementation class.

If we know only specification then If we know partial implementation then

we need to use interface. we need to use abstract class.

15)What is polymorphism?
Polymorphism has taken from Greek Word.

18
Here poly means many and morphism means forms.

The ability to represent in different forms is called polymorphism.

In java, polymorphism is categories into two types.

1)Compile time polymorphism/ static polymorphism / early binding.


A polymorphism which exhibits at compile time is called compile time polymorphism.

ex: Method overloading

Method Hiding

2)Runtime polymorphism / dynamic polymorphism / late binding.


A polymorphism which exhibits at runtime is called run time polymorphism.

ex: Method overriding

16) What is Inheritance?


Inheritance is a mechanism where one class will derived from the properties from

another class.

Using "extends" keyword we can implements inheritance.

We have five types of inheritance.

1) Single level inheritance.

2) Multi level inheritance

3) Multiple inheritance

4) Hierarchical inheritance

5) Hybrid inheritance

17) What are the inheritance not support by java?


Java does not support multiple inheritance and hybrid inheritance.

18) Why java does not support multiple inheritance?


There is a chance of raising ambiguity problem that's why java does not

support multiple inheritance.

19
Ex:

P1.m1() p2.m1()

|-----------------------------|

C.m1();

But from java 1.8 version onwards java supports multiple inheritance through

default methods of interface.

19) What is Has-A relationship?


Has-A relationship is also known as composition and aggregation.

There is no specific keyword to implement Has-A relationship but mostly we will use new operator.

The main objective of Has-A relationship is to provide reusability.

Has-A relationship will increase dependency between two components.

ex:

class Engine

- //engine specific functionality

class Car

Engine e=new Engine();

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.

20)What is marker interface?


An interface which does not have any constants and abstract methods is called marker interface.

In general, empty interface is called marker interface.

Marker interfaces are empty interfaces but by using those interfaces we get some ability to do.

ex: Serializable

Remote

21) What is inner class?


Sometimes we will declare a class inside another class such concept

is called inner class.

ex:class Outer_Class

class Inner_Class

- //code to be execute

Inner classes introduced as a part of event handling to remove GUI bugs.

But because of powerful features and benefits of inner classes, Programmers started

to use inner classes in regular programming code.

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.

Enum,Exception and Error is a special class and Annotation is a special interface.

In general, a package is a collection of classes and interfaces.

Package is also known as folder or a directory.

In java, packages are divided into two types.

All package names we need to declare under lower case letters only.

1)Predefined packages:
Built-In packages are called predefined packages.

ex: java.lang , java.io, java.util

2)Userdefined package:
Packages which are created by ther user are called userdefined packages.

It is highly recommanded to use package name in the reverse order of url.

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.

The main advantages of array are.

1)We can represent multiple elements using single variable name.


ex: int[] arr={10,20,30};

2)Performance point of view array is recommanded to use.


The main disadvantages of array are.

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.

In java, arrays are categorised into three types.

1)Single Dimensional Array

2)Two Dimensional Array / Double Dimensional Array

3)Multi-Dimensional Array / Three Dimensional Array

2)What is the difference b/w length and length() ?


Length length()
It is a final variable which is It is a final method which is applicable

applicable only for arrays only for String objects.

It will return size of an array. It will return number of character present in String.

Ex: ex:

class Test class Test

{ {

public static void main(String[] args) public static void main(String[] args)

{ {

int[] arr=new int[3]; String str="hello";

System.out.println(arr.length);//3 System.out.println(str.length());//5

System.out.println(arr.length()); //CTE System.out.println(str.length);//C.T.E

} }

} }

3)What is Recursion?
A method is called self for many number of times is called Recursion.

Recursion is similar to loopings.

23
In Recursion post Increment and Decrement are used.

4) What is Enum?
Enum is a group of named constants.

Enum concept is introduced in 1.5 version.

Using enum we can create our own datatype called enumerated datatype.

When compare to old language enum, java enum is more powerful.

Enum is a special class.

To declare enum we need to use enum keyword.

Syntax:

enum enum_type_name

val1,val2,....,valN

Ex:

enum Months

JAN,FEB,MAR

5) what is Wrapper classes?


The main objective of wrapper class is used to wrap primitive to wrapper object

and vice versa.

To defined serveral utility methods.

Primitive type Wrapper class

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.

wrapper class constructor

Byte byte or String

Short short or String

Integer int or String

Long long or String

Float float or String

Double double or String

Boolean boolean or String

Character char

STRINGS
1) What is Strings?
String is a collection/set of characters.

String is a immutable object.

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.

It is used for reference comparision or address comparision.

.equals()
It is a method present in String class.

It is used for content comparision.

It is a case sensitive.

3)Difference between StringBuffer and StringBuilder?

StringBuffer StringBuilder
All the methods present in All the methods present in StringBuilder are

StringBuffe are synchronized. not synchronized.

At a time only one thread Multiple threads are allowed to access

is allowed to access Hence we can StringBuilder object.

StringBuffer object. achieve thread safety.

Hence we can't achieve

achieve thread safety.

Waiting time of a thread will There is no waiting thread effectively

increase effectively performance is high.

performance is low.

StringBuffer introduced in 1.0v. StringBuilder introduced in 1.5v.

26
EXCEPTION HANDILING
1)What is the difference between Exception and Error?
Exception
Exception is a problem for which we can provide solution programmatically.

Exception will raise due to syntax errors.

ex:

ArithmeticException

FileNotFoundException

IllegalArgumentException

Error:
Error is a problem for which we can't provide solution programmatically.

Error will raise due to lack of system resources.

ex:

OutOfMemoryError

StackOverFlowErrr

LinkageError and etc

As a part of application development it is a responsibility of a programmer to provide smooth


termination for every java program.

We have two types of terminations.

1)Smooth termination / Graceful termination

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
{

public static void main(String[] args)

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

public static void main(String[] args)

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.

The main objective of exception handling is to provide gaceful termination.

In java , exceptions are divided into two types.

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

is called checked exception.

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

ClassCastException and etc

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

3) What is try block?


It is a block which contains risky code.

A try block always associate with catch block.

A try block is used to throw the exception to catch block.

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 always associate with try block

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.

If there is no exception in try block then catch block won't be executed.

Syntax:

try

- //Risky code

catch(ArithmeticException ae)

- //Error handling code

How to display exception details


Throwable class defines following three method to display exception details.

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.

4)What is finally block?


It is never recommanded to maintain cleanup code inside try block because if any exception raised in try
block then try won't be executed.

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

5)What is the difference between final, finally and finalized method?


final
A final is a modifier which is applicable for variables,methods and classes.

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.

7) What is throws statement?


If any checked exception raised in our program we must and should handle that exception by using try
and catch block or by using throws statement.

8) what is Generics?
Array is a typesafe.

We can provide guarantee that what type of elements are present in array.

If requirement to store String values then we need to use String[] array.

ex:

String[] str=new String[100];

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:

String[] str=new String[100];

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

elements. hetrogenous data elements.

Arrays are fixed in size. Collections are growable in nature.

Performance point of view array is Memory point of view Collection is

32
recommanded to use. recommanded to use.

It is typesafe. It is not typesafe.

Arrays are not implemented based on Collections are implemented based on

data structure concept so we can't data structure concept so we can expect

expect any ready made methods.For readymade methods.

every logic we need to write the code

explicitly.

It holds primitive and object types. It holds only object type.

2) What is Collection?
Collection is an interface which is present in java.util package.

It is a root interface for entire collection framework.

If we want to represent group of individual objects in a single entity then we need to use Collections.

3)What is the Difference between ArrayList vs Vector?


ArrayList Vector
The underlying data structure is The underlying data structure is resizable or

doublyArrayList. growable array in Vector.

Insertion order is preserved. Insertion order is preserved.

Duplicate objects are allowed. Duplicate objects are allowed.

Hetrogeneous objects are allowed. Hetrogeneous objects are allowed.

Null insertion is possible. Null insertion is possible.

It implements Serializable It implements Serializable

and Cloneable, Random Access and Cloneable, Random Access interface.

interface.

33
4) What is the Difference between ArrayList vs LinkedList?
ArrayList LinkedList
The underlying data structure is The underlying data structure is

resize or growable ArrayList. doubly LinkedList.

Insertion order is preserved. Insertion order is preserved.

Duplicate objects are allowed. Duplicate objects are allowed.

Hetrogeneous objects are allowed. Hetrogeneous objects are allowed.

Null insertion is possible. Null insertion is possible.

It implements Serializable It implements Serializable

and Cloneable, Random Access and Cloneable, Random Access interface.

interface.

If our frequent operation is If our frequent operation is

retrieval or select operation then insert or delete in the middle then

we need to use ArrayList. LinkedList is a best choice.

5) What is the Difference between List vs Set


LIST SET
It is a child interface of Collection interface. It is a child interface of Collection 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

order is preserved. to use Set interface.

6) What is the Difference between HashSet vs LinkedHashSet?


HashSet LinkedHashSet
The underlying data structure is The underlying data structure is

Hashtable. Hashtable and LinkedList.

Insertion order is not preserved. Insertion order is preserved.

34
bcoz objects are arrange based on

hashcode of an oject.

Duplicate objects are not allowed. Duplicate objects are not allowed.

Hetrogeneous objects are allowed. Hetrogeneous objects are allowed.

Null insertion is possible. Null insertion is possible.

It implements Serializable

and Cloneable interface.

Introduced in 1.4v. Introduced in 1.4v.

7) What is the Difference between HashSet vs TreeSet?


HashSet TreeSet
The underlying data structure is The underlying data structure is

Hashtable. Balanced Tree.

Insertion order is not preserved. Insertion order is preserved.

bcoz objects are arrange based on bcoz it is based on sorting

hashcode of an oject. order of an object.

Duplicate objects are not allowed. Duplicate objects are not allowed.

Hetrogeneous objects are allowed. Hetrogeneous objects are allowed.

Null insertion is possible. Null insertion is possible only once.

It implements Serializable It implements Serializable

and Cloneable interface. Navigableset and Cloneable interface.

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.

Both key and value are objects only.

35
Duplicate keys are not allowed but values can be duplicated.

Each key-value pair is called "one entry".

9) What is the Difference between HashMap vs LinkedHashMap?


HashMap LinkedHashMap
The underlying data structure is The underlying data structure is

Hashtable. Hashtable. It is a child class of HashMap

class.

Insertion order is not preserved Insertion order is not preserved.

and it is based on hashcode of the

keys.

Duplicate keys are not allowed.

but values can be duplicated.

Hetrogeneous objects are allowed

for both keys and values.

Null insertion is possible

for keys(only once) and for values

(any number).

Introduced in 1.2v. Introduced in 1.4v.

10) What is the Difference between HashMap vs TreeMap


HashMap TreeMap
The underlying data structure is The underlying data structure is

Hashtable. RED BLACK TREE.

Insertion order is not preserved Insertion order is not preserved.

and it is based on hashcode of the All entries will store in the sorting

keys. order of keys.

36
Duplicate keys are not allowed. Duplicate keys are not allowed but values

can be duplicated.

Hetrogeneous objects are allowed

for both keys and values

Null insertion is possible see below QUESTION AND ANSWER

for keys(only once) and for values

(any number).

11)What is TreeMap?
The underlying data structure is RED BLACK TREE.

Duplicate keys are not allowed but values can be duplicated.

Insertion order is not preserved. All entries will store in the sorting order of keys.

If we depends upon natural sorting order then keys can be homogeneous

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.

But there is no restrictions on NULL values

12) What is the Difference between TreeMap vs Hashtable?


TreeMap HashTable
The underlying data structure is The underlying data structure is doubly LinkedList.

RED BLACK TREE.

Insertion order is not preserved. Insertion order is not preserved.

Duplicate keys are not allowed Duplicate keys are not allowed but values are allowed.

37
but values can be duplicated.

Hetrogeneous keys and values are allowed.

SEE ABOVE QUESTION & ANS

and values can't be Null otherwise we willget

NullPointerException.

13)Comparable vs Comparator?
OR

What is the difference between Comparable and Comparator interface?


Comparable
Comparable interface present in java.lang package.

Comparable interface contains following one method i.e compareTo() method.

Ex:public int compareTo(Object o)

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.

Comparator interface contains following two methods.

1) public int compare(Object obj1,Object obj2)

2) public boolean equals(Object obj)

Whenever we are using Comparator interface we should write

implementation only for compare() method.

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.

14)Type of Datastructure in java?

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.

We have three types of cursors in java.

1)Enumeration

2)Iterator

3)ListIterator

1)Enumeration
Enumeration interface present in java.util package.

It is used to read objects one by one from Legacy Collection objects.

Enumeration object can be created by using elements() method.

ex: Enumeration e=v.elements();

Enumeration interface contains following two methods.

ex: public boolean hasMoreElements();

public Object nextElement();

2)Iterator
It is used to retrieve the objects one by one from any Collection object.Hence it is known as universal
cursor.

Using Iterator interface we can perform read and remove operation.

We can create Iterator object by using iterator() method.

ex: Iterator itr=al.iterator();

Iterator interface contains following three methods.

ex: public boolean hasNext();

39
public Object next();

public void remove();

3)ListIterator
It is a child interface of Iterator interface.

It is used to read objects one by one from List Collection objects.

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.

We can create ListIterator interface by using listIterator() method.

ex: ListIterator litr=al.listIterator();

MULTI-THREADING
1) What is the difference between Thread and Process?
Thread
Thread is a light weight sub process.

We can run multiple threads concurently.

One thread can communicate with another thread.

ex: class is one thread

constructor is one thread

block is one thread and etc.

PROCESS
Process is a collection of threads.

We can run multiple process concurently.

One process can't communicate with another process.They are independent to each other.

ex: Opening a notepad and typing java notes is one process.

40
Downloading a file from internet is one process.

Taking class in zoom metting is one process.

2)What is Multi-tasking?
Executing several task simultenously such concept is called multi-tasking.

Multi-tasking is divided into two types.

1)Thread based multi-tasking


Executing several task simultenously where each task is a same part of a program.

It is best suitable for programmatic level.

2)Process based multi-tasking


Executing several task simultenously where each task is a independent process.

It is best suitable for OS level.

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.

The main important application area of multi-threading are.

1)To develop multimedia graphics

2)To develop animation

3)To develop video games

Ways to start a thread in java


We can start or create or instantiate a thread in two ways.

1)By extending Thread class

2)By implementing Runnable interface

Life cycle of a thread


Once if we create a thread object then our thread will be in new/born state.

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.

4)What is Thread priority?


In java, every thread has a priority automatically generated by JVM or explicitly provided by the
programmer.

The valid range for thread priority is 1 to 10.1 is a least priority and 10 is a highest priority.

Thread class defines following standard constants as thread priorities.

ex:

Thread.MAX_PRIORITY -- 10

Thread.NORM_PRIORITY -- 5

Thread.MIN_PRIORITY -- 1

5)What is Setting and Getting Name of a thread?


In java, every thread has a name automatically generated by JVM or explictly provided by the
programmer.

We have following methods to set and get name of a thread.

ex: public final void setName(String name)

public final String getName()

In how many ways we can prevent a thread from execution


There are three ways to prevent(stop) a thread from execution.

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.

Ex: public static native void yield()

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

ex: public final void join()throws InterruptedException

public final void join(long ms)throws InterruptedException

public final void join(long ms,int ns)throws InterruptedException.

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.

ex: public static native void sleep()throws InterruptedException

public static native void sleep(long ms)throws InterruptedException

public static native void sleep(long ms,int ns)throws InterruptedException

6)What is Lock Mechanism in Java?


synchronization is build around an entity called lock.

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.

7)What is Daemon Thread?


Deamon thread is a service provide thread which provides service to user threads.

The life of deamon thread is same as user threads. Once threads executed deamon thread will terminate
automatically.

There are many daemon thread are running in our system.

ex: Garbage collector , Finalizer and etc.

To start a deamon thread we need to use setDaemon(true) method.

To check a thread is a daemon or not we need to use isDaemon() method.

43
Problems without synchronization:
If we won't have synchronization then we will face following problems.

1) Thread interference.

2) Data inconsistency problem.

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 advantage of synchronization is we solve data inconsistence problem.

The main disadvantage of synchronization is ,it will increase waiting time of a thread which reduce the
performance of the system.

If there is no specific requirement then it is never recommanded to use synchronization concept.

synchronization internally uses lock mechanism.

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.

9)What is Synchronized block?


If we want to perform synchronization on specific resource of a program then we need to use

synchronization.

ex: If we have 100 lines of code and if we want to perform synchronization only for

10 lines then we need to use synchronized block.

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

to access object lock which is acquired by first thread.

Here both the threads are waiting release the thread but no body will

release such situation is called DeadLock.

12) What are the Drawbacks of multithreading?


1)DeadLock

2)Thread Starvation

JAVA 1.8 FEATURES


1)Functional Interface
An interface that contains exactly one abstract method is known as functional interface.

ex:

Runnable -> run()

Comparable -> compareTo()

ActionListener -> actionPerformed()

It can have any number of default and static methods.

Function interface is also known as Single Abstract Method Interface or SAM interface.

It is a new feature in java which helps in to achieve functional programming .

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 is used to enable functional programming.

It is used to concise the code (To reduce the code).

Lamda Expression can be used when we have functional interface.

Lamda expression considered as a method not a class.

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.

Stream is an interface which is present in java.util.stream package.

Stream is use to perform bulk operations on Collections.

We can create Stream object as follow.

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.

2)How many steps are there to develop jdbc application?


There are six steps are there to develop jdbc application.

1)Register JDBC driver with DriverManager service.

2)Establish the connection with database software.

3)Create statement object

4)Sends and executes SQL query in database software.

5)Gather the result from database software to result.

6)Close all jdbc connection objects.

3)How many drivers are there in jdbc?


We have four types of drivers in jdbc?

1) Type1 JDBC driver (JDBC-ODBC bridge driver)

2) Type2 JDBC driver (Native API)

3) Type3 JDBC driver (Net Protocol)

4) Type4 JDBC driver (Native Protocol)

4)How many statements are there in JDBC?


We have three statements in jdbc.

1)Simple Statement

2)PreparedStatement

3)CallableStatement

5)What is DatabaseMetaData?
DatabaseMetaData is an interface which is present in java.sql package.

DatabaseMetaData provides metadata of a database.

47
DatabaseMetaData gives information about database product name, database product version,
database driver name, database driver version, database username and etc.

We can create DatabaseMetaData object by using getMetaData() method of Connection obj.

ex:

DatabaseMetaData dbmd=con.getMetaData();

5)What is ResultSetMetaData?
ResultSetMetaData is an interface which is present in java.sql package.

ResultSetMetaData provides metadata of a table.

ResultSetMetaData gives information about number of columns, datatype of a columns, size of a column
and etc.

We can create ResultSetMetaData object by using getMetaData() method of ResultSet obj.

ex:

ResultSetMetaData rsmd=rs.getMetaData();

6)Types of Queries in jdbc?


We have two types of queries in jdbc.

1)Select query
It will give bunch of records from database table.

ex:select * from student order by sno;

To execute select query we need to executeQuery() method.

2)Non-Select query
It will give numeric value represent number of records effected in a

database table.

ex: delete from student;

To execute non-select query we need to use executeUpdate() method.

7)What is JDBC Connection pool?


It is a factory containing a set of readily available JDBC connection objects before actual being used.

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.

8)Types of ResultSet objects?


We have two types of ResultSet objects in jdbc.

1)Non-Scrollable ResultSet object

2)Scrollable ResultSet object

1)Non-Scrollable ResultSet object


By default every ResultSet object is a non-scrollable ResultSet object.

It allows us to read the records sequentially or uni-directionally such type of ResultSet object is called
non-scrollable ResultSet object.

2)Scrollable ResultSet object


It allows us to read the records non-sequentially , bi-directionally or randomly such type of ResultSet
object is called scrollable ResultSet object.

9)Write a jdbc application to create a table in database?(or)

9)Write a jdbc application to perform aggregate function?


import java.sql.*;

class CreateTableApp

public static void main(String[] args)throws Exception

Class.forName("oracle.jdbc.driver.OracleDriver");

Connecton con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","admin");

String qry="create table student(sno number(3),

49
sname varchar2(10),sadd varchar2(12))";

PreparedStatement ps=con.prepareStatement(qry)

int result=ps.executeUpdate();

if(result==0)

System.out.println("Table not created");

else

System.out.println("Table created");

ps.close();

con.close();

10)Write a jdbc application to insert the record into student table


import java.sql.*;

import java.util.*;

class CreateTableApp

public static void main(String[] args)throws Exception

Scanner sc=new Scanner(System.in);

System.out.println("Enter the student no: ");

int no=sc.nextInt();

System.out.println("Enter the student name :");

String name=sc.next();

System.out.println("Enter the student address :");

50
String add=sc.next();

Class.forName("oracle.jdbc.driver.OracleDriver");

Connecton con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:XE","system","admin");

String qry="insert into student values(?,?,?)";

PreparedStatement ps=con.prepareStatement(qry);

//set the values

ps.setInt(1,no);

ps.setString(2,name);

ps.setString(3,add);

int result=ps.executeUpdate();

if(result==0)

System.out.println("Table not created");

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

web server , proxy server ,HTTP server and etc.

or

Servlet is a java based dynamic web resource program which is used to generate

dynamic web pages.

or

Servlet is a single instance multi-thread java based web resource program which is used

to develop web applications.

2)What is web application?


Web application is a collection of web resource programs having the capability to

generate web pages.

We have two types of web pages.

1)Static web page

2)Dynamic web page

3)What is web resource program?


We have two types of web resource programs.

1)Static web resource program


It is responsible to generate static web pages.

Ex: HTML program

CSS program

Bootstrap program

Angular program and etc.

52
2)Dynamic web resource program
It is responsible to generate dynamic web pages.

ex: Servlet program

JSP program and etc.

4) What is Web container


It is a software application or program which is used to manage whole life cycle of

web resource program i.e from birth to death.

Servlet container manages whole life cycle of servlet program.

Similarly , JSP container manages whole life cycle of jsp program.

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.

ServletConfig object is used to read configuration information from web.xml file

We can create ServletConfig object by using getServletConfig() method.

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.

We can create ServletContext object by using getServletContext() method.

ex: ServletContext context=getServletContext():

Or ServletConfig config=getServletConfig();

53
ServletContext context=config.getServletContext();

7) what is Servlet Filters?


Filter is an object which is executed at the time of preprocessing and

postprocessing of the request.

The main advantages of using filter is to perform filter task such as


1) Counting number of request

2) To perform validation

3) Encyrption and Decryption

and etc.

Like Servlet, Filter is having it's own Filter API.

The javax.servlet package contains thre interfaces of Filter API.

1)Filter

2)FilterChain

3)FilterConfig

8)Differences between GET And POST methodology?


GET POST
It is a default methodology. It is not a default methodology.

It sends the request fastly. It sends the request bit slow

It will carry limited amount of data. It will carry unlimited amount of data.

It is not suitable for secure data. It is suitable for secure data.

It is not suitable to perform It is suitable to perform encyrption and

encryption or fileuploading. file uploading.

To process GET methodology we need To process POST methodology we need to use

to use doGet(-,-) method. doPost(-,-) method.

54
9)Explain Servlet Life cycle methods?
We have three life cycle methods in Servlets

1)public void init(ServletConfig config)throws ServletException


It is used for instantiation event.

This method will execute just before Servlet object creation.

2)public void service(ServletRequest req,ServletResponse res)throws


ServletException,IOException
It is used for request processing event.

This method will execute when request goes to servlet program.

3)public void destroy


It is used for destruction event.

This method will execute just before Servlet object destruction.

10)Limitations with servlets


> To work with servlets strong java knowledge is required.

> It is suitable for only java programmers.

> Configuration of servlet program in web.xml file is mandatory.

> Handling exceptions are mandatory.

> It does not give any implicit object.

(Object which can be used directly without any configuration is called implicit object).

> We can't maintain html code and java code sperately.

> It does not support tag based language.

JSP QUESTIONS
1)Advantages of JSP
> To work with JSP strong java knowledge is not required.

> It is suitable for java and non-java programs.

55
> It supports tag based language.

> It allows us to create custom tags in jsp.

> Configuration of jsp program in web.xml file is optional.

> Handling exceptions are optional.

> It gives 9 implicit objects.

> We can maintain html code and java code sperately.

> It gives all the features of servlets.

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,

most of which start with <% and end with %>.

3) Types of Jsp Implicit Objects


There are 9 implicit objects present in jsp.

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.

The list of implicit objects are.

Object Type

out JspWriter

request HttpServletRequest

response HttpServletRespons

config ServletConfig

application ServletContext

session HttpSession

pageContext pageContext

page Object

56
exception Throwable

4) Types of JSP Tags/Elements?


1)Scripting tags

i)Scriptlet tag
ex: <% code %

ii)Expression tag
ex: <%= code %>

iii)Declaration tag
ex: <%! code %>

2)Directive Tags

i)Page directive tag


ex: <%@page attribute=value %>

ii)include directive tag


ex: <%@include attribute=value %>

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.

syntax: <% code %>

5)JSP life cycle methods


JSP contains three life cycle methods.

57
1)_jspInit()
It is used for instantiation event

This method will execute just before JES class object creation.

JES class stands for Java Equivalent Servlet class.

2)_jspService()
It is used for request arrival event

This method will execute when request goes to JSP program.

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

(ABC_jsp.class and ABC_jsp.java) object.

2)Request processing phase


In this phase, our JES class will be execute and result will send

to browser window as dynamic response.

8)MVC in JSP?
MVC stands for Model View Controller.

It is a design partern which seperates business logic , persistence logic and data.

Controller acts like an interface between Model and View.

Controller is used to intercept with all the incoming requests.

Model contains data.

View represent User interface i.e UI.

9)What is JES clSass?

58
59
60

You might also like