0% found this document useful (0 votes)
2 views15 pages

Java Notes

Java is an object-oriented programming language characterized by its simplicity, portability, and security. It supports key OOP concepts such as classes, inheritance, and polymorphism, and is designed to be platform-independent, allowing code to run on various systems without modification. Java also features automatic garbage collection, multithreading, and dynamic loading of classes, making it robust and efficient for application development.

Uploaded by

samsri.works
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)
2 views15 pages

Java Notes

Java is an object-oriented programming language characterized by its simplicity, portability, and security. It supports key OOP concepts such as classes, inheritance, and polymorphism, and is designed to be platform-independent, allowing code to run on various systems without modification. Java also features automatic garbage collection, multithreading, and dynamic loading of classes, making it robust and efficient for application development.

Uploaded by

samsri.works
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

Features of Java Object-oriented

A list of most important features of Java language is given below. 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
incorporates both data and behavior.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed Java is platform independent because it is different from other languages like C, C++, etc. which
12. Dynamic 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.
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
Sun, Java language is a simple programming language because: 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
Java has removed many complicated and rarely-used features, for example, explicit Anywhere(WORA).
pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage Secured
Collection in Java.
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
No explicit pointer

Java Programs run inside a virtual machine sandbox Classes and Objects:
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc. Classes
Robust:
Robust simply means strong. Java is robust because: A Class is a collection of data members and member functions. Data members are used
It uses strong memory management. to store information; member functions are used to perform operations on data.
There is a lack of pointers that avoids security problems. A class is a group of objects which have common properties.
There is automatic garbage collection in java which runs on the Java Virtual Machine to It is a template or blueprint from which objects are created.
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 A class in Java can contains:
make Java robust.

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.

Portable:Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation. Syntax to declare a class:
High-performance: class ClassName
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
Fileds or Data members;
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
Methods or member functions;
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. Field declarations Syntax:
Multi-threaded:A thread is like a separate program, executing concurrently. We can write Java Class classname
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 Datatype variablename1;
area. Threads are important for multi-media, Web applications, etc. Datatype variablename2;
Dynamic:Java is a dynamic language. It supports dynamic loading of classes. It means classes .
are loaded on demand. It also supports functions from its native languages, i.e., C and C++. .
Java supports dynamic compilation and automatic memory management (garbage .
collection). Datatype variablenamen;
}
Method declaration Syntax: Write briefly about Type Casting:
Returntype methodname(ArgumentsList)
{ Converting one data type variable value into another data type variable is called type
Method body; casting.
} (OR)
Assigning a value of one type to a variable of another type is known as Type Casting.
Object:
Example:
An entity that has state and behaviour is known as an object e.g. chair, bike, marker, pen, int x = 10;
table, car etc. It can be physical or logical. byte y = (byte)x;
An object has three characteristics:
State : Represents the data (value) of an object. In Java, type casting is classified into two types,
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
Widening Casting(Implicit)
etc.
Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.

Here we are converting byte to short, short to int, int to long, long to float and float to double.

Narrowing Casting (Explicitly done)

Syntax to declare a object:


Classname objectname=new Classname( );

Programs: Programs on Classes and objects refer the class notes.


Here we are converting Here we are converting double to float, float to long, long to int, int to
short and short to byte.

Widening or Automatic type converion

Automatic Type casting take place when,

The two types are compatible

The target type is larger than the source type


}
Example :
OUTPUT:
class Test
{ Double value 100.04
public static void main(String[] args) Long value 100
{ Int value 100
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required Write briefly about Garbage Collection
[Link]("Int value "+i);
[Link]("Long value "+l); In Java destruction of object from memory is done automatically by the JVM.
[Link]("Float value "+f); This technique is called Garbage Collection. This is accomplished by the JVM. Unlike
} C++ there is no explicit need to destroy object.

} Advantages of Garbage Collection

OUTPUT: 1. Programmer doesn't need to worry about dereferencing an object.


2. It is done automatically by JVM.
Int value 100 3. Increases memory efficiency and decreases the chances for memory leak.
Long value 100
Float value 100.0 finalize() method
Narrowing or Explicit type conversion:
Sometime an object will need to perform some specific task before it is destroyed such as
When you are assigning a larger type value to a variable of smaller type, then you need to closing an open connection or releasing any resources held. To handle such situation
perform explicit type casting. finalize() method is used.
finalize() method is called by garbage collection before collecting object.
Example :

class Test

{
public static void main(String[] args) Syntax of finalize() method
{
double d = 100.04; protected void finalize()
long l = (long)d; //explicit type casting required {
int i = (int)l; //explicit type casting required //finalize-code
}
[Link]("Double value "+d);
[Link]("Long value "+l); Note:
[Link]("Int value "+i);
}
1. finalize() method is defined in [Link] class, therefore it is available to all the Abstract class in Java
classes. A class which is declared as abstract is known as an abstract class. It can have abstract and
2. finalize() method is declare as proctected/public inside Object class. non-abstract methods. It needs to be extended and its method implemented. It cannot be
3. finalize() method gets called only once by a thread named GC (Garbage Collector)thread. instantiated.
An abstract class must be declared with an abstract keyword.
gc() Method
gc() method is used to call garbage collector explicitly. It only requests the JVM for garbage It can have abstract and non-abstract methods.
collection. This method is present in System and Runtime class. It cannot be instantiated.
It can have constructors and static methods also.
Example for gc() method.
It can have final methods.
public class Test
{

public static void main(String[] args)


{
Test t = new Test();
t=null;
[Link]();
}
public void finalize()
{
[Link]("Garbage Collected");
}
}

