0% found this document useful (0 votes)
52 views113 pages

Java Programming Basics and Concepts

The document provides an overview of Java, covering its creation, bytecode, and key features known as Java buzzwords, such as object-oriented programming, simplicity, security, and platform independence. It also explains fundamental concepts like classes, objects, methods, type casting, type conversion, and arrays, along with examples of their implementation in Java. The document emphasizes the importance of understanding object-oriented principles, encapsulation, inheritance, and polymorphism in Java programming.

Uploaded by

pranavirdy208
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)
52 views113 pages

Java Programming Basics and Concepts

The document provides an overview of Java, covering its creation, bytecode, and key features known as Java buzzwords, such as object-oriented programming, simplicity, security, and platform independence. It also explains fundamental concepts like classes, objects, methods, type casting, type conversion, and arrays, along with examples of their implementation in Java. The document emphasizes the importance of understanding object-oriented principles, encapsulation, inheritance, and polymorphism in Java programming.

Uploaded by

pranavirdy208
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

Introduction: Creation of Java, Byte code, Java Buzzwords, Object Oriented Programming,

A simple program, Type conversion and casting, Arrays. Classes: Class fundamentals,
declaring Objects, assigning object reference variables. A Closer Look at Methods and
Classes: Introducing methods, constructors, this keyword, garbagecollection, the finalize ()
method.

Creation of Java

• Java is one of the most popular programming languages worldwide. It was created by
James Gosling and Patrick Naughton, employees of Sun Microsystems, with support from
Bill Joy, co-founder of Sun Microsystems.

• Sun officially presented the Java language at SunWorld on May 23, 1995. Then, in 2009,
the Oracle company bought the Sun company.

• The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".

• Currently, Java is used in internet programming, mobile devices, games, e-business


solutions, etc.

Byte code

• Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an
assembler which is an alias representation of a C++ code.

• As soon as a java program is compiled, java bytecode is generated. In more apt terms,
java bytecode is the machine code in the form of a .class file. With the help of java
bytecode we achieve platform independence in java.

• This essentially means that we only need to have basic java installation on any platforms
that we want to run our code on.

• Resources required to run the bytecode are made available by the Java Virtual Machine,
which calls the processor to allocate the required resources. JVM's are stack-based so
they stack implementation to read the codes.
• Bytecode is essentially the machine level language which runs on the Java Virtual
Machine.

• Whenever a class is loaded, it gets a stream of bytecode per method of the class.
Whenever that method is called during the execution of a program, the bytecode for that
method gets invoked.

• Javac not only compiles the program but also generates the bytecode for the program.
Thus, we have realized that the bytecode implementation makes Java a platform-
independent language.

• Portability ensures that Java can be implemented on a wide array of platforms like
desktops, mobile devices, severs and many more.

Java Buzzwords

• The primary objective of Java programming language creation was to make it portable,
simple and secure programming language.

• Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as Java buzzwords.
Object-oriented- Java is an object-oriented programming language. Everything in Java is an
object. Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.

Simple- Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language because:

Secured- Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader
o Bytecode Verifier
o Security Manager

Platform Independent- Java is platform independent because it is different from other


languages like C, C++, etc. which are compiled into platform specific machines while Java is a
write once, run anywhere language. A platform is the hardware or software environment in
which a program runs.

• There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
• The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:

• Runtime Environment
• API(Application Programming Interface)
• Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Robust- The English mining of Robust is strong. Java is robust because:

• It uses strong memory management.


• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Portable- Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.

Architecture-neutral- Java is architecture neutral because there are no implementation


dependent features, for example, the size of primitive types is fixed. In C programming, int
data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-
bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures
in Java.

Dynamic- Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.

Interpreted & High-performance- Java is faster than other traditional interpreted


programming languages because Java bytecode is "close" to native code. It is still a little bit
slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.

Multi-threaded- A thread is like a separate program, executing concurrently. We can write


Java programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications, etc.

Distributed- Java is distributed because it facilitates users to create distributed applications


in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any machine on the internet.

Object Oriented Programming


• Object-oriented programming (OOP) is a fundamental programming paradigm based on
the concept of “objects”. These objects can contain data in the form of fields (often
known as attributes or properties) and code in the form of procedures (often known as
methods).
• OOP is at core of Java. In fact, all Java programs are to at least some extent objct-
oriented.
• OOP is so integral to Java that it is best to understand its basic principles before you
begin writing even simple programs.

An object consists of:


• A unique identity: Each object has a unique identity, even if the state is identical to that
of another object.
• State/Properties/Attributes: State tells us how the object looks or what properties it
has.
• Behavior: Behavior tells us what the object does.

Examples of object states and behaviors in Java:

Let's look at some real-life examples of the states and behaviors that objects can have.
Example 1:

• Object: car.
• State: color, brand, weight, model.
• Behavior: break, accelerate, turn, change gears.

Example 2:

• Object: house.
• State: address, color, location.
• Behavior: open door, close door, open blinds.

The three OOP Principles

All object-oriented programming language provides mechanisms that help you implement the
object-oriented model. They are

• Encapsulation
• Inheritance
• Polymorphism
Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private here.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

• If one task is performed in different ways, it is known as polymorphism. For example: to


convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
• In Java, we use method overloading and method overriding to achieve polymorphism.

• Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.

A simple program

class Simple
{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[],
[Link]().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is
visible to all.
o static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to
create an object to invoke the static method. The main() method is executed by
the JVM, so it doesn't require creating an object to invoke the main() method.
So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will
discuss it in coming section.
o [Link]() is used to print statement. Here, System is a class, out is
an object of the Print Stream class, println() is a method of the Print Stream
class. We will discuss the internal working of [Link]() statement in
the coming section.
Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
destination data type may be smaller than the source data type when converting the data
type to another data type, that’s why it is also called narrowing conversion.

Syntax/Declaration:-

destination_datatype = (target_datatype)variable;
(): is a casting operator.

Type conversion : In type conversion, a data type is automatically converted into another data
type by a compiler at the compiler time. In type conversion, the destination data type cannot
be smaller than the source data type, that’s why it is also called widening conversion. One
more important thing is that it can only be applied to compatible data types.

int x=30;
float y;
y=x; // y==30.000000.
[Link] TYPE CASTING TYPE CONVERSION

In type casting, a data type is


Whereas in type conversion, a data
converted into another data type by
1. type is converted into another data
a programmer using casting
type by a compiler.
operator.

Type casting can be applied


Whereas type conversion can only be
2. to compatible data types as well
applied to compatible datatypes.
as incompatible data types.

In type casting, casting operator is


Whereas in type conversion, there is
3. needed in order to cast a data type
no need for a casting operator.
to another data type.

In typing casting, the destination


Whereas in type conversion, the
data type may be smaller than the
4. destination data type can’t be
source data type, when converting
smaller than source data type.
the data type to another data type.

Type casting takes place during the Whereas type conversion is done at
5.
program design by programmer. the compile time.

Whereas type conversion is also


Type casting is also called narrowing
called widening conversion because
conversion because in this, the
6. in this, the destination data type can
destination data type may be
not be smaller than the source data
smaller than the source data type.
type.

Whereas type conversion is less used


Type casting is often used in coding
in coding and competitive
7. and competitive programming
programming as it might cause
works.
incorrect answer.

Type casting is more efficient and Whereas type conversion is less


8.
reliable. efficient and less reliable.
Java Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, you
can place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

[Link](cars[0]);

// Outputs Volvo

Change an Array Element


To change the value of a specific element, refer to the index number:

cars[0] = "Opel";

Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

[Link](cars[0]);
// Now outputs Opel instead of Volvo

Array Length
To find out how many elements an array has, use the length property:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

[Link]([Link]);

// Outputs 4

Classes: Class fundamentals


To create a class, use the keyword class:

Create a class named "Main" with a variable x:

public class Main


{
int x = 5;
}
Create an Object
In Java, an object is created from a class. We have already created the class named
Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name,
and use the keyword new:

Create an object called "Obj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main Obj = new Main();

[Link](Obj.x);

}
Multiple Objects

You can create multiple objects of one class:

Create two objects of Main:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

[Link](myObj1.x);

[Link](myObj2.x);

Declaring Objects
An entity that has state and behavior is known as an object e.g., chair, bike, marker,
pen, table, car, etc. It can be physical or logical (tangible and intangible). The example
of an intangible object is the banking system.

assigning object reference variables

Java, being an object-oriented programming language, allows the use of reference


variables to work with objects and their data. In Java, objects are created dynamically
on the heap memory, and reference variables are used to hold the memory address of
these objects.

Understanding Reference Variables:

In Java, a reference variable is a variable that holds the memory address of an object rather
than the actual object itself. It acts as a reference to the object and allows manipulation of its
data and methods. Reference variables are declared with a specific type, which determines
the methods and fields that can be accessed through that variable.
When an object is created using the new keyword, memory is allocated on the heap to store
the object's data. The reference variable is then used to refer to this memory location, making
it possible to access and manipulate the object's properties and behaviors.

class Car {
String brand;
int year;
}
public class ReferenceVariableExample {
public static void main(String[] args) {
// Declare a reference variable of type Car
Car myCar;
// Create a new Car object and assign its reference to myCar
myCar = new Car();
// Access and modify the object's properties
[Link] = "Toyota";
[Link] = 2021;
// Use the reference variable to perform actions on the object
[Link]("Brand: " + [Link]);
[Link]("Year: " + [Link]);
}
}
Benefits and Usage of Reference Variables

o Object Manipulation: Reference variables allow programmers to work with objects,


