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

Complete Java-JSP NOTES

The document provides a comprehensive overview of Java, including its history, features, and applications. It covers fundamental concepts such as JDK, JRE, JVM, data types, operators, control statements, OOP principles, and more advanced topics like JDBC and JSP. Additionally, it includes a simple Java program example to illustrate the structure and execution of Java applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Complete Java-JSP NOTES

The document provides a comprehensive overview of Java, including its history, features, and applications. It covers fundamental concepts such as JDK, JRE, JVM, data types, operators, control statements, OOP principles, and more advanced topics like JDBC and JSP. Additionally, it includes a simple Java program example to illustrate the structure and execution of Java applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 279

JAVA INDEX

Introduction  Constructor overloading


 What is java and its applications  This Keyword
 Features of Java  Static method
 History of java  garbage collection
 JDK AND JRE,JVM Inheritance
 Tokens  Inheritance [Single, Multilevel,
 Installation of Java hierarchical,Multiple]
 Structure of Java Program  super keyword
Data Types  Method overriding
 What is data type?  Final keyword
 Variables Data Abstraction and Interfaces
 Hello world example  Abstract Classes
 Command Line Arguments  Introduction to Interface
Operators  Defining interfaces
 Arithmetic operators  Implementing interfaces
 Bitwise Operators  interface variables
 Relational Operators  Extending interfaces
 Logical Operators Packages
 Assignment Operator  Creating package
 The Ternary Operator  Accessing package
 Increment or Decrement operator /Unary  Access specifiers
operators Wrapper classes
Control Statements  Introduction
 Branching statements  Byte
 Looping statement  Short
 Jump Statements  Integer
OOPS Features  Long
 Class  Double
 Object  Float
 Encapsulation  Character
 Inheritance  Boolean
 Data Abstraction Exception Handling
 Polymorphism  Introduction to Exception handling
Introduction to Classes and methods  Try and catch
 Declaring Objects  Nested try
 Introduction to method  Finally
 Method overloading  Throw
 Introduction to Constructors  Throws
 Types of constructors  Custom Exception
Multithreading Web technology
 Introduction to thread HTML:
 The Main Thread  HTML Introduction
 Thread Life Cycle  HTML Elements
 Creating Thread  HTML Attributes
 Thread Priority  HTML Headings
 How to set and get thread names  HTML Lists
 Synchronization  HTML Formatting
Arrays  HTML Anchor
 What is an array?  HTML Image
 Types of arrays  HTML Table
 Single dimensional  HTML Frames
 Two dimensional  HTML Form
Strings:  HTML Marquee
 What is String and its methods  HTML Span
 What is String Buffer and its methods  HTML Div
 What is String Builder and its methods HTML 5.0
IO STREAMS  HTML Audio
 file input output basic introduction  HTML Video
 Byte Stream in Java  HTML Datalist
 Serialization  HTML Progress
 Deserializatoin:  HTML Header
Collection Framework and Generics  HTML Footer
 Introduction to collection framework:  HTML SVG
 All Interfaces and Classes. CSS
Awt  Introduction to css
 AWT Basics  id and class selector
 Event Handling  Inline style sheet
 Layout Managers  Internal style sheet
 AWT EXAMPLES  External style sheet
Java Swing  CSS colors
 Swing Basics  CSS Background
 Ways to create a swing  CSS Font
 SWING EXAMPLES  CSS Text
Applets  CSS Box model
 What is applet  CSS Padding
 Life cycle of applet  CSS Margin
 Applet programs  CSS Border
 CSS Anchor
JavaScript  Callable Statement
 Introduction to JavaScript Servlets
 variables  Servlets
 operators  Introduction to servlets
 Arrays  Servlet Interface
 Functions  Generic servlet
 control statements  Http servlet
 Normal validation  RequestDispatcher
 Regular expression  Cookies
 Built-in Objects  Sessions
 Event handling  Development application
Advanced java: JSP
JDBC  Introduction to jsp
 jsp life cycle
 Introduction to JDBC
 jsp elements
 JDBC Driver Types
 jsp directives
 Steps for Connecting with Database
 Implicit objects
 Connecting jdbc with MS ACCESS DB
 action tags
WITH DSN
 java beans
 Connecting jdbc with ORACLE DB
 Expression lanaguage
 Driver Manager
 Exception handling
 Connection
 MVC
 Statement
 JSTL Tags
 PreparedStatement
 Development applications
 ResultSet
 CRUD Operations
 DatabaseMetaData
 Batch Processing
INTRODUCTION TO JAVA
Java:
 Java is application software which is suitable for creating desktop and web applications and
also suitable for mobile applications
 Java is a platform independent, more powerful, secure, high performance, multithreaded and
Object oriented programming language.
Applications of java:
According to Sun, 3 billion devices run java. There are many devices where java is currently used.
Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
HISTORY OF JAVA:
The history of java starts from Green Team. Java team members (also known as Green
Team), initiated a revolutionary task to develop a language for digital devices such as set-top boxes,
televisions etc.For the green team members, it was an advance concept at that time. But, it was suited
for internet programming. Later, Java technology as incorporated by Netscape. Currently, Java is
used in internet programming, mobile devices, games, e-business solutions etc. There are given the
major points that describe the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in
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.
3) Firstly, it was called "Green talk" 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.
5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc..
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why they choosed java name for java language? The team gathered to choose a new name. The
suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique,
and easy to spell and fun to say.
According to James Gosling "Java was one of the top choices along with Silk". Since java was so
unique, most of the team members preferred java.
8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in (January 23, 1996).
Java Version History: There are many java versions that has been released. Current stable release of
Java is Java SE 9.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)
11. Java SE 9 (27th July, 2017)
Difference between JDK AND JRE, JVM
JDK:
 JDK stands for Java Development Kit.
 JDK physically exists. It contains JRE + development tools

JRE:
 JRE stands for java runtime engine and It is also the implementation of JVM
 JRE contains of Jvm+Libraries
JVM:
 JVM stands for Java virtual machine which converts byte code instructions to object code.
JVM ARCHITECTURE:
1) Classloader: Class loader is a subsystem of JVM that is used to load class files.
2) Class (Method) Area: Class (Method) Area stores class structures such as the runtime constant
pool, field and method data, the code for methods.
3) Heap: It is the runtime data area in which objects are allocated.
4) Stack: Here normal variables are stored
5) Program Counter Register: PC (program counter) registers. It contains the address of the Java
virtual machine instruction currently being executed.
6) Native Method Stack: It contains all the native methods used in the application.
7) Execution Engine:
It contains:
1) A virtual processor (Interpreter): Read byte code stream then execute the instructions.
3) Just-In-Time(JIT) compiler: It is used to improve the performance.

Features of Java
Features of a language are nothing but the set of services or facilities provided by the
language vendors to the industry programmers. Some important features of java are
Important Features of Java
 Simple
 Object Oriented
 Platform Independent
 Architectural Neutral
 Portable
 Multi Threading
 Robust
 Distributed
 Dynamic
 Secured
 Exception Handling
 High Performance
Simple:
 It is free from pointer due to this execution time of application is improved. [Whenever we
write a Java program without pointers then internally it is converted into the equivalent
pointer program].
 It has Rich set of API (application programming interface).
 It contains user friendly syntax for developing any applications.
Object Oriented: It supports OOP's concepts because of this it is most secure language and
simplify the software application development.
Platform Independent: A program or technology is said to be platform independent if and only if
which can run on all available operating systems with respect to its development and compilation.
(Platform represents O.S).

Architectural Neutral: Architecture represents processor. A Language or Technology is said to be


Architectural neutral which can run on any available processors in the real world without considering
their development and compilation.

The languages like C, CPP are treated as architectural dependent.


Portable: If any language supports platform independent and architectural neutral feature known as
portable. The languages like C, CPP, and Pascal are treated as non-portable language. It is a portable
language According to SUN microsystem..

Secure: It is a more secure language compared to other language, In this language, all code is
covered in byte code after compilation which is not readable by human.
Exception handling: It is a mechanism to handle the exceptions.
Multithreaded: A flow of control is known as a thread. When any Language executes multiple
threads at a time that language is known as multithreaded e. It is multithreaded. Threads are
important for multi-media, Web applications etc.
Robust: Simply means of Robust are strong. It is robust or strong Programming Language because
of its capability to handle Run-time Error, automatic garbage collection, the lack of pointer concept,
Exception Handling. All these points make it robust Language.
Distributed: Using this language we can create distributed applications. RMI and EJB are used for
creating distributed applications. In distributed application multiple client system depends on
multiple server systems so that even problem occurred in one server will never be reflected on any
client system..
Dynamic: It supports Dynamic memory allocation due to this memory wastage is reduced and
improve performance of the application. The process of allocating the memory space to the input of
the program at a run-time is known as dynamic memory allocation, to programming to allocate
memory space by dynamically we use an operator called 'new' 'new' operator is known as dynamic
memory allocation operator.
High performance: It has high performance because of following reasons;
 Garbage collector, collect the unused memory space and improve the performance of the
application.
 It has no pointers so that using this language we can develop an application very easily.
 It support multithreading, because of this time consuming process can be reduced to
executing the program.
Tokens:
Smallest individual units in a program are known as tokens. A java program is a collection of
tokens. Java language includes five types of tokens. They are
 Keywords
 Identifiers
 Operators
 Separators
Keywords:
Keywords have specific meaning in java; we cannot use them as names for variables,
classes, methods and so on. All keywords are to be written in lower-case letters.
Example - class, import, static, while etc.
Identifiers: These are used for naming classes, methods, variables, objects, packages and interfaces
in a program. Java identifiers follow the following rules.
 They can have alphabets, digits and the underscore and dollar sign.
 They must not begin with a digit.
 Uppercase and lowercase letters are different.
 They can be any length.
 No spaces allowed between the words.
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce
result.
Example: +,-,*,/,%,<,>,<= etc.
Separators:
Separators are symbols used to indicate where groups of code are divided and arranged.
Example:( ), { }, [ ], ‘.’, ‘,’ etc.
Structure of Java Program:
Structure of a java program is the standard format released by Language developer to the
Industry programmer. Sun Micro System has prescribed the following structure for the java
programmers for developing java application.
 A package is a collection of classes, interfaces and sub-packages. A sub package contains
collection of classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by
default and this package is known as default package.
 Class is keyword used for developing user defined data type and every java program must start
with a concept of class.
 "ClassName" represent a java valid variable name treated as a name of the class each and
every class name in java is treated as user-defined data type.
 Data member represents either instance or static they will be selected based on the name of
the class.
 User-defined methods represents either instance or static they are meant for performing the
operations either once or each and every time.
 Each and every java program starts execution from the main() method. And hence main()
method is known as program driver.
 Since main() method of java is not returning any value and hence its return type must be void.
 Since main() method of java executes only once throughout the java program execution and
hence its nature must be static.
 Since main() method must be accessed by every java programmer and hence whose access
specifier must be public.
 Each and every main() method of java must take array of objects of String.
 Block of statements represents set of executable statements which are in term calling user-
defined methods are containing business-logic.
 The file naming conversion in the java programming is that which-ever class is containing
main () method, that class name must be given as a file name with an extension .java.
First Java Program:
Requirements for java Program:
For executing any java program we need given things.
1. Install the JDK any version if you don't have installed it.
2. Set path of the jdk/bin directory.
3. Create the java program
4. Compile and run the java program
Syntax for compilation:
Javac fileName/className.java
Syntax for execution:
Java ClassName
Create First program
Example
class First{
public static void main(String[] args) {
System.out.println("Hello Java");
System.out.println("My First Java Program");
}
}
To compile: javac First.java
To execute: java First
Output
Hello Java
My First Java Program
Main() Method in Java
main() method is starting execution block of a java program or any java program start their
execution from main method. If any class contain main() method known as main class.
Syntax of main() method:
public static void main(String args[])
{
.......
.......
}
Public
public is a keyword in a java language whenever if it is preceded by main() method the
scope is available anywhere in the java environment that means main() method can be executed
from anywhere. main() method must be accessed by every java programmer and hence whose
access specifier must be public.
Static
static is a keyword in java if it is preceded by any class properties for that memory is
allocated only once in the program. Static method are executed only once in the program. main()
method of java executes only once throughout the java program execution and hence it declare
must be static.
Void
void is a special datatype also known as no return type, whenever it is preceded by main()
method that will be never return any value to the operating system. main() method of java is not
returning any value and hence its return type must be void.
String args[]
String args[] is a String array used to hold command line arguments in the form of String
values.
In case of main() method following changes are acceptable
1. We can declare String[] in any valid form.
String[] args
String args[]
String []args
2. Instance of String[] we can take var-arg String parameter is String...
Syntax
main(String[] args) --> main(String... args)

3. We can change the order of modifiers i.e Instead of


Syntax
public static we can take static public
4. Instead of args we can take any valid java identifier.
Syntax
public static void main(String a[])
Data Types:
Data types specify the size and type of values that can be stored. Data types in Java are
 Primitive types or built-in types
 Derived types

Integer Types:

Integer types can hold whole numbers such as 123, -96, and 5639. The size of the values that
can be stored depends on the integer data type we choose. Java supports four types of integers. They
are byte, short, int, and long. Table shows the memory size and range of all the four integer data
types.

Size
Type Minimum Value Maximum Value
(in bytes)
byte 1 -128 127
short 2 -32,768 32767
int 4 -2,147,483,648 2,147,483,647
long 8 -9,223,372,036854,775,808 9,223,372,036854,775,807
Note: Appending the letter L or I at the end of the number. Example: 123L or 123l
Character Type:
In order to store character constants in memory, Java provides a character data type called
char. basically, it can hold only a single character.

Floating Point Types:


Floating point type containing fractional parts.Example:27.59, -1.375
 There are two kinds of floating point types.
 The float type values are single-precision numbers.
 Double type values are double-precision numbers. We must append F to the numbers.
Example: 1.23f, 7.56923e5F
Boolean Type: Boolean type is used when we want to test a particular condition during the
execution of the program. There are only two values that a boolean type can take: true or false.
Variables
1. Variable is an identifier which holds and its value can be changed at the execution time of
program.
2. Variable is an identifier which can be used to identify input data in a program.
Syntax
Variable_name = value;
Rules to declare a Variable
1. Every variable name should start with either alphabets or underscore ( _ ) or dollar ($ )
symbol.
2. No space is allowed in the variable declarations.
3. Except underscore ( _ ) no special symbols are allowed in the middle of variable declaration
4. Variable name always should exist in the left hand side of assignment operators.
5. Maximum length of variable is 64 characters.
6. No keywords should access variable name.
Variable declarations
In which sufficient memory will be allocated and holds default values.
Syntax
Datatype variable_name;
byte b1;
Variable initialization
It is the process of storing user defined values at the time of allocation of memory space.
Variable assignment
Value is assigned to a variable if that is already declared or initialized.
Syntax
Variable_Name = value
int a = 100;
Type casting?
We often need to store a value of one type into a variable of another type. In such situation, we
must cast the value to be stored by processing it. Java provides two ways type cast variables
1. Implicit type cast
2. Explicit type cast
Implicit type cast:
When we assign a smaller value to another type of bigger value this type of type casting is
possible. Compiler is the responsible to perform this type casting. It is also called widening or
promotion or upcasting. In this type of typecasting there is no matter of data loss. This is also known
as automatic type casting. The following is possible in java.
Example:
byte b=75;
int a =b;
above two statements are valid statements. Here the byte type is converting into integer type
Explicit type cast – When we assign a large variable type to small type. It is the programmer
responsibility to handle this type situation. Java provides another way to cast large variable type to
small type by using a cast operator. It looks like following format
Type variable-1 = (Type) variable-2;
Examples:
int m=50;
byte n=(byte)m;
Above two statements are valid statements. Here the int type is converting into byte type. In this
process there may be chance of losing data. The following are various possible conversions where
explicit type casting is required

Java Variable Example: Widening


class Ex4{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}
Output:
10
10.0
Java Variable Example: Narrowing (Typecasting)
class Ex5{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Output:
10.5
10
Commonad line arguments
If any input value is passed through the command prompt at the time of running of the
program is known as command line argument by default every command line argument will be
treated as string value and those are stored in a string array of main() method.
Syntax for Compile and Run CMD programs

Example of command-line argument in java


class Ex2{
public static void main(String args[]){
System.out.println("Argument is: "+args[0]);
}
}
Output
Argument is: Porter
Operators:
It is a special symbol that tells the compiler to perform specific mathematical or logical
Operation.
Java supports following lists of operators.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Ternary or Conditional Operators
 Unary (Increment/decrement operators)
Arithmetic Operators
Given table shows all the Arithmetic operator supported by Java Language. Lets suppose
variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
class Arith_Operators {
public static void main(String[] args){
int a=4,b=2;
System.out.println("(a+b)="+(a+b));
System.out.println("(a-b)="+ (a-b));
System.out.println("(a*b)="+(a*b));
System.out.println("(a/b)="+(a/b));
System.out.println("(a%b)="+(a%b));
}
}
Output:
(a+b)=6
(a-b)=2
(a*b)=8
(a/b)=2
(a%b)=0

Relational Operators: Which can be used to check the Condition, it always returns true or false.

Operators Example (int A=8, B=3) Result


< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=B True
Example for Relational_Operators
class Relational_Operators {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Logical Operator: Which can be used to combine more than one Condition?. Suppose you want to
combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B) &&
(B>C). Here && is Logical Operator.

Operator Example (int A=8, B=3, C=-10) Result

&& (A<B) && (B>C) False

|| (B!=-C) || (A==B) True

! !(A <B) is false True

class Logical_Operators
{
public static void main(String args[])
{
int a = 110;
int b = 20;
int c=30;
System.out.println ((a>b) &&(a>c)));
System.out.println( ((a>b)||(a>c)));
System.out.println(!(a>b));
}
}
Output:
true
true
false
Assignment operators
Which can be used to assign a value to a variable? Let’s suppose variable A hold 8
and B hold 3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
class Assing_Operators {
public static void main(String[] args){
int a=6;
System.out.println(a+=2);
System.out.println(a-=2);
System.out.println(a*=2);
System.out.println(a/=2);
System.out.println(a%=2);} }
Output:
8
6
12
6
0
Ternary operator:
If any operator is used on three operands or variable is known as ternary operator. It can
be represented with “?:”
The general form of ternary operator is exp1? exp2:exp3;
Here exp1, exp2, exp3 are expressions.
If exp1 is true, then exp2 is evaluated and its value becomes the value of expression. If exp1 is false,
then the exp3 is evaluated and its value becomes the value of the expression.
import java.util.Scanner;
class Ternary_Operators{
public static void main(String args[])
{
int a,b;
Scanner s=new Scanner(System.in);
System.out.println("Enter any Two numbers:");
a=s.nextInt();
b=s.nextInt();
int c=(a>b)?a:b;
System.out.println(a+" is big");
}
}
Output:
Enter any Two numbers:
6
5
6 is big
Increment and Decrement operators:
Post Increment (n++): First execute the statement then increase the value by one.
Pre Increment (++n): First increase the value by one then execute the statement.
Example:
class IncrementTest{
public static void main(String[] args){
System.out.println("***Post increment test***");
int n = 10;
System.out.println(n); //10
System.out.println(n++); // 10
System.out.println(n); // 11
System.out.println("***Pre increment test***");
int m = 10;
System.out.println(m); //10
System.out.println(++m); // 11
System.out.println(m); // 11
}
}
Output:
***Post increment test***
10
10
11
***Pre increment test***
10
11
11
Post Decrement (n--): First execute the statement then decrease the value by one.
Pre Decrement (--n): First decrease the value by one then execute the statement.
class DecrementTest{
public static void main(String[] args){
System.out.println("***Post increment test***");
int n = 10;
System.out.println(n); //10
System.out.println(n--); // 10
System.out.println(n); // 9
System.out.println("***Pre increment test***");
int m = 10;
System.out.println(m); //10
System.out.println(--m); // 9
System.out.println(m); // 9
}
}
Output:
***Post increment test***
10
10
9
***Pre increment test***
10
9
9
BIT-WISE operators:- These are used for manipulating data at bit level they are two types:
1. Bitwise logical operators.
2. Bitwise shift operators.
Bit wise logical operators:-These are used for the bitwise logical decision making.
& bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
Bitwise shift operators:-The shift operators take binary patterns and shift the bits to the left or right.
<< - left shift
>> - right shift
E1 E2 E1 & E2 E1 | E2 E1 ^ E2

1 1 1 1 0

1 0 0 1 1

0 1 0 1 1

0 0 0 0 0

Example:
import java.util.Scanner;
class Bitwise_Operators
{ public static void main(String args[])
{
int a,b;
Scanner s=new Scanner(System.in);
System.out.println("Enter any Two numbers:");
a=s.nextInt();
b=s.nextInt();
System.out.println(a&b);
System.out.println(a|b);
System.out.println(a^b);
System.out.println(a<<b);
System.out.println(a>>b);
}
}
Output:
Enter any Two numbers:
4
2
0
6
6
16

Control statements
Control statements enable us to specify the flow of program control; ie, the order in which
the instructions in a program must be executed. They make it possible to make decisions, to perform
tasks repeatedly or to jump from one section of code to another
There are four types of control statements in java:
1. Decision making statements
2. Selection statements
3. Iteration statements
4. Jump statements
Decision making statements:
Decision making statement is depending on the condition block need to be executed or not
which is decided by condition.
If the condition is "true" statement block will be executed, if condition is "false" then
statement block will not be executed.
There are three types of decision making statement.
1. If
2. If else
3. Else if ladder
If Statement
1. If is most basic statement of Decision making statement.
2. It tells to program to execute a certain part of code only if particular condition is true.
Syntax:

Example
import java.util.Scanner;
class DecisionEx1
{
public static void main(String args[])
{
int a,b;
System.out.println("Enter two values");
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
if(a>b)
{
System.out.println(a+" is big");
}
}
}
Output:
Enter two values
5
2
5 is big
If-else statement
In general it can be used to execute one block of statement among two blocks, in C language
if and else are the keywords
Syntax.
Example
import java.util.Scanner;
class DecisionEx2
{
public static void main(String args[])
{
int a,b;
System.out.println("Enter two values");
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
if(a>b)
{
System.out.println(a+" is big");
}
else
{
System.out.println(b+"is big");

}
}
}
Output:
Enter two values
7
4
7 is big
If else-if ladder Statement: The if else-if statement is used to execute one code from multiple
conditions. The syntax of if else-if statement is given below:
Syntax:
Example.
package BasicPrograms;
import java.util.Scanner;
public class DecisionEx3 {
public static void main(String args[])
{
int a,b;
System.out.println("Enter two values");
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();

if(a==b)
System.out.println("both are equal");
else if(a>b)
System.out.println(a+"is big");
else
System.out.println(b+" is big");

}
}
Output:
Enter two values
3
3
both are equal
Selection statement:
A switch statement is used for multiple way selections that will branch into different code
segments based on the value of a variable or expression. This expression or variable must be of
integer data type. Here, depending on the value of the expression, a particular corresponding case
will be executed.
Syntax:

Rules for apply switch


1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch.
Example
import java.util.*;
class switchCase
{
public static void main(String arg[])
{
int ch;
System.out.println("Enter any number (1 to 7) :");
Scanner s=new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1:
System.out.println("Today is Monday");
break;
case 2:
System.out.println("Today is Tuesday");
break;
case 3:
System.out.println("Today is Wednesday");
break;
case 4:
System.out.println("Today is Thursday");
break;
case 5:
System.out.println("Today is Friday");
break;
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
default:
System.out.println("Only enter value 1 to 7");
}
}
}
Output:
Enter any number (1 to 7) :
3
Today is Wednesday
Looping Statement
Looping statements are the statements execute one or more statement repeatedly several
number of times. In java programming language there are three types of loops; while, for and do-
while.
Difference between conditional and looping statement
Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.
While loop: In while loop first check the condition if condition is true then control goes inside the
loop body otherwise goes outside of the body. while loop will be repeats in clock wise direction.
Syntax:

Example while loop


class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<5)
{
System.out.println(i);
i++;
}
Output:
0
1
2
3
4
do-while
A do-while loop is similar to a while loop, except that a do-while loop is execute at least
one time.
A do-while loop is a control flow statement that executes a block of code at least once, and
then repeatedly executes the block, or not, depending on a given condition at the end of the block
(in while).
Syntax:

Example:
class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<3);
}
}
Output
Hello world !
Hello world !
Hello world !

for loop: for loop is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements
Syntax
for ( initialization; condition; increment )
{
statement(s);
}
Initialization: This step is executed first and this is execute only once when we are entering into the
loop first time. This step is allowed to declare and initialize any loop control variables.
Condition: This is next step after initialization step, if it is true, the body of the loop is executed, if it
is false then the body of the loop does not execute and flow of control goes outside of the for loop.
Increment or Decrements: After completion of Initialization and Condition steps loop body code is
executed and then Increment or Decrements steps is execute. This statement allows to update any
loop control variables.
Example:
class ForDemo{
public static void main(String args[]){
int i;
for (i=0: i<5; i++){
System.out.println("Hello Friends !");
}
}
}
Output:
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Jumping statements:
1. Java supports two jump statements: break, continue.
2. These statements transfer control to another part of the program.
break:
 break can be used inside a loop to come out of it.
 break can be used inside the switch block to come out of the switch block.
 break can be used in nested blocks to go to the end of a block. Nested blocks represent a