OUTPUT: Garbage Collected

Can the Garbage Collection be forced explicitly ?

No, the Garbage Collection can not be forced explicitly. We may request JVM for garbage
collection by calling [Link]() method.
Syntax:
Abstract Methods and classes:
Abstraction is a process of hiding the implementation details and showing only abstract class classname
functionality to the user.
Ways to achieve Abstraction: {
There are two ways to achieve abstraction in java
Body of the abstract class
1. Abstract class (0 to 100%)
2. Interface (100%) }

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an [Link]("Rate of Interest is: "+[Link]( ));
abstract method. }
}
Syntax:
Explain in detail about Final variables, Final Methods and Final Classes.
Abstract returntype methodname (ArgumentsList); //no method body
The final keyword in java is used to restrict the user.
Program: Write a Java Program on abstract methods and abstract classes The java final keyword can be used in many contexts.
Final can be:
In this example, Bank is an abstract class that contains only one abstract method 1. variable
getRateOfInterset( ). Its implementation is provided by the SBI,PNB classes. 2. method
3. class
abstract class Bank
{
abstract int getRateOfInterest( );
}
class SBI extends Bank
{
int getRateOfInterest ()
{
return 7;
}
}
class PNB extends Bank
1) Java final variable
{
If you make any variable as final, you cannot change the value of final variable
int getRateOfInterest() The final variables will be constant.
{
return 8; 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 Bike
class TestBank {
{ final int speedlimit=90;//final variable
public static void main(String args[ ]) void run()
{
{
speedlimit=400;
Bank b; }
b=new SBI( ); public static void main(String args[])
[Link]("Rate of Interest is: "+[Link]( )); {
b=new PNB( ); Bike obj=new Bike( );
[Link](); }
} }
}
2) Java final method class Honda1 extends Bike
{
If you make any method as final, you cannot override it. void run()
Final Methods are not used in derived classes. {
[Link]("running safely with 100kmph");
Example of final method }
public static void main(String args[])
class Bike
{
{
Honda1 honda= new Honda1();
final void run()
[Link]();
{
}
[Link]("running");
}
}
}
JVM:
class Honda extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}
public static void main(String args[])
{
Honda h= new Honda();
[Link]();
}
}
Here in above example we are using final method run( ) in derived class. This is violating
the rule of final methods. That is we cannot use same function in derived class. That means, we
cannot override the methods.
3) Java final class
If you make any class as final, you cannot extend it. That is, we cannot use final
class as base class for other classes.
JVM is a engine that provides runtime environment to drive the Java Code or applications. It
This means, we cannot inherit properties from final class
converts Java bytecode into machines language. JVM is a part of JRE(Java Run Environment). It
Example of final class
stands for Java Virtual Machine
final class Bike
{ 4. First, Java code is complied into bytecode. This bytecode gets interpreted on different
Void run( ) machines
{ 5. Between host system and Java source, Bytecode is an intermediary language.
[Link]("running safely with 90kmph"); 6. JVM is responsible for allocating memory space.

Section Description

Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are
optional.

Three types of comment line representation:


Single line (//)
Multi line (/* */)
Documentation Comments (/** */ )

Import This line indicates that if you want to use a class of another package, then
statements you can do this by importing it directly into your program.
Example:
import [Link].*;
Generating machine code is a two step process:
Interface Interfaces are like a class that includes a group of method declarations. It's
statement an optional section and can be used when programmers want to
Step 1:The process of compiling a java program into bytecode which is also reffered to as virtual implement multiple inheritances within a program.
machine code.
Class A Java program may contain several class definitions. Classes are the
Step 2:The virtual machine code is not machine specific. The machine specific code is generated
Definition main and essential elements of any Java program.
by the java interpreter. The process of converting bytecode into machine code is performed by
java Interpreter
Main Method Every Java stand-alone program requires the main method as the starting
Java Program Structure: Class point of the program. This is an essential part of a Java program. There
may be many classes in a Java program, and only one class defines the
main method. Methods contain data type declaration and executable
statements

History of Java: The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital cable television industry
at the time. The history of java starts with Green Team. Java team members (also known as
Green Team), initiated this project to develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was suited for internet programming. Later, Java technology
was incorporated by Netscape. The principles for creating Java programming were "Simple,
Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted and Dynamic".
UNIT-II

In java, programmers can create several classes &Interface. After creating these classes and
interface, it is better if they are divided into some groups depending on their relationship. Thus,
the classes and interface which handle similar or same task are put into the same directory or folder,
which is also known as package.

epresents a directory that contain related


group of classes & interface.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, TYPES OF PACKAGES
etc. There are given the significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in There are basically only 2 types of java packages. They are as follow :
June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set-top boxes. System Packages or Java API/ Built -in Packages
3) Firstly, it was called "Greentalk" by James Gosling, and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project. User Defined Packages.

SYSTEM PACKAGES OR JAVA API


Why Java named "Oak"?
As there are built in methods , java also provides inbuilt packages which contain lots of classes
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like
&interfaces. These classes inside the packages are already defined & we can use them by importing
U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak relevant package in our program. Java has an extensive library of packages, a programmer need
Technologies. not think about logic for doing any task.
Why Java Programming named "Java"?
JAVA SYSTEM PACKAGES & THEIR CLASSES
7) Why had they chosen java name for java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They [Link]
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say. Language Support classes. These are classes that java compiler itself uses & therefore they are
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was automatically imported. They include classes for primitive types, strings, maths function, threads
so unique, most of the team members preferred Java than other names.
8) Java is an island of Indonesia where first coffee was produced (called java coffee). &exception.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of java .util
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995. Language Utility classes such as vector, hash tables ,random numbers, date etc.
12) JDK 1.0 released in(January 23, 1996).
[Link]

