Complete Java-JSP NOTES
Complete Java-JSP NOTES
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).
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)
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.
Relational Operators: Which can be used to check the Condition, it always returns true or false.
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:
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
2) Method overloading is Method overriding occurs in two classes that have IS-
performed within class. A (inheritance) relationship.
}
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.
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.
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.
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");
}
}
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)
char Character
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.
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.
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:
}
}
}
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:
int rows=2,col=2;
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
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(); }
}
}
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
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);
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.
Method Description
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");
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());
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.
For registering the component with the Listener, many classes provide the registration methods. For
example:
Button
TextField
Checkbox
Choice
List
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
f.setLayout(new BorderLayout());
Button b1=new Button("first");
b1.setBackground(Color.green);
b1.setForeground(Color.white);
}
}
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);
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.
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.
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.
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
The methods of Component class are widely used in java swing that are given below.
Method Description
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.
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.
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>
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
Syntax:
<ul [ type = “disc” | “square” | “circle” ] > … </ul>
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 – 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.
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.
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.
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:
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 %.
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.
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.
Alternate Marquee
It scrolls the text from right to left and goes back left to right.
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.
<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 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 video controls which is displayed with play/pause buttons.
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.
<!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:
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">
style="fill:red;stroke:yellow;stroke-width:5;fill-rule:nonzero;" />
</svg>
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 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
{
<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.
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
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>
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.
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.
<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>
<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()”>
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.
The forName () method of Class class is used to register the driver class.
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(
2. Go to Administrative tools
3. Select Data Source(ODBC)
8. Go to Administrative tools
9. Select Data Source(ODBC)
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:
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.
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 (?,?,?)");
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.
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
//con.commit();
con.close();
}
}
Functions:
}
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");
}
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.*;
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.
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.
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 ();
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.
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
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.
Methods Description
void include(ServletRequest request, includes the content of a resource (servlet, JSP page,
HTML file) in the response
ServletResponse 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
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.
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.
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();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
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.
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
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.
jsp: setProperty action tag if you have to set value of the incoming specific property
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}
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
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;
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>
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" %>
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
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”);
%>