block written within another block.
Syntax: break;
class Jump{
public static void main(String args[]) {
int n=5;
for(int i=1;i<=n;i++) {
if(i==3 {
break;
}
System.out.println(i);

}
}
Output:
1
2
continue: This statement is useful to continue the next repetition of a loop/ iteration.When continue
is executed, subsequent statements inside the loop are not executed.
Syntax: continue;
class Jump{
public static void main(String args[]){
int n=5;
for(int i=1;i<=n;i++){
if(i==3) {
continue;
}
System.out.println(i);
}
}
Output:
1
2
4
5
Note: goto statement is not available in java, because it leads to confusion and forms infini
Oops features
The general concepts of Object oriented programming are:
● Objects & Classes
● Encapsulation & Abstraction
● Inheritance
● Polymorphism
● Dynamic Binding
● Message communication
Classes & Objects –
 A class is a non primitive data type and an object as a variable of that data type..
 The combination of data and methods create an object.
 An object may represent a person, a place, a vehicle etc.
 An object is used to access data, methods in a class.
 An object uses some space in the memory.
Encapsulation
 The wrapping up of data and methods into a single unit is known as encapsulation.
 The data is not accessible by the outside of the class, only access by the methods in that class.
 The protection of data from direct access is called data hiding.
 Example: Capsule which is wrapped with different medicines.
Abstraction:
 Abstraction refers to the act of representing essential features without including the
background details.
 Example: : SMS,we don't know the internal processing.
Inheritance –
 The relation between two classes is called an Inheritance.
 The old class is called base or parent class and new class is called derived or child class.
 Inheritance provides the idea of reusability (new class adds features of the old class).
Polymorphism –
 The word ‘poly’ means ‘many’ and ‘morphic’ means ‘forms’.
 Polymorphism means perform different operations by using the same method.
Dynamic Binding –
 Binding means linking the code of a method.
 Dynamic binding means the code associated with a given method call is executed at run time.
Message communication –
An object oriented program contains a set of objects. The process of oop is
 Creating classes that define objects.
 Creating objects from class definition.
Class:
 A class is a collection of variables and methods and no memory is allocated for them.
 A class is a group of objects that has common properties.
 A class is the logical entity.
 A class is also a user defined data type
Object:
 Object is an instance of class; object has state and behaviors also Identity.
 An object is used to access data, methods in a class.
 An object uses some space in the memory.
State: Represents data (value) of an object such as Account_No...ect.
Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw etc.
Identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Example: In real world many examples of object and class like dog, cat, and cow are belong to
animal's class. Each object has state and behaviors. For example a dog has state:- color, name,
height, age as well as behaviors:- barking, eating, and sleeping.
Syntax to declare a Class
class Class_Name
{
data member;
method;
}
Simple Example of Object and Class:In this example, we have created a Employee class that
have two data members eid and ename. We are creating the object of the Employee class by new
keyword and printing the objects value.
Example
class Employee{
int eid; // data member (or instance variable)
String ename; // data member (or instance variable)
eid=101;
ename="Hitesh";
public static void main(String args[]){
Employee e=new Employee(); // Creating an object of class Employee
System.out.println("Employee ID: "+e.eid);
System.out.println("Name: "+e.ename);
}
}
Output
Employee ID: 101
Name: Hitesh
Note: A new keyword is used to allocate memory at runtime, new keyword is used for create an
object of class, later we discuss all the way for create an object of class.
How to declare an object:
ClassName referencevariable;
Reference=new ClassName ();
Or
ClassName object=new ClassName();
Example:
Employee e=new Employee (); // Creating an object of class Employee
Java methods:
A method is a set of code which is referred to by name and can be called (invoked) at any
point in a program simply by utilizing the method's name. Think of a method as a subprogram that
acts on data and often returns a value.
Each method has its own name. When that name is encountered in a program, the execution
of the program branches to the body of that method. When the method is finished, execution returns
to the area of the program code from which it was called, and the program continues on to the next
line of code.
Good programmers write in a modular fashion which allows for several programmers to work
independently on separate concepts which can be assembled at a later date to create the entire
project. The use of methods will be our first step in the direction of modular programming.
Example 2:
class Employee1
{
private int empno;
private String empName;
private float salary;
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public static void main(String args[]){
Employee1 e1=new Employee1();
e1.setEmpno(101);
e1.setEmpName("kiran");
e1.setSalary(50000);
System.out.println("The employee no is "+e1.getEmpno());
System.out.println("The employee name is "+e1.getEmpName());
System.out.println("The employee salary is "+e1.getSalary());
}
}
Output:
The employee no is 101
The employee name is kiran
The employee salary is 50000.0
Method Overloading:
If a class has multiple methods by same name with different parameters or different order of
parameters, it is known as Method Overloading.
Advantage:
 Method overloading increases the readability of the program.
Syntax
class class_Name{
Returntype method(){.........}
Returntype method(datatype1 variable1)
{.........}
Returntype method(datatype1 variable1, datatype2 variable2)
{.........}
Returntype method(datatype2 variable2)
{.........}
Returntype method(datatype2 variable2, datatype1 variable1)
{.........}
}
There are two ways to overload the method in java
1. By changing number of arguments or parameters
2. By changing the data type
Explanation of Code
class MethodOverloading1{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
void sum(float a,float b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
MethodOverloading1 obj=new MethodOverloading1();
obj.sum(10, 20);
obj.sum(10, 20, 30);
obj.sum(3.4f,6.5f);
}
}
Output:
30
60
30.0
Constructors
1. Constructor is a special method which will be called automatically whenever object is
created.
2. Constructors are mainly created for initializing the object.
3. Initialization is a process of assigning user defined values at the time of allocation of memory
space.
Advantages of constructor
 A constructor eliminates placing the default values
 A constructor eliminates calling the normal methods implicitly.
Rules or properties of a constructor
1. Constructor name must be similar to name of the class.
2. Constructor should not return any value even void also. Constructor definitions should not
be static. Because constructors will be called each and every time, whenever an object is
creating.
Types of constructors
 Default or no argument Constructor
 Parameterized constructor.
Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters. If
any class does not contain at least one user defined constructor then the system will create a default
constructor at the time of compilation it is known as system defined default constructor.
Syntax
class className
{
..... // Call default constructor
clsname ()
{
Block of statements; // Initialization
}
.....
}
Note: System defined default constructor is created by java compiler and does not have any
statement in the body part. This constructor will be executed every time whenever an object is
created if that class does not contain any user defined constructor.
Example of default constructor.
In below example, we are creating the no argument constructor in the Test class. It will be
invoked at the time of object creation.
Example
class TestDemo
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=10;
b=20;
}
void display()
{
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
public static void main(String [] args)
{
TestDemo t1=new TestDemo ();
t1.display();
}
}
Output:
I am from default Constructor...
Value of a: 10
Value of b: 20
Example of system default constructor that displays the default values
class Student{
int roll;
float marks;
String name;
void show()
{
System.out.println("Roll: "+roll);
System.out.println("Marks: "+marks);
System.out.println("Name: "+name);
}
}
class TestDemo{
public static void main(String [] args)
{
Student s1=new Student();
s1.show();
}
}
Output:
Output:
Roll: 0
Marks: 0.0
Name: null
Explanation: In the above class, we are not creating any constructor so compiler provides a default
constructor. Here 0, 0.0 and null values are provided by default constructor.
parameterized constructor
If any constructor contain list of variable in its signature is known as paremetrized
constructor. A parameterized constructor is one which takes some parameters.
Syntax
class ClassName
{
.......
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}
Syntax to call parametrized constructor
ClassName objref=new ClassName(value1, value2,.....);
OR
new ClassName(value1, value2,.....);
Example of Parametrized Constructor
class TestDemo1
{
int a, b;
Test(int n1, int n2)
{
System.out.println("I am from Parameterized Constructor...");
a=n1;
b=n2;
}
void display()
{
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
public static void main(String args [])
{
TestDemo1 t1=new TestDemo1 (10, 20);
t1.display();
}
}
Output:
I am from Parameterized Constructor...
Value of a = 10
Value of b = 20
.
This keyword
This is a keyword is used for following purposes
1. It refers the current class object(both state and behavior)
2. It also refers to current class constructor
3. If there is ambiguity between the instance variable and method parameter, this keyword
resolves the problem of ambiguity.
Example-1
class Student11
{
int id;
String name;
Student11(int id,String name)
{
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
The this keyword can be used to invoke current class method (implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
class S{
void m(){
System.out.println ("method is invoked");
}
void n(){
this.m ();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Output:
Method is invoked
Rules to use this()
this() constructir always should be the first statement of the constructor. One constructor can call
only other single constructor at a time by using this().

Static:
 The static is a keyword in java which is used for memory management mainly.
 We can apply static keyword with variables, methods, blocks and nested class.
 The static keyword belongs to the class than instance of the class.
Java static variable:
If you declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees, college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.
Syntax for Static variable:
class A
{
static int b;
}
Advantage of static variable:
 It makes your program memory efficient (i.e. it saves memory).
Java static method:
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than object of a class.
o A static method can be invoked without creation of object
o A static method can access static data member and can change the value of it.
Syntax for Static method:
static void fun2()
{
......
......
}
Example of static method:
//Program of changing the common property of all objects (static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change ();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm
create object first then call main () method that will lead the problem of extra memory allocation.
Java static block:
 Is used to initialize the static data member.
 It is executed before main method at the time of classloading
Example of static block
class staticBlock{
stati {
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main

Q) Can we execute a program without main() method?


Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
Static nested class:
 A static class i.e. created inside a class is called static nested class in java.
 It cannot access non-static data members and methods. It can be accessed by outer class
name.
 It can access static data members of outer class including private.
Example for static nested class
class TestOuter1
{
static int data=30;
static class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
Java Garbage Collection:
 In java, garbage means unreferenced objects.
 Garbage Collection is process of removing the runtime unused memory automatically.
 In other words, it is a way to destroy the unused objects.
 To do so, we were using free () function in C language and delete () in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection:
 It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.
 It is automatically done by the garbage collector (a part of JVM) so we don't need to make
extra efforts.
How can an object be unreferenced?
There are many ways:
1. By nulling the reference
2. By assigning a reference to another
3. By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee (); e=null;
2) By assigning a reference to another:
Employee e1=new Employee ();
Employee e2=new Employee ();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object: new Employee ();
Finalize () method:
This is a method which is always invoked by garbage collector just before destroying an
object to perform clean up activities.
This method is defined in Object class as:
protected void finalize () { }
Note: The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
GC () method: The gc () method is used to invoke the garbage collector to perform cleanup
processing. The gc () is found in System and Runtime classes.
public static void gc () {}
Note: Garbage collection is performed by a daemon thread called Garbage Collector (GC). This
thread calls the finalize () method before object is garbage collected.
Simple Example of garbage collection in java:
public class TestGarbage1 {
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
Inheritance
Inheritance:
1. It is a mechanism in which one object acquires all the properties and behaviors of parent
class.
2. The idea behind inheritance in java is that you can create new classes that are built upon
existing classes.
3. When you inherit from an existing class, you can reuse methods and fields of parent class,
and you can add new methods and fields also.
4. Inheritance represents the IS-A relationship, also known as parent-child relationship.
5. Parent Class is also known as Super/Base class.
6. Child class is also known as Sub/Derived class.
Why use inheritance in java:
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
extends: It is a keyword which extends the properties and behavior of its parent class.
A class that is inherited is called a super class. The new class is called a subclass.
Types of Inheritance
 Single inheritance.
 Multi level inheritance.
 Hierarchical inheritance.
 Multiple inheritance.
Single inheritance: means extending only one child class from only one parent class.
Multi Level Inheritance: means extended from a child class. Here child is working as both child
for a parent class and a parent for the child class.
Hierarchical inheritance: means one parent class having many child classes.
Multiple inheritance: means a child class is derived from multiple parent classes. But Java does
not directly implement multiple inheritance, and this concept will be implemented using 'Interface'.
Syntax of Java Inheritance:
Class Subclass-name extends Super class-name
{
//methods and fields
}
Example for Single Inheritance:
class Employee
{ int empno;
String ename;
void display()
{
System.out.println(empno+" "+ename);
}
}
class BankEmployee extends Employee
{
int hra;
void display()
{
System.out.println(empno+" "+ename+" "+hra);
}
public static void main(String args[])
{
BankEmployee b1=new BankEmployee();
b1.empno=12;
b1.ename="mahesh";
b1.hra=52;
b1.display();
}
}
Output:
12 mahesh 52
Example for MultiLevel Inheritance:
class Car{
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
Example for Hierarchical Inheritance
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
method of Class A
method of Class A
method of Class A
Method Overriding:
 If a subclass contain the same methods as declared in the parent class, it is known as method
overriding .
 In other words, if a subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
 Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding:
1. Method must have same name as in the parent class
2. Method must have same parameter as in the parent class.
3. Method must be IS-A relationship (inheritance).
Runtime Polymorphism Achieved through Method Overriding
class Parent{
void property()
{
System.out.println("Gold");
}
}
class Child extends Parent{
void property()
{
System.out.println("Gold and land");
}
public static void main(String args[]) {
Parent parent=new Parent();
Child child=new Child();
parent.property();
child. property ();
}
}
Output:
Gold
Gold and land
Difference between method overloading and method overriding
No. Method Overloading Method Overriding
1) Method overloading is Method overriding is used to provide the specific
used to increase the implementation of the method that is already
readability of the program. provided by its super class.

2) Method overloading is Method overriding occurs in two classes that have IS-
performed within class. A (inheritance) relationship.

3) In case of method In case of method overriding, parameter must be


overloading, parameter same.
must be different.

4) Method overloading is the Method overriding is the example of run time


example of compile time polymorphism.
polymorphism.

5) Return type can be same Return type must be same


or different in method
overloading. But you must
have to change the
parameter.
Super keyword:
1. It is used to access the super class instatance variable
2. It is used to access the super class instance method.
3. It is used to access the super class constructor.
Real time example:
class Vehicle{
int speed=30;
Vehicle()
{
System.out.println("Vehicle speed is"+speed);
}
void message(){
System.out.println("this is vehicle class");
}
}
class Bike extends Vehicle {
int speed=50;
Bike() {
super();
System.out.println("Bike speed is"+speed);
}
void display(){
super.message();
System.out.println("super class varible"+super.speed);
System.out.println("this is Bike class");
}
public static void main(String args[])
{

Bike b=new Bike();


b.display();
}
}
Output:
Vehicle speed is30
Bike speed is50
this is vehicle class
super class varible30
this is Bike class
Final keyword:
 Final is a keyword which is used to restrict the user.
 The java final keyword can be used in many contexts.
Final can be:
1. variable
2. method
3. class

In Java programming we have two types of classes they are


 Concrete class
 Abstract class
Concrete class: A concrete class is a class which contains fully defined methods or implemented
method.
NOTE: Every concrete class has specific features and these classes are used for specific
requirement, but not for common requirement.
Abstraction
Abstraction:
It is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details.
Example 1: Sending SMS, you just type the text and send the message. You don't know the internal
processing about the message delivery.
Example 2: ATM Machine; All are performing operations on the ATM machine like cash
withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about
ATM.
NOTE: Abstraction lets you focus on what the object does instead of how it does it.
There are two ways to achieve abstraction
1. Abstract class
2. Interface
Abstract class:
 A class that is declared with abstract keyword is known as abstract class.
 An abstract class is class which contains some defined methods and some undefined
methods.
 In java programming undefined methods are known as un-Implemented or abstract
method.
Syntax:
abstract class className
{
..................................................
}
Abstract method:
An abstract method is one which contains only declaration or prototype but it never contains
body or definition.
Syntax:
abstract ReturnType methodName (List of formal parameter)
Create an Object of abstract class: An object of abstract class cannot be created directly, but it can
be created indirectly. It means you can create an object of abstract derived class. You can see in
above example
Example:
abstract class Animal{
void drinks()
{
System.out.println("animal drink the water");
}
abstract void eat();
}
class Cow extends Animal
{
void eat()
{
System.out.println("cow eats grass");
}
public static void main(String args[])
{
Animal animal=new Cow();
animal.eat();
animal.drink();
}

}
Output:
cow eats grass
animal drink the water
Interface:
 Interface is a collection of public static final variables (constants) and abstract methods.
 The interface is a mechanism to achieve fully abstraction and multiple inheritance.
 There can be only abstract methods in the interface.
Properties of Interface:
 It is implicitly abstract. So we no need to use the abstract keyword when declaring an
interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.
 All the data members of interface are implicitly public static final.
Declaring Interfaces:
The interface keyword is used to declare an interface.
Example
interface Person
{
datatype variablename=value;
//Any number of final, static fields
returntype methodname (list of parameters or no parameters)
//Any number of abstract method declarations
}
Implementing Interfaces:
Implements is a keyword which is used to implement an interface.
Example
interface Moveable
{
int AVG_SPEED = 40;
void move();
}
class Vehicle implements Moveable
{
public void move()
{
System.out.println("Average speed is :"+AVG_SPEED);
}
public static void main (String[] arg)
{
Moveable mv=new Vehicle();
mv.move();
}
}
Output:
Average speed is :40
When we use abstract and when Interface:
If we do not know about any thing implementation just we have requirement specification
then we should be go for Interface
If we are talking about implementation but not completely (partially implemented) then we
should be go for abstract
Difference between Abstract class and Interface
Abstract class Interface
It is collection of abstract method and
1 It is collection of abstract method.
concrete methods.

There properties can be reused commonly in There properties commonly usable in any
2
a specific application. application of java environment.

3 It does not support multiple inheritance. It support multiple inheritance.

Abstract class is preceded by abstract


4 It is preceded by Interface keyword.
keyword.

Which may contain either variable or


5 Which should contains only constants.
constants.

The default access specifier of abstract class There default access specifier of interface
6
methods are default. method are public.

These class properties can be reused in other These properties can be reused in any other
7
class using extend keyword. class using implements keyword.

Inside interface we can not take any


8 Inside abstract class we can take constructor.
constructor.

For the abstract class there is no restriction For the interface it should be compulsory to
9 like initialization of variable at the time of initialization of variable at the time of variable
variable declaration. declaration.

There are no any restriction for abstract class For the interface variable can not declare
10
variable. variable as private, protected, transient, volatile.

There are no any restriction for abstract class For the interface method can not declare
11 method modifier that means we can use any method as strictfp, protected, static, native,
modifiers. private, final, synchronized.

Multiple Inheritance using interface:


interface Developer
{
void disp();
}
interface Manager
{
void show();
}
class Employee implements Developer, Manager
{
public void disp()
{
System.out.println("Hello Good Morning");
}
public void show()
{
System.out.println("How are you ?");
}
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}
Output:
Hello Good Morning
How are u?
Packages
Package: A package is a collection of similar types of classes, interfaces and sub-packages.
Purpose of package:
 The purpose of package concept is to provide common classes and interfaces for any program
separately.
 In other words if we want to develop any class or interface which is common for most of the
java programs than such common classes and interfaces must be placed in a package

Packages in Java are the way to organize files when a project has many modules. Same like we
organized our files in Computer. For example we store all movies in one folder and songs in other
folder, here also we store same type of files in a particular package for example in awt package have
all classes and interfaces for design GUI components.
Type of packages:
1. Predefined or built-in package
2. User defined package
Predefined package: These are the packages which are already designed by the Sun Microsystems
and supply as a part of java API, every predefined package is collection of predefined classes,
interfaces and sub-package.
User defined package: If any package is design by the user is known as user defined package. User
defined package are those which are developed by java programmer
Rules to create user defined package:
 Package statement should be the first statement of any package program.
 Choose an appropriate class name or interface name and whose modifier must be public.
 Any package program can contain only one public class or only one public interface but it
can contain any number of normal classes.
 Package program should not contain any main class (that means it should not contain any
main())
 Modifier of constructor of the class which is present in the package must be public. (This is
not applicable in case of interface because interfaces have no constructor.)
 The modifier of method of class or interface which is present in the package must be public
(This rule is optional in case of interface because interface methods by default public)
 Every package program should be save either with public class name or public Interface
name.
Compile package programs:
For compilation of package program first we save program with public className.java and it
compile using below syntax:
Syntax:
javac -d . className.java
Syntax:
javac -d path className.java
Explanations: In above syntax "-d" is a specific tool which is tell to java compiler create a separate
folder for the given package in given path. When we give specific path then it creates a new folder at
that location and when we use. (dot) then it crates a folder at current working directory.
Note: Any package program can be compile but cannot be execute or run. These programs can be
executed through user defined program which are importing package program.
Example of package program:
A.java
package vawe;
public class A
{
public static void main(String args[])
{
System.out.println("welcome to package");
}
}

Note: -d represents current directory


Access Modifiers in java:
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or
class.
There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc. Here, we will learn access modifiers.
private access modifier: The private access modifier is accessible only within class.
Simple example of private access modifier
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor: If you make any class constructor private, you cannot create the
instance of that class from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
Default access modifier: If you don't use any modifier, it is treated as default bydefault. The default
modifier is accessible only within package.
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.
Example of default access modifier
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Protected access modifier: 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.Example of protected access
modifier: 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 A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output: Hello
Public access modifier: The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Wrapper classes
 For each and every fundamental data type there exist a pre-defined class, such predefined
class is known as wrapper class.
 The purpose of wrapper class is to convert Primitive type data into Objects
Why use wrapper classes:
We know that in java whenever we get input form user, it is in the form of string value so
here we need to convert these string values in different different data types (numerical or
fundamental data), for this conversion we use wrapper classes.
class WraperDemo{
public static void main(String args[]) {
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
System.out.println(a+b);
}
}
The following table gives fundamental data type corresponding wrapper class name and
conversion method from numerical String into numerical values or fundamental value
Fundamental Wrapper Conversion method from numeric string into
DataType CalssName fundamental or numeric value
byte Byte public static byte parseByte(String)

short Short public static short parseShort(String)

int Integer public static integer parseInt(String)

long Long public static long parseLong(String)

float Float public static float parseFloat(String)

double Double public static double parseDouble(String)

char Character

boolean Boolean public static boolean parseBoolean(String)


How to use wrapper class methods:
All the wrapper class methods are static in nature so we need to call these method using
class.methodName ().
 for Integer: int x=Integer.parseInt(String);
 for float: float x=Float.parseFloat(String);
 for double: double x=Double.parseDouble(String);
Each and every wrapper class contains the following generalized method for converting numeric
String into fundamental values.

Here xxx represents any fundamental data type


Exception Handling
Exception Handling:
 The objective of exception handling is graceful termination of the program(we should not
miss anything)
 Defining an altenative way to continue with rest of the program normally(maintain normal
flow of program)
 It converts system error messages into user friendly error messages
 It is used to handle run time errors
For Example: when you divide any number by zero then system generate / by zero so this is not
understandable by user so you can convert this message into user friendly error message like Don't
enter zero for denominator.
Let's take a scenario:
------------------------------
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of
the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling,
rest of the statement will be executed. That is why we use exception handling in java.
Exception: An Exception is an Un-Expected event/situation that disrupts the normal flow of the
application.
Drawback:we miss/loose something when exception is raised.

Type of Exceptions:
1. Checked Exception
2. Un-Checked Exception
Checked Exception:
1. Checked Exceptions are exceptions which are checked by compiler that means these
exceptions are occurred at compile time rather than runtime.
2. These exceptions are directly sub-classed of java.lang.Exception class.
Un-Checked Exception:
1. Un-checked exceptions are exceptions which are not checked by the compiler and which are
checked at runtime
2. These exceptions are directly sub-class of java.lang.RuntimeException class.

Difference between checked Exception and un-checked Exception:

Difference between Error and Exception:

Use five keywords for Handling the Exception


1. try
2. catch
3. finally
4. throws
5. throw
Syntax for handling the exception:
try
{
// statements causes problem at run time
}
catch(type of exception-1 object-1)
{
// statements provides user friendly error message
}
catch(type of exception-2 object-2)
{
// statements provides user friendly error message
}
finally
{
// statements which will execute compulsory
}
Try block:
1. Try block is a block which contains Exception caused statements
2. In other words try block always contains problematic statements.
Important points about try block
1. If any exception occurs in try block then CPU controls comes out to the try block and executes
appropriate catch block..
2. Each and every try block must be immediately followed by catch (or) finally block
Syntax
try
{
.....
}
/* Here no other statements are allowed
between try and catch block */
catch()
{
....
}
4. One try block can contains another try block that is nested or inner try block can be possible.
Syntax
try
{
.......
try
{
.......
}
}
Catch block:
1. Inside catch block we write the block of statements which will generates user friendly error
messages.
2. Catch block will execute exception occurs in try block.
3. You can write multiple catch blocks for generating multiple user friendly error messages to
make your application strong. You can see below example.
4. At a time only one catch block will be executed out of multiple catch blocks.
5. In catch block you declare an object of sub class and it will be internally referenced by JVM.
Example for Exception handling
import java.util.Scanner;
class ExceptionDemo
{
public static void main(String[] args)
{
int n=10, a,res;
System.out.println("Enter a number");
Scanner s=new Scanner(System.in);
a=s.nextInt();
try
{
res=n/a;
}
catch(Exception e)
{
System.out.println("Denominator not be zero");
}
}
}
Output:
Enter a number
0
Denominator not be zero
Multiple catch block
You can write multiple catch blocks for generating multiple user friendly error messages to
make your application strong. You can see below example.
Example
import java.util.*;
class ExceptionDemo
{
public static void main(String[] args)
{
int a, b, ans=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any two numbers: ");
try
{
a=s.nextInt();
b=s.nextInt();
ans=a/b;
System.out.println("Result: "+ans);
}
catch(ArithmeticException ae)
{
System.out.println("Denominator not be zero");
}
catch(Exception e)
{
System.out.println("Enter valid number");
}
}
}
Finally block:
1. Finally is a block that is used to execute important code such as closing connection, stream
etc.
2. Finally block is always executed whether there is an exception or not.
3. Finally block must be followed by try or catch block.
4. Writing finally block is optional.
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}
finally
{
System.out.println("I am from finally block");
}
}
}
Exception Classes
Exception are mainly classified into two type checked exception and un-checked exception.
Checked Exception Classes
 FileNotFoundException
 ClassNotFoundException
 IOException
 InterruptedException
Un-Checked Exception Classes
 ArithmeticException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
 NumberFormateException
 NullPointerException
 NoSuchMethodException
 NoSuchFieldException
FileNotFoundException
If the given filename is not available in a specific location (in file handling concept) then
FileNotFoundException will be raised. This exception will be thrown by the FileInputStream,
FileOutputStream, and RandomAccessFile constructors.

ClassNotFoundException
If the given class name is not existing at the time of compilation or running of program then
ClassNotFoundException will be raised. In other words this exception is occurred when an
application tries to load a class but no definition for the specified class name could be found.
IOException
This is exception is raised whenever problem occurred while writing and reading the data in
the file. This exception is occurred due to following reason;
 When try to transfer more data but less data are present.
 When try to read data which is corrupted.
 When try to write on file but file is read only.
InterruptedException
This exception is raised whenever one thread is disturb the other thread. In other words this
exception is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is
interrupted, either before or during the activity.
ArithmeticException
This exception is raised because of problem in arithmetic operation like divide by zero. In
other words this exception is thrown when an exceptional arithmetic condition has occurred. For
example, an integer “divides by zero".
Example
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
}
}
}
ArrayIndexOutOfBoundsException
This exception will be raised whenever given index value of an array is out of range. The
index is either negative or greater than or equal to the size of the array.
Example
int a[]=new int[5];
a[10]=100; //ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
This exception will be raised whenever given index value of string is out of range. The index
is either negative or greater than or equal to the size of the array.
Example
String s="Hello";
s.charAt(3);
s.charAt(10); // Exception raised
chatAt() is a predefined method of string class used to get the individual characters based on index
value.

NumberFormateException
This exception will be raised whenever you trying to store any input value in the un-
authorized datatype.
Example: Storing string value into int datatype.
Example
String s="hello";
int i=Integer.parseInt(s);//NumberFormatException
NoSuchMethodException
This exception will be raised whenever calling method is not existing in the program.
NullPointerException
A NullPointerException is thrown when an application is trying to use or access an object
whose reference equals to null.
Example
String s=null;
System.out.println (s.length());//NullPointerException
StackOverFlowException
This exception throws when full the stack because the recursion methods are stored in stacks
area.
Throw:
 throw keyword is used to explicitly throw an exception.
 We can throw either checked or uncheked exception by throw keyword.
 The throw keyword is mainly used to throw custom exception.
Example throw keyword using Unchekced Exception
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException();
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try
{
validate(13);
}catch(Exception e){
System.out.println("Doesn't enter the value bellow 18");
}
System.out.println("rest of the code...");
}
}
Output:
Doesn't enter the value bellow 18
rest of the code...
throws
 throws keyword is used to declare an exception.
 It gives information to the programmer that there may occur an exception so it is better for
the programmer to provide the exception handling code so that normal flow can be
maintained.
Note: 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 performing
check up before the code being used.
Syntax
returnType methodName(parameter)throws Exception_class....
{
.....
}
Example of throws keyword
import java.io.IOException;
class TestThrow1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
public static void main(String args[])
{
TestThrow1 obj=new TestThrow1();
obj.m();
System.out.println("normal flow...");
}
}
Output:
Exception is caught atjava.io.IOException: device error
normal flow...
Java Custom Exception:
If you are creating your own Exception that is known as custom exception or user-defined
exception.
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try{
validate(13);
}catch(Exception m)
{
System.out.println("Doesn't enter any value bellow 18 years");
}
System.out.println("rest of the code...");
}
}
Output:
Doesn't enter any value bellow 18 years
rest of the code...
Difference between throw and throws keyword
No. Throw throws
1) Java throw keyword is used to Java throws keyword is used to declare an
explicitly throw an exception. exception.

2) Checked exception cannot be Checked exception can be propagated with


propagated using throw only. throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws
IOException,SQLException.
Que) Can we rethrow an exception?
Yes, by throwing same exception in catch block.
Multithreading
Multithread:
 Multithreading is a process of executing multiple threads simultaneously.
 The aim of multithreading is to achieve the concurrent execution.
 A Thread is basically a lightweight sub-process, a smallest unit of processing.
 Threads share a common memory area. They don't allocate separate memory area so saves
memory, and context-switching between the threads takes less time than process.
 Multithreading is mostly used in games, animation, server side programming etc.
Life cycle of a Thread (Thread States)
State of a thread are classified into five types they are
1. New State
2. Runnable(ready) state
3. Running State
4. Waiting State(Blocking)
5. Dead State(Terminated state)

New State
The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.
Ready State
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
Running State
The thread is in running state if the thread scheduler has selected it.
Waiting State (Non Runnable or Blocked state)
This is the state when the thread is still alive, but is currently not eligible to run.
Dead State
If the thread execution is stoped permanently than it comes under dead state
Note: If the thread is in new or dead state no memory is available but sufficient memory is
available if that is in ready or running or waiting state.
Multithreading can be achieved in two different ways.
1. Using thread class
2. Using Runnable interface
Using thread class
In java language multithreading program can be created by following below rules.
1. Create any user defined class and make that one as a derived class of thread class.
class Class_Name extends Thread
{
........
}
2. Override run() method of Thread class (It contains the logic of performing any operation)
3. Create an object for user-defined thread class and attached that object to predefined thread
class object.
4. Class_Name obj=new Class_Name Thread t=new Thread(obj);
5. Call start () method of thread class to execute run() method.
6. Save the program with filename.java
Example
class Thread1 extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
System.out.println("Thread 1 :"+i);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}

}
}
}
class Thread2 extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
System.out.println("Thread 2 :"+i);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}

}
}
}
class Result
{
public static void main(String args[])
{
Thread1 t1=new Thread1(); // ready state
Thread2 t2=new Thread2 ();
t1.start(); // running state
t2.start();
}
}
Output:

By using the Runnable interface:


class MyThread1 implements Runnable
{
public void run()
{
for (int i=1;i<5;i++)
{
System.out.println("Thread 1 :"+i);
try
{
Thread.sleep (1000);
}
catch (InterruptedException e)
{
System.out.println (e);
}

}
}
}
class MyThread2 implements Runnable
{
public void run()
{
for(int i=1;i<5;i++)
{
System.out.println("Thread 2 :"+i);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
}
class Result
{
public static void main(String args[])
{
MyThread1 mt1=new MyThread1();
MyThread2 mt2=new MyThread2 ();
Thread t1 =new Thread(mt1);
Thread t2=new Thread(mt2);
t1.start();
t2.start();
}
}
Output:

Constructors of Thread class


1. Thread()
2. Thread(String name)
3. Thread(object)
4. Thread(object, String name)
Thread ()
Which will be execute to set the predefined name for newly created thread, these names are
generally in the form of thread -0, thread -1, ....
Syntax to call constructor:
Thread t=new Thread ();
Thread (String name)
Which can be used to provide user defined name for newly created thread?
Syntax
Thread t=new Thread ("new thread");
Thread (object)
Which can be used to provide default name for newly created user defined thread?
Syntax
UserdefinedThreadclass obj=new UserdefinedThreadclass ();
Thread t=new Thread ("obj");
Object, String name
Which will be used to provide user defined name for the newly created user defined thread?
Syntax
UserdefinedThreadclass obj=new UserdefinedThreadclass ();
Thread t=new Thread (object, "secondthread");
Methods of Thread class
1. getPriority()
2. setPriority()
3. getName()
4. setName()
5. isDeamon()
6. run()
7. start()
8. sleep()
9. currentThread()
10. wait()
11. notify()
12. notifyAll()
getPriority ()
This method is used to get the current priority of thread.
Thread t=new Thread ();
int x=t.getPriority();
System.out.println(x);
setPriority ()
This method is used to set the current priority of thread.
Thread t=new Thread ();
t.setPriority (any priority number between o to 10)
or
t.setPriority (Thread.MAX-PRIORITY)
getName()
This method is used to get the current executing thread name.
Thread t=new Thread();
String s=t.getName();
System.out.println(s);
setName()
This method is used to set the userdefined name for the thread.
Thread t=new Thread();
t.setName("mythread");
isDeamon()
Which returns true if the current thread is background thread otherwise return false.
Thread t=new Thread();
boolean b=t.isDeamon();
run()
Which contains the main business logic that can be executed by multiple threads
simultaneously in every user defined thread class run method should be overridden.

public Class_Name extends Thread


{
public void run()
{
.....
.....
}
}
start ()
Used to convert ready state thread to running state.
Thread t=new Thread ();
t.start ();
sleep ()
Used to change running state thread to ready state based on time period it is a static method
should be called with class reference.
public static final sleep(long millisecond)throws InterruptedException
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
........
........
}
}
Once the given time period is completed thread state automatically change from waiting to running
state.
currentThread()
Used to get the current thread detail like thread name thread group name and priority
Thread t=new Thread();
t.currentThread();
Note:
The default thread name is thread-0, (if it is a main thread default name is main)
The default thread group name is main
Default thread priority is "5" is normal priority.
Example for Setting and getting for Thread
class NamesForThread extends Thread
{
public void run()
{
System.out.println("The First thread name is "+Thread.currentThread().getName());
}
public static void main(String args[])
{
System.out.println("The current thread is "+Thread.currentThread().getName());
NamesForThread t1=new NamesForThread();
t1.start();
t1.setName("NamesForThread");
}
}
Output:
The current thread is main
The First thread name is NamesForThread
Thread class properties
Thread class contains constant data members, constructors, and predefined methods.
Constant data members
1. MAX-PRIORITY
2. MIN-PRIORITY
3. NORM-PRIORITY
MAX-PRIORITY
Which represent the Maximum priority that a thread can have whose values is 10.
Syntax:
public static final int MAX-PRIORITY=10
MIN-PRIORITY
Which represents the minimum priority that a thread can have?
Syntax:
public static final int MIN-PRIORITY=0
NORM-PRIORITY
Which represent the default priority that is assigned to a thread.
Syntax:
public static final int NORM-PRIORITY=5
Example
class MyThread1 extends Thread{
public void run(){
System.out.println("it is mythread1() method");
}
}
class MyThread2 extends Thread{
public void run()
{
System.out.println("it is mythread2() method");
}
}
class Result {
public static void main(String[] args) {
MyThread1 m1=new MyThread1();
MyThread2 m2=new MyThread2();
m1.start();
m2.start();
m1.setPriority(Thread.NORM_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
}
}
Output:
it is mythread2() method
it is mythread1() method
Synchronization:
It is the capability to control the access of multiple threads to any shared resource. Java
Synchronization is better option where we want to allow only one thread to access the shared
resource.
Synchronized method:
Whenever we want to allow only one thread at a time among multiple thread for execution of
a method than that should be declared as synchronized method.
Syntax:
class Class_Name implement Runnable or extends Thread
{
public void run()
{
synchronized void fun()
{
.......
.......
}
public void run()
{
fun();
....
}
}
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
Inter-thread communication:
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in
its critical section and another thread is allowed to enter (or lock) in the same critical section to be
executed.It is implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()
class Customer
{
int amount=10000;
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try{
wait();
}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{
public void run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
Arrays:
Normally, array is a collection of similar type of elements that have contiguous memory
location. Java array is an object the contains elements of similar data type. It is a data structure where
we store similar elements. We can store only fixed set of elements in a java array. Array in java is
index based; first element of the array is stored at 0 index.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multi dimensionalArray
Single Dimensional Array in java
Syntax to Declare an Array in java
DataType [] arr; (or)
dataType arr[];
Instantiation of an Array in java
arrayRefVar=new datatype[size];
Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Declaration, Instantiation and Initialization of Java Array:
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Example for single dimensional:
import java.util.Arrays;
import java.util.Scanner;
public class One_DimensionalArray {
public static void main(String ar[]){
Scanner s=new Scanner(System.in);
System.out.println("how many elements u want to eneter");
int n=s.nextInt();
int a[]=new int[n];
System.out.println("Enter the elements ");
for(int i=0;i<a.length;i++)
{
a[i]=s.nextInt();
}
System.out.println("after the elements ");
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]+" ");
}
System.out.println("after sorting the elements ");
Arrays.sort(a);
/*for(int j=0;j<a.length;j++)
{
System.out.println(a[j]+" ");
}
*/
for(int j:a)
{
System.out.println(j+" ");
}
System.out.println("the element at found at"+Arrays.binarySearch(a, 3));
}
}
Output:
how many elements u want to eneter
5
Enter the elements
44
2
0
5
3
after the elements
44
2
0
5
3
after sorting the elements
0
2
3
5
44
the element at found at2
Passing Array to method in java:
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
public class Passing_Array_Method
{
static void min(int arr[])
{
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]+" ");
}
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
Output:
33
3
4
5
Twodimensional: In such case, data is stored in row and column based index (also known as matrix
form).
Syntax to Declare Twodimensional Array
dataType [][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Twodimensional Array
int[][] arr=new int[3][3];//3 row and 3 column
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Twodimensional array: Let's see the simple example to declare instantiate, initialize
and print the 2Dimensional array.
Addition of 2 matrices in java
import java.util.Scanner;
public class Two_dimensional
{
public static void main(String args[])
{

Scanner s=new Scanner (System.in);

int rows=2,col=2;

int first[][]=new int[2][2];


int second[][]=new int[2][2];
int result[][]=new int[2][2];

System.out.println("enter elements into first matrix");

for(int i=0;i<rows;i++)
{
for(int j=0;j<col;j++)
{
first[i][j]=s.nextInt();
}
}
System.out.println("enter elements into second matrix");

for(int i=0;i<rows;i++)
{
for(int j=0;j<col;j++)
{
second[i][j]=s.nextInt();
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<col;j++)
{
result[i][j]=first[i][j]+second[i][j];
}
}
System.out.println("the resultant matrix is");
for(int i=0;i<rows;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(result[i][j]+" ");

}
System.out.println(" ");
}
}
}
Output:
enter elements into first matrix
1
2
3
4
enter elements into second matrix
2
3
4
5
the resultant matrix is
3 5
7 9
Strings
String:
 It is a predefined class in java.lang package can be used to handle the String.
 String class is immutable that means whose content cannot be changed
 String is also a sequence of characters
Ways to create string object
There are two ways to create a string object
1. By string literal
2. By new keyword
String literal:
 Java String literal is created by using double quotes.
 Strings are strored in special memory called string constant pool
For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome"; //will not create new instance
Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool.
By using new keyword:
String s1=”welcome”;
String s2=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s1 will refer to the object in
Example for Immutable String
class StingEx1
{
public static void main(String arg[])
{
String s=”sachin”;
s.concat("Tendulkar"); //concat() method appends the string at the end
System.out.println(s); //will print Sachin because strings are immutable objects
}
}
Output:
sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new object
is created with sachintendulkar. That is why string is known as immutable.

As you can see in the above figure that two objects are created but s reference variable still refers to
"Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For
example:
Methods of String class
length():This method is used to get the number of character of any string.
Example
class StingEx2
{
public static void main(String arg[])
{
int l;
String s=new String("Java");
l=s.length();
System.out.println("Length: "+l);
}
}
Output:
Length: 4
charAt(index): This method is used to get the character at a given index value.
Example
class StingEx3
{
public static void main(String arg[])
{
char c;
String s=new String("Java");
c=s.charAt(2);
System.out.println("Character: "+c);
}
}
Output:
Character: v
toUpperCase(): This method is use to convert lower case string into upper case.
Example
class StingEx4
{
public static void main(String arg[])
{
String s="Java";
System.out.println("String: "+s.toUpperCase());
}
}
Output:
String: JAVA
toLowerCase(): This method is used to convert lower case string into upper case.
Example
class StingEx5
{
public static void main(String arg[])
{
String s="JAVA";
System.out.println("String: "+s.toLowerCase());
}
}
Output:
String: java
concat (): This method is used to combined two string.
Example
class StingEx6{
public static void main(String arg[]){
String s1="Hitesh";
String s2="Raddy";
System.out.println("Combined String: "+s1.concat(s2));
}
}
Output:
Combined String: HiteshRaddy
String comparision
We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
String compare by equals() method
The String equals() method compares the original content of the string. It compares values of string
for equality. String class provides two methods:
o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this String to another string,
ignoring case.
class StingEx7{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
class StingEx8{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
String compare by == operator
The = = operator compares references not values.
class StingEx9{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
class StingEx10{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
subString(): This method is used to get the part of given string.
Example
class StingEx11
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8)); // 8 is starting index
}
}
Example
class StingEx12
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.substring(8, 12));
}
}
Output
prog
indexOf(): This method is used find the index value of given string. It always gives starting index
value of first occurrence of string.
Example
Class StingEx13
{
public static void main(String arg[])
{
String s="Java is programming language";
System.out.println(s.indexOf("programming"));
}
}
Output:
8
trim(): This method remove space which are available before starting of string and after ending of
string.
Example
class StingEx14
{
public static void main(String arg[])
{
String s=" Java is programming language ";
System.out.println(s.trim());
}
}
Ouput:
Java is programming language
String Buffer:
 It is a predefined class in java.lang package can be used to handle the String, whose object is
mutable that means content can be modified.
 StringBuffer class is working with thread safe mechanism that means multiple threads are
not allowed simultaneously to perform operation of StringBuffer.
Important Constructors of StringBuffer class:
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
Important methods of StringBuffer class:
1. public synchronized StringBuffer append(String s): is used to append the specified string
with this string. The append() method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the specified
string with this string at the specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int, float), insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String str): is
used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to delete
the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity at least
equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified position.
9. public int length(): is used to return the length of the string i.e. total number of characters.
10. public String substring(int beginIndex): is used to return the substring from the specified
beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the substring from
the specified beginIndex and endIndex.
12. What is mutable string?: A string that can be modified or changed is known as mutable
string. StringBuffer and StringBuilder classes are used for creating mutable string

append (): The append () method concatenates the given argument with this string.
class StingEx17{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
output:
Hello Java
insert(): The insert() method inserts the given string with this string at the given position.
class StingEx18{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
output:
output:
HJavaello
replace(): The replace() method replaces the given string from the specified beginIndex and
endIndex.
class StingEx19{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
delete():The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class StingEx20{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);} }
reverse(): The reverse() method of String Builder class reverses the current string.
class StingEx21{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
StringBuilder
 It is a predefined class in java.lang package can be used to handle the String.
 StringBuilder class is almost similar to StringBuffer class.
 It is also a mutable object.
 StringBuilder is not thread safe

When we use String, StringBuffer and StringBuilder

1. If the content is fixed and would not change frequently then we use String.
2. If content is not fixed and keep on changing but thread safety is required then we use
StringBuffer
3. If content is not fixed and keep on changing and thread safety is not required then we use
StringBuilder.
IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system
to make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code understand
the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams.
They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream: It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.
Byte Stream Classes: Byte stream is defined by using two abstract class at the top of hierarchy, they
are InputStream and OutputStream.

Byte stream is defined by using two abstract classes at the top of hierarchy, they are
InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
DataOutputStream An output stream that contain method for writing java standard data
type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
These classes define several key methods. Two most important are
read() : reads byte of data.
write () : Writes byte of data.
Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are
Reader and Writer.
Some important Character stream classes.
Stream class Description
BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
Reading Console Input
We use the object of BufferedReader class to take inputs from the keyboard.
BufferedReader class explanation
Java BufferedReader class is used to read the text from a character-based input stream. It can
be used to read data line by line by readLine() method. It makes the performance fast. It inherits
Reader class.
Reading Characters
read () method is used with BufferedReader object to read characters. As this function
returns integer type value has we need to use typecasting to convert it into char type.
int read() throws IOException
Below is a simple example explaining character input.
import java.io.*;
class CharRead
{
public static void main( String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a character");
char c = (char)br.read(); //Reading character
System.out.println("the entered character is :"+c);
}
}
Output:
Enter a character
E
the entered character is :E
Reading Strings: To read string we have to use readLine() function with BufferedReader class's
object.
String readLine () throws IOException
Program to take String input from Keyboard in Java
import java.io.*;
class MyInput
{
public static void main(String[] args) throws IOException
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter the string");
text = br.readLine(); //Reading String
System.out.println("The Entered string is :"+text);
}
}
Output:
Enter the string
kiran
The Entered string is :kiran
Program to read numbers from Buffered Reader class
import java.io.*;
class MyInput
{
public static void main(String[] args) throws IOException
{
int a,b;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter a value");
a=Integer.parseInt(br.readLine());
System.out.println("Enter b value");
b=Integer.parseInt(br.readLine());
System.out.println("the sum of two values are :"+(a+b));
}
}
Output:
Enter a value
4
Enter b value
5
the sum of two values are :9
Program to read from a file using BufferedReader class
import java. io.*;
class ReadTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
br.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}

Program to write to a File using FileWriter class


import java. Io *;
class WriteTest
{
public static void main(String[] args)
{
try
{
File fl = new File("d:/myfile.txt"); //
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ; // Output stream that writes to file
fw.write(str);
fw.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
Serialization and Deserializatoin:
Serialization:
 Serialization is the mechanism of saving the state of an object permanently in the form of a
file.
(Or)
 Serialization is a mechanism of writing the state of an object into a byte stream.
 It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
 It is mainly used to travel object's state on the network (known as marshaling).
java.io.Serializable interface
 Serializable is a marker interface (has no data member and method).
 It is used to "mark" java classes so that objects of these classes may get certain capability.
The Cloneable and Remote are also marker interfaces.
 It must be implemented by the class whose object you want to persist.
 The String class and all the wrapper classes implements java.io.Serializable interface by
default.
Student.java:
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Note: The above class is known as java bean class or component style based programming or POJO
(Plain Old Java Object) class.
Steps for SERIALIZATION process:
1. Create an object of Serializable sub class.
For example:
Student s=new Student();
2. Call the constructor to place user defined values in a Serializable sub class object.
For example:
Student(211,"ravi");
3. Choose the file name and open it into write mode or output mode with the help of
java.io.FileOutputStream
For example:
FileOutputStream fout=new FileOutputStream("f.txt");
4. Since an object of FileOutputStream cannot write the entire object at a time to the file.Hence, it
is recommended to use a predefined class called ObjectOutputStream class. ObjectOutputStream
class contains the following constructor which takes an object of FileOutputStream class.
For example:
ObjectOutputStream out=new ObjectOutputStream(fout);
5. In order to write the entire object at a time to the file ObjectOutputStream contains the
following method:
For example:
out.writeObject(s1);
6. Close the files which are opened in write mode.
For example:
Out.close();
Fout.close();
Write a java program which will save the Serializable sub class object into a file?
Persist.java
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
System.out.println("STUDENT OBJECT SAVED SUCCESSFULLY ");
out.close();
fout.close();
}
}
OUTPUT:
STUDENT OBJECT SAVED SUCCESSFULLY
De-Serializable:
It is the process of retrieving the record from the file into main memory of the computer.
Steps for DE-SERIALIZATION process:
1. Choose the file name and open it into read mode with the help of FileInputStream class.

For example:
FileInputStream fis=new FileInputStream("f.txt");

2. Since an object of FileInputStream cannot read the entire object at a time from the file. Hence, it is
recommended to create an object of ObjectInputStream class
ObjectInputStream class contains the following constructor which takes object of
FileInputStream as a parameter.

For example:
ObjectInputStream ois=new ObjectInputStream (fis);

3. ObjectInputStream class contains the following method which will read the entire object at a
time where ever ObjectInputStream is pointing.

For example:
Object obj=ois.readObject ();
4. An object of Object does not contain set of get methods and they are defined in its sub class
called Student. Hence, an object of Object must be type casted to Serializable sub class object.
For example:
s= (Student) obj;
5.Apply set of get methods to obtain the data from de-serialized object i.e., s.
For example:
System.out.println(s.id+" "+s.name);
6. Close the files which are opened in read mode or input mode.
For example:
ois.close ();
fis.close ();

Persist.java
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
FileInputStream fis=new FileInputStream("f.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Student s=(Student)ois.readObject();
System.out.println(s.id+" "+s.name);
ois.close ();
fis.close ();
}
}
Output:
211 ravi
Collection Framework

What is Collection?
A Collection is simply an object that groups multiple elements into a single unit.
(Or)
If u want to represent a group of individual elements as a single entity
What is Framework?
A Framework provides readymade architecture and represents set of classes and
interfaces.
Where use Collection Framework?
All the operations that we want to perform on a data such as searching, sorting, insertion,
deletion etc. Before storing or moving the data to permanent memory location, first performed by
Java Collection Framework
Collection Framework API:
Collection Framework API is a java API that is contains all Interfaces and classes of
Collection Framework which is used for perform searching, sorting, insertion, manipulation,
deletion operations.
Java.util package
Interfaces in Collection Framework
 List [Duplicates are allowed and Insertion order must be preserved]
The implementation classes are Array List, Vector, and Linked list, Stack….etc.
 Set [no duplicates and no order]
The implementation classes are HashSet
 Sorted Set : [No duplicates and all the objects should be stored a/c to some sorting
algorithms]
The implementation classes are TreeSet
Second part of Collection Framework
 Map [I] : [If we want to represent group of key and value pairs] [sno,snames]
 Hash Map: [If we want to represent group of key and value pairs in no order and
duplicates are not allowed]
 Sorted Map [I]: [If we want to represent group of key and values a/c to some sorting
order keys and duplicates are not allowed][Ex: sno a/c to asc ing order and same is
alphabetical order]
Collection Framework are mainly divided in two types they are;
 Legacy Collection Framework(Old and these are synchronized)
 New Collection Framework(Non synchronized)
List Interface:
List Interface is used to store multiple objects with duplicates that means it allows to store
duplicate elements. List Interface are implemented in following collection classes.
1. Vector
2. Array List
Vector:
Vector implements List Interface. Like Array List it also maintains insertion order but it is
rarely used in non-thread environment as it is synchronized and due to which it gives poor
performance in searching, adding, delete and update of its elements.
Creating a vector class object:
Vector vec = new Vector ();
Methods of Vector Class:
void addElement(Object element): It inserts the element at the end of the Vector.
int size(): It returns the current size of the vector.
Object firstElement(): It is used for getting the first element of the vector.
Object lastElement (): Returns the last element of the array.
Enumeration Interface:
It is one of the predefined interface and whose object is always used for retrieving the data
from any legacy collection framework variable (like vector, stack, Hash Table etc.) only in forward
direction but not in backward direction.
Methods of Enumeration Interface:
public boolean hasMoreElements (): Return true if Enumeration contains more elements otherwise
returns false.
public object nextElement(): Returns the next elements of Enumeration.
Create an object of Enumeration

Syntax
Vector v=new Vector();
Enumeration e=v.elements ()
VectorEx.java:
import java.util.*;
public class VectorEx {
public static void main(String args[])
{
Vector<Integer> v=new Vector<Integer>();
v.addElement(22);
v.addElement(23);
v.addElement(52);
v.addElement(66);
System.out.println("Size is: "+v.size());
System.out.println("The first element of the vector is : "+v.firstElement());
System.out.println("The last element of the vector is : "+v.lastElement());
Enumeration<Integer> en = v.elements();
System.out.print("Elements are:");
while(en.hasMoreElements())
{
System.out.print(en.nextElement() + " ");
}
}
}
Output:
Size is: 4
The first element of the vector is: 22
The last element of the vector is: 66
Elements are: 22 23 52 66
Array List:
Array List is a replacement of vector class, It is a new class used to store multiple
objects.
Points to Remember
 ArrayList class is not Synchronized.
 In the ArrayList value will be stored in the same order as inserted.
 ArrayList class uses a dynamic array for storing the elements.
 It extends AbstractList class and implements List interface.
 ArrayList class can contain duplicate elements.
Syntax:
ArrayList al=new ArrayList ();
Iterator Interface:
It is one of the predefined interface present in java.util.* package. The purpose of this interface is
that to retrieve the elements of collection only in forward direction but not in backward direction.
Points to Remember
 Using Iterator elements of collection can be accessed only in forward direction.
 Iterator can be available to all the collection classes.
 Every collection class contains Iterator () and that returns Iterator object, using this object
reference elements can be retrieved from collection.
Methods of Iterator Interface
 public boolean hasNext()
 public object next()
public boolean hasNext()
This method return true provided by Iterator interface object is having next element otherwise
it returns false.
public object next(): This method is used for retrieving next element of any collection framework
variable provided public Boolean hasNext(). If next elements are available then this method returns
true otherwise it return false.
ArrayListEx.java
import java.util.*;
class ArrayListEx{
public static void main(String args[])
{
ArrayList<Integer> arrayList=new ArrayList<Integer>(); // creating arraylist
arrayList.add(10);
arrayList.add(20);
arrayList.add(30);
System.out.print("The array list elements are :");
//By using for each loop
/*for(int i : arrayList)
{
System.out.print(i+" ");
}*/

// by using Iterator Interface which access the elements in forward direction only for legacy only
Iterator<Integer> itr=arrayList.iterator(); // getting Iterator from arraylist to traverse elements
while(itr.hasNext())
{
System.out.print(itr.next()+" ");
}
}
}
Output:
Size is: 4
The first element of the vector is: 22
The last element of the vector is: 66
22 23 52 66

Linked List class


A Linked List is a Collection of nodes. Linked List class uses doubly linked list to store the
elements. It extends the Abstract List class and implements List and Deque interfaces.

Important points Linked List

 A Linked List is a Collection of nodes.


 Linked List class is not synchronized.
 Linked List class can contain duplicate elements.
 Linked List organize the data in the form of nodes.
Syntax:
LinkedList ll=new LinkedList();
Here ll represent object name and it can be treated as Collection framework variable and it
allows us to store multiple values either of same type or different type or both the types.

Methods of LinkedList:

 public void addFirst(Object): are used for adding the elements at first position of
LinkedList.
 public void addLast(Object): are used for adding the elements at last position of
LinkedList.
 public Object getFirst(): are used for get first position elements of LinkedList.
 public Object getLast(): are used for get last position elements of LinkedList.
 public Object removedFirst(): are used for remove first position elements of LinkedList.
 public Object removedLast(): are used for remove last position elements of LinkedList.