Input /Output support classes. They provide facilities for the input & output of data

[Link]

Set of classes for implementing graphical user interface. They include classes for windows, Example :
buttons, list, menus & so on.
package myPackage;
[Link]
public class class1
Classes for networking. They include classes for communicating with local computers as well as
with internet servers. {

[Link] -------------

// Body of class1
Classes for creating & implementing applets.
}
USER DEFINED PACKAGES :

The users of the Java language can also create their own packages. They are called user-defined In the above example, myPackage is the name of the package. The class class1 is now considered
packages. User defined packages can also be imported into other classes & used exactly in the as a part of this package. This listing would be saved as a file called [Link] & located in a
same way as the Built in packages. directory named mypackage.

STEPS FOR CREATING PACKAGE :To create a user defined package the following steps
Creating User Defined Packages
should be involved :-
Syntax :

package packageName; 1: Declare the package at the beginning of a file using the syntax :

package packageName;
public class className
2: Define the class that is to be put in the package & declare it public.
{

------------- Java also supports the concept of package hierarchy. This is done by specifying multiple names in
a package statement, seprated by dots (.).
// Body of className
Ex :- package [Link];
------------
ACCESSING A PACKAGE
}
Java package can be accessed either using a fully qualifiedclass name or using a shortcut approach
We must first declare the name of the package using the package keyword followed by the package through the import statement.
name. This must be the first statement in a Java source file. Then define a classes as normally as
define a class. Syntax :

import package1[.package2][.package3].classname;
Here, package1 is the name of the top level package, package2 is the name of the package that is How to run java package program
inside the package & so on. We can have any number of packages in a package hierarchy. Finally
the explicit classname is specified. The import statement must end with a semicolon (;). The You need to use fully qualified name e.g. [Link] etc to run the class.
import statement should appear before any class definitions in a source file. Multiple import
statements are allowed. To Compile: javac d . [Link]
To Run: java [Link]
Ex :

import [Link];
Interfaces in Java
or
An interface in java is a blueprint of a class. It has static constants and abstract methods.
import firstpackage.*;
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
Simple example of java package in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.
The package keyword is used to create a package in java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
1. //save as [Link]
2. package mypack;
How to declare an interface?An interface is declared by using the interface keyword. It
3. public class Simple{
provides total abstraction; means all the methods in an interface are declared with the empty
4. public static void main(String args[]){
body, and all the fields are public, static and final by default. A class that implements an
5. [Link]("Welcome to package");
interface must implement all the methods declared in the interface.
6. }
7. } The relationship between classes and interfaces

How to compile java packageIf you are not using any IDE, you need to follow the syntax given As shown in the figure given below, a class extends another class, an interface extends another
below: interface, but a class implements an interface

javac -d directory javafilename


For example
javac -d . [Link]

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

public void compute();

class Demo5 implements marks

int rno;

String name;

int m1,m2,m3;

public void store(int a,String b)

{
Extending Interfaces
rno=a;
When one interface inherits from another interface, that sub-interface inherits all the methods
and constants that its super interface declared. In addition, it can also declare new abstract name=b;
methods and constants. To extend an interface, you use the extends keyword just as you do in
the class definition, an interface can directly extend multiple interfaces. }

This can be done using the following syntax: interface InterfaceName extends interfacel[, public void display()
interface2, , interfaceN]
{
Example Program on Extending Interface:
[Link]("The Student Roll Number is "+rno);
import [Link].*;
[Link]("The Student Name is "+name);
interface student
}
{
public void read(int x, int y, int z)
public void store(int a,String b);
{
public void display();
m1=x;
}
m2=y;
interface marks extends student
m3=z;
{
}
public void read(int a,int b,int c);
public void compute() Threads in Java

{ To achieve multiple tasks parallel, Programmer uses threads. Multithreading gives Java the ability
to achieve multiple tasks in parallel. One task does not wait for another to complete. That is,
int tot=m1+m2+m3;
without completing one task, another task can start and also can execute.
float avg=(tot)/3;
MULTITHREADING REALTIME EXAMPLES
[Link]("The total is "+tot);
Background jobs like running application servers like Oracle application server, Web
[Link]("The average is "+avg); servers like Tomcat etc which will come into action whenever a request comes.
Typing MS Word document while listening to music.
} Railway ticket reservation system where multiple customers accessing the server.
public static void main(String args[])
Multithreading in Java
{
Multithreading in java is a process of executing multiple threads simultaneously.
Demo5 d=new Demo5(); A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
[Link](01,"Aman"); However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
[Link](); switching between the threads takes less time than process. Java Multithreading is mostly
used in games, animation, etc
[Link](40,50,65); Every thread in Java is created and controlled by the [Link] class.
[Link](); A thread can be in one of the following states,
} 1. New born state(New)
2. Ready to run state (Runnable)
} 3. Running state(Running)
4. Blocked state
Implementing Interfaces 5. Dead state

