Java Programming Basics and Concepts
Java Programming Basics and Concepts
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".
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
• 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).
Portable- Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
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++.
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.
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
• 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]().
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
Type casting takes place during the Whereas type conversion is done at
5.
program design by programmer. the compile time.
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
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:
[Link](cars[0]);
// Outputs Volvo
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:
[Link]([Link]);
// Outputs 4
To create an object of Main, specify the class name, followed by the object name,
and use the keyword new:
int x = 5;
[Link](Obj.x);
}
Multiple Objects
int x = 5;
[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.
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
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:
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.
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.
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.
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.
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
public Main() {
x = 5; // Set the initial value for the class attribute 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:
int x;
public Main(int y) {
x = y;
[Link](myObj.x);
// Outputs 5
this keyword
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".
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.
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.
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.
@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");
}
}
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.
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));
}}
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));
}}
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");}
}
Consider the following Java program, in which we have used different constructors in the
class.
Student(){
[Link]("this a default constructor");
}
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.
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.
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.
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");}
}
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]();
}
}
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
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.
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.
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.
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.
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
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.
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]);
}
}
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...
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...
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...
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
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
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...
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
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]();
}
}
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.
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.
Note :
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.
Syntax:
interface <interface_name>{
interface printable{
void print();
}
class A6 implements printable{
public void print(){[Link]("Hello");}
In this tutorial, we will learn about Java exceptions, it's types, and the difference
between checked and unchecked exceptions.
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:
1. Checked Exception
2. Unchecked Exception
3. Error
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
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.
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.
[Link]
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.
The catch block must be used after the try block only. You can use multiple catch
block with a single try block.
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
}
....
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
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 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.
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.
[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...");
}
}
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.
[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.
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.
[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]
try {
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]
try {
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.
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}
}
}
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.
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 [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.
• 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:
</select>
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
// defining a class
public class ColServlet extends HttpServlet
// 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");
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
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.
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.
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:
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
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:
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:
SingleThreadModel {
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]
// 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");
[Link]("welcome");
[Link](" to servlet");
C. File: [Link]
<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.
<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].*;
[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.
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
Non-authoritative
203
Information
204 No 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
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
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.
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.
The request was not completed. The server did not support the
501 Not Implemented
functionality required.
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
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.
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.
For example:
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:
4. In order to obtain cookie name, cookie value and to set its age we have to use the
following methods:
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:
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].*;
[Link]:
import [Link].*;
import [Link].*;
import [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].*;
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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.
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?
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.
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.
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.
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.
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.
[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>
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.
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.
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>
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
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:
<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.
[Link]((6*4));
It is to be noted that you will never terminate an expression using semicolon within
Expression Tag. Like this:
<!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>
Servlet JSP
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.
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.
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.
The facility of writing custom tags is not The facility of writing custom tags is
present. present.
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>
<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.
```jsp
<%!
// Declare fields or methods here
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!";
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.
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.
2. Reusability: They promote reusability of code and best practices across projects, which can
improve development efficiency and maintainability.
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#).
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.
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.
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.
```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
<!-- Define a bean -->
<bean id="myService" class="[Link]">
<!-- Dependencies can be injected here -->
</bean>
```
```java
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
```java
import [Link];
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class MyApplication {
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.
Choose a build tool like Maven or Gradle to manage dependencies and build your project.
Here’s a basic example using Maven:
```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>
```
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 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 {
```
properties
# Application properties
[Link]=8080
```
5. Run Your Application
```java
import [Link];
import [Link];
@SpringBootApplication
public class SpringDemoApplication {
Open a web browser or use tools like curl or Postman to access your application endpoints:
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
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.
5. Test: Provides support for unit testing and integration testing of Spring components.
This diagram illustrates how different modules within the Spring Framework interact and
provide various functionalities to developers building Java applications.
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 .