access their properties, and invoke their methods. They enable object-oriented
programming principles such as encapsulation, inheritance, and polymorphism.
o Memory Efficiency: Reference variables only store the memory address of an object
rather than the entire object itself. This approach helps conserve memory by avoiding
unnecessary object duplication.
o Object Passing: Reference variables are often used when passing objects as
arguments to methods or returning objects from methods. This allows for efficient
memory usage and facilitates modular programming.
o Dynamic Behavior: Reference variables enable dynamic behavior in Java programs.
Different objects can be assigned to the same reference variable, allowing flexibility in
handling different types of objects at runtime.
o Object Lifetime Control: Using reference variables, developers can control the
lifetime of objects dynamically. When a reference variable is no longer referencing an
object, the object becomes eligible for garbage collection, freeing up memory
resources.

Introducing methods
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods.

Method Declaration

The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:

o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the samepackage only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter,
left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Naming a Method

While defining a method, remember that the method name must be a verb and start with
a lowercaseletter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding
method runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is defined
in the [Link] class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
}
}

User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will define
the method.

import [Link];
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from user
int num=[Link]();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
}

Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
[Link]("It is an example of static method.");
}
}

Instance Method
The method of the class is known as an instance method. It is a non-static method defined in
the class. Before calling or invoking the instance method, it is necessary to create an object
of its class. Let's see an example of an instance method.

public class InstanceMethodExample


{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
[Link]("The sum is: "+[Link](12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}

Abstract Method
The method that does not has method body is known as abstract method. In other words,
without an implementation is known as abstract method. It always declares in the abstract
class. It means the class itself must be abstract if it has abstract method. To create an abstract
method, we use the keyword abstract.
Syntax

abstract void method_name();

abstract class Demo //abstract class


{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
[Link]("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
[Link]();
}
}
Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {
x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main


(This will call the constructor)

[Link](myObj.x); // Print the value of x

// Outputs 5

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we
set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5),
which will set the value of x to 5:

public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

[Link](myObj.x);

// Outputs 5
this keyword

The this keyword refers to the current object in a method or constructor.

The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). If you omit the keyword in the example above, the
output would be "0" instead of "5".

this can also be used to:

• Invoke current class constructor


• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

public class Main {


int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
[Link]("Value of x = " + myObj.x);
}
}

garbage collection
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short. When Java programs run on the JVM, objects are created on the heap, which
is a portion of memory dedicated to the program.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection is the process
of looking at heap memory, identifying which objects are in use and which are not, and
deleting the unused objects. An in-use object, or a referenced object, means that some part
of your program still maintains a pointer to that object. An unused or unreferenced object is
no longer referenced by any part of your program.

the finalize () method. To be continued in second module.

Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up
activities and minimize memory leaks.

Syntax
protected void finalize() throws Throwable

Protected method: protected is an access specifier for variables and methods in Java. When
a variable or method is protected, it can be accessed within the class where it's declared and
other derived classes of that class.

all classes inherit the Object class directly or indirectly in Java. The finalize() method is
protected in the Object class so that all classes in Java can override and use it.

When to Use finalize() Method in Java?

Garbage collection is done automatically in Java, which the JVM handles. Java uses the
finalize method to release the resources of the object that has to be destroyed.

GC call the finalize method only once, if an exception is thrown by finalizing method or the
object revives itself from finalize(), the garbage collector will not call the finalize() method
again.

It's not guaranteed whether or when the finalized method will be called. Relying entirely on
finalization to release resources is not recommended.

There are other ways to release the resources used in Java, like the close() method for file
handling or the destroy() method. But, the issue with these methods is they don't work
automatically, we have to call them manually every time.
In such cases, to improve the chances of performing clean-up activity, we can use the
finalize() method in the final block. finally block will execute finalize() method even though
the user has used close() method manually.

We can use the finalize() method to release all the resources used by the object.* In the final
block, we can override the finalize() method.* An example of overriding the finalize method
in Java is given in the next section of this article.

public class Student


{
public static void main(String[] args)
{
Student s1 = new Student();
s1 = null;
[Link]();
[Link]("Garbage collector is called");
}

@Override
protected void finalize()
{
[Link]("Finalize method is called.");
}
}

Explanation:

In this example, the s1 object is eligible for garbage collection. When [Link]();
invokes the garbage collector, it calls the object class's finalize() method. The
overridden finalize() method of the Student class is called, and it prints Finalize
method is called.
2. Explicit Call to finalize() Method

When we call the finalize() method explicitly, the JVM treats it as a normal method; it cannot
remove the object from memory. The finalize() method can release memory and resources
related to an object only when a Garbage collector calls it. Compiler will ignore the finalize()
method if it's called explicitly and not invoked by the Garbage collector. Let's understand
this practically:
public class Demo
{
public static void main(String[] args)
{
Demo demo1 = new Demo();
Demo demo2 = new Demo();
demo1 = demo2;
[Link](); // Explicit call to finalize method
[Link]("Garbage collector is called");
[Link](); // Implicit call to finalize() method
}

@Override
protected void finalize()
{
[Link]("Finalize() method is called");
}
}

Best Practices to Use finalize() Method Correctly

Try to avoid the use of the finalize method. In case you need to use it, the following
are points to remember while using the finalize() method:

Do not use the finalize() method to execute time-critical application logic, as the
execution of the finalize method cannot be predicted.

Call the [Link]() method in the finally block; it will ensure that the finalize
method will be executed even if any exception is caught. Refer to the following
finalize() method template:
@Override
protected void finalize() throws Throwable
{
try{
//release resources here
}catch(Throwable t){
throw t;
}finally{
[Link]();
}
}

Conclusion

• finalize() is an Object class method in Java, and it can be used in all other classes
by overriding it.
• The garbage collector uses the finalize() method to complete the clean-up
activity before destroying the object.
• JVM allows invoking of the finalize() method in Java only once per object.
• Garbage collection is automated in Java and controlled by JVM.
• Garbage Collector calls the finalize method in java of that class whose object is
eligible for Garbage collection.
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand
the behavior of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

class Adder
{
static int add(int a,int b)
{
return a+b;}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}}

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
[Link]([Link](11,11));
[Link]([Link](12.3,12.6));
}}

Why Method Overloading is not possible by changing the return type of


method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
[Link]([Link](11,11));//ambiguity
}}
Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:

class TestOverloading4{
public static void main(String[] args){[Link]("main with String[]");}
public static void main(String args){[Link]("main with String");}
public static void main(){[Link]("main without args");}
}

Constructor overloading in Java


In Java, we can overload constructors like methods. The constructor overloading can be
defined as the concept of having more than one constructor with different parameters so that
every constructor can perform a different task.

Consider the following Java program, in which we have used different constructors in the
class.

public class Student {


//instance variables of the class
int id;
String name;

Student(){
[Link]("this a default constructor");
}

Student(int i, String n){


id = i;
name = n;
}

public static void main(String[] args) {


//object creation
Student s = new Student();
[Link]("\nDefault Constructor values: \n");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);

[Link]("\nParameterized Constructor values: \n");


Student student = new Student(10, "David");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]
e);
}
}
In the above example, the Student class constructor is overloaded with two
different constructors, I.e., default and parameterized.

Method Overloading and Type Promotion

Access Modifiers in Java

There are two types of modifiers in Java: access modifiersand non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table.

Access within within outside outside package


Modifier class package package by
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.

class A{
private int data=40;
private void msg(){[Link]("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.

//save by [Link]
package pack;
class A{
void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
}
}

3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.
It provides more accessibility than the default modifer.

In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

//save by [Link]
package pack;
public class A{
protected void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
[Link]();
}
}

4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.

//save by [Link]

package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save by [Link]
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}

Java static keyword

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java sta)c variable


If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Understanding the problem without static variable


class Student{
int rollno;
String name;
String college="DSCE";
}

Suppose there are 500 students in my college, now all instance data members will get
memory each time when the object is created. All students have its unique rollno and name,
so instance data member is good in such case. Here, "college" refers to the common property
of all objects. If we make it static, this field will get the memory only once.

Example of static variable

//Java Program to demonstrate the use of static variable


class Student{
int rollno;//instance variable
String name;
static String college ="DSCE";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){[Link](rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//[Link]="DSCE";
[Link]();
[Link]();
}
}
2) Java sta.c method
If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "DSCE";
//static method to change the value of static variable
static void change(){
college = "DSU";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){[Link](rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}
}

Output:111 Karan DSU


222 Aryan DSU
333 Sonoo DSU

3) Java sta)c block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of staOc block


class A2{
static
{
[Link]("static block is invoked");
}
public static void main(String args[]){
[Link]("Hello main");
}
}
Output: static block is invoked
Hello main

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block only.
We will have detailed learning of these. Let's first learn the basics of final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}
}//end of class

Output: Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method


class Bike{
final void run()
{
[Link]("running");
}
}

class Honda extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[])


{
Honda honda= new Honda();
[Link]();
}
}
Output: Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


final class Bike{}

class Honda1 extends Bike{


void run(){[Link]("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
[Link]();
}
}
Output:Compile Time Error

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and
fields in your current class also.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

Example Program

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported.


Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

class Animal{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
Output:
barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can
see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
[Link]("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}

Output:

weeping...

barking...

eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}}

Output:

meowing...
eating...

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class


instance variable.
We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:
black
white

2) super can be used to invoke parent class


method
The super keyword can also be used to invoke parent class method. It should be used
if subclass contains the same method as parent class. In other words, it is used if
method is overridden.