To declare a class that implements an interface, you include an implements clause in the class
declaration. Your class can implement more than one interface, so the implements keyword is
followed by a comma-separated list of the interfaces implemented by the class.

A class that implements an interface must implement all the methods declared in the interface. The
methods must have the exact same signature (name + parameters) as declared in the interface

All variables in an interface are public, even if you leave out the public keyword in the variable
declaration.

The running thread ends its life when it has completed executing the run( ) method which
is called natural dead.
The thread can also be killed at any stage by using the stop( ) method.
Extending Thread Class

class Multi extends Thread { // Create a class by extending Thread class

public void run(){

[Link]("thread is running..."); // Defining run( ) in above class

public static void main(String args[]){

New Born State:-- Multi t1=new Multi(); // Creating an object for class

The thread enters the new born state as soon as it is created. The thread is created using [Link](); // Call the start( ) by using object
the new operator.
From the new born state the thread can go to ready to runnable mode or dead state. }
Ready to run mode (Runnable Mode):--
}
If the thread is ready for execution but waiting for the CPU the thread is said to be in Explain various Thread Methods:
ready to running mode.
All the events that are waiting for the processor are queued up in the ready to run mode We have various methods which can be called on Thread class object.
and are served in FIFO manner or priority scheduling. These methods are very useful when writing a multithreaded application.
Running State:--
Thread class has following important methods.
If the thread is in execution then it is said to be in running state. Method Signature Description
The thread can finish its work and end normally.
The thread can also be forced to give up the control when one of the following conditions
arise String getName() Retrieves the name of running thread.
A thread can be suspended by suspend( ) method. A suspended thread can be revived by
using the resume() method.
A thread can be made to sleep for a particular time by using the sleep(milliseconds) void setName(String name) It is used to set name for thread
method.
Blocked State:--
void start() This method will start a new thread of execution by
A thread is said to be in blocked state if it prevented from entering into the runnable state calling run() method of Thread/runnable object.
and so the running state.
The thread enters the blocked state when it is suspended, made to sleep or wait.
Dead State:--
void run() This method is the entry point of the thread. In most cases, thread scheduler schedules the threads according to their priority.
Execution of thread starts from this method.
The Thread class defines 3priority constants.

void sleep This method stops the thread for mentioned time MIN_PRIORITY=1
duration in argument (sleeptime in ms)
(intsleeptime) NORM_PRIORITY=5
MAX_PRIORITY=10
Default priority of a thread is 5 (NORM_PRIORITY).
void yield() By invoking this method the current thread pause its
The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
execution temporarily and allow other threads to
execute.
Program: Write a JAVA Program on Thread Priorities.
void join() This method used to queue up a thread in execution.
import [Link].*;
Once called on thread, current thread will wait till
calling thread completes its execution classTestPriority extends Thread

booleanisAlive() This method will check if thread is alive or dead {

public void run()


intgetPriority() To retrieve priority of Thread
{

void setPriority(priorityConstant) It is used to set the priority value. There are 3 [Link]("running thread name is:"+[Link]().getName());
priorities. [Link]("running thread priorityis:"+[Link]().getPriority());

MIN_PRIORITY }
MAX_PRIORITY
}
NORM_PRORITY
class Demo2

currentThread() It is used to know currently executed Thread status. {

public static void main(String args[])


Explain about Priority of a Thread (Thread Priority):
{
Each thread has a priority.
Priorities are represented by a number between 1 and 10. TestPriority m1=new TestPriority();

TestPriority m2=new TestPriority();


UNIT-III
[Link](Thread.MIN_PRIORITY); What is a web application?
A web application is an application accessible from the web. A web application is composed of
[Link](Thread.MAX_PRIORITY); web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and
JavaScript.
[Link]();
JSP technology is used to create web application just like Servlet technology. It can be thought
[Link](); 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.
Write a JAVA Program on Implementing Thread Using Runnable Interface: A server(generally referred to as application or web server) supports the Java Server Pages. This
server will act as a mediator between the client browser and a database. The following diagram
Class Multi3 implements Runnable{ shows the JSP architecture.
JSP Architecture Flow
public void run(){
1. eb browser.
[Link]("thread is running..."); 2. The JSP request is sent to the Web Server.
3. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet
}
Engine.
4. If the JSP file has been called the first time then the JSP file is parsed otherwise servlet is
instantiated. The next step is to generate a servlet from the JSP file. The generated servlet
public static void main(String args[]){ output is sent via the Internet form web server to users web browser.
5. Now in last step, HTML results are displayed on the users web browser.
Multi3 m1=new Multi3();

Thread t1 =new Thread(m1);

[Link]();

Important Note:
If you are not extending the Thread class, your class object would not be treated as a thread
object. So you need to explicitly create Thread class object. We are passing the object of your
class that implements Runnable so that your class run() method may execute.
Explain in detail about Lifecycle of JSP Web Container translates JSP code into a servlet class source(.java) file in step 1,
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
then in step 2 , compiles that into a java servlet class.
a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with
one additional first step, which is, translation of JSP code to Servlet code. In the step 3, the servlet class bytecode is loaded using classloader. The Container then creates
The Following are the JSP Lifecycle steps: an instance of that servlet class.
The initialized servlet can now service request. For each request the Web Container call
1. Converting JSP to Servlet code. the _jspService() method. When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class into memory. JSP Scripting Elements
4. Creating servlet instance. In JSP there are three types of scripting elements:
JSP Expressions: It is a small java code which you can include into a JSP page. The syntax is
5. Initialization by calling jspInit() method
JSP Scriptlet
6. Request Processing by calling _jspService() method lines of Java code in here.
7. Destroying by calling jspDestroy() method JSP Declaration
here you can declare a variable or a method for use later in the code.

JSP Expressions

Using the JSP Expression you can compute a small expression, always a single line, and get the
result included in the HTML which is returned to the browser. Using the code we have previously

Eg Code:
The time on the server is <%= new [Link]() %>
Output:
The time on the server is Thursday January 21 07:21:43 GMT 2016.
Explanation

Examples
In the first example we are going to see an expression for converting a string from lower case to
upper case. Here is the code:
The Expression

that we are calling a Java functi


case.
The HTML: Converting a string to uppercase: HELLO WORLD

JSP Scriptlets

This JSP Scripting Element allows you to put in a lot of Java code in your HTML code. This Java
code is processed top to bottom when the page is the processed by the web server. Here the result
<jsp:declaration>
code fragment
what you want to mix with HTML. The syntax is pretty much the same only you don
</jsp:declaration>
in an equal sign after the opening % sign.

Code:
<%! int i = 0; %>
1. <h2> Hello World</h2> <%! int a, b, c; %>
2. <%! Circle a = new Circle(2.0); %>
3. <% JSP directives
4. The jsp directives are messages that tells the web container how to translate a JSP page into the
5. for(inti=0; i<= 5; i++) corresponding servlet.
6. The entire JSP page process is controlled by this directive [Link]
7. { Directives has been categorized into three types as follows.
1) Page directive
8.
2) include directive
9. [Link]( );
3) taglib directive
10.
11. }
12. Syntax of JSP Directive
13. %> 1. <%@ directive attribute="value" %>

Output: JSP page directive

The page directive defines attributes that apply to an entire JSP page.
I really love counting: 1
I really love counting: 2 import
I really love counting: 3 The import attribute is used to import class,interface or all the members of a package.
I really love counting: 4 It is similar to import keyword in java class or interface.
Explanation:
Example of import attribute
scriptlet. Just to remember println means print line. In every iteration of the l
1. <html>
2. <body>
readable and easy to manage. 3.
4. <%@ page import="[Link]" %>
JSP Declarations 5. Today is: <%= new Date() %>
A declaration declares one or more variables or methods that you can use in Java code later in the 6.
JSP file. You must declare the variable or method before you use it in the JSP file. 7. </body>
8. </html>

<%! declaration; [ declaration; ]+ ... %>


The include directive is used to include the contents of any resource it may be jsp file, html file 9. </html>
or text file.

import
contentType
extends
info
buffer JSP Taglib directive
language
The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD
isELIgnored (Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so
isThreadSafe it will be better to learn it in custom tag.
autoFlush
Syntax JSP Taglib directive
session 1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
pageEncoding
errorPage Example of JSP Taglib directive

Advantage of Include directive In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.
Code Reusability
1. <html>
Syntax of include directive
2. <body>
3.
1. <%@ include file="resourceName" %>
4. <%@ taglib uri="[Link] prefix="mytag" %>
Example of include directive 5.
6. <mytag:currentDate/>
In this example, we are including the content of the [Link] file. To run this example you 7.
must create an [Link] file. 8. </body>
9. </html>
1. <html>
2. <body>
3. JSP Actions
4. <%@ include file="[Link]" %>
There are many JSP action tags or elements. Each JSP action tag is used to perform some
5. specific tasks.
6. Today is: <%= [Link]().getTime() %> The action tags are used to control the flow between pages and to use Java Bean.
7.
8. </body>

jsp:forward action tag <jsp:text>Wecome to JSP Applications</jsp:text>


The jsp:forward action tag is used to forward the request to another resource it may be jsp, html
or another resource.
<jsp:setProperty> Action
Syntax of jsp:forward action tag without parameter
This setProperty action tag is used to set the property of a Bean(class). While using this
1. <jsp:forward page="relativeURL | <%= expression %>" />
The syntax of the setProperty action:
Example of jsp:forward action tag
In this example, we are simply forwarding the request to the [Link] file.

[Link]
1. <html>
2. <body> Example:
3. <h2>this is index page</h2>
4. <jsp:setProperty name = "test" property = "message" value = "Hello JSP..." />
5. <jsp:forward page="[Link]" />
6. </body> <jsp:getProperty> Action
7. </html> It is used to
[Link] The syntax of the getProperty action:
1. <html>
2. <body> <jsp:getPropertyname="bean name"property="property_name"/>
3. <% [Link]("Today is:"+[Link]().getTime()); %>
4. </body>
5. </html> The setProperty and getProperty action tags are used for developing web application with Java
Bean. In web devlopment, bean class is mostly used because it is a reusable software component
that represents data.
<jsp:include> Action:
The include action is used to insert the files into the current page. Jsp Implicit Objects
The syntax of the include action:
<jsp: include page = " URL" /> These objects are created by JSP Engine during translation phase (while translating JSP to
Servlet). They are being created inside service method so we can directly use them
Here page is an attribute is used to specify the address of the included page in the current page.
within Scriptlet without initializing and declaring them. There are total 9 implicit objects
available in JSP.
Example:
<jsp: include page="[Link]" /> Implicit Objects and their corresponding classes:

The <jsp:text> Action:


out [Link]
The text action can be used to write the template text in JSP pages and documents.
The syntax of the include action:
request [Link]
<jsp:text>Template data</jsp:text>
Example: response [Link]
session [Link] hi hello

application [Link] println()

exception [Link] Example:


page [Link]
pageContext [Link]
config [Link]
output:

hi
The output which needs to be sent to the client (browser) is passed through this object. In simple hello
words out implicit object is used to write content to the client.
3) void newLine(): This method adds a new line to the output. Example
Methods of OUT Implicit Object
Example:
void print()
void println()
void newLine()
void clear() [Link]();
void clearBuffer()
void flush()
boolean isAutoFlush()
Output:
int getBufferSize()
This will write content without a new line
int getRemaining()

1)void print(): This method writes the value which has been passed to it. below 4)void clear( ): It clears the output buffer without even letting it write the buffer content to the
client.
Example:
Example:

[Link]();
void println(): This method is similar to the print() method, the only difference between print
and println is that the println() method adds a new line character at the end. 5)void clearBuffer(): This method is similar to the clear() method. The only difference between
them is that when we invoke [Link]() on an already flushed buffer it throws an exception,
Example:

6)boolean isAutoFlush() : It returns a Boolean value true/false. It is used to check whether the
buffer is automatically flushed or not.

output : 7)int getBufferSize(): This method returns the size of output buffer in bytes.

Example: Example of JSP request implicit object


[Link]
[Link]
<form action="[Link]">
<body>
<input type="text" name="uname">
<% <input type="submit" value="go"><br/>
[Link]( "print statement " ); </form>
[Link]( "println" ); [Link]
[Link]("Another print statement"); <%
%> String name=[Link]("uname");
</body> [Link]("welcome "+name);
%>
Request: The main purpose of request implicit object is to get the data on a JSP page which has
been entered by user on the previous JSP page. While dealing with login and signup forms in JSP Response Object:
we often prompts user to fill in those details, this object is then used to get those entered details on It is basically used for modifying or delaying with the response which is being sent to the client
an another JSP page (action page) for validation and other purposes. (browser) after processing the request.
Methods of request Implicit Object
1) getParameter (String name) : 1)void setContentType(String type) This method tells browser, the type of response data
by setting up the MIME type
Example at login page user enters user-id and password and once the credentials
Example
are verified the login page gets redirected to user information page, then using
[Link] we can get the value of user-id and password which user has [Link]("text/html");
input at the login page.
[Link]("image/gif");
String Uid= [Link]("user-id"); [Link]("image/png");
String Pass= [Link]("password"); [Link]("application/pdf");