LinkedListDemo.java
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListDemo {
public static void main(String[] args)
{
LinkedList<Integer> linkedList=new LinkedList<Integer>();
linkedList.add(45);
linkedList.add(50);
linkedList.addFirst(10);
linkedList.addLast(20);
ListIterator<Integer> li=linkedList.listIterator();
System.out.print("Forward Direction :");
while(li.hasNext())
{
System.out.print(li.next()+" ");
}
System.out.println();
System.out.print("Reverse Direction :");
while(li.hasPrevious())
{
System.out.print(li.previous()+" ");
}
}
}
Output:
Forward Direction: 10 45 50 20
Reverse Direction: 20 50 45 10
Stack:
1.
It Follows LIFO (Last in First out mechanism) principle
2. It is available in the package import java.util.Stack
Methods in Stack :
1. push() : It adds the object to the stack
2. pop() : It removes the object at top of the stack
3. peek(): It returns the top of stack
StackADT.java
import java.util.Stack;
public class StackADT
{
public static void main(String[] args)
{
Stack<Integer> stack=new Stack<Integer>();
stack.push(10);// Inserts 10 element into the stack
stack.push(3);
stack.push(5);
stack.push(7);

System.out.println ("After inserting the Elements in stack are :"+stack);


stack.pop (); //delete 7 element from stack
stack.pop ();
System.out.println ("After Deleting the Elements in stack are :"+stack);
System.out.println ("the top element of the stack is :"+stack.peek());
}
}
Output:
After inserting the Elements in stack are :[10, 3, 5, 7]
After Deleting the Elements in stack are :[10, 3]
the top element of the stack is :3
Set Interface:
1. Set Interface contains unique elements only.
2. Set Interface maintains no order
3. Set Interface is available in the package import java.util.Set
4. The implementation class for Set interface is HashSet
SetEx.java
import java.util.*;
class SetEx{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Vijay
Ravi
Sorted Set:
1. Sorted Set Interface contains unique elements only.
2.Maintains ascending order.
3. Set Interface is available in the package import java.util.SortedSet
4. The implementation class for Sorted Set interface is TreeSet
TreeSetEx.java
import java.util.*;
class TreeSetEx
{
public static void main( String args[])
{
SortedSet<String> al=new TreeSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ajay
Ravi
Vijay
Queue Interface:
1. Queue is an interface available at the package import java.util.Queue;
2. Queue follows FIFO (First in first out) model.

import java.util.LinkedList;
import java.util.Queue;
class QueueAdt
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<String>();
queue.add("suresh");
queue.add("mahesh");
queue.add("padma");
queue.add("prakash");
System.out.println("the queue elements are :"+queue);
System.out.println("Delete :"+queue.remove());
System.out.println("Delete :"+queue.remove());
System.out.println("the queue elements are :"+queue);
queue.add("siraj");
queue.add("kishore");
System.out.println("the queue elements are :"+queue);
System.out.println("Top element of queue is :"+queue.element());
}
}
Output:
the queue elements are :[suresh, mahesh, padma, prakash]
Delete :suresh
Delete :mahesh
the queue elements are :[padma, prakash]
the queue elements are :[padma, prakash, siraj, kishore]
Top element of queue is :padma
Java Map Interface
A map contains values on the basis of key i.e. key and value pair. Each key and value pair is
known as an entry. Map contains only unique keys.
Map is useful if you have to search, update or delete elements on the basis of key.
Useful methods of Map interface

Method Description

Object put (Object key, Object value) It is used to insert an entry in this map.

void putAll (Map map) It is used to insert the specified map in this map.

Object remove (Object key) It is used to delete an entry for the specified key.

Set entrySet () It is used to return the Set view containing all the keys and
values.
Map. Entry Interface
Entry is the sub interface of Map. So we will be accessed it by Map. Entry name. It
provides methods to get key and value.

Methods of Map. Entry interface

Method Description

Object getKey() It is used to obtain key.

Object getValue() It is used to obtain value.

Hash map:
 A Hash Map contains values based on the key.
 It contains only unique elements.
 It may have one null key and multiple null values.
 It maintains no order.
 It is available at the package import java.util.HashMap
 It is the implementation class for the Map interface
MapInterfaceExample.java
import java.util.*;
class MapInterfaceExample{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
map.put(102,"Rahul");
//System.out.println(map);
/*for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
} */
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
Output:
102 Rahul
100 Amit
101 Vijay

TreeMap:
A TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
 It contains only unique elements.
 It cannot have null key but can have multiple null values.
 It is same as HashMap instead maintains ascending order.
TreeMapEx.java
import java.util.*;
class TreeMapEx{
public static void main(String args[]){
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
100 Amit
101 Vijay
102 Rahul

AWT
AWT stand for abstract window toolkits. Any user interacts with java program in two different
ways;
 CUI (Command user Interface)
 GUI (Graphical user Interface)
If any user interact with java program by passing same commands through command prompt is
known as CUI, if any user interact with java program through a graphical window known as GUI.
In core java GUI can be design using some predefined classes. All these classes are defined
in java.awt package.
The predefined classes of awt package are classified into following types;

Container classes
These are the predefined classes in java.awt package which can be used to display all non-
container classes to the end user in the frame of window.
Container classes are; frame, panel.
Non-container classes
These are the predefined classes used to design the input field so that end user can provide
input value to communicate with java program; these are also treated as GUI component. Non-
container classes are; Label, Button, List etc...
Non-container classes
These are the predefined classes used to design the input field so that end user can provide
input value to communicate with java program, these are also treated as GUI component.
Label
It can be any user defined name used to identify input field like textbox, textarea etc.
Example
Label l1=new Label("uname");
Label l2=new Label("password");
TextField
This class can be used to design textbox.
Example
TextField tf=new TextField();
Example
TextField tf=new TextField(40);
Button
This class can be used to create a push button.
Example
Button b1=new Button("submit");
Button b2=new Button("cancel");
TextArea
This class can be used to design a textarea, which will accept number of characters in rows
and columns formate.
Example
TextArea ta=new TextArea(5, 10);
// here 5 is no. of rows and 10 is no. of column
Note: In above example at a time we can give the contains in textarea is in 5 rows and 9 column (n-1
columns).
Checkbox
This class can be used to design multi selection checkbox.
Example
Checkbox cb1=new Checkbox(".net");
Checkbox cb2=new Checkbox("Java");
Checkbox cb3=new Checkbox("html");
Checkbox cb4=new Checkbox("php");
CheckboxGroup
This class can be used to design radio button. Radio button is used for single selection.
Example
CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb=new Checkbox("male", cbg, "true");
Checkbox cb=new Checkbox("female", cbg, "false");
Note: Under one group many number of radio button can exist but only one can be selected at a time.
Choice
This class can be used to design a drop down box with more options and supports single
selection.
Example
Choice c=new Choice();
c.add(20);
c.add(21);
c.add(22);
c.add(23);
List
This class can be used to design a list box with multiple options and support multi selection.
Example
List l=new List(3);
l.add("goa");
l.add("delhi");
l.add("pune");
Note: By holding clt button multiple options can be selected.
Scrollbar
This class can be used to display a scroolbar on the window.
Example
Scrollbar sb=new Scrollbar(type of scrollbar, initialposition, thamb width, minmum value, maximum
value);
Initial position represent very starting point or position of thumb.
Thumb width represent the size of thumb which is scroll on scrollbar
Minimum and maxium value represent boundries of scrollbar
Type of scrollbar
There are two types of scrollbar are available;
scrollbar.vertical
scrollbar.horizental
Example
Scrollbar sb=new Scrollbar(Scrollbar.HORIZENTAL, 10, 5, 0, 100);
Awt Frame
Frame
It is a predefined class used to create a container with the title bar and body part.
Example
Frame f=new Frame();
Mostly used methods
setTitle()
It is used to display user defined message on title bar.
Example
Frame f=new Frame();
f.setTitle("myframe");
setBackground()
It is used to set background or image of frame.
Example
Frame f=new Frame();
f.setBackground(Color.red);
Example
Frame f=new Frame();
f.setBackground("c:\image\myimage.png");
setForground()
It is used to set the foreground text color.
Example
Frame f=new Frame();
f.setForground(Color.red);
setSize()
It is used to set the width and height for frame.
Example
Frame f=new Frame();
f.setSize(400,300);
setVisible()
It is used to make the frame as visible to end user.
Example
Frame f=new Frame();
f.setVisible(true);
Note: You can write setVisible(true) or setVisible(false), if it is true then it visible otherwise not
visible.
setLayout()
It is used to set any layout to the frame. You can also set null layout it means no any layout
apply on frame.
Example
Frame f=new Frame();
f.setLayout(new FlowLayout());
Note: Layout is a logical container used to arrange the gui components in a specific order
add()
It is used to add non-container components (Button, List) to the frame.
Example
Frame f=new Frame();
Button b=new Button("Click");
f.add(b);
Explanation: In above code we add button on frame using f.add(b), here b is the object of Button
class..
import java.awt.event.*;
import java.awt.*;
class Ex1
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setTitle("myframe");
f.setBackground(Color.cyan);
//f.setForeground(Color.red);
f.setSize(500,300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Output:

import java.awt.*;
import java.awt.event.*;
public class Ex2 extends Frame{
Label lb1,lb2;
TextField tf1,tf2;
Button b1;
public Ex2()
{
setLayout(null);

lb1=new Label("Username");
lb2=new Label("Password");

tf1=new TextField();
tf2=new TextField();

b1=new Button("submit");

lb1.setBounds(50, 50, 100, 30);


add(lb1);
tf1.setBounds(120, 50, 140, 20);
add(tf1);

lb2.setBounds(50, 100, 100, 30);


add(lb2);
tf2.setBounds(120, 100, 140, 20);
add(tf2);

b1.setBounds(50, 140, 100, 40);


add(b1);

setTitle("myframe");
setBackground(Color.cyan);
//f.setForeground(Color.red);
setSize(500,300);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Ex2 f=new Ex2();

}
}
Output:

Ex3.java
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Ex3 extends Frame{

public Ex3()
{

setTitle("myframe");
setBackground(Color.cyan);
//f.setForeground(Color.red);
setSize(500,300);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Ex3 f=new Ex3();

}
}
Output:

Ex4.java
import java.awt.*;
import java.awt.event.*;
class Ex4 extends Frame
{
Label user_id,fn,ln,ftn,DOB,sex,country,mobile,address;
TextField ID, f_name, l_name, Father1, Father2, dob, add1, mobile_no;
Choice c;
Button b1, b2, b3,b4;
CheckboxGroup cg1;
Checkbox male, female;
public Ex4()
{
setTitle("Employee Detail");
setBackground(Color.cyan);
setLayout(null);
fn=new Label("Emp Name");
ftn=new Label("Father Name:");
DOB=new Label("Date of birth:");
sex=new Label("Sex:");
address=new Label("Address:");
country=new Label("Country:");
mobile=new Label("Mobile no:");
Font f=new Font("Arial", Font.BOLD, 15);
fn.setFont(f);
ftn.setFont(f);
DOB.setFont(f);
sex.setFont(f);
address.setFont(f);
country.setFont(f);
mobile.setFont(f);
fn.setBounds(20,50,100,40);
ftn.setBounds(20,100,100,40);
DOB.setBounds(20,150,100,40);
sex.setBounds(20,200,100,40);
address.setBounds(20,250,100,50);
country.setBounds(20,300,100,50);
mobile.setBounds(20,350,100,40);
add(fn);
add(ftn);
add(DOB);
add(sex);
add(address);
add(country);
add(mobile);
f_name=new TextField("",20);
Father1=new TextField("",20);
dob=new TextField("Day/Month/Year",20);
add1=new TextField("",40);
mobile_no=new TextField("",20);
f_name.setBounds(200,60,200,20);
Father1.setBounds(200,110,200,20);
dob.setBounds(200,160,140,20);
add1.setBounds(200,260,200,20);
mobile_no.setBounds(200,360,130,20);
add(f_name);
add(Father1);
add(dob);
cg1=new CheckboxGroup();
male=new Checkbox("Male", cg1, true);
female=new Checkbox("Female", cg1, false);
add(male);
add(female);
male.setBounds(200,200,50,50);
female.setBounds(300,200,60,50);
add(add1);
c=new Choice();
c.addItem("City");
c.addItem("New Delhi");
c.addItem("Raipur");
c.addItem("Chandigarh");
c.addItem("Dehradun");
c.addItem("Patna");
c.addItem("Dispur");
c.addItem("Other");
c.setBounds(200,310,130,20);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(c);
add(mobile_no);
Font fa=new Font("Arial", Font.BOLD, 15);
b1=new Button("Submit");
b2=new Button("Exit");
b3=new Button("AddNew");
b1.setBounds(170,430,80,30);
b2.setBounds(270,430,80,30);
b3.setBounds(370,430,80,30);
b1.setBackground(Color.pink);
b2.setBackground(Color.pink);
b3.setBackground(Color.pink);
add(b1);
add(b2);
add(b3);
b1.setFont(fa);
b2.setFont(fa);
b3.setFont(fa);
setSize(600,500);
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} //cons
public static void main(String s[])
{
Ex4 obj=new Ex4();
}

} // class
Output:

Ex5.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class Ex5
{
Ex5()
{
Frame f=new Frame();
f.setSize(600,400);
f.setBackground(Color.pink);
f.setLayout(new BorderLayout());

Panel p1=new Panel();


p1.setBackground(Color.cyan);
Label l1 =new Label("Enter Uname");
TextField tf1=new TextField(15);
Label l2=new Label("Enter Passward");
TextField tf2=new TextField(15);
p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
f.add("North",p1);

Panel p2=new Panel();


p2.setBackground(Color.yellow);
Button b1=new Button("Send");
Button b2=new Button("Clear");
p2.add(b1);
p2.add(b2);
f.add("South",p2);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}

public static void main(String[] args)


{
Ex5 pf=new Ex5();
}
}
Output:

Event handling:
Chaging the state of an object is known as an event.For example ,click on button,dragging
mouse etc. the java.awt.event package provides many event classes and Listener interfaces for event
handling.

Steps to perform Event Handling

1. Register the component with the Listener


2. Overrides its methods
Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For
example:

Button

public void addActionListener(ActionListener a){}


MenuItempublic void addActionListener(ActionListener a){}

TextField

public void addActionListener(ActionListener a){}

public void addTextListener(TextListener a){}

TextArea : public void addTextListener(TextListener a){}

Checkbox

public void addItemListener(ItemListener a){}

Choice

public void addItemListener(ItemListener a){}

List

public void addActionListener(ActionListener a){}

public void addItemListener(ItemListener a){}

import java.awt.*;
import java.awt.event.*;
class Ex1 implements ActionListener
{
Frame f;
Button b1,b2,b3,b4;
Ex1()
{
f=new Frame();
f.setSize(500,500);
f.setLayout(new BorderLayout());
Panel p=new Panel();
p.setBackground(Color.cyan);
b1=new Button("Red");
b2=new Button("green");
b3=new Button("Blue");
b4=new Button("Exit");
p.add(b1);
p.add(b2);
p.add(b3);
p.add(b4);
f.add("North",p);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}//constructor
public void actionPerformed(ActionEvent e)
{
try
{
if(e.getSource().equals(b1))
{
f.setBackground(Color.red);
}
else if(e.getSource().equals(b2))
{
f.setBackground(Color.green);
}
else if(e.getSource().equals(b3))
{
f.setBackground(Color.blue);
}
else if(e.getSource().equals(b4))
{
System.exit(0);
}
}
catch (Exception ec)
{
System.out.println(ec);
}
}
public static void main(String[] args)
{
Ex1 a1=new Ex1();

}
}
Output:
Ex2.java
import java.awt.*;
import java.awt.event.*;
class Ex2 extends Frame implements MouseListener
{
Ex2()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent e)
{
setBackground(Color.RED);
}
public void mousePresed(MouseEvent e)
{
setBackground(Color.BLUE);
}
public void mouseReleased(MouseEvent e)
{
setBackground(Color.YELLOW);
}
public void mousePressed(MouseEvent e)
{
setBackground(Color.RED);
}
public void mouseEntered(MouseEvent e)
{
setBackground(Color.CYAN);
}
public void mouseExited(MouseEvent e)
{
setBackground(Color.BLACK);
}
public static void main(String[] args)
{
Ex2 om=new Ex2();
om.setSize(500,500);
om.setVisible(true);
om.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Output:

Ex3.java
import java.awt.*;
import java.awt.event.*;
class Ex3
{
Frame f;
Label statusLabel;
Ex3()
{
f=new Frame();
f.setSize(500,300);
f.setLayout(new BorderLayout());
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
Panel p=new Panel();
p.setBackground(Color.cyan);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
Checkbox chkJava = new Checkbox("Java");
Checkbox chkHtml = new Checkbox("Html");
Checkbox chkPHP = new Checkbox("PHP");
p.add(chkJava);
p.add(chkHtml);
p.add(chkPHP);
f.add("North",p);
chkJava.addItemListener(new CustomItemListener());
chkHtml.addItemListener(new CustomItemListener());
chkPHP.addItemListener(new CustomItemListener());
f.add(statusLabel);
f.setVisible(true);
}
class CustomItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText(e.getItem() +" Checkbox: " );
}
}
public static void main(String[] args)
{
Ex3 obj=new Ex3();
}
}

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is
an interface that is implemented by all the classes of layout managers. There are following classes
that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components
Example of BorderLayout class:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class BorderDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setTitle("myframe");
f.setSize(500,400);
f.setBackground(Color.white);

f.setLayout(new BorderLayout());
Button b1=new Button("first");
b1.setBackground(Color.green);
b1.setForeground(Color.white);

Button b2=new Button("second");


b2.setBackground(Color.yellow);
b2.setForeground(Color.black);

Button b3=new Button("third");


b3.setBackground(Color.red);
b3.setForeground(Color.white);

Button b4=new Button("fourth");


b4.setBackground(Color.red);
b4.setForeground(Color.white);
/*Button b5=new Button("center");
b5.setBackground(Color.cyan);
b5.setForeground(Color.white);*/
f.add("North",b1);
f.add("South",b2);
f.add("East",b3);
f.add("West",b4);
//f.add(b5);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Output:
FlowLayoutEx.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
class FlowLayoutEx
{
public static void main(String[] args)
{
Frame f=new Frame();
f.setTitle("myframe");
f.setBackground(Color.cyan);
f.setForeground(Color.red);
f.setLayout(new FlowLayout());
Button b1=new Button("Submit");
Button b2=new Button("Cancel");
f.add(b1);
f.add(b2);
f.setSize(500,300);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

}
}
Output:

Grid.java
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
class Grid extends Frame
{
Grid()
{
Frame f=new Frame();
f.setTitle("myframe");
f.setSize(500,400);
f.setBackground(Color.white);

f.setLayout(new GridLayout(2,2));
Button b1=new Button("one");
b1.setBackground(Color.green);
b1.setForeground(Color.white);

Button b2=new Button("two");


b2.setBackground(Color.yellow);
b2.setForeground(Color.black);

Button b3=new Button("three");


b3.setBackground(Color.red);
b3.setForeground(Color.white);

Button b4=new Button("four");


b4.setBackground(Color.cyan);
b4.setForeground(Color.white);

f.add("one",b1);
f.add("two",b2);
f.add("three",b3);
f.add("four",b4);
//f.add(b5);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

}
public static void main(String [] args)
{
Grid g1=new Grid();
}
}
Output:
Swing
1. It is a part of Java Foundation Classes (JFC) that is used to create window-based
applications.
2. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform-dependent. Java swing components
are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.

4) AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.
What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.
Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int sets size of the component.


height)

public void sets the layout manager for the


setLayout(LayoutManager m) component.

public void setVisible(boolean b) sets the visibility of the component. It is


by default false.
Java Swing Examples
There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
/f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Output:

Applets
Applet is a predefined class in java.applet package used to design distributed application. It is a
client side technology. Applets are run on web browser.
Advantage of Applet:
 Applets are supported by most web browsers.
 Applets works on client side so less response time.
 Secured: No access to the local machine and can only access the server it came from.
 Easy to develop applet, just extends applet class.
 To run applets, it requires the Java plug-in at client side.
 Android, do not run Java applets.
 Some applets require a specific JRE. If it required new JRE then it take more time to
download new JRE.
Life cycle of applet
1. init()
2. start()
3. stop
4. destroy
init(): Which will be executed whenever an applet program start loading, it contains the logic to
initiate the applet properties.
start(): It will be executed whenever the applet program starts running.
stop(): Which will be executed whenever the applet window or browser is minimized.
destroy(): It will be executed whenever the applet window or browser is going to be closed (at the
time of destroying the applet program permanently).
Design applet program
We can design our own applet program by extending applet class in the user defined class.
Syntax
class className extends Applet
{
......
// override lifecycle methods
......
}
Note: Whenever an applet program is running inti() and start() will be executed one after another,
but stop() and destroy() will be executed if the browser is minimized and closed by the end user,
respectively.
Note:
Applet program may or may not contain life cycle methods.
Running of applet programs
Applet program can run in two ways.
1. Using html (in the web browser)
2. Using appletviewer tool (in applet window)
Running of applet using html
In general no Java program can directly execute on the web browser except markup language
like html, xml etc.
Html supports a predefined tag called <applet> to load the applet program on the browser window.
Syntax
<applet code="udc.class">
height="100px"
width="100px"
</applet>
Example 1
Some browser does not support <applet> tag so that Sun MicroSystem was introduced a special tool
called appletviewer to run the applet program.
In this Scenario Java program should contain <applet> tag in the commented lines so that
appletviewer tools can run the current applet program.
Example of Applet
import java.applet.*;
import java.awt.*;
public class LifeApp extends Applet
{
String s= " ";
public void init()
{
s=s+ " int ";
}
public void start()
{
s=s+ "start ";
}
public void stop()
{
s=s+ "stop ";
}
public void destroy()
{
s=s+ " destory ";
}
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,30);
setBackgroundColor(Color."red");
g.setFont(f);
g.drawString(s,200,250);
}
}

applet.html
/*<applet code="LifeApp.class" height="500",width="800">
</applet>*/
Execution of applet program
javac LifeApp.java
appletviewer applet.html
Note:
init() always execute only once at the time of loading applet window and also it will be
executed if the applet is restarted.
Example 2:
//JavaApp.java
import java.applet.*;
import java.awt.*;
public class JavaApp extends Applet
{
public void paint(Graphics g)
{
Font f=new Font("Arial",Font.BOLD,30);
g.setFont(f);
setForeground(Color.red);
setBackground(Color.white);
g.drawString("Student",200,200);
}
}
myapplet.html
<html>
<title> AppletEx</Title>
<body>
<applet code="JavaApp.class"
height="70%"
width="80%">
</applet>
</body>
</html>
Output:
javac JavaApp.java
appletviewer myapplet.html

Example 3:
Parameter in Applet:
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
Myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

Output:

Example 4:
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
Applet2.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>
HTML
Introduction
 WWW is stands for World Wide Web.
 The World Wide Web (WWW) is a global information medium which users can read and
write
via computer connected to the internet.
 The Web, or World Wide Web, is basically a system of Internet servers that support specially
formatted documents. The documents are formatted in a markup language called HTML
(Hypertext Markup Language) that supports links to other documents, as well as graphics,
audio, and video files.
 In short, World Wide Web (WWW) is collection of text pages, digital photographs, music
files,
Videos and animations you can access over the Internet.
 Web pages are primarily text documents formatted and annotated with Hypertext Markup
Language (HTML). In addition to formatted text, web pages may contain images, video, and
Software components that are rendered in the user's web browser as coherent pages of
Multimedia content.
 The terms Internet and World Wide Web are often used without much distinction. However,
the two are not the same.
 The Internet is a global system of interconnected computer networks. In contrast, the World
Wide Web is one of the services transferred over these networks. It is a collection of text
Documents and other resources, linked by hyperlinks and URLs, usually accessed by web
Browsers, from web servers.
 There are several applications called Web browsers that make it easy to access the World
Wide Web; For example: Firefox, Microsoft’s Internet Explorer, Chrome Etc.
 Users access the World-Wide Web facilities via a client called a browser, which provides
Transparent access to the WWW servers.
History of WWW:
Tim Berners-Lee, in 1980 was investigating how computer could store information with
random links. In 1989, while working at European Particle Physics Laboratory, he proposed to idea
of global hypertext space in which any network-accessible information could be referred to by single
“universal Document Identifier”. After that in 1990, this idea expanded with further program and
knows as World Wide Web.
Internet and WWW:
The Internet, linking your computer to other computers around the world, is a way of
transporting content. The Web is software that lets you use that content…or contribute your own.
The Web, running on the mostly invisible Internet, is what you see and click on in your computer’s
browser.
What is The Web (World Wide Web)
 The World Wide Web, or simply Web, is a way of accessing information over the medium of
the Internet. It is an information-sharing model that is built on top of the Internet.
 The Web uses the HTTP protocol, only one of the languages spoken over the Internet, to
transmit data. The Web also utilizes browsers, such as Internet Explorer or Firefox, to access
Web documents called Web pages that are linked to each other via hyperlinks. Web
documents also contain graphics, sounds, text and video.
HTTP Protocol: Request and Response.
 HTTP stands for Hypertext Transfer Protocol.
 HTTP is based on the client-server architecture model and a stateless request/response
protocol that operates by exchanging messages across a reliable TCP/IP connection.
 An HTTP "client" is a program (Web browser) that establishes a connection to a server for
the
purpose of sending one or more HTTP request messages. An HTTP "server" is a program
(generally a web server like Apache Web Server) that accepts connections in order to serve
 HTTP requests by sending HTTP response messages.
 Errors on the Internet can be quite frustrating — especially if you do not know the difference
between a 404 error and a 502 error. These error messages, also called HTTP status codes are
response codes given by Web servers and help identify the cause of the problem.
 For example, "404 File Not Found" is a common HTTP status code. It means the Web server
cannot find the file you requested. The file -- the webpage or other document you try to load
in
your Web browser has either been moved or deleted, or you entered the wrong URL or
document name.
 HTTP is a stateless protocol means the HTTP Server doesn't maintain the contextual
information about the clients communicating with it and hence we need to maintain sessions
in case we need that feature for our Web-applications
 HTTP header fields provide required information about the request or response, or about the
object sent in the message body. There are four types of HTTP message headers:
General-header:
These header fields have general applicability for both request and response messages.
Request-header:
These header fields have applicability only for request messages.
Response-header:
These header fields have applicability only for response messages.
Entity-header:
These header fields define Meta information about the entity-body.
As mentioned, whenever you enter a URL in the address box of the browser, the browser
translates the URL into a request message according to the specified protocol; and sends the request
message to the server.
For example, the browser translated the URL http://www.test101.com/doc/index.html into
The following request message:
GET /docs/index.html HTTP/1.1
Host: www.test101.com
Accept: image/gif, image/jpeg, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Here, Step by step communication between client and server mention into following figure.

Fig 1: Communication between HTTP Client and HTTP Server


Web Browser and Web Server.
Web server and web browser are the terms which are commonly used for website. The basic
purpose of both is to develop a platform for internet web directory. So that any users can anytime
access any kind of website. Major difference between them is on their function and how they
perform their functions. Check for the detail of both topics before understanding the differences
between them.
Web Browser
Web browser is a client, program, software or tool through which we sent HTTP request to
web server. The main purpose of web browser is to locate the content on the World Wide Web and
display in the shape of web page, image, audio or video form.

We can also call it a client server because it contacts the web server for desired information.
If
the requested data is available in the web server data then it will send back the requested information
again via web browser.
Microsoft Internet Explorer, Mozilla Firefox, Safari, Opera and Google Chrome are examples
of web browser and they are more advanced than earlier web browser because they are capable to
understand the HTML, JavaScript, AJAX, etc. Now days, web browser for mobiles are also
available, which are called micro browser.

Web Server
Web server is a computer system, which provides the web pages via HTTP (Hypertext Transfer
Protocol). IP address and a domain name is essential for every web server.
Whenever, you insert a URL or web address into your web browser, this sends request to the
Web address where domain name of your URL is already saved. Then this server collects the all
Information of your web page and sends to browser, which you see in form of web page on
Your browser.
Lot of web server software is available in the market in shape of NCSA, Apache, Microsoft
and
Netscape. Storing, processing and delivering web pages to clients are its main function. All the
Communication between client (web browser) and server takes place via HTTP.
Here, we can easily understand concept of web browser and web server by following figure.

Fig 2: Communication between web Browser and Web Server

What is HTML?
Stands for Hypertext Markup Language.
Most documents that appear on the World Wide Web were written in HTML.
HTML is a markup language, not a programming language. In fact, the term HTML is an
acronym that
Stands for Hypertext Markup Language.
We can apply this markup language to your pages to display text, images, sound and movie files,
and
Almost any other type of electronic information.
We use the language to format documents and link them together, regardless of the type of
Computer with which the file was originally created.

HTML Elements
An element consists of three basic parts: an opening tag, the element's content, and finally, a
closingtag.
Every (web) page requires four critical elements: the html, head, title, and body elements.

1. <html> Element...</html>
 <html> begins and ends each and every web page.
 Its purpose is to encapsulate all the HTML code and describe the HTML document to the
web browser.
2. <head> Element
 The <head> element is "next" as they say. As long as it falls somewhere between your
<html>
tag and your web page content (<body>).
 The head functions "behind the scenes." Tags placed within the head element are not directly
Displayed by web browsers.
 We will be placing the <title> element here.
 Other elements used for scripting (JavaScript) and formatting (CSS) will eventually be
introduced and you will have to place them within your head element.
<html>
<head>
</head>
</html>
3. The <title> Element
 Place the <title> tag within the <head> element to title your page.
 The words you write between the opening and closing <title></title> tags will be displayed at
the top of a viewer's browser.
4. The <body> Element
 The <body> element is where all content is placed. (Paragraphs, pictures, tables, etc).
 The body element will encapsulate all of your webpage's viewable content.
HTML: <! -- Comments -->
 A comment is a way for you as the web page developer to control what lines of code are to be
Ignored by the web browser.
 Comment syntax may be a little complicated, there is an opening and a closing much like
tags.
1. <!-- Opening Comment
2. -- > Closing Comment
<!--Note to self: This is my banner image! Don't forget -->
HTML - Headings 1:6
 A heading in HTML is just what we might expect, a title or subtitle.
 By placing text inside of <h1> (heading) tags, the text displays bold and the size of the text
Depends on the number of heading (1-6).
 Headings are numbered 1-6, with 1 being the largest heading and 6 being the smallest.
<html>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>

HTML Lists:
HTML Lists are used to specify lists of information. All lists may contain one or more
list elements.
List is one of the most effective ways of structuring a Website or its contents are to use lists.
HTML provides three types of lists:
1. Ordered List or Numbered List (ol)
2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)
Ordered list (or )Numbered List:
 In Ordered list, all the list items are marked with numbers.
 It is known as numbered list also.
 The ordered list starts with <ol> tag and ends with </ol> and the list items start with <li> tag
and
</li>
 Different numbering schemes can be specified depending upon preference.
 A list can number from any value. The starting value is given by the “start” attribute.
 Elements of a list may be formatted with any of the usual text formatting tags and may be
images or hyperlinks.

Syntax:
<ol [ type=”1” | “a” | “A” | “I” | “i” ] [ start = “number” ] > … </ol>

Note: <li>…</li>

Unordered list (or) Bulleted List:

 In Unordered list, all the list items are marked with bullets.
 It is also known as bulleted list also.
 The Unordered list starts with <ul> tag and ends with </ul>
 List items start with the <li> tag and </li>.
 Different types of bullet symbols can be specified by using the “type” attribute in <ul>tag

Attribute Value Symbol Description

Disc  Black filled circle

Square  Black filled Square

Circle o Empty circle

Syntax:
<ul [ type = “disc” | “square” | “circle” ] > … </ul>

Description List or Definition List:


 Description list is also a list style which is supported by HTML and XHTML.
 It is also known as definition list where entries are listed like a dictionary.
 The definition list is very appropriate when you want to present glossary, list of terms or
other name-value list.
Definition List makes use of following three tags.

 <dl> − Defines the start of the list


 <dt> − Definition term
 <dd> − Defining definition
 </dl> − Defines the end of the list

Example for List:


<html>
<head><title>Lists Example</title></head>
<body>
<h1>UN ordered list</h1>
<ul type="disc">
<li>C-LANGUAGE</li>
<li>JAVA</li>
<li>.NET</li>
</ul>
<h4>ordered list :< /h4>
<ol type=”1” start=”1”>
<li>Dennis Ritchie</li>
<li>JAMES GOSLING </li>
<li>MICROSOFT</li>
</ol>
<dl>
<dt>HTML</dt>
<dd>Hyper text mark up langauge </dd>
</dl>
</body>
</html>

HTML Nested Lists


 You can also nest one list within another, so you could make an unordered list inside a
numbered one:
<ol type=”1”>
<li> Clear out garage</li>
<ul type=”disc”>
<li> Tomatoes</li>
</ul>
<li> repair fence </li>
</ol>
Line Breaks
Line breaks are different then most of the tags we have seen so far. A line break ends the line
you are currently on and resumes on the next line.
<p>Darshan<br >
Computer<br></p>
Formatting Tags:
 HTML formatting tags are used for formatting a text style. It will become necessary to make
minor changes to the formatting of those elements.
Tag Example Results
<b> <b>Bold Text</b> An example of Bold Text
<big> <big>Big Text</big> An example of Big Text
<center> <center>Center Text</center> An example of
Center Text
<i> <i>Italic Text</i> An example of Italic Text
<small> <small>Small Text</small> An example of Small Text
<strong> <strong>Strong Text</strong> An example of Strong Text
<sub> <sub>Subscript Text</sub> An example of Subscript Text
<sup> <sup>Superscript Text</sup> An example of Superscript Text
<s> <s>Strike Text</s> An example of Strike Text
<strike> <strike>Strike Text</strike> An example of Strike Text
<u> <u>Underline Text</u> An example of Underline Text

<q> <q>Short Quotation Text</q> An example of “Short Quotation Text”


<pre> <pre> tag is used for indicating Dono:1
preformatted text</pre> House:1
Ex: IGMS COMPLEX
<pre> Dono:1
House:1
IGMS COMPLEX </pre>
<p> The <p> tag defines a paragraph.

Formatingtags.html
<html>
<head> <title> upendra computers </title> </head>
<body>
<h3> upendra sir</h3>
<center>Formating tags</center>
<p> Hai this
Nalanda
Degree college</p>
<pre> Dono:1
House:1
IGMS COMPLEX </pre><b> this is bold </b><br>
<i> this is for italic </i> <br>
<u>this is for underline</u><br>
<strong> this is for strong </strong> <br>
<sup>H</sup>2 <br>
<sub>H</sub>2 <br>
<strike>HTML</strike>
<p align=”left”>this is paragraph tag</p>
</body> </html>

HTML - Hypertext Reference (href) or Hyperlinks or Anchors


HTML Anchor
The HTML anchor tag defines a hyperlink that links one page to another page. The "href"
attribute is the most important attribute of the HTML a tag.
href attribute of HTML anchor tag
The href attribute is used to define the address of the file to be linked. In other words, it
points out the destination page.
The syntax of HTML anchor tag is given below.
<a href = "..........."> Link Text </a>
Appearance of HTML anchor tag
 An unvisited link is displayed underlined and blue.
 A visited link displayed underlined and purple.
 An active link is underlined and red.
Note: Hypertext references can be Internal, Local, or Global.
Internal - Links to anchors on the current page
Local - Links to other pages within your domain
Global - Links to other domains outside of your site
EX: Internal: ref="#anchorname" -> Use the #id selector
<p id="top">Hyperlinks are utilized by a web browser to move from one page to another...</p>
<! -- place any paragraph text here -- >
<a href="#top">Take me to the top of the page.</a>
Local - href="../picturefile.jpg"
Global - href=http://www.xyz.com/
<a href="http://www.google.com/" target="_blank" >Google Home</a>
<a href="http://www.google.com/" target="_self" >Google Home</a>
Link Targets
The target attribute defines whether to open the page in a separate window, or to open the
link
in the current browser window.

HTML – Images
 Use the <img /> tag to place an image on your web page.
1. Image src
 Above we have defined the src attribute.
 Src stands for source, the source of the image or more appropriately, where the picture file is
located.
 There are two ways to define the source of an image. First you may use a standard URL.
(src=http://www.Xyz.com/pics/htmlT/sunset.gif) As your second choice, you may copy or
upload the file onto your web server and access it locally using standard directory tree
methods.
(src="../sunset.gif")
 The location of this picture file is in relation to your location of your .html file.
2. Alternative Attribute
 The alt attribute specifies alternate text to be displayed if for some reason the browser cannot
Find the image, or if a user has image files disabled.

<img src="http://example.com/brokenlink/sunset.gif" alt="Beautiful Sunset" >

3. Image Height and Width


 To define the height and width of the image, rather than letting the browser compute the size,
Use the height and width attributes.
<img src="sunset.gif" height="50" width="100" height=”100” alt=”image example”
align=”center”>
Images as Links:
 Images are very useful for links and can be created with the HTML below.
<a href="http://www.xyz.com/"><img src="sunset.gif"></a>

Style Attribute:
HTML Style is used to change or add the style on existing HTML elements. There is a
default style for every HTML element e.g. background color is white, text color is black etc.
The style attribute can by used with any HTML tag. To apply style on HTML tag, you should
have the basic knowledge of css properties e.g. color, background-color, text-align, font-family, font-
size etc.
The syntax of style attribute is given below:
style= "property: value"
HTML Style color:
The color property is used to define the text color.
Let's see a simple example of styling html tags by color property of css.
<h3 style="color:green">This is Green Color</h3>
<h3 style="color:red">This is Red Color</h3>
HTML Style background-color:
The background-color property is used to define background color for the HTML tag.
Let's see an example of styling html tag by of css background-color property
<h3 style="background-color:yellow;">This is yellow background</h3>
<h3 style="background-color:red;color:white">This is red background</h3>
HTML Style font-family:
The font-family property specifies the font family of the HTML tag.
Let's see an example of styling html tag by css font-family property
<h3 style="font-family:times new roman">This is times new roman font family</h3>
<p style="font-family:arial">This is arial font family</p>
HTML Style font-size
The font-size property is used to define the text size of the HTML tag.
Let's see an example of font-size property
<h3 style="font-size: 200">This is h3 tag</h3>
HTML Style text-align
The text-align property is used to define the horizontal text alignment for the HTML element.
Let's see an example of styling html tag by css text-align property
<h3 style="text-align: right; background-color: pink ;"> this text is located at right side</h3>
<p style="text-align: center; background-color: pink ;"> this text is located at center side</p>
HTML - Font
The <font> tag is used to add style, size, and color to the text on your site. Use the size,
color,
and face attributes to customize your fonts.
1. Font Size
 Set the size of your font with size. The range of accepted values is from 1(smallest) to
7(largest).The default size of a font is 3.
<p><font size="5">Here is a size 5 font</font></p>
2. Font Color
 Set the color of your font with color.
<font color="red">This text is red</font>
3. Font Face
 Choose a different font face using any font you have installed.
<p><font face="Bookman Old Style, Book Antiqua, Garamond">This paragraph has
had its font...</font></p>
Tables:
The best way to split a page into different sections is to use HTML <table> Tag.This is very
often used in conjunction with the <tr> and the <td> tags.
The following attributes are commonly used to define the properties of this table:
 width: This specifies the width of the table. Can be specified in pixels or in relative terms
(for example, 100%).
 border: This specifies whether the table will have a border. The number indicates the
thickness of the border.
 cellspacing: The amount of space between the cell wall and the cell border.
 cellpadding: The amount padding between cells and the each cell wall in a table.
 bgcolor: This specifies the background color for this table. The color value may be specified
as the color name or the six-character color code.

Table row :<tr>


The <tr> tag is used to create a row in a table. The following attributes are commonly used to
define the properties of this row:

 bgcolor: This specifies the background color for this row. The color value may be specified
as the color name or the six-character color code.
 height: This specifies the height of the row.
 rowspan: This specifies the number of rows this particular row occupies.

Table data:<td>

The <td> tag is used to create colon in a table. Columns are specified within each row. The
following attributes are commonly used to define the properties of the column:

 width: This specifies the width of the column. Can be specified in pixels or in relative terms
(for example, 50%).
 bgcolor: This specifies the background color for this column. The color value may be
specified as the color name or the six-character color code.
 colspan: This specifies the number of columns this particular column occupies.

Table heading :<th>:

<th> tag is used to crate a table heading in column.


<th> SNAME</th>
Example for table:
<html>
<head>
<title>Tables Example</title>
</head>
<body>
<table border="2" width="400" height="100" align="center" cellspacing="0" cellpadding="0">
<caption> <b>Student Table</b> </caption>
<tr bgcolor="green">
<th>Sno</th>
<th>Sname</th>
<th>CollegeName</th>
</tr>
<tr bgcolor="cyan" align="center">
<td>101</td>
<td>kiran</td>
<td>NDC</td>
</tr>
<tr bgcolor="pink" align="center">
<td>102</td>
<td>suresh</td>
<td>Layola</td>
</tr>
</table></body></html>
Output:

Colspan:
If you want to make a cell span more than one column, you can use the colspan attribute.
Let's see the example that span two columns.
<html>
<head>
<title>Tables Example</title>
</head>
<body>
<table border="1" align="center" cellpadding="10">
<tr bgcolor="red">
<th>Name</th>
<th colspan="2">MobileNo</th>
</tr>
<tr bgcolor="cyan" >
<td>upendra</th>
<td>9291676235</td>
<td>9291676236</td>
</tr>
<table>
</body>
</html>
Output:

Rowspan:
If you want to make a cell span more than one row, you can use the rowspan attribute.
Let's see the example that span two rows.
<html>
<head>
<title>Tables Example</title>
</head>
<body>
<table border="1" align="center" cellpadding="10">

<tr bgcolor="red">
<th>Name</th>
<td>Upendra sir</td>
</tr>

<tr bgcolor="green">
<th rowspan="2">Mobile no</th>
<td>9291676235</td>
</tr>

<tr bgcolor="cyan">
<td>9391676235</td>

</tr>
</table>

<table>
</body>
</html>
Output:

Frames
The main objective of frame is we can display more than one HTML document in the same
browser window. Each HTML document is called a frame, and each frame is independent of the
others.
Frameset Element
The frameset element holds two or more frame elements. Each frame element holds a
separate document. The frameset element states only HOW MANY columns or rows there will be in
the frameset.
Syn: <frameset cols="25%,75%">…….</frameset>

Frame Element:
The <frame> tag defines one particular window (frame) within a frameset.
Syn: <frame src="frame_a.htm" name=”string” />

Frame Attributes:

Frameset Attributes:

The <frameset> element holds one or more <frame> elements. Each <frame> element can
hold a separate document.

The <frameset> element specifies HOW MANY columns or rows there will be in the
frameset, and HOW MUCH percentage/pixels of space will occupy each of them.

Frameset attributes:

Syntax
<frame noresize="noresize">
Example:

<html>
<head> <title>frames example</title> </head>
<frameset cols="25%,75%">
<frame src="frame_a.htm" />
<frame src="frame_b.htm" />
</frameset>
</html>
In the above example the first column is set to 25% of the width of the browser window. The
second column is set to 75% of the width of the browser window. The document "frame_a.htm" is
put into the first column, and the document "frame_b.htm" is put into the second column

Note: The frameset column size can also be set in pixels (cols="200,500"), and one of the
columns can be set to use the remaining space, with an asterisk (cols="25 %,*").
Nested frames:

Nested frames are process of subdividing already existing frames

i.e. for example if the webpage is divided into either row wise or column wise frames first,
and then again the row wise frames are subdivided into column wise or column wise frames into
row wise frames is called nested frames

Example:
<html>
<head>
<title>frames example</title>
<frameset cols="25%,75%">
<frameset rows=”50, 50”>
<frame src="frame_a.htm" />
<frame src="frame_b.htm" />
</frameset>
<frame src="frame_a.htm" />
</frameset>
</html>
Note: For More examples plz refer the lab manual programs

Forms:
Forms are used to input the values. Using forms we will be able to handle HTML controls
like buttons, checkboxes, radio buttons, select controls, text areas and more. To use HTML controls
we must enclose them in HTML forms.
The action attribute tells the HTML where to send the collected information, while the
method
Attribute describes the way to send it.
Following are attributes of <form>:
1. Name:
The name attribute specifies the name of a form which is used to reference elements in a
JavaScript.
<form action="URL"> Value: URL
2. Action:
The required action attribute specifies where to send the form‐data when a form is submitted.
<form action="URL"> Value: URL
3. Method:
The method attribute specifies how to send form‐data (the form‐data is sent to the page
specified in the action attribute).
<form method="get|post">
Available Controls:
Controls are created using <INPUT> tag & TYPE attribute.
1. Form:
<form> … </form> creates an HTML form, used to enclose HTML controls. The attributes
are:
a) Action: Gives the URL which will handle the form data.
b) Method: Indicates a method or protocol for sending data to the target URL. The Get
method is the default.
2. Text Fields:
<input type=”text”> creates a text field that the user can enter or edit text inside it. The
attributes are:
a) size: Sets the size of the control.
b) value: The value entered in the text field.
c) maxlength: sets the maximum number of characters enter in the text field.
3. Password:
<input type=”password”> creates a password text field, which shows asterisks on the text
field. The attributes are:
a) maxlength: sets the maximum length f the data in the control.
b) Name: gives the name of the control.
c) Value: represents the value entered in the textfield.
4. Checkbox:
<input type=”checkbox”> creates a checkbox in a form. The attributes are:
a) Checked: Indicates if the checkbox should appear checked initially or not.
b) Size: sets the size of the checkbox.
c) Value: represents the result of the checkbox when clicked, which is passed to the forms
action URL.
5. Radio buttons:
<input type=”radio”> creates a radio button in the form. The attributes are:
a) Checked: Indicates if the checkbox should appear checked initially or not.
b) Value: represents the result of the checkbox when clicked, which is passed to the forms
action URL.
6. Selection lists:
<select> … </select> Creates a drop-down lists, where the user can select choice from the
list of elements. And <option>…..</option> tag is used to provide values . The attributes are:
a) name: represents the name of the control.
b) value: the value of selected item.
7. Submit button:
<input type=”submit”> creates a submit button that the user can click to send data in the
form back to web server. The attributes are:
a) Name: sets the name of the control.
b) Value: Text to be displayed on the button.
8. Reset button:
<input type=”reset”> creates a reset button in a form that resets all fields to their original
values. The attributes are:
a) Name: sets the name of the control.
b) Value: Text to be displayed on the button.
9. <Textarea> tag
It is used to specify a text are or multi line text box. In a text area you can write an unlimited
characters. It is mostly use in users feedback, home address etc.
Example:
<textarea cols="5 rows="5" name="Feedback" >
a) cols: It is an attribute which specifies the number of columns in text area
b) rows: It is an attribute which specifies the number of rows in text area
c) name: It Specifies unique name for the input element
Example for forms:
<html>
<head>
<title>Welcome to Forms application</title>
</head>
<body>
<form>
<table align="left">
<tr><th>Name </th><td> <input type="text" name="name" size="30"></td></tr>
<tr><th>Password </th><td> <input type="password” name="pwd" size="30"></td></tr>
<tr><th>Emaild Id </th><td> <input type="email" name="email" size="30"></td></tr>
<tr><th>Mobile No </th><td> <input type="text" name="mbno" size="30"></td></tr>
<tr><th>Gender </th><td> <input type="radio" name="sex" value="male"
checked="true">Male
<input type="radio" name="sex" value="female" checked="false"/> Female</td></tr>
<tr><th>College </th><td>
<input type="checkbox" name="college" value="NDC" >NDC
<input type="checkbox" name="college" value="KLU" >KLU </td></tr>
<tr><th>Comments </th><td ><textarea name="comments" rows="5" cols="25">
</textarea></td></tr>
<tr><th> Country </th><td>
<select name="country" >
<option value="USA"> america
<option value="INDIA" selected> India
<option value="RSA">Rashya
</select> </td></tr>
<tr><td><input type="submit" value="Submit" ></td><td><input type="reset"
value="reset"></td></tr>
</table>
</form>
</body>
</html>
Output:

<Marquee> tag:
The marquee tag is a non-standard HTML element which causes text to scroll up, down, left
or right automatically.
Attributes
Marquee's element contains several attributes that are used to control and adjust the
appearance of the marquee.

Attribute Description

behavior It facilitates user to set the behavior of the marquee to one of the three
different types: scroll, slide and alternate.

direction Defines direction for scrolling content. It may be left, right, up and
down.
width Defines width of marquee in pixels or %.

height Defines height of marquee in pixels or %.

Scroll Marquee:
It is a by default property. It is used to scroll the text from right to left, and restarts at the right
side of the marquee when it is reached to the end of left side. After the completion of loop text
disappears.

<marquee width="100%" behavior="scroll" bgcolor="pink">


This is an example of a scroll marquee...
</marquee>

Slide Marquee
In slide marquee, all the contents to be scrolled will slide the entire length of marquee but
stops at the end to display the content permanently.

<marquee width="100%" behavior="slide" bgcolor="pink">


This is an example of a slide marquee...
</marquee>

Alternate Marquee
It scrolls the text from right to left and goes back left to right.

<marquee width="100%" behavior="alternate" bgcolor="pink">


This is an example of a alternate marquee...
</marquee>

Direction attribute
Syntax:
<marquee direction=”up/down/left/right” >

Example:
<marquee direction="up" width="100px">
<a>html</a><br>
<a>css</a><br>
<a>javascript</a>
</marquee>

<Span> tag:
 A <span> element used to color a part of a text:
 The <span> tag is used to group inline-elements in a document.

<p>My mother has <span style="color:blue;font-weight:bold">blue</span> eyes and my father has


<span style="color:darkolivegreen;font-weight:bold">dark green</span> eyes.</p>

Note: Try to learn <Div> tag after learning CSS


Difference between HTML div tag and span tag

<div> tag:

 The <div> tag defines a division or a section in an HTML document.


 The <div> element is very often used together with CSS, to layout a web page.
 Note: By default, browsers always place a line break before and after the <div> element.
 <div> tag are used for group the large section of Html elements together.
 <div> tag is just like a container which is used to wrap other Html page elements and divides
the Html documents into sections. Suppose on your web page lot of Html elements like <p>,
<h2> and <img> and you want to separate these elements from others elements then apply
<div> tag.

Example 1:
<div style="border: 1px solid pink; padding: 20px; font-size: 20px">
<p>Welcome to VaweInstitutes.com, Here you get trainings on latest technologies.</p>
<p>This is second paragraph</p>
</div>
Example 2:
<html>
<body>
<div style="background:#00FF99">
<h3>Heading inside a div</h3>
<p>Text inside a div element.</p>
</div>
<div style="background:#FFCAFF">
<h3>Heading inside a div</h3>
<p>Text inside a div.</p>
</div>

<div style="background:#66FFFF">
<h3>Heading inside a div</h3>
<p>Text inside a div.</p>
</div>
</body>
</html>
Output:

Example 3: Login Form


In this example, we are creating box using div tag. There is a login form inside the box. Let's
see the CSS and HTML code.
CSS Code:
.loginform{
padding:10px;
border:1px solid pink;
border-radius:10px;
float:right;
margin-top:10px;
}
.formheading{
background-color:red;
color:white;
padding:4px;
text-align:center;
}
.sub{
background-color:blue;
padding: 7px 40px 7px 40px;
color:white;
font-weight:bold;
margin-left:70px;
border-radius:5px;
}
HTML Code:
<div class="loginform">
<h3 class="formheading">Please Login</h3>
<form action="LoginServlet" method="post">
<table>
<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"/></td></tr>
<tr><td colspan="2" style="text-align:center"><input class="sub" type="submit"
value="login"/></td></tr>
</table>
</form>
</div>

Example 4:
<div id="my_menu" align="right">
<a href="#">HOME</a> |
<a href="#">CONTACT</a> |
<a href="#">ABOUT</a> |
<a href="#">SITEMAP</a>
</div>
<div id="my_content" align="left" bgcolor="white">
<h4>HTML title here</h4>
<p>An HTML tag that is widely used to break apart a Web page into elements, each with its
own layout attributes. The SPAN tag is somewhat similar to DIV, except that SPAN defines a small
amount of text, whereas DIV defines an entire block of data on the page.</p>
<h4>Second HTML title here</h4>
<p>The Div macro wraps content in a div tag with optional class and styles. The div tag is a
non-visual (by default) element that can be used to apply additional properties to content contained
within it. Unlike the span tag</p>
</div>
Introduction to HTML5
The DOCTYPE declaration for HTML5 is very simple:
<! DOCTYPE html>
The character encoding (charset) declaration is also very simple:
<meta charset="UTF-8">
New HTML5 Elements:
 New semantic elements like <header>, <footer>, <article>, and <section>.
 New form control attributes like number, date, time, calendar, and range.
 New graphic elements: <svg> and <canvas>.
 New multimedia elements: <audio> and <video>.
HTML 5 Tags
There is a list of newly included tags in HTML 5. These HTML 5 tags (elements) provide a
better document structure. This list shows all HTML 5 tags in alphabetical order with description.
HTML Audio Tag
HTML audio tag is used to define sounds such as music and other audio clips. Currently there are
three supported file format for HTML 5 audio tag.
1. mp3
2. wav
3. ogg
HTML Audio Tag Example
<!DOCTYPE>
<html>
<body>
<audio controls>
<source src="koyal.mp3" type="audio/mpeg">
Your browser does not support the html audio tag.
</audio>
</body>
</html>
NOTE: <source src="koyal.ogg" type="audio/ogg">
Attributes of HTML Audio Tag
There is given a list of HTML audio tag.
Attribute Description

controls It defines the audio controls which are displayed with


play/pause buttons.

autoplay It specifies that the audio will start playing as soon as it is


ready.

src It specifies the source URL of the audio file.


loop It specifies that the audio file will start over again, every time
when it is completed.
HTML Audio Tag Attribute Example
Here we are going to use controls, autoplay, loop and src attributes of HTML audio tag.
<!DOCTYPE>
<html>
<body>
<audio controls autoplay loop>
<source src="koyal.mp3" type="audio/mpeg"></audio>
</body>
</html>
HTML Video Tag
HTML 5 supports <video> tag also. The HTML video tag is used for streaming video files
such as a movie clip, song clip on the web page.
Currently, there are three video formats supported for HTML video tag:
1. mp4
2. webM
3. ogg
Let's see the table that defines which web browser supports video file format.
HTML Video Tag Example
Let's see the code to play mp4 file using HTML video tag.
<!DOCTYPE>
<html>
<body>
<video controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the html video tag.
</video>
</body>
</html>

NOTE: <source src="movie.ogg" type="video/ogg">

Attributes of HTML Video Tag


Let's see the list of HTML 5 video tag attributes.
Attribute Description

controls It defines the video controls which is displayed with play/pause buttons.

height It is used to set the height of the video player.


width It is used to set the width of the video player.

autoplay It specifies that the video will start playing as soon as it is ready.

loop It specifies that the video file will start over again, every time when it is
completed.

muted It is used to mute the video output.

src It specifies the source URL of the video file.

HTML Datalist Tag


The HTML <datalist> tag is is used to provide an auto complete feature on form element. It
provides a list of predefined options to the users to select data.
The <datalist> tag should be used with an <input< element that contains a "list" attribute. The
value of "list" attribute is linked with the datalist id.
HTML datalist tag example
Let's see the simple example of HTML5 datalist tag. If you press A, it will show a list of
cricketers starting with A letter.
<!DOCTYPE>
<html>
<body>
<label>
Enter your favorite cricket player: Press any character<br />
<input type="text" list="CktPlayers">
<datalist id="CktPlayers">
<option value="Sachin Tendulkar">
<option value="Brian Lara">
<option value="Jacques Kallis">
<option value="Ricky Ponting">
<option value="Rahul Dravid">
<option value="Shane Warne">
<option value="Rohit Sharma">
<option value="Donald Bradman">
<option value="Saurav Ganguly ">
<option value="AB diVilliers">
<option value="Mahendra Singh Dhoni">
<option value="Adam Gilchrist">
</datalist>
</label>
</body>
</html>
HTML Progress Tag Example
Let's see HTML progress example without attribute.
<!DOCTYPE>
<html>
<body>
<progress></progress>
</body>
</html>

<!DOCTYPE>
<html>
<body>
Downloading progress:
<progress value="50" max="100"></progress>
</body>
</html>

<!DOCTYPE>
<html>
<head>
<style>
progress{width:300px;height:30px}
</style>
</head>
<body>
<progress value="50" max="100"></progress>
</body>
</html>
Header element in html
Generally a <header> element contains one or more heading elements, logo or icons or
author's information.
Headers.html
<! DOCTYPE>
<html>
<body>
<header>
<h2>ABCOnline.com</h2>
<p> World's no.1 shopping website</p>
</header>
</body>
</html>
Output:
CSS Code:

header{
border: 1px solid pink;
background-color:pink;
padding:10px;
border-radius:5px;
}
HTML Code:
<header>
<h2>ABCOnline.com</h2>
<p> World's no.1 shopping website</p>
</header>
Output:

HTML Footer Tag


HTML <footer> tag is used to define footer for a document or a section. It is generally used
in the last of the section (bottom of the page).
The footer tag is included in HTML5.
HTML <footer> tag contains information about its containing elements for example:
o author information
o contact information
o copyright information
o sitemap
o back to top links
o related documents etc.
Note: You can have one or many footer elements in one document.
If you want to put information like address, e-mail etc. about the author on your web page, all the
relevant elements should be included into the footer element.
<!DOCTYPE>
<html>
<body>
<footer>
<p>Posted by: upendra vajanepalli</p>
<p>
<address> vaweinstitutes, plot no. 6, near MMX Mall,Mohan Nagar, Ghaziabad Pin no.
201007 </address>
</p>
<p>Contact information:
<a href="mailto:[email protected]">[email protected]</a>.
</p>
</footer>
</body>
</html>

Output:

SVG
 SVG is an acronym which stands for Scalable Vector Graphics.
 VG is mostly used for vector type diagrams like pie charts, 2-Dimensional graphs in an X,Y
coordinate system etc.
<svg>
<circle cx="50" cy="50" r="40" stroke="yellow" stroke-width="4" fill="red" />
</svg>

Rectangle:
<svg>
<rect width="200" height="100" stroke="yellow" stroke-width="4" fill="red" />
</svg>
Polygon:
<svg height="210" width="500">

<polygon points="100,10 40,198 190,78 10,78 160,198"

style="fill:red;stroke:yellow;stroke-width:5;fill-rule:nonzero;" />

</svg>

CSS (Cascading Style sheet)

CSS
 CSS stands for Cascading Style Sheets
 Styles define how to display HTML elements
 CSS adds new look to html tags
 External Style Sheets can save a lot of work
 Styles are normally saved in external .css files.
CSS Syntax
A CSS rule has two main parts: a selector, and one or more declarations:

 The selector is normally the HTML element you want to style


 Each declaration consists of a property and a value.
 The property is the style attribute you want to change.
 Each property has a value.
CSS Selectors:
CSS selectors are used to select the content you want to style. Selectors are the part of CSS
rule set.
There are several different types of selectors in CSS.
1. CSS Element Selector
2. CSS Id Selector
3. CSS Class Selector

CSS Element Selector


The element selector selects the HTML element by name.
<! DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p >Me too!</p>
<p>And me!</p>
</body>
</html>

The id Selector
 The id selector is used to specify a style for a single, unique element.
 The id selector uses the id attribute of the HTML element, and is defined with a "#".
 The style rule below will be applied to the element with id="para1":
#para1
{

text-align: center; color: red;

<html >
<head>
<style>
#demo1{
color:red;
}
#demo2{
color:red;
}
</style>
</head>
<body>
<p id="demo1">welcome to First paragraph</p>
<h1>welcome to heading tag</h1>
<p id="demo2">welcome to Second paragraph tag</p>
</body>
</html>
The class Selector
 The class selector is used to specify a style for a group of elements. Unlike the id selector, the
class
 Selector is most often used on several elements.
 This allows you to set a particular style for many HTML elements with the same class.
 The class selector uses the HTML class attribute, and is defined with a "."

<html>
<head>
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p> </body>
</html>

Explain different ways to write the CSS. / Explain CSS with all types
There are three ways of inserting a style sheet:
 Inline style
 Internal/Embedded style sheet
 External style sheet
Inline CSS:
<html>
<!--
<head>
<link rel="stylesheet" type="text/css" href="test.css" />
</head>
-->
<body>
<p style="background: blue; color: white ;"> A new background and font color with inline
CSS</p></body></html>
Internal/Embedded CSS
 This type of CSS is only for Single Page.
 When using internal CSS, we must add a new tag, <style>, inside the <head> tag. The