class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void eat(){[Link]("eating bread...");}
void bark(){[Link]("barking...");}
void work(){
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:

eating...
barking...

3) super is used to invoke parent class


constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see
a simple example:

class Animal{
Animal(){[Link]("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
[Link]("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

Output:

animal is created
dog is created

Creating a Multilevel Inheritance Hierarchy in Java


Inheritance involves an object acquiring the properties and behaviour of
another object. So basically, using inheritance can extend the functionality of
the class by creating a new class that builds on the previous class by inheriting
it.

Multilevel inheritance is when a class inherits a class which inherits another


class. An example of this is class C inherits class B and class B in turn inherits
class A.

class A {
void funcA() {
[Link]("This is class A");
}
}
class B extends A {
void funcB() {
[Link]("This is class B");
}
}
class C extends B {
void funcC() {
[Link]("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
[Link]();
}
}

Method Overriding in Java

if subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.

o Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){[Link]("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
[Link]();
}
}

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Another way, it shows only essential things to the user and hides the internal details,
for example, sending SMS where you type the text and send the message. You don't
know the internal processing about the message deliver
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract
and non-abstract methods. It needs to be extended and its method implemented. It
cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body
of the method.

Example of abstract class

abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known
as an abstract method.

abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run.
Its implementation is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){[Link]("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
[Link]();
}
}

Understanding the real scenario of Abstract class


abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user

class Rectangle extends Shape{


void draw(){[Link]("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){[Link]("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.
g., getShape() method
[Link]();
}
}

Using final with inheritance


During inheritance, we must declare methods with the final keyword for
which we are required to follow the same implementation throughout all
the derived classes. Note that it is not necessary to declare final methods
in the initial stage of inheritance(base class always). We can declare a
final method in any subclass for which we want that if any other class
extends this subclass, then it must follow the same implementation of
the method as in that subclass.

Using final to Prevent Inheritance


When a class is declared as final then it cannot be subclassed i.e. no
other class can extend it. This is particularly useful, for example,
when creating an immutable class like the predefined String class. The
following fragment illustrates the final keyword with a class:
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}

Note :

• Declaring a class as final implicitly declares all of its methods as


final, too.
• It is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its
subclasses to provide complete implementations. For more on
abstract classes, refer abstract classes in java

Using final to Prevent Overriding


When a method is declared as final then it cannot be overridden by
subclasses. The Object class does this—a number of its methods are
final. The following fragment illustrates the finalkeyword with a
method:
class A
{
final void m1()
{
[Link]("This is a final method.");
}
}

class B extends A
{
void m1()
{
// ERROR! Can't override.
[Link]("Illegal!");
}
}

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?


An interface is declared by using the interface keyword. It provides total abstraction;
means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}

public static void main(String args[]){


A6 obj = new A6();
[Link]();
}
}

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.

finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there
may occur an exception in the method. It doesn't throw an exception. It
is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

[Link]

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}
Output:

Exception in thread main [Link]:/ by zero


rest of the code...

Java try-catch block


Java try block
Java try block is used to enclose the code that might throw an exception. It must be
used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute. So, it is recommended not to keep the code in try block that will
not throw an exception.

Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}

Java catch block


Java catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated type of exception.

The catch block must be used after the try block only. You can use multiple catch
block with a single try block.

Java Nested try block


In Java, using a try block inside another try block is permitted. It is called as nested try
block. Every statement that we enter a statement in try block, context of that exception
is pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).

Why use nested try block


Sometimes a situation may arise where a part of a block may cause one error and the
entire block itself may cause another error. In such cases, exception handlers have to
be nested.

Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}

}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....

Java Nested try Example


Example 1
Let's see an example where we place a try block within another try block for two
different exceptions.

public class NestedTryBlock{


public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}

[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}

[Link]("normal flow..");
}
}

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked
at the compile time instead of runtime and we can create custom exceptions making
the code recovery and debugging easier.
Java throw keyword
The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in
this section.

We can also define our own set of conditions and throw an exception explicitly using
throw keyword. For example, we can throw ArithmeticException if we divide a number
by another number. Here, we just need to set the condition and throw exception using
throw keyword.

The syntax of the Java throw keyword is given below.

throw Instance i.e.,

1. throw new exception_class("error message");

Let's see the example of throw IOException.

1. throw new IOException("sorry device error");

Where the Instance must be of type Throwable or subclass of Throwable. For example,
Exception is the sub class of Throwable and the user-defined exceptions usually extend
the Exception class.

Java throw keyword Example


Example 1: Throwing Unchecked Exception
In this example, we have created a method named validate() that accepts an integer as
a parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.

[Link]

In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException
otherwise print a message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}

Java throws keyword


The Java throws keyword is used to declare an exception. It gives an information to
the programmer that there may occur an exception. So, it is better for the programmer
to provide the exception handling code so that the normal flow of the program can
be maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers' fault that
he is not checking the code before it being used.

Syntax of Java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }

Which exception should be declared?


Ans: Checked exception only, because:

o unchecked exception: under our control so we can correct our code.


o error: beyond our control. For example, we are unable to do anything if there
occurs VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword


Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.

Java throws Example


Let's see the example of Java throws clause which describes that checked exceptions
can be propagated by throws keyword.

[Link] [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){[Link]("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}

Output:

exception handled
normal flow...
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.

The finally block follows the try-catch block.

Why use Java finally block?

o finally block in Java can be used to put "cleanup" code such as closing a file,
closing connection, etc.
o The important statements to be printed can be placed in the finally block.

Usage of Java finally


Let's see the different cases where Java finally block can be used.

Case 1: When an exception does not occur


Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.

[Link]

class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
[Link](data);
}
//catch won't be executed
catch(NullPointerException e){
[Link](e);
}
//executed regardless of exception occurred or not
finally {
[Link]("finally block is always executed");
}

[Link]("rest of phe code...");


}
}

Case 2: When an exception occurr but not handled by the


catch block
Let's see the the fillowing example. Here, the code throws an exception however the
catch block cannot handle it. Despite this, the finally block is executed after the try
block and then the program terminates abnormally.

[Link]

public class TestFinallyBlock1{


public static void main(String args[]){

try {

[Link]("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
[Link](data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
[Link](e);
}

//executes regardless of exception occured or not


finally {
[Link]("finally block is always executed");
}

[Link]("rest of the code...");


}
}

Case 3: When an exception occurs and is handled by the


catch block
Example:

Let's see the following example where the Java code throws an exception and the catch
block handles the exception. Later the finally block is executed after the try-catch block.
Further, the rest of the code is also executed normally.

[Link]

public class TestFinallyBlock2{


public static void main(String args[]){

try {

[Link]("Inside try block");

//below code throws divide by zero exception


int data=25/0;
[Link](data);
}

//handles the Arithmetic Exception / Divide by zero exception


catch(ArithmeticException e){
[Link]("Exception handled");
[Link](e);
}

//executes regardless of exception occured or not


finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}

JDBC

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database. There are four types of
JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We can use JDBC API to access tabular data stored in any relational database. By the
help of JDBC API, we can save, update, delete and fetch data from the database. It is
like Open Database Connectivity (ODBC) provided by Microsoft.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to dyna
the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the data
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of
responsible to execute queries with the database.

Syntax of createStatement() method


public Statement createStatement()throws SQLException

Example to create the statement object


Statement stmt=[Link]();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. T
returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


ResultSet rs=[Link]("select * from emp");

while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close()
Connection interface is used to close the connection.

Syntax of close() method


public void close()throws SQLException
import [Link].*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
[Link]("[Link]");

//step2 create the connection object


Connection con=[Link](
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=[Link]();

//step4 execute query


ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));

//step5 close the connection object


[Link]();

}catch(Exception e){ [Link](e);}

}
}

insert, update, delete and select query execution using java program.

JAVA SERVLETS

Java Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the web server,
process the request, produce the response, and then send a response back to the web
server.

Properties of Java Servlet

The properties of Servlets are as follows:

Servlets work on the server side.


Servlets are capable of handling complex requests obtained from the web server.

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this technology.
We have discussed these disadvantages below.

The servlet packages :

The [Link] package contains a number of classes and interfaces that describe and define the contracts
between a servlet class and the runtime environment

provided for an instance of such a class by a conforming servlet container. The Servlet interface is the
central abstraction of the servlet API.
All servlets implement this interface either directly, or more commonly, by extending a class that
implements the interface.

The two classes in the servlet API that implement the Servlet interface are GeneriISErvlet and HttpServlet .

For most purposes, developers will extend HttpServlet to implement their servlets while implementing web
applications employing the HTTP protocol.

The basic Servlet interface defines a service method for handling client requests. This method is called for
each request that the servlet container routes to an instance of a servlet.

Handling HTTP requests and responses :


• Servlets can be used for handling both the GET Requests and the POST Requests.

• The HttpServlet class is used for handling HTTP GET Requests as it has som specialized methods that
can efficiently handle the HTTP requests. These methods are;

doGet()
doPost()
doPut()
doDelete() doOptions() doTrace() doHead()

An individual developing servlet for handling HTTP Requests needs to override one of these methods in
order to process the request and generate a response. The servlet is invoked dynamically when an end-
user submits a form.

Example:

<form name="F1" action=/servlet/ColServlet> Select the color:

<select name = "col" size = "3">

<option value = "blue">Blue</option>

<option value = "orange">Orange</option>

</select>

<input type = "submit" value = "Submit"> </form>