2) getCookies( ) : 2) void sendRedirect(String address) It redirects the control to a new JSP page. For e.g.
It returns an array of cookie objects received from the client. This method is mainly used When the browser would detect the below statement, it would be redirected to the
when dealing with cookies in JSP. [Link] from the current JSP page.
[Link]( );
3) getRequestURI( ) : [Link]("[Link]
This method ([Link]()) returns the URL of current JSP page. 3) void addCookie(Cookie cookie)
[Link]( ); This method adds a cookie to the response. The below statements would add 2
4) getMethod() : Cookies Author and Siteinfo to the response.
It returns HTTP request method. [Link](). For example it will return GET for [Link](Cookie Author);
a Get request and POST for a Post Request. [Link](Cookie Siteinfo);
[Link]( ); 4) void sendError(int status_code, String message)
It is used to send error response with a code and an error message. For example
[Link](404, "Page not found error"); <% [Link]("message"); %>

5)void setStatus(int statuscode) This method is used to set the HTTP status to a given value.
For e.g. the below statement would set HTTP response code to 404 (Page not found).

[Link](404);

Example of response implicit object


[Link]

<form action="[Link]">
<input type="text" name="uname"> UNIT IV
<input type="submit" value="go"><br/>
JAVA Database Connectivity
</form>
[Link]
1) Introduction to JDBC
<% Java Database Connectivity(JDBC) is an Application Programming Interface(API)
[Link]("[Link] used to connect Java application with Database. JDBC is used to interact with various
%> type of Database such as Oracle, MS Access, My SQL and SQL Server. JDBC can also
4)Exception Object: be defined as the platform-independent interface between a relational database and Java
programming. It allows java program to execute SQL statement and retrieve result from
Exception implicit object is used in exception handling for displaying the error messages. database.
This object is only available to the JSP pages, which has isErrorPage set to true.
JDBC Driver
Example: JDBC Driver is required to process SQL requests and generate result. The following are the
different types of driver available in JDBC.
<%@ page isErrorPage="true" %>
<html> Type-1 Driver or JDBC-ODBC bridge
<body> Type-2 Driver or Native API Partly Java Driver
Sorry following exception occured:<%= exception %> Type-3 Driver or Network Protocol Driver
</body> Type-4 Driver or Thin Driver
</html>
1) Essential JDBC Classes
JDBC API is available in two packages [Link], core API and [Link] JDBC optional packages.
5) page implicit object: Following are the important classes and interfaces of JDBC.