Below is an example of simple CSS code.
<html>
<head>
<style type="text/css">
p
{
color: white;
}
body
{
background-color: black;
}
</style>
</head>
<body>
<p>White text on a black background!</p>
</body>
</html>
External Style Sheet
 When using CSS it is preferable to keep the CSS separate from your HTML.
 Placing CSS in a separate file allows the web designer to completely differentiate between
content (HTML) and design (CSS).
 External CSS is a file that contains only CSS code and is saved with a ".css" file extension.
 This CSS file is then referenced in your HTML using the <link> instead of <style>.
File Creation
 Open up notepad.exe, or any other plain text editor and type the following CSS code.
body{ background-color: gray;} p { color: blue; }h3{ color: white; }
 Save the file as a CSS (.css) file.
 Name the file "test.css" (without the quotes). Now create a new HTML file and fill it with the
following code.
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css" /></head>
<body>
<h3> A White Header </h3>
<p> This paragraph has a blue font.
The background color of this page is gray because we changed it with CSS! </p>
</body>
</html>
Why Use External CSS?
 It keeps your website design and content separate.
 It's much easier to reuse your CSS code if you have it in a separate file. Instead of typing
the same CSS code on every web page you have, simply have many pages refer to a single
CSS file with the "link" tag.
 You can make drastic changes to your web pages with just a few changes in a single CSS file.
CSS Colors
Colors in CSS can be specified by the following methods:
 Normal colors
 Hexadecimal colors
 RGB colors
Hexadecimal colors
 Hexadecimal color values are supported in all major browsers.
 A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB
(blue) hexadecimal integers specify the components of the color. All values must be between
00 and FF.
 For example, the #0000ff value is rendered as blue, because the blue component is set to its
highest value (ff) and the others are set to 00.
Define different HEX colors:
#p1 {background-color: #ff0000;} /* red */
#p2 {background-color: #00ff00;} /* green */
#p3 {background-color: #0000ff;} /* blue */
RGB color values are supported in all major browsers.
An RGB color value is specified with: rgb(red, green, blue). Each parameter (red, green, and
blue) defines the intensity of the color and can be an integer between 0 and 255 or a percentage value
(from 0% to 100%).
For example, the rgb(0,0,255) value is rendered as blue, because the blue parameter is set to its
highest value (255) and the others are set to 0.
Also, the following values define equal color: rgb(0,0,255) and rgb(0%,0%,100%).
Define different RGB colors:
#p1 {background-color: rgb(255, 0, 0);} /* red */
#p2 {background-color: rgb(0, 255, 0);} /* green */
#p3 {background-color: rgb(0, 0, 255);} /* blue */
Explain CSS Background with all its attributes
CSS background properties are used to define the background effects of an element.
1. CSS Background Color
 The background-color property specifies the background color of an element
 The background color of a page is defined in the body selector:
Below is example of CSS backgrounds
body {background-color: #b0c4de;}
2. CSS Background Image
 The background-image property specifies an image to use as the background of an element.
body {background-image:url('paper.gif');}
3. Background Image Repeat
 You can have a background image repeat vertically (y-axis), horizontally (x-axis), in both
Directions, or in neither direction.
p {background-image: url(smallPic.jpg); background-repeat: repeat; }
h4 {background-image: url(smallPic.jpg); background-repeat: repeat-y; }
ol {background-image: url(smallPic.jpg); background-repeat: repeat-x; }
ul {background-image: url(smallPic.jpg);background-repeat: no-repeat; }
4. CSS Background Image Positioning
 The background-position property sets the starting position of a background image.
p {background-image: url(smallPic.jpg); background-position: 20px 10px;}
h4 {background-image: url(smallPic.jpg); background-position: 30% 30%;}
ol {background-image: url(smallPic.jpg); background-position: top center;}
Explain CSS Font with all its attributes
 CSS font properties define the font family, boldness, size, and the style of a text.
1. CSS Font Color
 Set the text-color for different elements:
h4 { color: red; }
h5 { color: #9000A1; }
h6 { color: rgb(0, 220, 98); }
2. CSS Font Family
 The font family of a text is set with the font-family property.
h4 {font-family: sans-serif ;}
h5 {font-family: serif; }
h6 { font-family: arial; }
h4 { color: red; }
h5 { color: #9000A1; }
h6 { color: rgb(0, 220, 98); }
2. CSS Font Family
 The font family of a text is set with the font-family property.
h4 { font-family: sans-serif; }
h5 { font-family: serif; }
h6 { font-family: arial; }
3. CSS Font Size
 The font-size property sets the size of the text.
p { font-size: 120%; } ol{ font-size: 10px; } ul{ font-size: x-large; }
4. CSS Font Style
 The font-style property is mostly used to specify italic text.
This property has three values:
 normal - The text is shown normally
 italic - The text is shown in italics
 oblique - The text is "leaning" (oblique is very similar to italic, but less supported)
p { font-style: italic; }h4{ font-style: oblique; }
5. CSS Font Variant
 The font-variant property specifies whether or not a text should be displayed in a smallcaps
font or normal.
p { font-variant: small-caps; }
p { font-variant: normal; }
Explain CSS Text with all its attributes.
 While CSS Font covers most of the traditional ways to format your text, CSS Text allows you
to
control the spacing, decoration, and alignment of your text.
1. Text Decoration
 The text-decoration property is used to set or remove decorations from text.
 The text-decoration property is mostly used to remove underlines from links for design
purposes.
h4{ text-decoration: line-through; }
h5{ text-decoration: overline; }
h6{ text-decoration: underline; }
a { text-decoration: none; }
2. Text Indent
 The text-indentation property is used to specify the indentation of the first line of a text.
p { text-indent: 20px; }
h5 { text-indent: 30%; }
3. Text Align
 The text-align property is used to set the horizontal alignment of a text.
p { text-align: right; }
h5{ text-align: justify; }
4. Text Transform
 The text-transform property is used to specify uppercase and lowercase letters in a text.
h5{ text-transform: uppercase; }
h5{ text-transform: lowercase; }
5. CSS Word Spacing
 With the CSS attribute word-spacing you are able to specify the exact value of the spacing
Between your words. Word-spacing should be defined with exact values.
p { word-spacing: 10px; }
6. CSS Letter Spacing
 With the CSS attribute letter-spacing you are able to specify the exact value of the spacing
Between your letters. Letter-spacing should be defined with exact values.
p { letter-spacing: 3px; }
1. Possible Values

Note:
Px: stands for pixels (1px=1 dot) –browser dependent
Pt: Stands for points (inches)(similar to px)
Em: stands for element (recommended in all browsers)(1em=16px)
Padding - Shorthand property
 To shorten the code, it is possible to specify all the padding properties in one property.
This is called a shorthand property.
padding:25px 50px;
Note: 25px refers to top and bottom
50px refers to both left and right
Explain CSS Margin.
 The CSS margin properties define the space around elements.
p {margin: 5px; border: 1px solid black;}
 The top, right, bottom, and left margin can be changed independently using separate
properties. A shorthand margin property can also be used, to change all margins at once.

1. Margin - Individual sides


 In CSS, it is possible to specify different margins for different sides:
margin-top: 100px;
margin-bottom:100px;
margin-right:50px;
margin-left:50px;
2. Margin - Shorthand property
 To shorten the code, it is possible to specify all the margin properties in one property. This
is called a shorthand property.
margin:100px 50px;
Explain CSS Border with all its attributes.
 The CSS border properties allow you to specify the style and color of an element's border.
1. Border Style Types
 The border-style property specifies what kind of border to display.
p.solid {border-style: solid; } p.double {border-style: double; } p.groove {border-style: groove; }
p.dotted {border-style: dotted; } p.dashed {border-style: dashed; } p.inset {border-style: inset; }
p.outset {border-style: outset; } p.ridge {border-style: ridge; } p.hidden {border-style: hidden;
2. Border Width
 The border-width property is used to set the width of the border.
table { border-width: 7px; border-style: outset; }
td { border-width: medium; border-style: outset; }
p { border-width: thick; border-style: solid; }
3. Border Color
 The border-color property is used to set the color of the border.
 Border colors can be any color defined by RGB, hexadecimal, or key terms. Below is an
example of each of these types.
table { border-color: rgb( 100, 100, 255); border-style: dashed; }
td { border-color: #FFBD32; border-style: ridge; }
p { border-color: blue; border-style: solid; }
4. Border: border-(direction)
 If you would like to place a border on only one side of an HTML element, or maybe have a
 unique look for each side of the border, then use border-(direction).
 The direction choices are of course: top, right, bottom, and left. CSS allows you to treat
 each side of a border separately from the other three sides.
 Each side can have its own color, width, and style set, as shown below.
p { border-bottom-style: dashed ; border-bottom-color: yellow; border-bottom-width: 5px; }
h4 { border-top-style: double; border-top-color: purple; border-top-width: thick;}
1. CSS Anchor/Link States
The four links states are:
 a:link - a normal, unvisited link
 a:visited - a link the user has visited
 a:hover - a link when the user mouse over it
 a:active - a link the moment it is clicked
a:link{color:#FF0000;} /*unvisited link*/
a:visited{color:#00FF00;} /* visited link */
a:hover{color:#FF00FF;} /* mouse over link */
a:active {color:#0000FF;} /* selected link */
2. Text Decoration
 The text-decoration property is mostly used to remove underlines from links.
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:underline;}
a:active {text-decoration:underline;}
3. Background Color
 The background-color property specifies the background color for links.
a:link {background-color:#B2FF99;}
a:visited {background-color:#FFFF85;}
a:hover {background-color:#FF704D;}
a:active {background-color:#FF704D;}

Java script
What is JavaScript?
 HTML and CSS concentrate on a static rendering of a page; things do not change on the page
over time, or because of events.
 To do these things, we use scripting languages, which allow content to change dynamically.
 Not only this, but it is possible to interact with the user beyond what is possible with HTML.
 Scripts are programs just like any other programming language; they can execute on the
client side or the server.
 JavaScript was invented by Brendan Eich in 1995.
 JavaScript is used to program the behavior of web pages
 JavaScript can be placed in the <body> and the <head> sections of an HTML page.
 In HTML, JavaScript code must be inserted between <script> and </script> tags.
 Java script is used for checking the client side validation

Advantages of client side scripting


 The web browser uses its own resources, and eases the burden on the server.
 It has fewer features than server side scripting.
 It saves network bandwidth.
Differentiate between server side and client side scripting languages
Client-side scripting languages
 The client-side environment used to run scripts is usually a browser.
 The processing takes place on the end users computer.
 The scripting language needs to be enabled on the client computer.
 When this is the case a message usually pops up to alert the user when script is attempting to
run.
Server-side scripting languages
 The server-side environment that runs a scripting language is a web server.
 A user's request is fulfilled by running a script directly on the web server to generate dynamic
HTML pages.
 This HTML is then sent to the client browser.
 It is usually used to provide interactive web sites that interface to databases or other data
stores on the server.
 The primary advantage to server-side scripting is the ability to highly customize the response
based on the user's requirements, access rights, or queries into data stores.
What is difference between Java script and JAVA?
 Java is a statically typed language; JavaScript is dynamic.
 Java is class-based; JavaScript is prototype-based.
 Java constructors are special functions that can only be called at object creation; JavaScript
"Constructors" are just standard functions.
 Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons
at the ends of certain lines.
Embedded JavaScript
 JavaScript can be embedded in an HTML document.
 To embed it in HTML you must write:
<script type=”text/javascript”>
</script>
 The script tag has effect of the stopping the JavaScript being printed out as well as
indentifying the code enclosed.
 The JavaScript can be placed in the head section of your HTML or the body.
<html>
<body>
<script type=”text/javascript”>
document.write("<h1>This is a heading</h1>");
</script>
</body>
</html>
 The Scripts placed in the body section are executed as the page loads and can be used to
generate
the content of the page.
 As well as the body section, JavaScript can also be placed in the head part.
 The advantages of putting a script in there are that it loads before the main body.
External JavaScript
 If you want to use the same script on several pages it could be a good idea to place the code
in a
Separate file, rather than writing it on each.
 That way if you want to update the code, or change it, you only need to do it once.
 Simply take the code you want in a separate file out of your program and save it with the
extension .js.
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
JavaScript Variables
 Variables in JavaScript behave the same as variables in most popular programming languages
(C,
 C++, etc) do, but in JavaScript you don't have to declare variables before you use them.
 A variable's purpose is to store information so that it can be used later. A variable is a
symbolic name
 that represents some data that you set.
 When using a variable for the first time it is not necessary to use "var" before the variable
name.
 Variable names must begin with a letter.
 Variable names are case sensitive (y and Y are different variables).

var x=5;
var y=6;
var z=x+y;

You can declare many variables in one statement. Just start the statement with var and separate
the
Variables by comma:
var name="Doe", age=30, job="carpenter";
var name="Doe",
age=30,
job="carpenter";
Variable declared without a value will have the value undefined.
 If you re-declare a JavaScript variable, it will not lose its value.
 The value of the variable carname will still have the value "Volvo" after the execution of the
following two statements.
varcarname="Volvo";
varcarname;
JavaScript Operators
 Operators in JavaScript are very similar to operators that appear in other programming
languages.
 The definition of an operator is a symbol that is used to perform an operation.
 Most often these operations are arithmetic (addition, subtraction, etc), but not always.

<body>
<script type="text/JavaScript">
<!--
var two = 2
var ten = 10
varlinebreak = "<br />"
document.write("two plus ten = ")
var result = two + ten
document.write(result)
//-->
</script>
</body>

JavaScript Array
 An array is a special variable, which can hold more than one value at a time.
 The Array object is used to store multiple values in a single variable.
 An array can be created in three ways.
 The following code creates an Array object called myCars.

Regular
varmyCars=new Array("Saab","Volvo","BMW");
varmyCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
Condensed
varmyCars=new Array("Saab","Volvo","BMW");
Literal
varmyCars=["Saab","Volvo","BMW"];
<html><body>
<script type=”text/javascript”>
var z= multXbyY(10,15);
document.write(“The result is” +z);
functionmultXbyY(x,y) {
document.write(“x is ” +x);
document.write(“y is ”+y);
return x*y;
}
</script>
</body></html>
User- Defined Objects/How user defined objects are created in JavaScript?
 JavaScript allows you to create your own objects.
 The first step is to use the new operator.
VarmyObj= new Object();
 This creates an empty object.
 This can then be used to start a new object that you can then give new properties and
methods.
 In object- oriented programming such a new object is usually given a constructor to initialize
values when it is first created.
 However, it is also possible to assign values when it is made with literal values.
<!DOCTYPE html>
<html>
<body>
<script language=”JavaScript” type=”text/JavaScript”>
person={
firstname: "Ketan",
lastname: "Chavda",
age: 24,
eyecolor: "blue"
}
document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>

<!DOCTYPE html>
<html>
<body>
<script>
function person(firstname, lastname, age)
{
this.firstname = firstname;
this.lastname = lastname;
this. age = age;
}
var person1=new person("Narendra","Modi",24);
document.write(person1.firstname + “ ”+ person1.lastname +” “+ person1.age);
</script>
</body>
</html>

In above the function person becomes the constructor invoked through the new keyword on
Assignment to the person1 variable.
 Here the values are passed as parameters to the constructor.
 Inside the constructor the this keyword takes on the value of the newly created object and
therefore applies properties to it.
********************************************************************************
Ex:
<p id="demo">welcome to</p>
<script>
document.getElementById("demo").innerHTML="upendra sir";
</script>
Ex:
<html>
<head>
<title>TODO supply a title</title>
<script>
function validation()
{
document.getElementById("demo").innerHTML="upendra sir";
}
</script>
</head>
<body>
<p id="demo">welcome to</p>
<button onclick="validation()">Click here</button>
</body>
</html>

Java script validation


 The idea behind JavaScript form validation is to provide a method to check the user entered
information before they can even submit it.
 JavaScript also lets you display helpful alerts to inform the user what information they have
entered incorrectly and how they can fix it.
Normal validation without using Regular expression:
<html>
<body>
<script>
function validateform()
{
var name=document.myform.name.value;
var password=document.myform.password.value;
var secondpassword=document.myform.password2.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
if(!isNaN(name)){
alert("Digists are not allowed");
return false;
}
if(password.length<6) {
alert("Password must be at least 6 characters long.");
return false;
}
if(password!=secondpassword) {
alert("Both password and confirm passwords must be same!");
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
Re-enter Password:<input type="password" name="password2"/><br>
<input type="submit" value="register">
</form>
</body>
</html>

Regular Expression:
 A regular expression is an object in JavaScript that describes a pattern of characters.
 When you search in a text, you can use a pattern to describe what you are searching for.
 A simple pattern can be one single character.
 A complicated pattern can consist of more characters, and can be used for parsing, format
checking, substitution and more.
 Regular expressions are used to perform powerful pattern-matching and "search-and-replace"
functions on text.
 JavaScript include a set of routines to manipulate strings and search patterns. These are
wrapped up as regular expression objects.
 JavaScript regular expressions are more than patterns: they include functions which you call
from your scripts when need a pattern finding.
Creating Regular Expressions:
A regular expression is a JavaScript object. They can be created statically when the script is
first parsed, or dynamically at run-time.

A static regular expression is created as follows:


regex = “fish”;

Dynamic regular expression is created using the new keyword to create an instance of the
RegExp class:
regex = new RegExp(“fish “);
Functions of Regular Expressions: These functions are classified into two types they are
1. Class RegExp functions
2. Class string functions
Class RegExp functions:

Test (): The test() method searches a string for a specified value, and returns true or false, depending
on the result.
syntax:
var patt1=new RegExp("a");
document.write(patt1.test("This is a pattern"));
Since there is an "a" in the string, the output of the code above will be: true

exec (): The exec() method searches a string for a specified value, and returns the text of the found
value. If no match is found, it returns null.
Syntax:
var patt1=new RegExp("a");
document.write(patt1.exec("This is a pattern"));
Since there is an "a" in the string, the output of the code above will be: a

Example:
<html>
<head>
<title> Pattern Matching </title>

<script language="javascript">
var msg = prompt("Enter a test string : ");
var hunt = prompt("Enter a regular expression : ");
var re = new RegExp(hunt);
var result = re.exec(msg);
document.writeln("<h2> Search Results </h2>");
if( result )
document.write(" Found : " + result[0] );
else
document.write("Not found");
</script>
</head>
<body>
</body>
</html>
Class string functions:
Match (pattern):
This function searches for pattern of characters in a string, if it is found the result will be stored in
an array, other wise it returns null.

Replace (pattern1, pattern2):


This function searches for characters of pattern1 in a given string; if the search is successful then
pattern1 is replaced with pattern2.
Search (pattern):
This function searches for pattern of characters in a string; if the match is successful it returns
the index of the starting character in pattern, otherwise it returns
“-1”
Split (pattern):
This function is used to split the entire string into two parts based on pattern (or) regular expression
passed as a parameter.
Example for match function:
<html>
<head>
<title> Pattern Matching </title>
<script language="javascript">

var msg = prompt("Enter a test string : ");


var re=new RegExp("ndc");
var result = msg.match(re);
if ( result )
document.write(" Found : " + result[0] );
else
document.write("null");
</script>
</head> <body> </body> </html>
Example for replace:

<html>
<head>
<tile>replace of string</title>
</head>
<body>
<script>
var msg=prompt(“enter a string”);
var hunt=prompt(“enter regular exp”);
msg=msg.replace(hunt,”nalanda”);
document.write(“<h1> replaced string is</h1>”);
document.write(msg);
< /script>
</body> </html>
Example for split:

<html>
<head>
<tile>spliting of string</title>
</head>
<body>
<script>
var msg=prompt(“enter a string”);
var hunt=prompt(“enter regular exp”);
var results=msg.split(hunt);
document.write(“<h1> split result is <h1>”);
for(var i=0; i<results.length ;i++)
{
document.write(“ result is” +result[i]);
document.write(“<br>”);
}
</script>
</body></html>
Validations in JavaScript using Regular expression:
A. Name validation:
1. first name should be [^a-z A-Z] means including white spaces
function validate() {
var regexp1=new RegExp("[^a-z A-Z]");
if(regexp1.test(document.getElementById("age").value))
{
alert("Only alphabets from a-z are allowed");
return false;
}
}
B. phono validation
function validate()
{
var x=document.getElementById("age").value;
var phoneno = /^\d{10}$/;
if(x.match(phoneno))
{
return true;
}
else
{
alert("Not a valid Phone Number");
return false;
}
}
C. Email id Validation:
function validate(){
var x=document.getElementById("age").value;
var phoneno = "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$";
if(x.match(phoneno)) {
return true;
}
else {
alert("Enter valid mail id ");
return false;
}
}
D: password field
This regex will enforce these rules:
At least one upper case English letter, (?=.*?[A-Z])
At least one lower case English letter, (?=.*?[a-z])
At least one digit, (?=.*?[0-9])
At least one special character, (?=.*?[#?!@$%^&*-])
Minimum eight in length .{8,} (with the anchors)

function validate(){
var x=document.getElementById("pwd").value;
var pass = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$";
if(x.match(pass))
{
return true;
}
else
{
alert("valid password");
return false;
}

}
HTML <input> pattern Attribute
The pattern attribute is new in HTML5.
Syntax
<input pattern="regexp">
The pattern attribute specifies a regular expression that the <input> element's value is checked
against.
Note: The pattern attribute works with the following input types: text, date, search, url, tel, email,
and password.

An HTML form with an input field that can contain only three letters (no numbers or special
characters):

<form action="/action_page.php">
Country code: <input type="text" name="country_code"
pattern="[A-Z a-z]{3}" title="Three letter country code">
<input type="submit">
</form>
An <input> element with type="password" that must contain 8 or more characters that are of
at least one number, and one uppercase and lowercase letter:

<form action="/action_page.php">
Password: <input type="password" name="pw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8
or more characters">
<input type="submit">
</form>

An <input> element with type="email" that must be in the following order:


[email protected] (characters followed by an @ sign, followed by more characters, and
then a "."
After the "." sign, you can only write 2 to 3 letters from a to z:

<form action="/action_page.php">
E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-
z]{2,3}$">
<input type="submit">
</form>
Built-in Objects in JavaScript?
Document object:
A document is a Webpage that is being either displayed or created. Each HTML document
loaded into a browser window becomes a Document object.
The Document object provides access to all HTML elements in a page, from within a script.
The document has a number of properties that can be accessed by JavaScript programs and used to
manipulate the content of the page.
write() :Writes HTML expressions or JavaScript code to a document.
Ie: document. write (“hai”);
writeln() :Same as write(), but adds a newline character after each statement
Ie: document. writeln (“hai”);
Close(): it gives signal to browser that my script is over
Document.close();
FORM OBJECT
Two aspects of the form can be manipulated though JavaScript. First, most commonly the
data is entered onto the form can be checked at submission. Second, we can actually build forms
through JavaScript.
The elements of the form are held in an array. This means that any of the properties of those
elements that can set using HTML code can be accessed though JavaScript.
onClick=”method”
This method can be applied to all form elements. The event is triggered when the user clicks
on that element.
onSubmit=”method”
This event can only be triggered by the form itself and occurs when a form is submitted.
BROWSER OBJECT:
No two browser models will process the JavaScript in the same way. It is important that find
out which browser is being used to view the page, so that make a choice for visitors such as:
 Exclude browsers that are unable to use code;
 Redirect them to a non-scripted version of site;
 Present scripts that are tailored to suit each browser.
The browser is a JavaScript object and can be queried from within code. The browser object is
actually called the navigator object. The following are the some properties:
navigator.appCodeName
The internal name for the browser. For both major products this is Mozilla, which was the
name of the original Netscape code source.
navigator.appName
This is the public name of the browser – navigator or Internet Explorer for the big two.
navigator.appVersion
The version number, platform on which the browser is running, and (for Internet Explorer)
the version of navigator with which it is compatible.
navigator.plugins:
An array containing details of all installed plug-ins.
example:
<html>
<head>
<script language="javascript">
document.write("<br> <b> appcode name : </b>" + navigator.appCodeName);
document.write(" <br> <br> <b> app name : </b>" + navigator.appName);
document.write(" <br> <br> <b> version : </b>" + navigator.appVersion);
document.write(" <br> <br> <b> user agent : </b>" + navigator.userAgent);
document.write("<br> <b> mime type : </b>" + navigator.mimeTypes.length);
document.write(" <br> <br> <b> plugins : </b>" + navigator.plugins.length);
document.write(" <br> <br> <b> plugins : </b> <br>" );
for(i=0; i<navigator.plugins.length; i++)
document.write(navigator.plugins[i].name + " , ");
</script> </head>
<body>
</body>
</html>
Date Object:
JavaScript includes a well-developed Date class which provides functions to perform many
different date manipulations. In JavaScript, dates and times represent the number of milliseconds
since 1st January 1970 UTC.
Date(): Construct an empty date object.
Date(milliseconds): Construct a new Date object based upon the number of milliseconds which have
elapsed since 00:00:00 hours on 01/01/1970.
Date(string): Create a Date object based upon the contents of a text string. The string must be in the
format which is created by the Date.parse() function.
Date(year, month, day [, hour, minute, second ] ): Create a new Date object based upon numerical
values for the year, month and day. Optional time values may also be supplied. January is
represented by the integer value 0, December by 11.
parse(string): Returns the number of milliseconds since midnight on 01/01/1970 which the string
represents. The string must be in the format: Mon, 9 September 2010 10:35:22
FUNCTION DESCRIPTION
getDate() Return the day of the month.
getDay() Return an integer representing the day of the
week, Sunday is 0 and Saturday is 6.
getFullYear() Return the year as a four digit number.
getHours() Return the hour field of the Date object.
getMinutes() Return the minutes field of the Date object, from
0 to 59.
getMonth() Return the month field of the Date object. The
month is represented by an integer, 0 for January,
11 for December.
toString() Returns the Date as a string.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Event Handling in JavaScript.
JavaScript is event driven system or not. Justify.
JavaScript is an event-driven system An event is any change that the user makes to the
state of the browser.
Responses made by the browser on account of user’s interactions are often referred to
as Events. For example playing of audio clip as soon as the page is loaded, generation of informative
text as the mouse pointer is moved through a certain region of the web page, submission of user
entered data to the server upon clicking the submit button etc., forms normally observed events.
Once the event is generated, there is often requirement of code to process these events. Such
code is known as Event Handler. In general event handlers are of two types.
 Interactive event handlers.
 Non-interactive event handlers.
The event handlers which solely rely on the user’s activity for them to be invoked are
interactive event handler example, onClick, onBlur etc.
The event handlers which do not rely on the user’s activity for them to be invoked are non-
interactive event handlers, example, onLoad, onunLoad etc.
Syntax for Include an Event Handlers in JavaScript:
To include event handlers in JavaScript, we initially select an appropriate event handler
attribute for its corresponding event and include it in the given HTML tag.
<input type=”button” value=”reset” name=”button1” onClick=”fname()”>

EVENT HANDLER DESCRIPTION

click onClick The mouse is clicked over an element of a page.


dblclick onDblClick A form element or a link is clicked twice in rapid
succession.
load onLoad The page is loaded by the browser.

unload onUnload The user leaves the webpage.


mousemove onMouseMove The mouse, and hence cursor, is moved.

mouseover onMouseOver The mouse pointer is moved over an element.

mouseout onMouseOut The mouse pointer moves off an element.

keyup onKeyUp A depressed key is released.

submit onSubmit A form is submitted ( the submit button is clicked).


Example:
<html>
<head> <title> Pattern Matching </title>
<script language="javascript">
function fact()
{
var f = 1, i, n;
n = prompt("Enter a number");
for(i=1; i<=n; i++)
f = f * i;
alert("factrial is" +f);
}
function ndc()
{
alert("hai");
}
function ndc1()
{
alert("welcome");
}
function ndc4()
{
alert("nalanda colleg");
}
function ndc5()
{
alert("narasimham parimi");
}
</script>
</head>
<body onLoad="fact()" onUnLoad="ndc1()">
<form>
<input type="button" value="click" onClick="ndc()">
<input type="button" value="hai" onMouseMove="ndc4()" onMouseOut=”ndc5()”>
</form> </body></html>
the Message & Confirmation dialogs in JavaScript.
Alert
The alert built in function is useful for displaying a message on the screen that you don't want
your visitors to miss. They will have to select the OK button to proceed. Here is an example of an
alert function call:
alert('Alert Message');
Confirm :
The confirm function differs from the alert function only in that it has two buttons to choose
between instead of only one. The confirm function returns true or false depending on which of the
two buttons is selected. If OK is selected then the confirm function returns true, if Cancel is selected
it returns false.
Here's an example of the confirm function:
if (confirm('Select a button'))
alert('You selected OK');
else
alert('You selected Cancel');
Prompt Box:
A prompt box is often used if you want the user to input a value before entering a page. When
a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering
an input value. If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
Syntax:
prompt("sometext","defaultvalue");
Example:
<html>
<head>
<script>
var ndc;
ndc=prompt("enter a name");
document.write("name is " +ndc);
alert("my name is" +ndc);
confirm("welldone");
</script> <body> </body> </html>

Advanced JAVA (J2EE)


In IT we are developing two types of applications; they are standalone applications and Distributed
applications.
 A standalone application is one which runs in the context of local disk. With standalone
Applications we cannot achieve the concept of data sharing. For example C, C++, COBOL,
PASCAL, etc.
 A distributed application is one which always runs in the context of Browser or World Wide
Web. All distributed applications can be accessed across the globe. For example JAVA and
DOT NET.
JAVA always provides a facility called server independent, platform independent language.
In real time applications, in the case of server side programming one must follow the
Architecture to develop a distributed application.
To develop any distributed application, it is always recommended to follow either 3-tier
Architecture or 2-tier architecture or n-tier architecture.
3-tier architecture is also known as MVC architecture. M stands for Model (database
programming), V stands for View (client side programming, HTML/AWT/APPLET/Swing/JSP)
and C stands for Controller (server side programming, Servlets).
The general architecture of MVC or 3-tier:
1. Client makes a request.
2. Server side program receives the request.
3. The server looks for or search for the appropriate resource in the resource pool.
4. If the resource is not available server side program displays a user friendly message (page
Cannot be displayed). If the resource is available, that program will execute gives its result to
Server, server interns gives response to that client who makes a request.
5. When server want to deals with database to retrieve the data, server side program sends a
Request to the appropriate database.
6. Database server receives the server request and executes that request.
7. The database server sends the result back to server side program for further processing.
8. The server side program is always gives response to ‘n’ number of clients concurrently.
JDBC (Java Database Connectivity)
“JDBC is a kind of specification developed by SUN Microsystems to store the data
Permanently”.
In Information Technology we have two approaches’ to store the data permanently. They
are through files and through database.
Whatever data we store permanently in the form of a file, the file will not provide enough
Security to the data from unauthorized users.
In order to save or store the data permanently in the form of a file we must use the concept
of serialization.
JDBC Architecture:

The JDBC 4.0 Packages


The java.sql and javax.sql are the primary packages for JDBC 4.0. This is the latest JDBC
version at the time of writing this tutorial. It offers the main classes for interacting with your data
sources.
The new features in these packages include changes in the following areas −
 Automatic database driver loading.
 Exception handling improvements.
 Enhanced BLOB/CLOB functionality.
 Connection and statement interface enhancements.
 National character set support.
 SQL ROWID access.
 Annotations.
JDBC Drivers: JDBC Driver is a set of classes that provides the implementation of JDBC API.
Types of JDBC DRIVERS
 Type-1 Driver or JDBC-ODBC bridge[Partly Java Driver]
 Type-2 Driver or Native API [Partly Java Driver]
 Type-3 Driver or Network Protocol Driver [Fully java driver]
 Type-4 Driver or Thin Driver [Fully java driver]

JDBC-ODBC Bridge:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Advantages:
 Easy to use
 Can be easily connected to any database
Disadvantages:
 Slow execution time
 Dependent on ODBC Driver.
Native API Driver (Type-2 Driver):
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

Advantage:
 Faster as compared to Type-1 Driver
Disadvantage:
 Requires native library
Network Protocol Driver:
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly into the vendor-specific database protocol. It is fully written in java
Advantage:
 Does not require any native library to be installed.
 Database Independency.
 Provide facility to switch over from one database to another database.
Disadvantage:
 Slow due to increase number of network call.
Thin Driver:
This is Driver called Pure Java Driver because. This driver interacts directly with database. It
does not require any native database library that is why it is also known as Thin Driver.

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depends on the Database
Java.sql package:
This package includes classes and interface to perform almost all JDBC operation such as
creating and executing SQL Queries.
Important classes and interface of java.sql package
classes/interface Description
java.sql.BLOB Provide support for BLOB(Binary Large Object) SQL type.
java.sql.Connection creates a connection with specific database
java.sql.CallableStatement Execute stored procedures
java.sql.CLOB Provide support for CLOB(Character Large Object) SQL type.
java.sql.Date Provide support for Date SQL type.
java.sql.Driver Create an instance of a driver with the Driver Manager.
java.sql.DriverManager This class manages database drivers.
java.sql.PreparedStatement Used to create and execute parameterized query.
java.sql.ResultSet It is an interface that provide methods to access the result row-by-row.
java.sql.Savepoint Specify savepoint in transaction.
java.sql.SQLException Encapsulate all JDBC related exception.
java.sql.Statement This interface is used to execute SQL statements.

Steps to connect a Java Application to Database


The following 5 steps are the basic steps involve in connecting a Java application with Database
using JDBC.
1. Register the Driver(Loading the driver)
2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection

Loading the drivers:


Loading the drivers is nothing but creating an object of appropriate Driver class.
Step 1:
Register the Driver (Loading the driver):

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

 This method is used to dynamically load the driver class.


Syntax of forName () method:

public static void forName(String className)throws ClassNotFoundException


Example to register the Driver:
Class.forName (“sun.jdbc.odbc.JdbcOdbcDriver”);
Class.forName ("oracle.jdbc.driver.OracleDriver");
Step 2:

2) Create the connection object:


The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) throws
SQLException
DriverManager.getConnection ("jdbc: odbc: Test");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Step 3:
Create SQL query statements:

STATIC QUERY:
Static query is one in which the data is passed in the query itself.
For example:
1. Select * from Student where marks>50;
2. Insert into Student values (100, ‘abc’, 90.86);
In order to execute static queries we must obtain an object of java.sql.Statement interface.
In the interface java.sql.Connection we have the following method for obtaining an object of
Statement interface.

For example:
Statement st=con1.createStatement ();
 On database three categories of operations takes place, they are insertion, deletion and
updation.
 In order to perform these operations we must use the following method which is present in
Statement interface.
Step 4:
Execute the Sql statements:
Here, String represents either static insertion or static deletion or static sudation. The return
Type int represents the status of the query. If the query is not successful it returns zero and if the
Query is successful it returns non-zero.
Step 5:
Closing the connection object

Con.close(

Create DSN Name


1. Go to control panel

2. Go to Administrative tools
3. Select Data Source(ODBC)

4. Add new DSN name, select add


5. Select Access driver from the list, click on finish

6. Give a DSN name, click ok


7. Go to control panel

8. Go to Administrative tools
9. Select Data Source(ODBC)

10. Add new DSN name, select add


11. Select Access driver from the list, click on finish

12. Give a DSN name, click ok


NOTE: Here we are showing this example to create DSN in Window 7 os. For other operating
system you need to do small changes.
Write a jdbc program which will insert a record in the Student database With DSN using
Eclipse ide?
Answer:

import java.sql.*;
class InsertRec
{
public static void main (String [] args)throws SQLException,ClassNotFoundException
{

String url="jdbc:odbc:Test";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection(url);
System.out.println ("CONNECTION ESTABLISHED...");
Statement st=con.createStatement ();
int i=st.executeUpdate ("insert into student values (10,'suman');");
System.out.println (i+" ROWS SELECTED...");
con.close ();

}
}
Processing the query result:
In order to execute the select statement or in order to retrieve the data from database we
Must use the following method which is present in java.sql.Statement interface.
For example:
ResultSet rs=st.executeQuery (“select * from Student”);
The ResultSet object is pointing by default just before the first record, in order to bring first
Record we must use the below given method. Method returns true when rs contains next record
Otherwise it returns false.
public boolean next ();
In order to obtain the data of the record (collection of field values) we must use the
Following method:
public String getString (int colno);
Whatever the data retrieving from the record that data will be treated as string data.
For example:
String s1=rs.getString (1);
String s1=rs.getString (2);
String s1=rs.getString (3);
Write a java program to retrieve the data from student table?
Answer:
import java.sql.*;
class InsertRec
{
public static void main (String [] args)throws SQLException,ClassNotFoundException
{
String url="jdbc:odbc:Test";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection (url);
Statement st=con.createStatement ();

ResultSet rs=st.executeQuery ("select * from student");


while (rs.next ())
{
System.out.println (rs.getInt(1)+" "+rs.getString (2));
}
con.close ();

}
}
ResultSet:
1. An object of ResultSet allows us to retrieve the data by default only in forward direction but
not in backward direction and random retrieval.
2. Whenever we get the database data in ResultSet object which will be temporarily
Disconnected from the database.
3. ResultSet object does not allows us to perform any modifications on ResultSet object.
4. Hence, the ResultSet is by default non-scrollable disconnected ResultSet.
DYNAMIC or PRE-COMPILED QUERIES:
1. Dynamic queries are those for which the data is passed at runtime.
2. To execute dynamic queries we must obtain an object of PreparedStatement.
TYPE – 4 DRIVERS
In order to avoid the disadvantages of Type-1 drivers, we have to deal with Type-4 drivers.
Disadvantages of Type-1:
1. Since, it is developed in ‘C’ language; this type of driver is treated as platform dependent.
2. These are a waste of memory space. Since, we are creating a DSN (Data Source Name) for
Each and every database connection and it leads to less performance.
3. We are unable to develop 3-tier applications.
Advantages of Type-4:
1. This driver gives affective performance for every jdbc application. Since, there is no DSN.
2. Since, this driver is developed in java by database vendors, internally JVM need not to
Convert platform dependent to platform independent.
The only disadvantage of Type-4 is we are unable to develop 3-tier applications.
To connect java application with the Oracle database ojdbc14-10g file is required to be loaded.

Ways to load the jar file

Java\jdk1.7.0_79\jre\lib\ext

Write a java program to insert a record in dept database by accepting the data from keyboard
at Runtime using dynamic queries?
Answer:
import java.sql.*;
import java.io.*;
class InsertRecRun{
public static void main (String [] args){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println ("CONNECTION OBTAINED...");
PreparedStatement ps=con.prepareStatement ("insert into dept123 values (?,?,?)");

DataInputStream dis=new DataInputStream (System.in);


System.out.println ("ENTER DEPARTMENT NUMBER : ");
String s1=dis.readLine ();
int dno=Integer.parseInt (s1);

System.out.println ("ENTER DEPARTMENT NAME : ");


String dname=dis.readLine ();

System.out.println ("ENTER LOCATION NAME : ");


String loc=dis.readLine ();

ps.setInt (1, dno);


ps.setString (2, dname);
ps.setString (3, loc);

int i=ps.executeUpdate ();


System.out.println (i+"ROW(s) INSERTED...");
con.close ();
}
catch (Exception e)
{
System.out.println("Exception is occured at"+e);
}
}// main
}; // InsertRecRun

Write a java program to retrieve the records from a specified database by accepting input
from Keyboard?
Answer:
import java.sql.*;
import java.io.*;
class SelectRun{
public static void main (String [] args){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println ("CONNECTION OBTAINED...");
PreparedStatement ps=con.prepareStatement ("select * from dept123 where dno=?");
DataInputStream dis=new DataInputStream (System.in);
System.out.println ("ENTER DEPARTMENT NUMBER : ");
String s1=dis.readLine ();
int dno=Integer.parseInt (s1);
ps.setInt (1, dno);
ResultSet rs=ps.executeQuery ();
while (rs.next ())
{
System.out.print (rs.getString (1)+" "+rs.getString (2)+" "+rs.getString (3));
}

con.close ();
}
catch (Exception e)
{
System.out.println("Exception is occured at"+e);
}
}// main
};
Database Metadata interface:
Database Metadata interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of tables, name
of total number of views etc.
Commonly used methods of Database Metadata interface
 public String getDriverName()throws SQLException: it returns the name of the JDBC
driver.
 public String getDriverVersion()throws SQLException: it returns the version number of
the JDBC driver.
 public String getUserName()throws SQLException: it returns the username of the
database.
 public String getDatabaseProductName()throws SQLException: it returns the product
name of the database.
 public String getDatabaseProductVersion()throws SQLException: it returns the product
version of the database.
 public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the description of the
tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM
TABLE, SYNONYM etc.

How to get the object of DatabaseMetaData:


The getMetaData() method of Connection interface returns the object of
DatabaseMetaData.
Syntax:
public Database Metadata getMetaData ()throws SQLException
Simple Example of DatabaseMetaData interface:

import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("Driver Name: "+dbmd.getDriverName());
System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output: Driver Name: Oracle JDBC Driver
Driver Version: 10.2.0.1.0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release 10.2.0.1.0 -Production
Batch Processing:
Instead of executing a single query, we can execute a batch (group) of queries. It makes the
performance fast.
The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch
processing.
Methods of Statement interface:
The required methods for batch processing are given below:

Method Description

void addBatch(String query) It adds query into batch.

int[] executeBatch() It executes the batch of queries.

Example of batch processing in jdbc


Let's see the simple example of batch processing in jdbc. It follows following steps:
 Load the driver class
 Create Connection
 Create Statement
 Add query in the batch
 Execute Batch
 Close Connection
import java.sql.*;
class BatchProcessing{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Statement stmt=con.createStatement ();
stmt.addBatch("insert into user420 values(15,'abhi',400)");
stmt.addBatch("insert into user420 values(16,'umesh',500)");
stmt.executeBatch();//executing the batch

//con.commit();
con.close();
}
}
Functions:

A function is one which contains n number of block of statements to perform some


Operation and it returns a single value only.
Java Callable Statement Interface:
Callable Statement interface is used to call the stored procedures and functions. We can
have business logic on the database by the use of stored procedures and functions that will make the
performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may create
a function that receives date as the input and returns age of the employee as the output.
Creating a function:
create or replace function StuFun
(a in number, b in number, n1 out number) return number
as
n2 number;
begin
n1:=a*b;
n2:=a+b;
return (n2);
end;
/
FunConcept.java
import java.sql.*;
import java.io.*;
class FunConcept
{
public static void main (String [] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println ("DRIVERS LOADED...");
Connection con=DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println ("CONNECTION OBTAINED...");
DataInputStream dis=new DataInputStream (System.in);
System.out.println ("ENTER FIRST NUMBER : ");
String s1=dis.readLine ();
System.out.println ("ENTER SECOND NUMBER : ");
String s2=dis.readLine ();
int n1=Integer.parseInt(s1);
int n2=Integer.parseInt(s2);
CallableStatement cs=con.prepareCall("{?=call StuFun (?,?,?)}");
cs.setInt(2, n1);
cs.setInt(3, n2);
cs.registerOutParameter(1, Types.INTEGER);
cs.registerOutParameter(4, Types.INTEGER);
cs.execute ();
int res=cs.getInt(1);
int res1=cs.getInt(4);
System.out.println("SUM OF THE NUMBERS : "+res);
System.out.println("MULTIPLICATION OF THE NUMBERS : "+res1);
}
catch (Exception e)
{
e.printStackTrace ();
}
}// main
}// FunConcept
Output:
DRIVERS LOADED...
CONNECTION OBTAINED...
ENTER FIRST NUMBER :
5
ENTER SECOND NUMBER :
6
SUM OF THE NUMBERS : 11
MULTIPLICATION OF THE NUMBERS : 30
Procedure creation:
Create or replace procedure product_proc
(id IN NUMBER, name IN VARCHAR2)
is
begin
insert into product values(id,name);
end;
/
InsertProcedure1.java
import java.sql.*;
public class InsertProcedure1
{
public static void main(String[] args)
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","manager");

CallableStatement stmt=con.prepareCall("{call product_proc(?,?)}");


stmt.setInt(1,100);
stmt.setString(2,"laptop");
stmt.execute();
System.out.println("Row is inserted successfully");

}
catch(Exception e)
{
System.out.println("Exception is occured at"+e);
}

}
}
Output:
Row is inserted successfully
Getting Records from Database using procedure
CREATE PROCEDURE getPname_proc (prod_id IN NUMBER, prod_name OUT VARCHAR)
AS
BEGIN
SELECT pname INTO prod_name FROM product WHERE pid = prod_id;
END;
/
SelectProcedure.java
import java.sql.*;
public class SelectProcedure {
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","manager");

CallableStatement stmt=con.prepareCall("{call getPname_proc(?,?)}");


stmt.setInt(1,100);
stmt.registerOutParameter(2, Types.VARCHAR);
stmt.execute();
String pname=stmt.getString(2);
System.out.println("The product name is "+pname);

}
catch(Exception e)
{
System.out.println("Exception is occured at"+e);
}

}
Output:
The product name is laptop
SERVLETS
Any company want to develop the website that can be developed in two ways, they are static
website and dynamic website.
A static website is one where there is no interaction from the end user. To develop static
Website we can use the markup languages like HTML, DHMTL, XML, JavaScript etc.
A dynamic website is one in which there exist end user interaction. To develop dynamic
Websites, in industry we have lot of technologies such as CGI (Common Gateway Interface),
java, dot net, etc.
In the recent years SUN micro systems has developed a technology called Servlets to
Develop the dynamic websites and also for developing distributed applications.
A distributed application is one which always runs in the context of browser or www. The
result of distributed application is always sharable across the globe.
To develop distributed application one must follow the following:
Client-Server architecture:
 2-tier architecture (Client program, Database program).
 3-tier or MVC (Model [Database] View [JSP] Controller [Servlets]) architecture (Client
Program, Server program, Database program).
 n-tier architecture (Client program, Firewall program, Server program, Database program).
To exchange the data between client and server we use a protocol caller http which is a part
of TCP/IP.
 A client is the program which always makes a request to get the service from server.
 A server is the program which always receives the request, process the request and gives
response to ‘n’ number of clients concurrently.
A server is the third party software developed by third party vendors according to SUN micro
systems specification. All servers in the industry are developed in java language only. The basic
purpose of using server is that to get concurrent access to a server side program.
According to industry scenario, we have two types of servers; they are web server and
application server.
In the initial days of server side programming there is a concept called CGI and this was
implemented in the languages called C and PERL. Because of this approach CGI has the following
Disadvantages.
1. Platform dependency.
2. Not enough security is provided.
3. Having lack of performance. Since, for each and every request a new and separate process is
Creating (for example, if we make hundreds of requests, in the server side hundreds of new
and separate processes will be created)
To avoid the above problems SUN micro system has released a technology called Servlets.A
servlet is a simple platform independent, architectural neutral server independent java program
which extends the functionality of either web server or application server by running in the
context of www.
Advantages of SERVLETS over CGI:
1. Servlets are always platform independent.
2. Servlets provides 100% security.
3. Irrespective of number of requests, a single process will be created at server side. Hence,
Servlets are known as single instance multiple thread technology.
What is Servlet?
1. Servlet is a server side Web technology to generate the dynamic web content.
2. Servlet is an API that provides many interfaces and classes
3. Servlet is an interface that must be implemented for creating any servlet
4. Servlet has the capabilities of the servers and respond to the incoming request. It can respond
to any type of requests.
5. Servlet Technology uses Java, web applications made using Servlet
are Secured, Scalable and Robust.
Servlets is the standard specification released by SUN micro systems and it is implemented
By various server vendors such as BEA corporation (Web logic server), Apache Jakarta (Tomcat
Server).
In order to run any servlet one must have either application server or web server. In order to
Deal with servlet programming we must import the following packages:

javax.servlet.*;

javax.servlet.http.*;

The basic terminology used in servlet is given below:

1. HTTP
2. HTTP Request Types
3. Difference between Get and Post method
4. Container
5. Server and Difference between web server and application server
6. Content Type
7. Introduction of XML
8. Deployment
HTTP (Hyper Text Transfer Protocol)
1. Http is the protocol that allows web servers and browsers to exchange data over the web.
2. It is a request response protocol.

Http Request Methods


The http request methods are:
 GET()
 POST()
Get vs. Post
There are many differences between the Get and Post request. Let's see these differences:

GET POST

1) In case of Get request, only limited In case of post request, large amount
amount of data can be sent because data of data can be sent because data is sent
is sent in header. in body.

2) Get request is not secured because Post request is secured because data is
data is exposed in URL bar. not exposed in URL bar.

Servlet Container:
It provides the runtime environment for JavaEE (j2ee) applications. The client/user can
request only a static WebPages from the server. If the user wants to read the web pages as per input
then the servlet container is used in java. The servlet container is used in java for dynamically
generate the web pages on the server side. Therefore the servlet container is the part of a web server
that interacts with the servlet for handling the dynamic web pages from the client
Servlet Container managing the life cycle of servlet. Servlet container loading the servlets
into memory, initializing and invoking servlet methods and to destroy them. There are a lot of
Servlet Containers like Jboss, Apache Tomcat, WebLogic etc.How does this Servlet Container work?

The Servlet Container performs many operations that are given below:
o Life Cycle Management
o Multithreaded support
o Object Pooling
o Security etc.
Server: It is a running program or software that provides services.
There are two types of servers:
1. Web Server
2. Application Server
Web Server: Web server contains only web or servlet container. It can be used for servlet, jsp,
struts, jsf etc. It can't be used for EJB.
Example of Web Servers is: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb
etc.
Example of Application Servers is:
1. JBoss Open-source server from JBoss community.
2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic provided by Oracle. It more secured.
4. Websphere provided by IBM.
Content Type:
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.
It is a HTTP header that provides the description about what are you sending to the browser.
There are many content types:
 text/html
 application/msword
 application/vnd.ms-excel
 application/pdf
 application/x-zip
 images/jpeg
Introduction of XML:
o Xml (extensible Markup Language) is a markup language.
o XML is designed to store and transport data.
o XML is designed to carry data, not to display data.
o XML is platform independent and language independent.

Steps to Create Servlet Application using tomcat server


To create a Servlet application you need to follow the below mentioned steps. These steps are
common for all the Web server. In our example we are using Apache Tomcat server. Apache Tomcat
is an open source web server for testing servlets and JSP technology. Download latest version of
Tomcat Server and install it on your machine.
After installing Tomcat Server on your machine follow the below mentioned steps:
1. Create directory structure for your application.
2. Create a Servlet
3. Compile the Servlet
4. Create Deployment Descriptor for your application
5. Start the server and deploy the application
All these 5 steps are explained in details below, lets create our first Servlet Application.
1. Creating the Directory Structure
Sun Microsystem defines a unique directory structure that must be followed to create a
servlet application.
Create the above directory structure inside Apache-Tomcat\webapps directory. All HTML,
static files(images, css etc) are kept directly under Web application folder. While all the Servlet
classes are kept inside classes folder.

The web.xml (deployement descriptor) file is kept under WEB-INF folder.


Deployement Descriptor File (Web.xml):
The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are
many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run
the simple servlet program.
web.xml
<web-app>
<servlet>
<servlet-name>upendra sir</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upendra sir</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of some elements
that is used in the above web.xml file. The elements are as follows:
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke
the servlet.
Welcome-file-list in web.xml
The welcome-file-list element of web-app, is used to define a list of welcome files. Its sub
element is welcome-file that is used to define the welcome file.A welcome file is the file that is
invoked automatically by the server, if you don't specify any file name.

By default server looks for the welcome file in following order:


1. welcome-file-list in web.xml
2. index.html
3. index.htm
4. index.jsp

If none of these files are found, server renders 404 error.

If you have specified welcome-file in web.xml, and all the files index.html, index.htm and
index.jsp exists, priority goes to welcome-file.

If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file then
index.htm and at last index.jsp file.

Let's see the web.xml file that defines the welcome files.
web.xml:
<web-app>
....

<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
To compile a servlet file we need to copy the jar file i.e servlet-api.jar file in C:\Program
Files\Apache Software Foundation\Tomcat 7.0\lib and paste it in the path C:\Program
Files\Java\jdk1.7.0_79\jre\lib\ext
Ways to create a servlet:

• Servlet is an interface which contains three life cycle methods Without definition.
• GenericServlet is an abstract class which implements Servlet interface for defining life cycle
Methods i.e., life cycle methods are defined in GenericServlet with null body.
• Using GenericServlet class we can develop protocol independent applications.
• HttpServlet is also an abstract class which extends GenericServlet and by using this class we
Can develop protocol dependent applications.
• To develop our own servlet we must choose a class that must extends either GenericServlet
or HttpServlet.
Servlet Interface:
In servlets we have three life cycle methods, they are
public void init ();
public void service (ServletRequest req, ServletResponse res);
public void destroy ();

public void init ():


Whenever client makes a request to a servlet, the server will receive the request and it
automatically calls init () method i.e., init () method will be called only one time by the server
whenever we make first request.
In this method, we write the block of statements which will perform one time operations,
such as, opening the file, database connection, initialization of parameters, etc.
public void service (ServletRequest, ServletResponse):
After calling init () method, service () method will be called when we make first request from
second request to further subsequent requests, server will call only service method. Therefore,
service () method will be called each and every time as and when we make a request.
In service () method we write the block of statements which will perform repeated operations
such as retrieving data from database, retrieving data from file, modifications of parameters data, etc.
Hence, in service () method we always write business logic.
Whenever control comes to service () method the server will create two objects of
ServletRequest and ServletResponse interfaces.
Object of ServletRequest contains the data which is passed by client. After processing client
data, the resultant data must be kept in an object of ServletResponse.
An object of ServletRequest and ServletResponse must be used always within the scope of
service () method only i.e., we cannot use in init () method and destroy () method.
Once the service () method is completed an object of ServletRequest and an object of
ServletResponse will be destroyed.

public void destroy ():

The destroy () method will be called by the server in two situations; they are when the
server is closed and when the servlet is removed from server context. In this method we write the
block of statements which are obtained in init () method.
NOTE:

Life cycle methods are those which will be called by the server at various times to perform various
operations.

Write a servlet which displays a message “I LOVE MY MOM”?


import javax.servlet.*;
import java.io.*;
public class First extends GenericServlet
{
public First ()
{
System.out.println ("I AM FROM DEFAULT CONSTRUCTOR...");
}
public void init ()
{
System.out.println ("I AM FROM init METHOD...");
}
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
{
System.out.println ("I LOVE MY MOM...");
System.out.println ("I AM FROM service METHOD...");
}
public void destroy ()
{
System.out.println ("I AM FROM destroy METHOD...");
}
};

web.xml:

<web-app>
<servlet>
<servlet-name>upendra</servlet-name>
<servlet-class>First</servlet-class>
</servlet>

<servlet-mapping>
< servlet-name>upendra</servlet-name>
<url-pattern>Krishna</url-pattern>
</servlet-mapping>
</web-app>

1. Whenever client makes a request to a servlet that request is received by server and server goes to a
predefined file called web.xml for the details about a servlet.

2. web.xml file always gives the details of the servlets which are available in the server.

3. If the server is not able to find the requested servlet by the client then server generates an error
(resource not found) [A resource is a program which resides in server].

4. If the requested servlet is available in web.xml then server will go to the servlet, executes

the servlet and gives response back to client.

GenericServlet:
 GenericServlet class implements Servlet, ServletConfig andSerializable interfaces.
 It provides the implementation of all the methods of these interfaces except the service
method.
 GenericServlet class can handle any type of request so it is protocol-independent.
 You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
Index.html
<a href="hello">Invoke Generic Servlet</a
First.java
import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
HttpServlet class:
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
2. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
Servlet Collaboration:
When one servlet communicates to another servlet, it is known as servlet collaboration. There are
many ways of servlet collaboration:

 RequestDispacher interface
 sendRedirect() method etc.

RequestDispatcher is an interface, implementation of which defines an object which can dispatch


request to any resources(such as HTML, Image, JSP, Servlet) on the server.
Methods of RequestDispatcher
RequestDispatcher interface provides two important methods

Methods Description

void forward(ServletRequest request, forwards a request from a servlet to another resource


(servlet, JSP file, or HTML file) on the server
ServletResponse response)

void include(ServletRequest request, includes the content of a resource (servlet, JSP page,
HTML file) in the response
ServletResponse response)

How to get an Object of RequestDispatcher


getRequestDispatcher() method of ServletRequest returns the object of RequestDispatcher.
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.forward(request,response);

(OR)

RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.include(request,response);
Example
 index.html will have form fields to get user information.
 Validate.java will validate the data entered by the user.
 Welcome.java will be the welcome page.
 web.xml , the deployment descriptor.

index.html
<form method="post" action="Validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
</form>
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
String name = request.getParameter("user");
String password = request.getParameter("pass");

if(password.equals("studytonight"))
{
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);
}
else
{
out.println("<font color='red'><b>You have entered incorrect password</b></font>");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
finally {
out.close();
}
}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<h2>Welcome user</h2>");
} finally {
out.close();
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Validate</servlet-name>
<servlet-class>Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Send Redirect ():
The sendRedirect() method of HttpServletResponse interface can be used to redirect
response to another resource, it may be servlet, jsp or html file.It accepts relative as well as absolute
URL.It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server
Index.html:
<a href="MyServlet">Click here</a>
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
response.sendRedirect("http://www.studytonight.com");
}
finally
{
out.close();
}
}
}

Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
Introduction to Attributes
An attribute is an object that is used to share information in a web app. Attribute allows
Servlets to share information among themselves. Attributes can be SET and GET from one of the
following scopes :
1. request
2. session

Using Cookies for Session Management


Cookies are small pieces of information that are sent in response from the web server to the
client.
Cookies are the simplest technique used for storing client state.

Cookies are stored on client's computer. They have a lifespan and are destroyed by the client
browser at the end of that lifespan.
Cookies API:
Cookies are created using Cookie class present in Servlet API. Cookies are added
to response object using the addCookie() method.

This method sends cookie information over the HTTP response


stream. getCookies() method is used to access the cookies that are added to response object.
Example demonstrating usage of Cookies

Note: Try to use Mozilla Firefox browser

index.html
<form method="post" action="MyServlet">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");

if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);
response.sendRedirect("First");
}
}
}
First.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Cookie[] cks = request.getCookies();
out.println("Welcome "+cks[0].getValue());
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Http Session:

HttpSession object is used to store entire session with a specific client. We can store, retrieve
and remove attribute from HttpSession object. Any servlet can have access to HttpSession object
throughout the getSession() method of the HttpServletRequest object.
Container creates a session id for each user.The container uses this id to identify the
particular user.
index.html
<form action="First">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/First")
public class First extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='Second'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Second.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/Second")
public class Second extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Development applications
Registration Form:
In this example you will see how to develop a registration form in Servlet. To develop a
registration form you will need to connect your servlet application with database. Here we are
using MySQL database.

Create a Table in your Database

create table Student


(
name varchar(60),
email varchar(60),
pass varchar(100)
)
index.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="Register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
Register.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Register extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

String name = request.getParameter("name");


String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{

//loading drivers for mysql


Class.forName("com.mysql.jdbc.Driver");

//creating connection with the database


Connection con=DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/test","username","password");

PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");

ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();

if(i>0)
{
out.println("You are sucessfully registered");
}

}
catch(Exception se)
{
se.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" >

<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Login Form
In this example we will show you how to develop a login form using servlet. Here we are
using MySqldatabase. List of file to be created are:

 index.html
 Login.java
 Validate.java
 Welcome.java
 web.xml
To try this application you will need to create a table in your database and enter some record
into it. Refer the previos Lesson for creating table.

index.html

<html>
<head>
<title>login form</title>
</head>
<body>
<form method="post" action="login">
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="login" />
</form>
</body>
</html>
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

String email = request.getParameter("email");


String pass = request.getParameter("pass");
if(Validate.checkUser(email, pass))
{
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
Validate.java
import java.sql.*;
public class Validate
{
public static boolean checkUser(String email,String pass)
{
boolean st =false;
try{

//loading drivers for mysql


Class.forName("com.mysql.jdbc.Driver");

//creating connection with the database


Connection con=DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/test","root","studytonight");
PreparedStatement ps =con.prepareStatement
("select * from register where email=? and pass=?");
ps.setString(1, email);
ps.setString(2, pass);
ResultSet rs =ps.executeQuery();
st = rs.next();

}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class Welcome extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Welcome user");
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" >
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
JSP
Jsp stands for java server page and is also a 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 Tag etc.
Advantage of JSP over Servlet
There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom
tags in JSP that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
SP Lifecycle is depicted in the below diagram.

Life cycle of a JSP Page


The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (class file is loaded by the classloader)
o Initialization ( jspInit() method is invoked by the container).
o Reqeust processing ( _jspService() method is invoked by the container).
o Destroy ( jspDestroy() method is invoked by the container).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

Demo.jsp
<html>
<head>
<title>Demo JSP</title>
</head>
<%! int demvar=0;%>
<body>
Count is:
<% Out.println (demovar++); %>
<body>
</html>
Demo JSP Page is converted into demo_jsp servlet in the below code.

JSP Elements:
1. JSP Declaration
2. JSP Expression
3. JSP Comments
JSP Declaration:
Syntax of declaration tag:
<%! Dec var %>

Ex:
<body>
<%! int count =10; %>
</body>
JSP Scriptlet
Scriptlet tag allows writing Java code into JSP file.
 JSP container moves statements in _jspservice() method while generating servlet from jsp.
 For each request of the client, service method of the JSP gets invoked hence the code inside
the Scriptlet executes for every request.
 A Scriptlet contains java code that is executed every time JSP is invoked.
Syntax of Scriptlet tag:
<% java code %>
Here < %%> tags are scriplets tag and within it, we can place java code.
EX:
<% int num1=10;
int num2=40;
int num3 = num1+num2;
out.println("Scriplet Number is " +num3);
%>
JSP Expression
 Expression tag evaluates the expression placed in it.
 It accesses the data stored in stored application.
 It allows create expressions like arithmetic and logical.
Syntax:
<%= expression %>
EX:
<body>
<% out.println("The expression number is "); %>
<% int num1=10; int num2=10; int num3 = 20; %>
<%= num1*num2+num3 %>
</body>
JSP Comments
Comments are the one when JSP container wants to ignore certain texts and statements.
Syntax:
<% -- JSP Comments %>

T his tags are used to comment in JSP and ignored by the JSP container.
JSP Directives:
 JSP directives are the messages to JSP container. They provide global information about an
entire JSP page.
 JSP directives are used to give special instruction to a container for translation of JSP to
servlet code.
 In JSP life cycle phase, JSP has to be converted to a servlet which is the translation phase.
 In JSP, directive is described in <%@ %> tags.
Syntax of Directive:
<%@ directive attribute="" %>
There are three types of directives:
1. Page directive
2. Include directive
3. Taglib directive
JSP Page directive:
Syntax of Page directive:
<%@ page… %>
 It provides attributes that get applied to entire JSP page.
 It defines attributes, such as scripting language, error page,import…etc.
Following are its list of attributes associated with page directive:
1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. IsErrorPage
9. pageEncoding
10. errorPage
11. isELIgonored
More details about each attribute
Language:
It defines the programming language (underlying language) being used in the page.
Syntax of language:
<%@ page language="value" %>
Here value is the programming language (underlying language)
Example:
<%@ page language="java" %>
Extends:
This attribute is used to extend (inherit) the class like JAVA does
Syntax of extends:
<%@ page extends="value" %>
Example:
<%@ page extends="demotest.DemoClass" %>
Import:
This attribute is most used attribute in page directive attributes. It is used to tell the container
to import other java classes, interfaces, enums, etc. while generating servlet code. It is similar to
import statements in java classes, interfaces.
Syntax of import:
<%@ page import="value" %>
Example:
<%@ page import="java.util.Date" %>
Info:
 It defines a string which can be accessed by getServletInfo () method.
 This attribute is used to set the servlet description.
Syntax of info:
<%@ page info="value" %>
Here, the value represents the servlet information.
Session:
 JSP page creates session by default.
 Sometimes we don't need a session to be created in JSP, and hence, we can set this attribute
to false in that case. The default value of the session attribute is true, and the session is
created.
When it is set to false, then we can indicate the compiler to not create the session by default.
Syntax of session:
<%@ page session="true/false"%>
Here in this case session attribute can be set to true or false
Example:
<%@ page session="false"%>
Explanation of code:
In the above example, session attribute is set to "false" hence we are indicating that we don't
want to create any session in this JSP
IsThreadSafe:
 We can use this attribute to implement SingleThreadModel interface in generated servlet.
 If we set it to false, then it will implement SingleThreadModel and can access any shared
objects and can yield inconsistency.
Syntax of isThreadSafe:
<% @ page isThreadSafe="true/false" %>
Here true or false represents if synchronization is there then set as true and set it as false.
Example:
<%@ page isThreadSafe="true"%>
Explanation of the code:
In the above code, isThreadSafe is set to "true" hence synchronization will be done.
Error Page:
This attribute is used to set the error page for the JSP page if JSP throws an exception and
then it redirects to the exception page.
Syntax of errorPage:
<%@ page errorPage="value" %>
Here value represents the error JSP page value
Example:
<%@ page errorPage="errorHandler.jsp"%>
Explanation of the code:
In the above code, to handle exceptions we have errroHandler.jsp
Implicit objects:
 JSP implicit objects are created during the translation phase of JSP to the servlet.
 These objects can be directly used in scriplets that goes in the service method.
 They are created by the container automatically, and they can be accessed using objects.
Out:
 Out is one of the implicit objects to write the data to the buffer and send output to the client in
response
 Out object allows us to access the servlet's output stream
 Out is object of javax.servlet.jsp.jspWriter class
 While working with servlet, we need printwriter object
Example:
<body>
<% int num1=10;
int num2=20;
out.println("num1 is " +num1);
out.println("num2 is "+num2);
%>
</body>
Request:
The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container. It can be used to get request information such as parameter, header
information, remote address, server name, server port, content type, character encoding etc.
index.html:
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Session:
In JSP, session is an implicit object of type HttpSession.The Java developer can use this
object to set, get or remove attribute or to get session information.
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Response: In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.

index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect ("http://www.google.com");
%>
CONFIG:
In JSP, config is an implicit object of type ServletConfig. Config Implicit object is used for
getting configuration information for a particular JSP page like get the driver name, servlet name etc.
The config object is created by the web container for each jsp page. Generally, it is used to
get initialization parameter from the web.xml file.
web.xml
<web-app>
<servlet>
<servlet-name>StudentsTutorial</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>StudentsTutorial</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>

index.jsp
<html>
<head>
<title> JSP Config</title>
</head>
<body>
<%
String name=config.getServletName ();
out.print("Name of Servlet is: "+name);
%>
</body>
</html>

Exception:
 Exception is the implicit object of the throwable class.
 It is used for exception handling in JSP.
 The exception object can be only used in error pages.
<%@ page language="java" contentType="text/html” isErrorPage="true"%>
<html>
<head>
<title>Implicit Guru JSP 11</title>
</head>
<body>
<%
int [] num1= {1, 2, 3, 4};
out.println (num1 [5]);
%>
<%= exception %>
</body>
</html>
Action Tags:
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp
action tags are given below.
JSP Action Tags Description
jsp: forward forwards the request and response to another resource.
jsp: include includes another resource.
jsp: useBean creates or locates bean object.
jsp: setProperty sets the value of property in bean object.
jsp: getProperty prints the value of property of the bean.
Example of jsp: forward action tag without parameter
In this example, we are simply forwarding the request to the printdate.jsp file.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>

printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Example of jsp:forward action tag with parameter
In this example, we are forwarding the request to the printdate.jsp file with parameter and
printdate.jsp file prints the parameter value with date and time.
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="vawe.com" />
</jsp:forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body> </html>
Jsp: include action tag
Example of jsp: include action tag without parameter

File: index.jsp
<h2>this is index page</h2>
<jsp: include page="printdate.jsp" />
<h2>end section of index page</h2>
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
Difference between jsp include directive and include action

JSP include directive JSP include action

Includes resource at translation Includes resource at request


time. time.

Better for static pages. Better for dynamic pages.

Java Bean
 It should provide methods to set and get the values of the properties, known as getter and
setter methods.
Why use Java Bean?
It is a reusable software component. A bean encapsulates many objects into one object, so we
can access this object from multiple places. Moreover, it provides the easy maintenance.

Simple example of java bean class


//Employee.java
package mypack;
public class Employee {
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
How to access the java bean class?
To access the java bean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
Note: There are two ways to provide values to the object, one way is by constructor and second is by
setter method.

Calculator.java (a simple Bean class)


package com.vawe;
public class Calculator{
public int cube(int n){return n*n*n;}
}
index.jsp file
<jsp:useBean id="obj" class="com.vawe.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Jsp: setProperty and jsp: getProperty action tags
The setProperty and getProperty action tags are used for developing web application with
Java Bean. In web development, bean class is mostly used because it is a reusable software
component that represents data.
The jsp: setProperty action tag sets a property value or values in a bean using the setter
method.
<jsp: setProperty name="bean" property="*" />

jsp: setProperty action tag if you have to set value of the incoming specific property

<jsp: setProperty name="bean" property="username" />


jsp: getProperty action tag
The jsp: getProperty action tag returns the value of the property.
Syntax of jsp:getProperty action tag
<jsp:getProperty name="instanceOfBean" property="propertyName" />
Simple example of jsp:getProperty action tag
<jsp:getProperty name="obj" property="name" />
Example of bean development in JSP
In this example there are 3 pages:
o index.html for input of values
o process.jsp file that sets the incoming values to the bean object and prints the one value
o User.java bean class that have setter and getter methods

index.html
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
process.jsp
<jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
User.java
package org.sssit;
public class User
{
private String name, password, email;
//setters and getters
}
Expression Language (EL)
The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application etc.
There are many implicit objects
It is the newly added feature in JSP technology version 2.0.
Syntax for Expression Language (EL)
${expression}

Implicit Objects in Expression Language (EL):

Implicit Objects Usage

requestScope it maps the given attribute name with the value set in the request
scope

sessionScope it maps the given attribute name with the value set in the session
scope

applicationScope it maps the given attribute name with the value set in the
application scope

param it maps the request parameter to the single value

cookie it maps the given cookie name to the cookie value


EL param
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets
input from the user and sends the request to the process.jsp which in turn prints the name of the user
using EL.
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
EL session Scope:
In this example, we printing the data stored in the session scope using EL. For this purpose,
we have used sessionScope object.
index.jsp
<h3>welcome to index page</h3>
<%
session.setAttribute("user","sonoo");
%>
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }
EL cookie:
index.jsp
<h1>First JSP</h1>
<%
Cookie ck=new Cookie("name","abhishek");
response.addCookie(ck);
%>
<a href="process.jsp">click</a>
process.jsp
Hello, ${cookie.name.value}
Exception Handling:
The exception is normally an object that is thrown at runtime. Exception Handling is the
process to handle the runtime errors. There may occur exception any time in your web application.
So handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform
exception handling:
By error Page and isErrorPage attributes of page directive
By <error-page> element in web.xml file
Example of exception handling in jsp by the elements of page directive
There are 3 files:
Index.jsp for input values
Process.jsp for dividing the two numbers and displaying the result
Error.jsp for handling the exception
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
Example of exception handling in jsp by specifying the error-page element in web.xml file
There are 4 files:
web.xml file for specifying the error-page element
index.jsp for input values
process.jsp for dividing the two numbers and displaying the result
error.jsp for displaying the exception
web.xml:
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
index.jsp: file is same as in the above example
process.jsp:
Now, you don't need to specify the errorPage attribute of page directive in the jsp page.
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp file is same as in the above example
MVC:
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the incoming
requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentation i.e. UI (User Interface)
Advantage:
Easy to maintain the large application
Registration Form
For creating registration form, you must have a table in the database. You can write the
database logic in JSP file, but separating it from the JSP page is better approach. Here, we are going
to use DAO, Factory Method, DTO and Singletion design patterns. There are many files:
index.jsp for getting the values from the user
User.java, a bean class that have properties and setter and getter methods.
process.jsp, a jsp file that processes the request and calls the methods
Provider.java, an interface that contains many constants like DRIVER_CLASS,
CONNECTION_URL, USERNAME and PASSWORD
ConnectionProvider.java, a class that returns an object of Connection. It uses the Singleton and
factory method design pattern.
RegisterDao.java, a DAO class that is responsible to get access to the database

In this example, we are using the Oracle10g database to connect with the database. Let's first create
the table in the Oracle database:
CREATE TABLE "USER432"
( "NAME" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"PASS" VARCHAR2(4000)
)
/
We have created the table named user432 here.
index.jsp
We are having only three fields here, to make the concept clear and simplify the flow of the
application. You can have other fields also like country, hobby etc. according to your requirement.

<form action="process.jsp">
<input type="text" name="uname" value="Name..." onclick="this.value=''"/><br/>
<input type="text" name="uemail" value="Email ID..." onclick="this.value=''"/><br/>
<input type="password" name="upass" value="Password..." onclick="this.value=''"/><br/>
<input type="submit" value="register"/>
</form>

process.jsp
This jsp file contains all the incoming values to an object of bean class which is passed as an
argument in the register method of the RegisterDao class.

<%@page import="bean.RegisterDao"%>
<jsp:useBean id="obj" class="bean.User"/>
<jsp:setProperty property="*" name="obj"/>
<%
int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");
%>
User.java
It is the bean class that have 3 properties uname, uemail and upass with its setter and getter
methods.

package bean;

public class User {


private String uname,upass,uemail;

public String getUname() {


return uname;
}
public void setUname(String uname) {
this.uname = uname;
}

public String getUpass() {


return upass;
}

public void setUpass(String upass) {


this.upass = upass;
}

public String getUemail() {


return uemail;
}

public void setUemail(String uemail) {


this.uemail = uemail;
}
}
Provider.java
This interface contains four constants that can vary from database to database.
package bean;
public interface Provider {
String DRIVER="oracle.jdbc.driver.OracleDriver";
String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
String USERNAME="system";
String PASSWORD="oracle";
}
ConnectionProvider.java
This class is responsible to return the object of Connection. Here, driver class is loaded only
once and connection object gets memory only once.

package bean;
import java.sql.*;
import static bean.Provider.*;
public class ConnectionProvider {
private static Connection con=null;
static{
try{
Class.forName(DRIVER);
con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
}catch(Exception e){}
}
public static Connection getCon(){
return con;
}

}
RegisterDao.java
This class inserts the values of the bean component into the database.
package bean;
import java.sql.*;
public class RegisterDao {
public static int register(User u){
int status=0;
try{
Connection con=ConnectionProvider.getCon();
PreparedStatement ps=con.prepareStatement("insert into user432 values(?,?,?)");
ps.setString(1,u.getUname());
ps.setString(2,u.getUemail());
ps.setString(3,u.getUpass());
status=ps.executeUpdate();
}catch(Exception e){}

return status;
}

Login Form
In this example, we have created 5 pages:
o index.jsp a page that gets input from the user.
o ControllerServlet.java a servlet that acts as a controller.
o login-success.jsp and login-error.jsp files acts as view components.
o web.xml file for mapping the servlet.

File: index.jsp
<form action="ControllerServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>

File: ControllerServlet
package com.vawe;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("name");
String password=request.getParameter("password");
LoginBean bean=new LoginBean();
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean",bean);
boolean status=bean.validate();
if(status){
RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
rd.forward(request, response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
rd.forward(request, response);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
File: LoginBean.java
package com.javatpoint;
public class LoginBean {
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean validate(){
if(password.equals("admin")){
return true;
}
else{
return false;
}
}
}
File: login-success.jsp
<%@page import="com.vawe.LoginBean"%>
<p>You are successfully logged in!</p>
<%
LoginBean bean=(LoginBean)request.getAttribute("bean");
out.print("Welcome, "+bean.getName());
%>
File: login-error.jsp
<p>Sorry! username or password error</p>
<%@ include file="index.jsp" %>
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>com.vawe.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/ControllerServlet</url-pattern>
</servlet-mapping>
</web-app>

How to send a mail in jsp:


Required jar files:
1. activation.jar
2. mail.jar
mail.html
<body>
<form action="Sendmail.jsp">
mail id <input name="email" />
<input type="submit" value="submit" />
</form>
</body>
Mail.jsp
<html>
<body bgcolor="#FF9900">
<%@ page import="java.sql.*"%>
<%@ page import = "java.util.Date,java.text.SimpleDateFormat,java.text.ParseException"%>
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%
String host="", user="", pass="";
/*String cd=request.getParameter("da");
System.out.println(cd);*/
/*String emailid=request.getParameter("email");
System.out.println(emailid);*/
String emailid=request.getParameter("email");
System.out.println(emailid);
//String emailid="[email protected]";
host ="smtp.gmail.com"; //"smtp.gmail.com";
user ="[email protected]"; //"[email protected]" // email id to send the emails
pass ="upendra"; //Your gmail password
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String to =emailid; // out going email id
String from ="[email protected]"; //Email id of the recipient
String subject ="mail message";
//String messageText ="key is your user id";
String pwd="upendra vajanepalli";
String messageText ="password is "+pwd;
boolean sessionDebug = true;
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.fallback", "false");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setContent(messageText, "text/html"); // use setText if you want to send text
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
try {
transport.sendMessage(msg, msg.getAllRecipients());
//response.sendRedirect("error.html?success");
}
catch (Exception err) {
out.println("message not successfully sended");// assume it’s a fail
}
transport.close();
%>
</body>
</htm>

JSTL (JSP Standard Tag Library):


The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplifies the JSP.
2. Code Reusability We can use the JSTL tags in various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
Note:
For creating JSTL application, you need to load jstl.jar file.
JSTL Tags:
1. Core level tags
2. Sql level tags
JSTL Core:
JSTL Core provides several core tags such as if, for Each, import, out etc to support some basic
scripting task. Url to include JSTL Core Tag inside JSP page is →
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c: out> tag:
It is similar to JSP expression tag, but it can only be used with expression. It will display the
result of an expression, similar to the way < %=...% > work.
Index.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:out value="${'Welcome to vaweinstitutes}"/>
</body>
</html>
<c: set> Tag
This tag is similar to jsp: setProperty action tag.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html> <head> <title>Core Tag Example</title> </head>
<body>
<c:set var="Income" value="${500}"/>
<c:out value="${Income}"/>
</body>
</html
< c:if > tag: It is used for testing the condition and it display the body content, if the expression
evaluated is true.
<c:set var="count" value="100"/>
<c:if test="${count == 100}">
<c:out value="The count is 100"/>
</c:if>
JSTL Core <c: choose>, <c: when>, <c: otherwise> Tag:
It works like a Java switch statement in which we choose between a numbers of alternatives.
The c: when and c: otherwise works like if-else statement. But it must be placed inside c: choose tag.
Even/Odd Example using c: when and c: otherwise
<c:set value="100" var="num"></c:set>
<c:choose>
<c:when test="${num%2==0}">
<c:out value="${num} is even number"></c:out>
</c:when>
<c:otherwise>
<c:out value="${num} is odd number"></c:out>
</c:otherwise>
</c:choose>
<c: for Each> Tag
<c:forEach var="j" begin="1" end="3">
Item <c:out value="${j}"/><p>
</c:forEach>

Catch

 It catches any throwable exception which occurs in the body and shows as output.
 It is used for handling the errors and to catch them.
<c:catch var="vawe">
<% int num = 10/0; %>
</c:catch>
The Exception is : ${vawe}
JSTL SQL Tags:
The JSTL sql tags provide SQL support. The url for the sql tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
The SQL tag library allows the tag to interact with RDBMSs (Relational Databases) such as
Microsoft SQL Server, mySQL, or Oracle. The syntax used for including JSTL SQL tags library in your
JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

JSTL SQL <sql: setDataSource> Tag


<sql: setDataSource> tag is used for creating a simple data source suitable only for prototyping.
It is used to create the data source variable directly from JSP and it is stored inside a scoped
variable. It can be used as input for other database actions.
Example:
Consider the below information about your MySQL database setup:
o We are using the JDBC MySQL driver
o We are using the test database on local machine
o We are using the "root" as username and "root" as password to access the test database.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>sql:setDataSource Tag</title>
</head>
<body>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password="root"/>
</body>
</html>
Select query:
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password="root"/>
<sql:query dataSource="${db}" var="rs">
SELECT * from Students;
</sql:query>
<table border="2" width="100%">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.sno}"/></td>
<td><c:out value="${table.sname}"/></td>
</tr>
</c:forEach>
</table>

Insert and delete also select


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<title>sql:query Tag</title>
</head>
<body>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password="root"/>

<%-- <sql:update dataSource="${db}" var="count">


INSERT INTO Students VALUES (154,'Nasreen');
</sql:update> --%>

<%-- <sql:update dataSource="${db}" var="count">


delete from students where sno=154;
</sql:update> --%>

<sql:query dataSource="${db}" var="rs">


SELECT * from Students;
</sql:query>
<table border="2" width="100%">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.sno}"/></td>
<td><c:out value="${table.sname}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Jsp Crud operations:
We can easily create CRUD Example in JSP. Here, we are using DAO files for database and
JSTL for traversing records.
Need jar files
 jstl1.2.jar file
 mysql-connector.jar
Create table in mysql:
CREATE TABLE register (
id int(10) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
password varchar(100) NOT NULL,
email varchar(100) NOT NULL,
sex varchar(100) NOT NULL,
country varchar(100) NOT NULL,
PRIMARY KEY (`id`)
)
Directory Structure in Eclipse

index.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP CRUD Example</title>
</head>
<body>
<h1>JSP CRUD Example</h1>
<a href="adduserform.jsp">Add User</a>
<a href="viewusers.jsp">View Users</a>
</body>
</html>
adduserform.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Form</title>
</head>
<body>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>

userform.html

<a href="viewusers.jsp">View All Records</a><br/>


<h1>Add New User</h1>
<form action="adduser.jsp" method="post">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password"/></td></tr>
<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>
<tr><td>Country:</td><td>
<select name="country" style="width:155px">
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Add User"/></td></tr>
</table>
</form>
adduser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
int i=UserDao.save(u);
if(i>0){
response.sendRedirect("adduser-success.jsp");
}else{
response.sendRedirect("adduser-error.jsp");
}
%>
User.java
package com.javatpoint.bean;
public class User {
private int id;
private String name,password,email,sex,country;
//generate getters and setters
}
UserDao.java
package com.javatpoint.dao;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.javatpoint.bean.User;
public class UserDao {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
}catch(Exception e){System.out.println(e);}
return con;
}
public static int save(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"insert into register(name,password,email,sex,country) values(?,?,?,?,?)");
ps.setString(1,u.getName());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setString(5,u.getCountry());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int update(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement(
"update register set name=?,password=?,email=?,sex=?,country=? where id=?");
ps.setString(1,u.getName());
ps.setString(2,u.getPassword());
ps.setString(3,u.getEmail());
ps.setString(4,u.getSex());
ps.setString(5,u.getCountry());
ps.setInt(6,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User u){
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("delete from register where id=?");
ps.setInt(1,u.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}

return status;
}
public static List<User> getAllRecords(){
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
list.add(u);
}
}catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id){
User u=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
u=new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setSex(rs.getString("sex"));
u.setCountry(rs.getString("country"));
}
}catch(Exception e){System.out.println(e);}
return u;
}
}
adduser-error.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add User Error</title>
</head>
<body>
<p>Sorry, an error occurred!</p>
<jsp:include page="userform.html"></jsp:include>
</body>
</html>
viewusers.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Users</title>
</head>
<body>
<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Users List</h1>
<%
List<User> list=UserDao.getAllRecords();
request.setAttribute("list",list);
%>
<table border="1" width="90%">
<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>
<th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassword()}</td>
<td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()}</td>
<td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>
</c:forEach>
</table>
<br/><a href="adduserform.jsp">Add New User</a>
</body>
</html>
editform.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Edit Form</title>
</head>
<body>
<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.User"%>
<%
String id=request.getParameter("id");
User u=UserDao.getRecordById(Integer.parseInt(id));
%>
<h1>Edit Form</h1>
<form action="edituser.jsp" method="post">
<input type="hidden" name="id" value="<%=u.getId() %>"/>
<table>
<tr><td>Name:</td><td>
<input type="text" name="name" value="<%= u.getName()%>"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" value="<%= u.getPassword()%>"/></td></tr>
<tr><td>Email:</td><td>
<input type="email" name="email" value="<%= u.getEmail()%>"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>
<tr><td>Country:</td><td>
<select name="country">
<option>India</option>
<option>Pakistan</option>
<option>Afghanistan</option>
<option>Berma</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Edit User"/></td></tr>
</table>
</form>
</body> </html>
edituser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
int i=UserDao.update(u);
response.sendRedirect("viewusers.jsp");
%>
deleteuser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<%
UserDao.delete(u);
response.sendRedirect("viewusers.js”);

%>

You might also like