Here’s the code for [Link] that overrides the doGet() method to retrieve data from the HTTP
Request and it then generates a response as well.
// import the java packages that are needed for the servlet to work

import [Link] .*;


import [Link]. *;
import [Link]. *;

// defining a class
public class ColServlet extends HttpServlet

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,


IOException

// request is an object of type HttpServletRequest and it's used to obtain information

// response is an object of type HttpServletResponse and it's used to generate a response // throws is
used to specify the exceptions than a method can throw

{
String colname = [Link]("col");

// getParameter() method is used to retrieve the selection made by the user


[Link]("text/html");

PrintWriter info = [Link]();

info .println("The color is: ");


info .println(col);
[Link]();

Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init
method is used initialize the servlet. It is the life cycle method of the [Link]
interface. Syntax of the init method given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received.
If servlet is not initialized, it follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method. Notice that servlet is
initialized only once. The syntax of the service method of the Servlet interface is given
below:
1. public void service(ServletRequest request, ServletResponse response) 2. throws
ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:

1. public void destroy()

Servlet – Single Thread Model Interface

Single Thread Model Interface was designed to guarantee that only one thread is executed at a
time in a given servlet instance service method. It should be implemented to ensure that the
servlet can handle only one request at a time. It is a marker interface and has no methods. Once
the interface is implemented the system guarantees that there’s never more than one request
thread accessing a single instance servlet. This interface is currently deprecated because this
doesn’t solve all the thread safety issues such as static variable and session attributes can be
accessed by multiple threads at the same time even if we implemented the SingleThreadModel
interface.

Syntax:

public class Myservlet extends Httpservlet implements

SingleThreadModel {

Implementation: SingleThreadModel interface


We created three files to make this application:
1. [Link]
2. [Link]
3. [Link]
The [Link] file creates a link to invoke the servlet of URL-pattern “servlet1” and Myservlet
class extends HttpServlet and implements the SingleThreadModel interface. Class Myservlet
is a servlet that handles Single requests at a single time and sleep() is a static method in the
Thread class used to suspend the execution of a thread for two thousand milliseconds. When
another user will try to access the same servlet, the new instance is created instead of using the
same instance for multiple threads.

A. File: [Link]

<!DOCTYPE html>
<html>
<head>
<title>HttpSession Event Listeners</title>
</head>
<body>
<a href="servlet1">open the servlet</a>
</body>
</html>

B. File: [Link]

// Java Program to Illustrate MyServlet Class

// Importing required classes


import [Link].*;
import [Link].*;
import [Link].*;

// Class
public class MyServlet
extends HttpServlet implements SingleThreadModel {

// Method
// Use doGet() when you want to intercept on
// HTTP GET requests
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Sets the content type of the response being sent
// to the client
[Link]("text/html");

// Returns a PrintWriter object that can send


// character text to the client
PrintWriter out = [Link]();

[Link]("welcome");

// Try block to check for exceptions


try {
// Making thread to sleep for 2 seconds
[Link](2000);
}

// Catch block to handle exceptions


catch (Exception e) {
// Display exception/s with line number
[Link]();
}

[Link](" to servlet");

// Closing the output stream


// using close() method
[Link]();
}
}

C. File: [Link]

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="2.5" xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<servlet>
<servlet-name>MyServlet</servlet-name>

<servlet-class>MyServlet</servlet-class>

</servlet>
<servlet-mapping>

<servlet-name>MyServlet</servlet-name>

<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Output: When you run your [Link] file, you’ll see the following results.
To get the output, click on the link.

Drawback of SingleThreadModel Interface


• When there are thousands of concurrent requests to the web container the container
may either serialize requests to the same instance of the servlet or create that many
instances.

Handling Client Request form data:


• Whenever we want to send an input to a servlet that input must be passed through
html form.
• An html form is nothing but various controls are inherited to develop an application.
• Every form will accept client data end it must send to a servlet which resides in server
side.
• Since html is a static language which cannot validate the client data. Hence, in real
time applications client data will be accepted with the help of html tags by developing
form and every form must call a servlet.

Steps for DEVELOPING a FORM:

1. Use <form>...</form> tag.


2. To develop various controls through <input>...</input> tag and all <input> tag must
be enclosed with in <form>...</form> tag.
3. Every form must call a servlet by using the following:
<form name="name of the form" action="either absolute or relative add
ress" method="get or post">
.........
.........
</form>

Write an html program to develop the a form:

<html>
<title>About Personal Data</title>
<head><center><h3>Personal Information</h3></center></head>
<body bgcolor="#D8BFD8">
<form name="persdata" action="./DataSer">
<center>
<table bgcolor="#D2B48C" border="1">
<tr>
<th>Enter ur name : </th>
<td><input type="submit" name="persdata_eurn" value
=""></td>
</tr>
<tr>
<th>Enter ur course : </th>
<td><input type="text" name="persdata_eurc" value="
"></td>
</tr>
<tr>
<td align="center"><input type="button" name="persd
ata_send" value="Send"></td>
<td align="center"><input type="reset" name="persda
ta_clear" value="Clear"></td>
</tr>
</table>
</center>
</form>
</body>
</html>

Write a servlet which accepts client request and display the client requested data on
the browser?
import [Link].*;
import [Link].*;
import [Link].*;

public class DataServ extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) thro


ws ServletException, IOException {
[Link]("text/html");
PrintWriter pw = [Link]();
String name = [Link]("persdata_eurn");
String cname = [Link]("persdata_eurc");
[Link]("<center><h3>HELLO..! Mr/Mrs. " + name + "</h3></center>
");
[Link]("<center><h3>Your COURSE is " + cname + "</h3></center>
");
}

public void doPost(HttpServletRequest req, HttpServletResponse res) thr


ows ServletException, IOException {
doGet(req, res);
}
};

[Link]:

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DataServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/getdata</url-pattern>
</servlet-mapping>
</web-app>

Note:

1. Whenever we are not entering the data in html form that data will be treated as empty
space.
2. Query string represents the data which is passed by client to the servlet through html
form. URI stands for Uniform Resource Indicator which gives the location of servlet
where it is available. URL stands for Uniform Resource Locator which gives at which
port number, in which server a particular JSP or servlet is running. ht represents a
context path which can be either a document root or a war file.

Servlets - Http Status Codes


Code Message Description

Only a part of the request has been received by the server, but as long
100 Continue
as it has not been rejected, the client should continue with the request

101 Switching Protocols The server switches protocol.

200 OK The request is OK

201 Created The request is complete, and a new resource is created

The request is accepted for processing, but the processing is not


202 Accepted
complete.

Non-authoritative
203
Information

204 No Content

205 Reset Content

206 Partial Content

A link list. The user can select a link and go to that location. Maximum
300 Multiple Choices
five addresses

301 Moved Permanently The requested page has moved to a new url

302 Found The requested page has moved temporarily to a new url

303 See Other The requested page can be found under a different url

304 Not Modified

305 Use Proxy

This code was used in a previous version. It is no longer used, but the
306 Unused
code is reserved

307 Temporary Redirect The requested page has moved temporarily to a new url.

400 Bad Request The server did not understand the request

401 Unauthorized The requested page needs a username and a password

402 Payment Required You cannot use this code yet

403 Forbidden Access is forbidden to the requested page

404 Not Found The server cannot find the requested page.

405 Method Not Allowed The method specified in the request is not allowed.

The server can only generate a response that is not accepted by the
406 Not Acceptable
client.
Proxy Authentication You must authenticate with a proxy server before this request can be
407
Required served.

408 Request Timeout The request took longer than the server was prepared to wait.

409 Conflict The request could not be completed because of a conflict.

410 Gone The requested page is no longer available.

The "Content-Length" is not defined. The server will not accept the
411 Length Required
request without it.

412 Precondition Failed The precondition given in the request evaluated to false by the server.

Request Entity Too The server will not accept the request, because the request entity is
413
Large too large.

The server will not accept the request, because the url is too long.
414 Request-url Too Long Occurs when you convert a "post" request to a "get" request with a
long query information.

Unsupported Media The server will not accept the request, because the media type is not
415
Type supported.

417 Expectation Failed

The request was not completed. The server met an unexpected


500 Internal Server Error
condition.

The request was not completed. The server did not support the
501 Not Implemented
functionality required.

The request was not completed. The server received an invalid


502 Bad Gateway
response from the upstream server.

The request was not completed. The server is temporarily


503 Service Unavailable
overloading or down.

504 Gateway Timeout The gateway has timed out.

HTTP Version Not


505 The server does not support the "http protocol" version.
Supported

Methods to Set HTTP Status Code

The following methods can be used to set HTTP Status Code in your servlet program.
These methods are available with HttpServletResponse object.
[Link]. Method & Description

public void setStatus ( int statusCode )


This method sets an arbitrary status code. The setStatus method takes an int (the
1 status code) as an argument. If your response includes a special status code and a
document, be sure to call setStatus before actually returning any of the content
with the PrintWriter.

public void sendRedirect(String url)


2 This method generates a 302 response along with a Location header giving the URL
of the new document

public void sendError(int code, String message)


3 This method sends a status code (usually 404) along with a short message that is
automatically formatted inside an HTML document and sent to the client.

HTTP Status Code Example


Following is the example which would send a 407 error code to the client browser
and browser would show you "Need authentication!!!" message.

// Import required java libraries


import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

// Extend HttpServlet class


public class showError extends HttpServlet {

// Method to handle GET method request.


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set error code and reason.


[Link](407, "Need authentication!!!" );
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Now calling the above servlet would display the following result –
HTTP Status 407 - Need authentication!!!
type Status report

messageNeed authentication!!!

descriptionThe client must first authenticate itself with the proxy (Need
authentication!!!).

Apache Tomcat/5.5.29

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.

A cookie has a name, a single value, and optional attributes such as a comment, path
and domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Steps for developing Cookie:

1. Create an object of a Cookie.

Cookie ck=new Cookie (String, Object);

For example:

Cookie c1=new Cookie ("fno","10");


Cookie c2=new Cookie ("sno","20");

2. Every cookie must be added as a part of response (add the cookie to response object).

For example:

[Link] (c1);
[Link] (c2);

Here, c1 and c2 are Cookie class objects created in step-1 and addCookie () is an
instance method present in HttpServletResponse interface.
3. In order to get the cookies we must use the following method which is present in
HttpServletRequest.

For example:

Cookie ck []=[Link] ();


if (ck!=null)
{
[Link] ("COOKIES ARE PRESENT");
}
else
{
[Link] ("COOKIES ARE NOT PRESENT");
}

4. In order to obtain cookie name, cookie value and to set its age we have to use the
following methods:

public String getName ();


public Object getValue ();
public void setMaxAge (long sec);
public long getMaxAge ();

Methods 1 and 2 are used for obtaining name and value of the cookie. Methods 3 and 4 are
used for setting and obtaining the age of the cookie.

The default age of the cookie will be -1 and it will be available only for current browsing
session and a cookie will not be available when the browser is closed, the system is rebooted.
Cookies are prepared by server side program and there will be residing in client side.
For example:

Cookie c1=new Cookie ();


[Link] (24*60*60); // setting the cookie age for 24 hours.
String s=[Link] ();
Object obj=[Link] ();

Write a java program which illustrates the concept of setting and getting cookies by
specifying maximum age, default age and obtaining the cookies which are present at
client side?

[Link]:

<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>SetCookie</servlet-class>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>ShowCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
</web-app>

[Link]:

import [Link].*;
import [Link].*;
import [Link].*;

public class SetCookie extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) thro


ws ServletException, IOException {
// default maximum age is -1, indicating cookie applies only to cur
rent browsing session
[Link]("text/html");
Cookie c1 = new Cookie("ANDHRA PRADESH", "HYDERABAD");
Cookie c2 = new Cookie("TAMILNADU", "CHENNAI");
[Link](c1);
[Link](c2);
// c3 is valid for 5mins & c4 for 10mins, regardless of user quits
browser, reboots computer
Cookie c3 = new Cookie("KARNATAKA", "BANGLORE");
Cookie c4 = new Cookie("BIHAR", "PATNA");
[Link](300);
[Link](600);
[Link](c3);
[Link](c4);
[Link]("SUCCESSFUL IN SETTING COOKIES");
}

public void doPost(HttpServletRequest req, HttpServletResponse res) thr


ows ServletException, IOException {
doGet(req, res);
}
};