In JSP, page is an implicit object of type Object class. Class/interface Description


This object is assigned to the reference of auto generated servlet class. It is written as:

Object page=this; DriverManager This class manages the JDBC drivers. You need to register your
drivers to this.
For example:

Class/interface Description Class/interface Description

It provides methods such as registerDriver() and Connection This interface represents the connection with a specific database.
getConnection(). SQL statements are executed in the context of a connection.
This interface provides methods such as close(), commit(),
rollback(), createStatement(), prepareCall(), prepareStatement(),
Driver This interface is the Base interface for every driver class i.e. If setAutoCommit() setSavepoint() etc.
you want to create a JDBC Driver of your own you need to
implement this interface. If you load a Driver class
(implementation of this interface), it will create an instance of ResultSet This interface represents the database result set, a table which is
itself and register with the driver manager. generated by executing statements. This interface provides getter
and update methods to retrieve and update its contents
respectively.
Statement This interface represents a static SQL statement. Using the
Statement object and its methods, you can execute an SQL
statement and get the results of it. ResultSetMetaData This interface is used to get the information about the result set
It provides methods such as execute(), executeBatch(), such as, number of columns, name of the column, data type of
executeUpdate() etc. To execute the statements. the column, schema of the result set, table name, etc
It provides methods such as getColumnCount(),
getColumnName(), getColumnType(), getTableName(),
PreparedStatement This represents a precompiled SQL statement. An SQL statement getSchemaName() etc.
is compiled and stored in a prepared statement and you can later
execute this multiple times. You can get an object of this
interface using the method of the Connection interface named
prepareStatement(). This provides methods such as
3) Example to Connect Java Application with Oracle database
executeQuery(), executeUpdate(), and execute() to execute the
prepared statements and getXXX(), setXXX() (where XXX is
In this example, we are connecting to an Oracle database and getting data from emp table.
the datatypes such as long int float etc..) methods to set and get
Here, system and oracle are the username and password of the Oracle database.
the values of the bind variables of the prepared statement.
1. import [Link].*;
CallableStatement Using an object of this interface you can execute the stored 2. class ConnectProg{
procedures. This returns single or multiple results. It will accept 3. public static void main(String args[]){
input parameters too. You can create a CallableStatement using 4. try{
the prepareCall() method of the Connection interface. 5. //step1 load the driver class
Just like Prepared statement, this will also provide setXXX() and 6. [Link]("[Link]");
getXXX() methods to pass the input parameters and to get the
7.
output parameters of the procedures.
8. //step2 create the connection object
9. Connection con=[Link](
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=[Link](); [Link] ("INSERT INTO Customers " +
14. "VALUES (1002, 'McBeal', 'Ms.', 'Boston', 2004)");
15. //step4 execute query [Link]("INSERT INTO Customers " +
16. ResultSet rs=[Link]("select * from emp"); "VALUES (1003, 'Flinstone', 'Mr.', 'Bedrock', 2003)");
17. while([Link]()) [Link]("INSERT INTO Customers " +
18. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3)); "VALUES (1004, 'Cramden', 'Mr.', 'New York', 2001)");
[Link]();
19.
}
20. //step5 close the connection object catch (Exception e) {
21. [Link](); [Link]("Got an exception! ");
22. [Link]([Link]());
23. }catch(Exception e) }
24. { }
25. [Link](e);} }
26.
27. } 5) Explain the procedure to retrieve data from database.
28. }
Step 1: Register with JDBC Driver
[Link] (new [Link] ());
The next() method of the ResultSet interface moves the pointer of the current (ResultSet) object Step 2: Get the connection from database
to the next row, from the current position. Connection conn=[Link] (url, username, password);