[Link]:

import [Link].*;
import [Link].*;
import [Link].*;

public class ShowCookie extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) thro


ws ServletException, IOException {
[Link]("text/html");
PrintWriter pw = [Link]();
String title = "Active Cookies";
[Link]("<html><head><title>" + title + "</title></head></body>"
);
[Link]("<table border=\"1\" align=\"center\">");
[Link]("<tr><th>Cookie Name</th><th>Cookie Value</th></tr>");
Cookie ck[] = [Link]();
if (ck != null) {
for (int i = 0; i < [Link]; i++) {
[Link]("<tr><td>" + ck[i].getName() + "</td><td>" + ck[
i].getValue() + "</td></tr>");
}
} else {
[Link]("NO COOKIES PRESENT");
}
[Link]("</table></body></html>");
}

public void doPost(HttpServletRequest req, HttpServletResponse res) thr


ows ServletException, IOException {
doGet(req, res);
}
};

Implement the following screen by using cookies?


[Link]:

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServ</servlet-class>
</servlet>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServ</servlet-class>
</servlet>
<servlet>
<servlet-name>s3</servlet-name>
<servlet-class>FinalServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/test1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>s3</servlet-name>
<url-pattern>/test3</url-pattern>
</servlet-mapping>
</web-app>

[Link]:

<html>
<title>Complete example</title>
<body>
<center>
<form name="ex" action="./test1" method="post">
<table border="1">
<tr>
<th align="left">Enter ur name : </th>
<td><input type="text" name="ex_name" value=""></td>
</tr>
<tr>
<th align="left">Enter ur address : </th>
<td><textarea name="ex_add" value=""></textarea></td>
</tr>
<tr>
<th align="left">Enter ur age : </th>
<td><input type="text" name="ex_age" value=""></td>
</tr>
<tr>
<table>
<tr>
<td align="center"><input type="submit" name="ex_co
ntinue" value="Continue"></td>
</tr>
</table>
</tr>
</table>
</form>
</center>
</body>
</html>

[Link]:

import [Link].*;
import [Link].*;
import [Link].*;

public class FirstServ extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) thro


ws ServletException, IOException {
[Link]("text/html");
PrintWriter pw = [Link]();
String name = [Link]("ex_name");
String address = [Link]("ex_add");
String age = [Link]("ex_age");
Cookie c1 = new Cookie("name", name);
Cookie c2 = new Cookie("address", address);
Cookie c3 = new Cookie("age", age);
[Link](c1);
[Link](c2);
[Link](c3);
[Link]("<html><title>First Servlet</title><body bgcolor=\"green
\"><center>");
[Link]("<form name=\"first\" action=\"./test2\" method=\"post\"
><table bgcolor=\"lightblue\">");
[Link]("<tr><th>Enter ur experience : </th><td><input
type=\"text\" name=\"first_exp\"value=\"\">");
[Link]("</td></tr><tr><th>Enter ur skills : </th><td><input
type=\"text\" name=\"first_skills\" value=\"\">");
[Link]("</td></tr><table><tr><td align=\"center\"><input type=
\"submit\" name=\"first_submit\"value=\"Continue\">");
[Link]("</td></tr></table></table></form></center></body></htm
l>");
}

public void doPost(HttpServletRequest req, HttpServletResponse res) thr


ows ServletException, IOException {
doGet(req, res);
}
};

[Link]:

import [Link].*;
import [Link].*;
import [Link].*;

public class SecondServ extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) thro


ws ServletException, IOException {
[Link]("text/html");
PrintWriter pw = [Link]();
String exp = [Link]("first_exp");
String skills = [Link]("first_skills");
Cookie c4 = new Cookie("exp", exp);
Cookie c5 = new Cookie("skills", skills);
[Link](c4);
[Link](c5);
[Link]("<html><title>Second Servlet</title><body bgcolor=\"gree
n\"><center>");
[Link]("<form name=\"second\" action=\"./test3\" method
=\"post\"><table bgcolor=\"lightblue\">");
[Link]("<tr><th>Enter expected salary : </th><td><input ty
pe=\"text\" name=\"second_sal\"value=\"\">");
[Link]("</td></tr><tr><th>Enter preffered location
: </th><td><input type=\"text\"name=\"second_loc\" value=\"\">
");
[Link]("</td></tr><table><tr><td align=\"center\"><input
type=\"submit\" name=\"second_submit\" value=\"Submit\">");
[Link]("</td></tr></table></table></form></center></body></htm
l>");
}

public void doPost(HttpServletRequest req, HttpServletResponse res) thr


ows ServletException, IOException {
doGet(req, res);
}
};
Databasetable (info):

create table info (


name varchar2 (13),
addr varchar2 (33),
age number (2),
exp number (2),
skills varchar2 (13),
sal number (7,2),
loc varchar2 (17)
);
/

[Link]:

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class FinalServ extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) thro


ws ServletException, IOException {
ArrayList al = new ArrayList();
[Link]("text/html");
PrintWriter pw = [Link]();
String sal = [Link]("second_sal");
float salary = [Link](sal);
String location = [Link]("second_loc");
Cookie ck[] = [Link]();
for (int i = 0; i < [Link]; i++) {
[Link](ck[i].getValue());
}
String name = [Link](0).toString();
String address = [Link](1).toString();
String age1 = [Link](2).toString();
int age = [Link](age1);
String exp = [Link](3).toString();
int experiance = [Link](exp);
String skills = [Link](4).toString();
try {
[Link]("[Link]");
Connection con = [Link]("jdbc:oracle:thin:
@localhost:1521:Hanuman", "scott", "tiger");
PreparedStatement ps = [Link]("insert into info v
alues (?,?,?,?,?,?,?)");
[Link](1, name);
[Link](2, address);
[Link](3, age);
[Link](4, experiance);
[Link](5, skills);
[Link](6, salary);
[Link](7, location);
int j = [Link]();
if (j > 0) {
[Link]("<html><body bgcolor=\"lightblue\"><center><h1><
font color=\"red\"> Successfully ");
[Link]("Inserted</font></h1></center><a href=\"persona
[Link]\">Home</a></body></html>");
} else {
[Link]("<html><body bgcolor=\"cyan\"><center><h1><font
color=\"red\">Try Again");
[Link]("</font></h1></center><a href=\"[Link]\"
>Home</a></body></html>");
}
} catch (Exception e) {
[Link]("<html><body bgcolor=\"cyan\"><center><h1><font colo
r=\"red\">Try Again");
[Link]("</font></h1></center><a href=\"[Link]\">Home
</a></body></html>");
}
}

public void doPost(HttpServletRequest req, HttpServletResponse res) thr


ows ServletException, IOException {
doGet(req, res);
}
};

Disadvantages of Cookies:

1. When we remove the cookies which are residing in client side by going to tools -
internet options - delete cookies of browser, we cannot maintain identity of the client.
2. There is a restriction on size of the cookies (i.e., 20 cookies are permitted per web
application).
3. As and when number of cookies which leads to more network traffic flow and there is
a possibility of loosing performance of server side applications.

Session Tracking in Servlets


Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known


as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as the new
request. So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown
in the figure given below:
Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

A. Cookies
Cookies are little pieces of data delivered by the web server in the
response header and kept by the browser. Each web client can be assigned
a unique session ID by a web server. Cookies are used to keep the session
going. Cookies can be turned off by the client.

B. Hidden Form Field


The information is inserted into the web pages via the hidden form field,
which is then transferred to the server. These fields are hidden from the
user’s view.
Illustration:
<input type = hidden' name = 'session' value = '12345' >

C. URL Rewriting
With each request and return, append some more data via URL as request
parameters. URL rewriting is a better technique to keep session
management and browser operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is
established between an HTTP client and an HTTP server using the
HttpSession interface. A user session is a collection of data about a user
that spans many HTTP requests.

Illustration:
HttpSession session = [Link]( );
[Link]("username", "password");

JSP

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than
servlet such as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces
the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).
As depicted in the above diagram, JSP page is translated into Servlet by the
help of JSP translator. The JSP translator is a part of the web server which is responsible

for translating the JSP page into Servlet. After that, Servlet page is compiled by the
compiler and gets converted into the class file. Moreover, all the processes that happen
in Servlet are performed on JSP later like initialization, committing response to the
browser and destroy.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as [Link]. Put it in a folder and paste the folder in
the web-apps directory in apache tomcat to run the JSP page.

[Link]

Let's see the simple example of JSP where we are using the scriptlet tag to put Java
code in the JSP page. We will learn scriptlet tag later.

<html>
<body>
<% [Link](2*5); %>
</body>
</html>

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

Step-1: Save the JSP file using “.jsp” extension (ex- “[Link]”)
Step-2: Start the server
Step-3: Place your application inside a folder
Step-4: To execute the JSP script, simply start tomcat server and use a browser to
browse an URL of the JSP page i.e.
[Link] then you will see
the jsp file is being compiled.

How JSP more advantageous than Servlet?


• They are easy to maintain.
• No recompilation or redeployment is required.
• Less coding is required in JSP.
• JSP has access to the entire API of JAVA.
• JSP are extended version of Servlet.
Features of JSP
• Coding in JSP is easy : As it is just adding JAVA code to HTML/XML.
• Reduction in the length of Code : In JSP we use action tags, custom tags etc.
• Connection to Database is easier : It is easier to connect website to database and
allows to read or write data easily to the database.
• Make Interactive websites : In this we can create dynamic web pages which helps
user to interact in real time environment.
• Portable, Powerful, flexible and easy to maintain : as these are browser and server
independent.
• No Redeployment and No Re-Compilation : It is dynamic, secure and platform
independent so no need to re-compilation.
• Extension to Servlet : as it has all features of servlets, implicit objects and custom
tags
1. Declaration Tag : It is used to declare variables.
2. Java Scriplets : It allows us to add any number of JAVA code, variables and
expressions.
3. JSP Expression : It evaluates and convert the expression to a string.
4. JAVA Comments : It contains the text that is added for information which
has to be ignored.
o Create html page from where request will be sent to server eg [Link].
o To handle to request of user next is to create .jsp file Eg. [Link]
o Create project folder structure.
o Create XML file eg [Link].
o Create WAR file.
o Start Tomcat
o Run Application
5. It does not require advanced knowledge of JAVA
6. It is capable of handling exceptions
7. Easy to use and learn
8. It contains tags which are easy to use and understand
9. Implicit objects are there which reduces the length of code
10. It is suitable for both JAVA and non JAVA programmer
11. Difficult to debug for errors.
12. First time access leads to wastage of time
13. It’s output is HTML which lacks features.

Elements of JSP
The elements of JSP have been described below −

The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.

Following is the syntax of Scriptlet –


<% code fragment %>

You can write the XML equivalent of the above syntax as follows −

<jsp:scriptlet>

code fragment

</jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet.
Following is the simple and first example for JSP –

<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
[Link]("Your IP address is " + [Link]());
%>
</body>
</html>

NOTE − Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2


and your environment is setup as per environment setup tutorial.

Let us keep the above code in JSP file [Link] and put this file in C:\apache-
tomcat7.0.2\webapps\ROOT directory. Browse through the same using
URL [Link] The above code will generate the following
result

Creating a template JSP


One of the most important aspects of building a website is the creation of the
required templates. Sites generated by OpenCms are built by using one or more
templates that define a uniform layout of the content presented. Following the steps
described here, you should be able to get your JSP template up and running in a
short time.

Before you start


When realising a website project, one typically starts developing a template JSP by
transforming a static HTML prototype, as provided by a design agency for example,
into a template JSP. In this tutorial it is assumed that you have a prototype of your
choice available. The prototype should contain at least one HTML document
called [Link] that links to static CSS, JavaScript, and image resources relatively to
the index file. Please have your HTML prototype ready as a ZIP file.

The [Link] file should be located in a folder named templates/ whilst the static
resources should be located in a folder called resources/ like shown below:

Using Template Text


Besides JSP elements, notice that the [Link] page contains
mostly regular HTML, highlighted in Example 5-2.
Example 5-2. JSP page template text

<%@ page contentType="text/html" %>

<%@ taglib prefix="c" uri="[Link]


%>

<html>
<head>
<title>JSP is Easy</title>
</head>
<body bgcolor="white">
<h1>JSP is as easy as ...</h1>
<%-- Calculate the sum of 1 + 2 + 3 dynamically --%>
1 + 2 + 3 = <c:out value="${1 + 2 + 3}" />
</body>
</html>
USING Expressions in JSP

The expression tag is used to evaluate Java's expression within the JSP, which then
converts the result into a string and forwards the result back to the client browser via
the response object. Essentially, it is implemented for printing the result to the client
(browser). An expression tag can hold any java language expression that can be
employed as an argument to the [Link]() method.

The syntax of the expression tag in JSP looks something like

<%= expression %>


This is how the JSP container sees this when it encounters the above expression:

<%= (6*4) %>


It turns out to be:

[Link]((6*4));
It is to be noted that you will never terminate an expression using semicolon within
Expression Tag. Like this:

<%= (6*4); %>

Here is an example of an Expression tag:

<!DOCTYPE html>
<html>
<head>
<title>Expression Tag in JSP</title>
</head>
<% int rollNo = 02; %>
<body>
The next roll number is: <%= ++rollNo %>
</body>
</html>

Expressions of Values

In this chase, you have to pass the expression of values within the expression tag.

<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example1</title>
</head>
<body>
<%= 2+4*5 %>
</body>
</html>
Expression of Variables

In this case, you have to initialize a few variables, which can then be passed as the
expression of variables within the expression tag in order to evaluate the result.

<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<% int g = 60; int k = 40; int r = 20; %>
<%= g+k+r %>
</body>
</html>

What Is The Difference Between JSP And Servlet?


• The difference between Servlet and JSP is as follows:

Servlet JSP

Servlet is a java code. JSP is a HTML-based compilation code.

Writing code for servlet is harder than JSP JSP is easy to code as it is java in
as it is HTML in java. HTML.

Servlet plays a controller role in the JSP is the view in the MVC approach for
,MVC approach. showing output.

JSP is slower than Servlet because the


first step in the JSP lifecycle is the
Servlet is faster than JSP.
translation of JSP to java code and then
compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service() In JSP, we cannot override its service()
method. method.

In Servlet by default session management


In JSP session management is
is not enabled, user have to enable it
automatically enabled.
explicitly.
Servlet JSP

In Servlet we have to implement In JSP business logic is separated from


everything like business logic and presentation logic by using
presentation logic in just one servlet file. JavaBeansclient-side.

Modification in Servlet is a time-


consuming compiling task because it JSP modification is fast, just need to
includes reloading, recompiling, click the refresh button.
JavaBeans and restarting the server.

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

There is no method for running JavaScript While running the JavaScript at the client
on the client side in Servlet. side in JSP, client-side validation is used.

Packages can be imported into the JSP


Packages are to be imported on the top of
program (i.e, bottom , middleclient-side,
the program.
or top )

It cannot handle extensive data


It can handle extensive data processing.
processing very efficiently.

The facility of writing custom tags is not The facility of writing custom tags is
present. present.

Before the execution, JSP is compiled in


Servlets are hosted and executed on Web
Java Servlets and then it has a similar
Servers.
lifecycle as Servlets.

JSP | ScriptletTag
Java Server Page (JSP) is a technology for controlling the content or appearance of Web
pages through the use of servlets. Small programs that are specified in the Web page and run
on the Web server to modify the Web page before it is sent to the user who requested it.
There are total three Scripting Element in JSP

1. Scriptlet tag
2. Expression tag
3. Declaration tag

Scriptlet tag
This tag allow user to insert java code in JSP. The statement which is written will be moved
to jspservice() using JSP container while generating servlet from JSP. When client make a
request, JSP service method is invoked and after that the content which is written inside the
scriptlet tag executes.

Html program

<html>
<body>
<% [Link]("Dayananda Sagar college of Engineering"); %> <!-- scriptlet tag -->
</body>
</html>

Explanation
• The Syntax of JSP Scriptlet tag is begin with ”.
• We can write our java code inside this tag.
• In java we use [Link] for printing anything on console. In JSP, we use
only [Link] to write something on console because the out we’re referring to isn’t
[Link], it’s a variable in the effective method that wraps our JSP page.
• [Link] writes to the servlet container’s console (usually a log file); out is a
different class entirely which writes to the output stream for the generated response.

Here we are creating and HTML file to take username from [Link] this file as [Link].
<!--[Link] -->
<!-- Example of JSP code which prints the Username -->
<html>
<body>
<form action="[Link]">
<!-- move the control to [Link] when Submit button is click -->

Enter Username:
<input type="text" name="username">
<input type="submit" value="Submit"><br/>

</form>
</body>
</html>

Here we are creating A jsp file names as [Link]

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]
<html>

<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
<%
String name=[Link]("username");
[Link]("Hello "+name);
%>
</body>

</html>
JSP| Declaration Tag

In JSP (JavaServer Pages), the `<%! ... %>` declaration tag is used to declare fields and
methods that are inserted directly into the servlet class generated by the JSP container during
translation. These declarations are typically placed outside of the main service method
(`_jspService()`) and are therefore accessible to all parts of the JSP page.

Here is the syntax for the declaration tag in JSP:

```jsp
<%!
// Declare fields or methods here

// Example: declaring a field


private String myField;

// Example: declaring a method


public void myMethod() {
// Method body
}
%>
```

Key Points:
- The `<%! ... %>` tag allows you to declare instance variables, methods, and even static
variables and methods.
- Declarations within `<%! ... %>` are used to define elements of the servlet class, which is
generated from the JSP file by the servlet container.
- Variables and methods declared within `<%! ... %>` are accessible throughout the JSP page,
similar to how fields and methods are accessible within a class.

Example Usage:

```jsp
<%@ page language="java" %>
<html>
<head>
<title>Declaration Tag Example</title>
</head>
<body>
<%!
private String message = "Hello, World!";

public void printMessage() {


[Link](message);
}
%>

<h1>Using Declaration Tag in JSP</h1>


<%
printMessage();
%>
</body>
</html>
```

In this example:
- The `<%! ... %>` block declares a private field `message` and a public method
`printMessage()`.
- The `printMessage()` method is then called within regular scriptlet tags (`<% ... %>`) to
output the message on the JSP page.

This demonstrates how to use the declaration tag to define reusable fields and methods within
a JSP page.

Introduction to Spring Framework


Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of
frameworks because it provides support to various frameworks such
as Struts, Hibernate, Tapestry, EJB, JSF, etc. The framework, in broader sense, can be
defined as a structure where we find solution of the various technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context,
ORM, WEB MVC etc. We will learn these modules in next page. Let's understand the
IOC and Dependency Injection first.

Frameworks are pre-established structures or sets of tools and libraries that provide a
foundation to streamline the development of software applications. They are designed to
facilitate the creation and implementation of solutions to common problems in software
development, such as handling input/output operations, managing databases, or implementing
user interfaces.

Key characteristics of frameworks include:


1. Abstraction: Frameworks often abstract common functionalities into reusable components,
allowing developers to focus more on application-specific logic rather than low-level details.

2. Reusability: They promote reusability of code and best practices across projects, which can
improve development efficiency and maintainability.

3. Extensibility: Frameworks are typically designed to be extensible, allowing developers to


customize and extend their functionality as per the specific requirements of their projects.

4. Standardization: They often enforce standard practices and conventions, making it easier
for developers to collaborate and understand each other's code.

5. Integration: Many frameworks provide seamless integration with other tools and libraries,
reducing the effort needed to incorporate third-party components into an application.

Frameworks can be categorized based on their purpose, such as web development frameworks
(e.g., Django, Ruby on Rails), front-end frameworks (e.g., React, Angular), or general-purpose
frameworks (e.g., Spring for Java, .NET Framework for C#).

In summary, frameworks provide developers with a structured approach to building software


applications, offering ready-made solutions to common development challenges and promoting
efficient, standardized, and maintainable codebases.

Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of frameworks because
it provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc.
The framework, in broader sense, can be defined as a structure where we find solution of the
various technical problems.

The Spring Framework is an open-source framework for building Java applications. It provides
comprehensive infrastructure support and a lightweight container that helps developers create
high-performing, reusable, and easily maintainable applications.

Key features of the Spring Framework include:


1. Inversion of Control (IoC): Also known as Dependency Injection (DI), Spring manages
the dependencies between objects, allowing for loosely coupled components and easier unit
testing.

2. Aspect-Oriented Programming (AOP): Spring supports AOP, which allows developers to


modularize cross-cutting concerns such as logging, security, and transaction management.
3. Transaction Management: Spring provides a consistent transaction management interface
that can scale from a local transaction (using a single database) to global transactions (involving
multiple resources).

4. Model-View-Controller (MVC): Spring MVC framework is a robust and flexible


framework for developing web applications. It follows the MVC architectural pattern and
integrates well with other Spring components.

5. Data Access: Spring provides support for JDBC (Java Database Connectivity), ORM
(Object-Relational Mapping) frameworks like Hibernate, and data access templates,
simplifying database access and reducing boilerplate code.

6. Integration: Spring supports integration with other technologies like JMS (Java Message
Service), JMX (Java Management Extensions), JTA (Java Transaction API), and various web
frameworks.

7. Testing: Spring provides support for testing through its integration with JUnit and mock
objects, making it easier to write unit tests for Spring-based applications.

Initializing a Spring application


Initializing a Spring application typically involves several steps to set up the environment,
configure dependencies, and bootstrap the application. Here’s a basic outline of how you can
initialize a Spring application:

1. Project Setup
First, you need to set up a Java project in your preferred Integrated Development Environment
(IDE) like IntelliJ IDEA, Eclipse, or VS Code. You can use tools like Maven or Gradle to
manage dependencies.

2. Adding Spring Dependencies


In your project configuration file (e.g., `[Link]` for Maven or `[Link]` for Gradle),
include dependencies for the Spring Framework components you need. For a basic Spring
application, you typically need `spring-context`, `spring-core`, and potentially other modules
like `spring-web` for web applications.

Example `[Link]` snippet for Maven:

```xml
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>${[Link]}</version>
</dependency>
<!-- Other dependencies as needed -->
</dependencies>
```

3. Configuration
Create a configuration file where you define Spring beans, which are Java objects managed by
the Spring IoC container. This can be done using XML configuration
(`[Link]`) or Java-based configuration (`@Configuration` classes).

#### XML Configuration Example (`[Link]`):

```xml
<!-- Define a bean -->
<bean id="myService" class="[Link]">
<!-- Dependencies can be injected here -->
</bean>
```

#### Java Configuration Example (using `@Configuration`):

```java
@Configuration
public class AppConfig {

@Bean
public MyService myService() {
return new MyService();
}

// Other beans and configurations


}
```

4. Bootstrap the Spring Context


In your main application class (typically annotated with `@SpringBootApplication` for Spring
Boot applications), initialize the Spring ApplicationContext.

#### Example Main Class:

```java
import [Link];
import [Link];
import [Link];
import [Link];

@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {


[Link]([Link], args);

// Or, if not using Spring Boot:


// ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);

// Example of getting a bean from the context:


// MyService service = [Link]([Link]);
// [Link]();
}
}
```

5. Run the Application


Run your main application class. If you’re using Spring Boot (`@SpringBootApplication`), it
automatically scans for components and configurations and starts a web server if necessary (for
web applications). If you’re not using Spring Boot, manually create an `ApplicationContext`
to initialize your Spring beans.

Additional Steps for Web Applications


If your Spring application is a web application, you might need additional configurations for
servlet mappings, filters, and other web-related components. Spring Boot simplifies this
process with auto-configuration based on dependencies and properties.

By following these steps, you can effectively initialize and run a Spring application, leveraging
its powerful features for dependency injection, configuration management, and more.
Overall, the Spring Framework promotes good design principles, such as modularity,
flexibility, and separation of concerns, making it a popular choice for enterprise-level Java
development.

Steps for writing a Spring application


Writing a Spring application involves several steps to set up the environment, configure
components, and implement functionality. Here’s a structured approach to writing a basic
Spring application:

1. Set Up Your Development Environment


Ensure you have Java Development Kit (JDK) installed on your system. You can use an
Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code for
easier development.

2. Create a Maven or Gradle Project

Choose a build tool like Maven or Gradle to manage dependencies and build your project.
Here’s a basic example using Maven:

#### Maven Project Structure (`[Link]`):

```xml
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>spring-demo</artifactId>
<version>1.0.0</version>

<parent>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.1</version>
</parent>

<dependencies>
<!-- Spring Boot Starter for web applications -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Other dependencies as needed -->
</dependencies>

<properties>
<[Link]>11</[Link]>
</properties>

</project>
```

3. Define Application Components

Create a Controller
Create a Spring MVC controller to handle HTTP requests. Controllers map incoming requests
to appropriate methods and return responses.

```java
import [Link];
import [Link];

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello() {
return "Hello, Spring!";
}
}
```

Create a Service (Optional)

Create a service class to encapsulate business logic. Services are typically used to perform
operations that are more complex than what controllers should handle directly.

```java
import [Link];

@Service
public class HelloService {

public String getMessage() {


return "Hello from the service!";
}
}
```

4. Configure Your Application

Application Configuration (`[Link]` for Spring Boot)

```
properties
# Application properties
[Link]=8080
```
5. Run Your Application

Main Application Class

```java
import [Link];
import [Link];

@SpringBootApplication
public class SpringDemoApplication {

public static void main(String[] args) {


[Link]([Link], args);
}
}
```

6. Test Your Application

Open a web browser or use tools like curl or Postman to access your application endpoints:

- Access `[Link] to see the response from your controller.

7. Expand Your Application

As your application grows, you can add more components, services, repositories (for database
access), and configurations as needed. Spring provides extensive support for various aspects of
application development, including security, data access, messaging, and more.

Additional Tips

• Dependency Injection: Utilize Spring’s Dependency Injection (DI) to manage


dependencies between components.
• Annotations: Take advantage of annotations like `@Autowired`, `@Component`,
`@Service`, `@Repository`, etc., to simplify configuration and component
scanning.
• Testing: Write unit and integration tests using frameworks like JUnit and Spring’s
testing support (`@SpringBootTest`, `@WebMvcTest`, etc.).
By following these steps, you can effectively build and run a basic Spring application,
leveraging Spring’s powerful features for enterprise-grade Java development.

The Spring Framework is a comprehensive application framework for Java programming


language that provides infrastructure support for developing Java applications. Here's a high-
level overview of the architecture of the Spring Framework along with a simplified diagram:

Architecture Overview

1. Core Container: This is the foundation of the Spring Framework and includes the following
modules:
- Beans: Provides IoC (Inversion of Control) for managing Java objects.
- Core: Provides fundamental utilities and core functionalities.
- Context: Builds on the Beans module to provide additional functionalities such as support
for internationalization, event propagation, and resource loading.

2. Data Access/Integration: This layer provides support to integrate data access frameworks
and databases seamlessly.
- JDBC: Provides a JDBC-abstraction layer that removes the need for tedious JDBC coding.
- ORM: Supports integration with Object-Relational Mapping frameworks like Hibernate,
JPA (Java Persistence API), etc.
- Transaction: Supports programmatic and declarative transaction management for classes
implementing special interfaces and those annotated with @Transactional.

3. Web: Provides support for building web applications.


- Web: Provides basic web-oriented integration features, such as multipart file upload
functionality and the initialization of the IoC container using servlet listeners and a web-
oriented application context.
- Web-MVC: Contains Spring's Model-View-Controller (MVC) implementation for building
web applications.

4. AOP (Aspect-Oriented Programming): Implements cross-cutting concerns separately


from the main application logic.
- AOP: Provides aspect-oriented programming implementation allowing you to define
method-interceptors and pointcuts to cleanly decouple code that implements functionality that
should be separated.

5. Test: Provides support for unit testing and integration testing of Spring components.

Here's a simplified diagram representing the architecture of the Spring Framework:


Explanation:
- Core Container: Provides the fundamental functionality of the framework. It includes the
Beans module for IoC, Core for utilities, and Context for advanced features.
- Data Access/Integration: Supports various data access technologies such as JDBC and ORM
frameworks.
- Web: Includes the Web module and Web-MVC for building web applications.
- AOP: Implements Aspect-Oriented Programming for modularization of cross-cutting
concerns.
- Test: Provides support for testing Spring applications.

This diagram illustrates how different modules within the Spring Framework interact and
provide various functionalities to developers building Java applications.

Common questions

Powered by AI

JSP provides several advantages over Servlets in Java web development. JSP allows embedding Java code directly within HTML pages using various tags, which simplifies the process of creating dynamic pages compared to the more code-centric Servlet approach . JSPs require less code to write because they can use various tags, JSTL, and implicit objects, which reduces the length of code significantly . Unlike Servlets, JSP changes do not require recompilation or redeployment of the entire application, which makes them easier to maintain and update . Additionally, JSP is part of the MVC architecture, serving as the view layer that handles the display logic, making it more efficient for UI development compared to Servlets, which are more suited for the controller layer .

When parameters are introduced in Java constructors, they allow initialization of objects with specific values at the time of creation. Constructors with parameters are used to set initial states of the object attributes dynamically based on inputs provided to the constructor . In such contexts, the 'this' keyword plays a crucial role in differentiating between class attributes and parameters that share the same name. The 'this' keyword is used for clarity and disambiguation, ensuring that the right instance variable is being set . For example, if a constructor parameter and a class attribute have identical names, using 'this.attributeName = parameterName;' ensures that the constructor parameter's value is correctly assigned to the corresponding instance attribute, preventing variable shadowing and enhancing code readability .

While both 'throws' and 'try-catch' blocks are used in Java for exception handling, they serve different purposes and are used in different contexts. The 'throws' keyword is used in the method signature to indicate that the method can throw specified exceptions that need to be handled by the method that calls it . This mechanism informs the caller of the exceptions it should anticipate and is primarily used to propagate exceptions to higher-level methods for centralized handling. In contrast, 'try-catch' blocks are used to directly handle exceptions within the method. When an exception is anticipated during the execution of code within a try block, the associated catch block is where the exception is caught and processed, allowing the programmer to define the course of action, ensuring that the program continues to run smoothly even when errors occur . Therefore, 'throws' is about declaring possible exceptions to callers, whereas 'try-catch' is about handling exceptions immediately when and where they occur .

The life cycle of a JSP page involves several stages that facilitate the creation of dynamic web pages. Firstly, the JSP is translated into a Servlet, which entails converting the JSP page code into Servlet code by the JSP translator, a part of the web server . This translated Servlet is then compiled into an executable class file. After the class is loaded by the classloader, an instance of the Servlet is created, and the 'jspInit()' method is invoked to initialize the Servlet . During request processing, the '_jspService()' method is called to handle requests. Finally, when the Servlet is no longer needed, 'jspDestroy()' is called to clean up any resources . JSP's advantage in generating dynamic content lies in its design; HTML is embedded with Java code using tags, making it straightforward to create web pages that respond dynamically to user inputs and other conditions, facilitating an interactive user experience .

Inheritance in Java is a cornerstone concept of object-oriented programming (OOP) that allows one class (the child) to inherit fields and methods from another class (the parent). This mechanism promotes code reuse, enabling developers to build upon existing classes without rewriting code, thus reducing redundancy and enhancing maintainability. Inheritance facilitates the extension of classes by allowing new functionality to be added to derived classes without modifying the existing code of the parent class . This is exemplified in class hierarchies where the child class can extend and override inherited methods to provide more specialized behavior, realizing polymorphism. This capability promotes scalable architecture in software development, where complex systems can be developed incrementally leveraging already validated and tested base class implementations. By using inheritance wisely, programmers can design systems that are easier to extend and maintain, enhancing collaboration and evolution of codebases over time .

The 'this' keyword in Java is crucial for differentiating class fields from parameters when their names are identical. In constructors, 'this' is used to refer explicitly to instance variables of the current object, which helps resolve conflicts that occur when class fields are shadowed by method or constructor parameters with the same name. For instance, during constructor implementation, a common use is to assign a parameter value to an instance variable, where 'this.variable = variable;' is a standard practice, making clear that the instance of the class variable is being set . This eliminates ambiguity and ensures clarity in code, making it easier for developers to understand the purpose and flow of attribute assignments within class methods and constructors .

The 'final' keyword in Java is used to restrict modifications. When applied to variables, it makes the value of the variable constant, meaning it cannot be changed after initialization. As an example, a final variable speedlimit assigned a value cannot be changed later, and attempting to do so results in a compile-time error . When used with methods, the final keyword prevents the method from being overridden, as shown with the run() method in the Bike class, which cannot be overridden in a subclass without causing a compile-time error . When applied to classes, it prevents the class from being subclassed, thereby prohibiting any class inheritance. An example is the final class Bike, which cannot be extended by any other class .

The 'throws' keyword in Java is used in method signatures to declare that a method may throw certain types of exceptions, specifically checked exceptions which need to be anticipated by the caller of the method . This informs the caller about the exceptions that might be thrown, allowing for better handling by making the caller either catch the exception or further declare it using 'throws' . The main advantage of using 'throws' is that it enables the propagation of exceptions up the call stack, allowing higher levels of the application to handle exceptions appropriately. This can make code maintenance easier and increase readability by clearly specifying which method might have potential issues that need handling .

Static methods and instance methods in Java differ significantly in performance and functionality. Static methods belong to the class rather than any specific instance of the class, allowing them to be called without creating an object of the class . This can result in performance benefits as memory allocation is reduced, and they are faster as they don't need an instance to be invoked. However, static methods cannot access instance variables or non-static methods directly because they are not associated with any object instance and thus do not have access to any instance-specific data . In contrast, instance methods require an object of the class to be created first as they operate on the instance fields and can access other instance methods and variables within the class . These methods offer functionality related to the specific data of the object and are typically used when operations depend on the state of an object. The choice between static and instance methods depends on whether an operation pertains to a specific instance or the class as a whole .

JSP expression tags simplify the embedding of Java code within HTML, allowing dynamic data to be output easily and improving the efficiency of coding web pages. The syntax of a JSP expression tag, encapsulated in '<%= ... %>', directly outputs the result of the Java expression into the client response without the need for explicit 'out.print()' statements . This streamlines the process of generating HTML content dynamically, as it reduces the verbosity of the code by avoiding repetitive boilerplate code associated with other forms of output . By effectively bridging Java code and HTML, JSP expression tags contribute to increased efficiency of webpage development and maintenance. They offer a quick and intuitive way for developers to incorporate Java expressions that render dynamic content based on user input or other data, enhancing the overall user interface experience by providing real-time interaction capabilities .

You might also like