i.e., on calling the next() method for the first time the result set pointer/cursor will be moved to the url=
1st row (from default position). Step 3: Create Statement object
And on calling the next() method for the second time the result set cursor will be moved to the 2nd Statement stmt=[Link] ();
row. Step 4:
Execute the Query by using executeQuery() and store the result in ResultSet object.
4)Inserting into database
ResultSet rs=[Link] (sql);
Use the next() to retrieve data from table.
import [Link].*;
class JdbcInsert1 { while([Link]())
public static void main (String[] args) {
{ int eid=[Link](eid);
try { [Link](eid);
String url = "jdbc:msql://[Link]:1114/Demo"; String name=[Link](name);
Connection conn = [Link](url,"",""); [Link](name);
Statement st = [Link]();
}
[Link]("INSERT INTO Customers " +
"VALUES (1001, 'Simpson', 'Mr.', 'Springfield', 2001)");

Step 5: Close the Connection


[Link] ();
Program: 6) Explain the procedure to Store an image in database
import [Link].*;
class RetrievingData To store image into the database first we have to create table with two columns that is name and
{ photo in database as follows:
public static void main(String args[]) Create table student (Name varchar (20), Photo BLOB);
{ BLOB=A BLOB is binary large object that can hold a variable amount of data with a maximum
try length of 65535 characters.
{ These are used to store large amounts of binary data, such as images or other types of files.

The various steps involved in JDBC to store image in database


[Link] (new [Link] ()); Step 1: Register with JDBC Driver
Connection conn=[Link] (url, username, password); [Link] (new [Link] ());
Statement stmt=[Link] (); Step 2: Get the connection from database
Connection conn=[Link] (url, username, password);
ResultSet rs=[Link] (sql);
while([Link]())
{ Step 3: Create PreparedStatement object by passing sql query
int eid=[Link](eid); String
[Link](eid); PreparedStatement ps=[Link] (sql);
String name=[Link](name); Why use PreparedStatement?
[Link](name);
} PreparedStatement interface
[Link] ();
} The PreparedStatement interface is a subinterface of Statement. It is used to execute
catch(Exception e) parameterized query.
{ Improves performance: The performance of the application will be faster if you use
[Link](e); PreparedStatement interface because query is compiled only once.
}
} Step 4: Now we have to store data of two columnsas follows:
} a) Storing first column value using setString()
[Link]
Note:
Here, b) Storing second column value as follows:
next() is used to move cursor or resultset object (rs) to next row in a table. FileInputStream fin=new FileInputStream("d:\\[Link]");
getInt() is used to retrieve integer data from database table. [Link](2,fin,[Link]());
getString() is used to retrieve String data from database table. [Link]();
Step 5: Close the Connection
[Link] ();
Program: Step 3: Create PreparedStatement object by passing sql query
import [Link].*;
PreparedStatement ps=[Link] (sql);
class StoringImage
{ Step 4: Now we have to store data of two columns as follows:
public static void main(String args[]) a) Storing first column value using setString()
{ [Link]
try b) Storing second column value as follows:
{ File f=new File("d:\\[Link]");
FileReader fr=new FileReader(f);
[Link](2,fr);
[Link]();
[Link](new [Link] ()); Step 5: Close the Connection
Connection conn=[Link] (url, username, password); [Link] ();
Program:
PreparedStatement ps=[Link] (sql);
import [Link].*;
class StoringFile
FileInputStream fin=new FileInputStream("d:\\[Link]");
{
[Link](2,fin,[Link]());
public static void main(String args[])
[Link]();
{
[Link] ();
} try
catch(Exception e) {
{
[Link](e);
} [Link] (new [Link] ());
} Connection conn=[Link] (url, username, password);
}
7) Explain the procedure to store a file in database PreparedStatement ps=[Link] (sql);

To store file into the database first we have to create table with two columns that is name and File f=new File("d:\\[Link]");
profile in database as follows: FileReader fr=new FileReader(f);
Create table student (Name varchar (20), Profile CLOB); [Link](2,fr);
The various steps involved in JDBC to store file in database [Link]();
Step 1: Register with JDBC Driver [Link] ();
[Link] (new [Link] ()); }
Step 2: Get the connection from database catch(Exception e)
Connection conn=[Link] (url, username, password); {

[Link](e); {
}
}
} String
[Link] (new [Link] ());
8) Explain the procedure to retrieve an image from database
Connection conn=[Link] (url, username, password);
The various steps involved in JDBC to retrieve image from database
Step 1: Register with JDBC Driver PreparedStatement ps=[Link] (sql);
[Link] (new [Link] ()); ResultSet rs=[Link]();
Step 2: Get the connection from database if([Link]()) //now on 1st row
Connection conn=[Link] (url, username, password); {
Blob b=[Link](2); //2 means 2nd column data
byte i=[Link]();
Step 3: Create PreparedStatement object by passing sql query
FileOutputStream fout=new FileOutputStream();
PreparedStatement ps=[Link] (sql); [Link](i);
Step 4: create ResultSet Object using executeQuery() and use next() to retrieve data from }
database table. [Link] ();
ResultSet rs=[Link](); }
if([Link]()) //now on 1st row catch(Exception e)
{ {
Blob b=[Link](2); //2 means 2nd column data [Link](e);
byte i=[Link](); }
}
FileOutputStream fout=new FileOutputStream(); }
[Link](i);
} 9) Explain the procedure to retrieve a file from database

The various steps involved in JDBC to retrieve a file from database


Step 1: Register with JDBC Driver
Step 5: Close the Connection
[Link] (new [Link] ());
[Link] ();
Step 2: Get the connection from database
Program:
Connection conn=[Link] (url, username, password);
import [Link].*;
class StoringImage
{ Step 3: Create PreparedStatement object by passing sql query
public static void main(String args[])
{ PreparedStatement ps=[Link] (sql);
try
Step 4: create ResultSet Object using executeQuery() and use next() to retrieve data from }
database table. catch(Exception e)
ResultSet rs=[Link](); {
if([Link]()) //now on 1st row [Link](e);
{ }
Clob b=[Link](2); //2 means 2nd column data }
Reader i=[Link](); }
-----END----
FileWriter f=new FileWriter();
f..write(i);
}

Step 5: Close the Connection


[Link] ();
Program:
import [Link].*;
class StoringImage
{
public static void main(String args[])
{
try
{

String
[Link] (new [Link] ());
Connection conn=[Link] (url, username, password);

PreparedStatement ps=[Link] (sql);


ResultSet rs=[Link]();
if([Link]()) //now on 1st row
{
Clob b=[Link](2); //2 means 2nd column data
Reader i=[Link]();

FileWriter f=new FileWriter();


f..write(i);
}
[Link] ();

You might also like