You are on page 1of 152

Web Technology[KIT-501]

UNIT-1
Introduction
• Web Technology refers to the various tools and techniques that are utilized in the process
of communication between different types of devices over the internet.
• A web browser is used to access web pages. Web browsers can be defined as programs
that display text, data, pictures, animation, and video on the Internet.
• Hyperlinked resources on the World Wide Web can be accessed using software interfaces
provided by Web browsers.
Web Technology can be classified into the following sections:
World Wide Web (WWW): The World Wide Web is a system of interlinked hypertext
documents accessed via the Internet. Web is a huge collection of pages of information
linked to each other around the globe.
• Web Browser: The web browser is an application software to explore www (World
Wide Web). It provides an interface between the server and the client and requests to the
server for web documents and services.
• Web Server: Web server is a program which processes the network requests of the users
and serves them with files that create web pages. This exchange takes place using
Hypertext Transfer Protocol (HTTP).
• Web Pages: A webpage is a digital document that is linked to the World Wide Web and
viewable by anyone connected to the internet has a web browser.
• Web Development: Web development refers to the building, creating, and maintaining
of websites. It includes aspects such as web design, web publishing, web programming,
and database management. It is the creation of an application that works over the internet
i.e. websites.
Web Development can be classified into two ways:
• Frontend Development: The part of a website that the user interacts directly is termed as
front end. It is also referred to as the ‘client side’ of the application.
Front end Technologies
• HTML: HTML stands for Hypertext Markup Language. It is used to design the front-end
portion of web pages using a markup language. HTML is the combination of Hypertext
and Markup language. Hypertext defines the link between the web pages. The markup
language is used to define the text documentation within the tag which defines the
structure of web pages.
• CSS: Cascading Style Sheets fondly referred to as CSS is a simply designed language
intended to simplify the process of making web pages presentable. CSS allows you to
apply styles to web pages. More importantly, CSS enables you to do this independent of
the HTML that makes up each web page.
• JavaScript: JavaScript is a famous scripting language used to create magic on the sites to
make the site interactive for the user. It is used to enhancing the functionality of a website
to running cool games and web-based software.
• AJAX: Ajax is an acronym for Asynchronous Javascript and XML. It is used to
communicate with the server without refreshing the web page and thus increasing the
user experience and better performance.

Back End Frameworks and Technology


Introduction and Web Development Strategies
Identify target user
Make our design portable
Design for low bandwidth
Plan for clear presentation and easy access to information
Create smooth transitions

History of web and internet


World Wide Web:
The World Wide Web is a system of interlinked hypertext documents accessed via the
Internet. Web is a huge collection of pages of information linked to each other around the
globe.
• WWW is created by Sir Tim Berners Lee in 1989 at CERN in Geneva.
• In 1990, the first text only browsers were setup and CERN scientist could access
hypertext files and other information at CERN. HTML was based on a subset of the
standard generalized markup language (SGML).
• To transfer HTML document to remote sites a new protocol was devised called HTTP
(Hyper Text Transfer Protocol).
• In the fall of 1991, conference goes around the world started hearing about the promise
but sparks still were not flying.
• In 1993, there are only about 50 websites world wide. A browser that allowed user to take
advantage of the web’s graphical capabilities was developed at the National center for
Super Computing application (NCSA). NCSA called the browser Mosaic.
Protocols Governing Web:
Protocol: A protocol is a set of rules that is used to communicate applications to each other.
OR
A protocol is the interface required for communicating the different applications.
Classification:
HTTP
TCP/IP
FTP
E-MAIL
TELNET

Protocols Governing Web


• HTTP: HTTP is the primary protocol used to distribute information on the web. This
protocol is used to access, send and receive Hypertext markup language (HTML) files on
the Internet. Initial HTTP 0.9 does not allow for content typing and does not have
provisions for supplying meta -information Content Typing: To identify the type of data
being transferred.
Meta Information: It is supplemental data, such as environment variables that identify
the client’s computer Current version is HTTP 1.0
• TCP/IP: It is a set of rules that an application can use to package its information for
sending across the networks of networks.
TCP: This protocol ensure the delivery of information packets across network.
IP: This protocol is responsible logical addressing called IP address to route information
between network.
• FTP: It is used to transfer the files over networks.
• E-Mail: It is a method of exchanging digital messages across the Internet or other
computer networks.
• Telnet: Telnet lets you remotely log into another system and browse files and directories
on that remote system.
• Simple Mail Transfer Protocol(SMTP) : This protocol is used for transferring e-mail
between computers.
Introduction to client-server computing.
Client-server denotes a relationship between cooperating programs in an application,
composed of clients initiating requests for services and servers providing that function or
service.
Characteristics of Client Server Computing
• The salient points for client server computing are as follows:
• The client server computing works with a system of request and response. The client
sends a request to the server and the server responds with the desired information.
• The client and server should follow a common communication protocol so they can
easily interact with each other. All the communication protocols are available at the
application layer.
• A server can only accommodate a limited number of client requests at a time. So it uses a
system based to priority to respond to the requests.
• Denial of Service attacks hinders servers ability to respond to authentic client requests by
inundating it with false requests.
• An example of a client server computing system is a web server. It returns the web pages
to the clients that requested them.
Advantages of Client Server Computing
• The different advantages of client server computing are −
• All the required data is concentrated in a single place i.e. the server. So it is easy to
protect the data and provide authorization and authentication.
• The server need not be located physically close to the clients. Yet the data can be
accessed efficiently.
• It is easy to replace, upgrade or relocate the nodes in the client server model because all
the nodes are independent and request data only from the server.
• All the nodes i.e clients and server may not be build on similar platforms yet they can
easily facilitate the transfer of data.

Disadvantages of Client Server Computing


• The different disadvantages of client server computing are −
• If all the clients simultaneously request data from the server, it may get overloaded. This
may lead to congestion in the network.
• If the server fails for any reason, then none of the requests of the clients can be fulfilled.
This leads of failure of the client server network.
• The cost of setting and maintaining a client server model are quite high.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Unary Operator Example: ~ and !


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

public class OperatorExample{


public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Java Right Shift Operator


public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks
the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

Java Control Statements


Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code. Such statements are called control flow statements. It is one of
the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Simple if statement Example

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

if-else statement

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Example:
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the
program.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Loop Statements
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Java for loop


for(initialization, condition, increment/decrement) {
//block of statements
}
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in
java is given below.

for(data_type var : array_name/collection_name){


//statements
}

Example:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}

Java while loop


The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop. Unlike
for loop, the initialization and increment/decrement doesn't take place inside the loop statement in
while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
If the condition is true, then the loop body will be executed; otherwise, the statements after the
loop will be executed.

while(condition){
//looping statements
}

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can
use do-while loop.

do
{
//statements
} while (condition);

Java Arrays
Java array is an object which contains elements of a similar data type. Additionally, The elements of an array
are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
Types of Array in java
There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example 1 of Java Array


//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Example 2
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

For-each Loop for Java Array


We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){
//body of the loop
}

Example
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

//Java Program to demonstrate the way of passing an array


//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];

System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}

Getter and Setter in Java


In Java, Getter and Setter are methods used to protect your data and make your
code more secure. Getter and Setter make the programmer convenient in setting
and getting the value for a particular data type.

Getter in Java: Getter returns the value (accessors), it returns the value of data type
int, String, double, float, etc. For the program’s convenience, the getter starts with the
word “get” followed by the variable name.
Setter in Java: While Setter sets or updates the value (mutators). It sets the value for
any variable used in a class’s programs. and starts with the word “set” followed by the
variable name.
Java Scanner
Scanner class in Java is found in the java.util package. Java provides various ways to read input
from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by
default. It provides many methods to read and parse various primitive values.

The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(),
nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single
character from the scanner, you can call next().charAt(0) method which returns a single character.

Java Scanner Input Types

Method Description

Used for reading Boolean


nextBoolean()
value

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value


Method Description

nextInt() Used for reading Int value

nextLine() Used for reading Line value

nextLong() Used for reading Long value

nextShort() Used for reading Short value

Example:
// Java program to read data of various types using Scanner
// class.
import java.util.Scanner;
public class ScannerDemo1 {
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);

// String input
String name = sc.nextLine();

// Character input
char gender = sc.next().charAt(0);

// Numerical data input


// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();

// Print the values to check if the input was


// correctly obtained.
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("Mobile Number: " + mobileNo);
System.out.println("CGPA: " + cgpa);
}
}

Java Methods
The method in Java or Methods of Java is a collection of statements that perform some
specific task and return the result to the caller. A Java method can perform some
specific task without returning anything. Java Methods allow us to reuse the code
without retyping the code. In Java, every method must be part of some class that is
different from languages like C, C++, and Python.
1. A method is like a function i.e. used to expose the behavior of an object.
2. It is a set of codes that perform a particular task.
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}

Method Declaration

1. Modifier: It defines the access type of the method i.e. from where it can be accessed
in your application. In Java, there 4 types of access specifiers.
• public: It is accessible in all classes in your application.
• protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
• private: It is accessible only within the class in which it is defined.
• default: It is declared/defined without using any modifier. It is accessible within the
same class and package within which its class is defined.

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

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

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

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

Types of Method
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library method
or built-in method. We can directly use these methods just by calling them in the program
at any point.

In the above example, we have used three predefined methods main(), print(), and max().

2. User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Ways to Create Method in Java
There are two ways to create a method in Java:
1. Instance Method: Access the instance data using the object name.Declared inside a
class.

Syntax:

// Instance Method

void method_name(){

body // instance area

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

2. Static Method: Access the static data using class name. Declared inside class
with static keyword.

//Static Method

static void method_name(){

body // static area

Example:-
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We
can easily identify it because the method is prefixed with the word get. It is also known as getters. It returns
the value of the private field. It is used to get the value of the private field.

Example

1. public int getId()


2. {
3. return Id;
4. }

Mutator Method: The method(s) read the instance variable(s) and also modify the values. We
can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data type
that depends on the field. It is used to set the value of the private field.

Example
1. public void setRoll(int roll)
2. {
3. this.roll = roll;
4. }

Example of Getters and Setters


public class Student
{
private int roll;
private String name;
public int getRoll() //accessor method
{
return roll;
}
public void setRoll(int roll) //mutator method
{
this.roll = roll;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void display()
{
System.out.println("Roll no.: "+roll);
System.out.println("Student name: "+name);
}
}
Abstract Method
The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It means
the class itself must be abstract if it has abstract method. To create an abstract method, we use the
keyword abstract.

Syntax

abstract void method_name();

Example of abstract method

abstract class Demo //abstract class


{
//abstract method declaration
abstract void display();
}

public class MyClass extends Demo


{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

Different ways to overload the method

• Changing the Number of Parameters.


• Changing Data Types of the Arguments.
• Changing the Order of the Parameters of Methods
In Java, Method Overloading is not possible by changing the return type of the method only.

Method overloading in Java is also known as Compile-time Polymorphism, Static


Polymorphism, or Early binding. In Method overloading compared to the parent
argument, the child argument will get the highest priority.

// Java program to demonstrate working of method


// overloading in Java

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

1. Changing the Number of Parameters

// Java Program to Illustrate Method Overloading


// By Changing the Number of Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Product {
// Method 1
// Multiplying two integer values
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}

// Method 2
// Multiplying three integer values
public int multiply(int a, int b, int c)
{
int prod = a * b * c;
return prod;
}
}

// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of above class inside main()
// method
Product ob = new Product();

// Calling method to Multiply 2 numbers


int prod1 = ob.multiply(1, 2);

// Printing Product of 2 numbers


System.out.println(
"Product of the two integer value :" + prod1);

// Calling method to multiply 3 numbers


int prod2 = ob.multiply(1, 2, 3);

// Printing product of 3 numbers


System.out.println(
"Product of the three integer value :" + prod2);
}
}

2. Changing Data Types of the Arguments

// Java Program to Illustrate Method Overloading


// By Changing Data Types of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Product {
// Multiplying three integer values
public int Prod(int a, int b, int c)
{
int prod1 = a * b * c;
return prod1;
}

// Multiplying three double values.


public double Prod(double a, double b, double c)
{
double prod2 = a * b * c;
return prod2;
}
}

class GFG {
public static void main(String[] args)
{
Product obj = new Product();

int prod1 = obj.Prod(1, 2, 3);


System.out.println(
"Product of the three integer value :" + prod1);

double prod2 = obj.Prod(1.0, 2.0, 3.0);


System.out.println(
"Product of the three double value :" + prod2);
}
}
3. Changing the Order of the Parameters of Methods

Method overloading can also be implemented by rearranging the parameters of two or


more overloaded methods. For example, if the parameters of method 1 are (String name,
int roll_no) and the other method is (int roll_no, String name) but both have the same
name, then these 2 methods are considered to be overloaded with different sequences of
parameters.
// Java Program to Illustrate Method Overloading
// By changing the Order of the Parameters

// Importing required classes


import java.io.*;

// Class 1
// Helper class
class Student {
// Method 1
public void StudentId(String name, int roll_no)
{
System.out.println("Name :" + name + " "
+ "Roll-No :" + roll_no);
}

// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
System.out.println("Roll-No :" + roll_no + " "
+ "Name :" + name);
}
}
// Class 2
// Main class
class GFG {
// Main function
public static void main(String[] args)
{
// Creating object of above class
Student obj = new Student();

// Passing name and id


// Note: Reversing order
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
}
}

Constructors in Java
Java constructors or constructors in Java is a terminology used to construct something in
our programs. A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial
values for object attributes.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
Rules for creating Java constructor
There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In
other words, we can have private, protected, public or default constructor in Java.

Types of Java constructors

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}
Example
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.

Example
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Difference between constructor and method in Java

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior
of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you don't The method is not provided by the
have any constructor in a class. compiler in any case.

The constructor name must be same as the class name. The method name may or may not be
same as the class name.

Constructor Overloading in Java


Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.

1. //Java program to overload constructors


2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }
INHERITANCE

It is the mechanism in Java by which one class is allowed to inherit the features(fields
and methods) of another class. In Java, Inheritance means creating new classes based on
existing ones. A class that inherits from another class can reuse the methods and fields
of that class. In addition, you can add new fields and methods to your current class as
well.
Why Do We Need Java Inheritance?

• Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through Inheritance. It
is one of the ways by which Java achieves Run Time Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
How to Use Inheritance in Java?

The extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers to
increased functionality.

Syntax :

class derived-class extends base-class


{
//methods and fields
}

Java Inheritance Example

Programmer is the subclass and Employee is the superclass. The relationship between the two classes
is Programmer IS-A Employee. It means that Programmer is a type of Employee.

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

Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.

// Java program to illustrate the

// concept of single inheritance

import java.io.*;

import java.lang.*;

import java.util.*;

// Parent class

class one {

public void print_geek()

System.out.println("Geeks");

class two extends one {

public void print_for() { System.out.println("for"); }

// Driver class
public class Main {

// Main function

public static void main(String[] args)

two g = new two();

g.print_geek();

g.print_for();

g.print_geek();

Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as
the derived class also acts as the base class for other classes. In the below image, class A
serves as a base class for the derived class B, which in turn serves as a base class for the
derived class C.

// Java program to illustrate the


// concept of Multilevel inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

class one {
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one {


public void print_for() { System.out.println("for"); }
}

class three extends two {


public void print_geek()
{
System.out.println("Geeks");
}
}

// Drived class
public class Main {
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one subclass. In the below image, class A serves as a base class for the derived classes B,
C, and D.
// Java program to illustrate the

// concept of Hierarchical inheritance

class A {

public void print_A() { System.out.println("Class A"); }

class B extends A {

public void print_B() { System.out.println("Class B"); }

class C extends A {

public void print_C() { System.out.println("Class C"); }

class D extends A {
public void print_D() { System.out.println("Class D"); }

// Driver Class

public class Test {

public static void main(String[] args)

B obj_B = new B();

obj_B.print_A();

obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();

obj_D.print_A();

obj_D.print_D();

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }

What Can Be Done in a Subclass?


In sub-classes we can inherit members as is, replace them, hide them, or supplement them
with new members:
• The inherited fields can be used directly, just like any other fields.
• We can declare new fields in the subclass that are not in the superclass.
• The inherited methods can be used directly as they are.
• We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in the example above, toString() method is
overridden).
• We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
• We can declare new methods in the subclass that are not in the superclass.
• We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to access package from another package?


There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the
current package.

Example of package that import the packagename.*


//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();
}
}

Using packagename.classname
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there is no need
to import. But you need to use fully qualified name every time when you are accessing the class or interface.

Example of package by import fully qualified name

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}

Access Modifiers in Java


here are two types of modifiers in Java: access modifiers and non-access modifiers.

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

There are four types of Java access modifiers:

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

Example of private access modifier

public class A {
private int data ;
private A() {
System.out.println("Hello I am in Private Constructor");
}
private void msg() {

System.out.println("Hello Java");

}
/*public void msg(int a) {
data = a;
System.out.println("Hello Java");
System.out.println("data: "+ data);
}*/
}

Default Access Modifier

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package.
package pack;
class A{
void msg() {
System.out.println("Hello Java");
}
}
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
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.
package pack;
public class A{
protected void msg(){
System.out.println("Hello Java");
}
}
package mypack;
import pack.*;
public class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.msg();
}
}

Public Access Modifier

The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
package pack;
public class A{
public void msg(){
System.out.println("Hello Java");
}
}
package mypack;
import pack.*;
public class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.msg();
}
}

Exception Handling

• An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run
out of memory.

Types of Java Exceptions
Difference Between Checked and Unchecked Exceptions

1) Checked Exception

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

2) Unchecked Exception

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

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords


Common scenarios where exceptions may occur

• int a=50/0;//ArithmeticException

• String s=null;
System.out.println(s.length());//NullPointerException

• String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

• int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch/try-finally

Syntax of java try-catch


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

Syntax of try-finally block


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

1. Uncaught Exception
Class ExceptionExample{
Public static void main(String args[]){
Int d=0;
Int a=42;
System.out.println(a/d);
}
}
Output:

2. Using try and catch


Class ExceptionExample{
Public static void main(String args[]){
Try{
Int d=0;
Int a=42;
System.out.println(a/d);
}
Catch(ArithmeticException e){
System.out.println(“Division by Zero”);
}
}
}

Multiple catch Clauses


Class ExceptionExample{
Public static void main(String args[]){
Try{
Int d=0;
Int a=42;
Int a[]=new int[5];

A[42]=28;
System.out.println(a/d);
}
Catch(ArithmeticException e){
System.out.println(“Division by Zero”);
}
Catch(ArrayIndexOutOfBoundsException e){
System.out.println(“ArrayIndexOutOfBoundsException”);
}

}
}

Nested try Statements

The try statement can be nested. That is, a try statement can be inside the block of another try.

Each time a try statement is entered, the context of that exception is pushed on the stack.

If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.

class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };

c[42] = 99; // generate an out-of-bounds exception


}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

Throw
The general form of throw is shown here:
throw ThrowableInstance;

public class ThrowExample{

static void demo{

try{
throw new NullPointerException(“Demo”);
}
Catch(NullPointerException e){
System.out.println(“Inside Demo”);
Throw e;

}
}

Public static void main(String args[]){


Try{
Demo();

Catch(NullPointerException e){
System.out.println("Recaught: " + e);
}
}

finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow
through the method.

public class FinallyExample {


static void procA(){
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally{
System.out.println("procA's finally");
}
}

static void procB(){


try {
System.out.println("inside procB");
return;
}
finally{
System.out.println("procB's finally");
}
}

static void procC(){


try {
System.out.println("inside procC");

}
finally{
System.out.println("procC's finally");
}
}

public static void main(String args[]) {


try {
procA();
}
catch(Exception e) {
System.out.println("Exception: "+ e);
}
procB();
procC();
}
}

Creating Your Own Exception Subclasses


Although Java’s built-in exceptions handle most common errors, you will probably want to create your own exception
types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which
is, of course, a subclass of Throwable). Your subclasses don’t need to actually implement anything—it is their existence
in the type system that allows you to use them as exceptions.

class MyNewException extends Exception {


private int detail;
MyNewException(int a){
detail=a;
}
public String toString() {
return "MyNewException[" + detail +"]";
}
}
class ExceptionDemo{
static void compute(int a)throws MyNewException {
System.out.println("Called Compute"+"["+a+"]");
if(a>10)
throw new MyNewException(a);
System.out.println("Normal Exit");

public static void main(String args[]) {


try {
compute(1);
compute(20);
}
catch(MyNewException e) {
System.out.println("caught: "+e);
}
}
}

Questions

Ques. How is object created in java [2]

1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12. }
.
Ques What are package in java .How a user defined package is created in java .

In Java, a package is a way to organize and group related classes and interfaces. Packages provide a
mechanism for naming and organizing classes, which helps avoid naming conflicts and provides a clear
hierarchical structure for your code. You can think of packages as directories or folders in which you
store your Java files.
Here's how you can create and use packages in Java:
1. Package Declaration: To declare that a class belongs to a particular package, you include the
package declaration at the beginning of your Java file. For example:
package com.example.mypackage;
1. This declaration is typically the first line in your Java source file.
2. Directory Structure: In the file system, packages are represented as directories or folders. The
package declaration in your Java file should match the directory structure. In the example above,
the Java file should be located in a directory structure like this:
com/
└── example/
└── mypackage/
└── YourJavaFile.java

Accessing Classes from Packages: To use a class from a package, you import it at the beginning of your
Java file using the import statement. For example:
import com.example.mypackage.SomeClass;

Creating User-Defined Packages: To create your own package in Java, you should follow these steps:
• Choose a package name that is unique and meaningful for your project.
• Create a directory structure that mirrors your package name.
• Place your Java source files within the appropriate directory, and include the package declaration
in those files.
• When you compile your Java code, make sure the compiler recognizes the directory structure and
package declaration. For example, if you are using the javac compiler, you can use the -d option
to specify the output directory for compiled classes and ensure it matches your package structure:
1. javac -d /path/to/output_directory YourJavaFile.java
• To use classes from your user-defined package in other Java files, import them
By using packages in Java, you can organize your code into a logical and manageable structure, making it
easier to maintain and collaborate on larger projects. Additionally, packages help prevent naming
conflicts by encapsulating classes within their own namespaces.
Example:
java package com.mycompany.util;
public class MathUtils {
public static int add(int a, int b)
{ return a + b; }
public static int subtract(int a, int b)
{ return a - b; } }
3. Compile Classes:
• Compile the MathUtils.java class using the javac command:
bashCopy code
javac com/mycompany/util/MathUtils.java
4. Use the Package:
• In another Java class, you can import and use the MathUtils class from your user-defined
package:
import com.mycompany.util.MathUtils;
public class Main
{ public static void main(String[] args)
{ int result = MathUtils.add(10, 5);
System.out.println("Result: " + result); }
}
5. Compile and Run:
• Compile the Main.java class and run it:

javac Main.java
java Main
Ques: Explain Exceptions. How Exceptions are handled in java? Discuss the keywords try,
catch and finally with example code.
Ques: What is thread and how to create a thread in java
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area. They
don't allocate separate memory area so saves memory, and context-switching between the threads takes
less time than process.
Java Multithreading is mostly used in games, animation, etc.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate memory
area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-switching
between the threads. There can be multiple processes inside the OS, and one process can have
multiple threads.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the new state,
the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread.
Each and every thread runs for a short span of time and when that allocated time slice is over, the
thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for
their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting
for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads
lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running state.
Generally, the most common change in the state of a thread is from runnable to running and again
back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then,
either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the
blocked state. A thread in the blocked state is unable to perform any execution and thus never
consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains
idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.

When the main thread invokes the join() method then, it is said that the main thread is in the waiting
state. The main thread then waits for the child threads to complete their tasks. When the child
threads complete their job, a notification is sent to the main thread, which again moves the thread
from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler
to determine which thread to choose and which one to reject, and the chosen thread is then given
the opportunity to run.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A)
has entered the critical section of a code and is not willing to leave that critical section. In such a
scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid
such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for
a specific span of time, and not forever. A real example of timed waiting is when we invoke the
sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state.
After the time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the thread is dead,
and there is no way one can respawn (active after kill) the dead thread.

Java Threads | How to create a thread in Java


There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and allow
other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed
by a thread. Runnable interface have only one method named run().

1. public void run(): is used to perform action for a thread.

Starting a thread:

The start() method of Thread class is used to start a newly created thread. It performs the following tasks:

Backward Skip 10sPlay VideoForward Skip 10s

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...

2) Java Thread Example by implementing Runnable interface

FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }

Output:

thread is running...

If you are not extending the Thread class, your class object would not be treated as a thread object. So you
need to explicitly create the Thread class object. We are passing the object of your class that implements
Runnable so that your class run() method may execute.

3) Using the Thread Class: Thread(String Name)


We can directly use the Thread class to spawn new threads using the constructors defined above.

FileName: MyThread1.java

1. public class MyThread1


2. {
3. // Main method
4. public static void main(String argvs[])
5. {
6. // creating an object of the Thread class using the constructor Thread(String name)
7. Thread t= new Thread("My first thread");
8.
9. // the start() method moves the thread to the active state
10. t.start();
11. // getting the thread name by invoking the getName() method
12. String str = t.getName();
13. System.out.println(str);
14. }
15. }

Output:

My first thread

4) Using the Thread Class: Thread(Runnable r, String name)

Observe the following program.

FileName: MyThread2.java

1. public class MyThread2 implements Runnable


2. {
3. public void run()
4. {
5. System.out.println("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, String name)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
20. // getting the thread name by invoking the getName() method
21. String str = th1.getName();
22. System.out.println(str);
23. }
24. }

Output:

My new thread

Now the thread is running ...

Ques. What are the advantages and drawback of an applet? [5]

Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
runs inside the browser and works at client side.
Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac
Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.

Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.

Ques: Define the lifecycle of Applet.

Lifecycle of Java Applet

1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and place
the applet code in html file. Now click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

myapplet.html

1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:

To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile
it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose
only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java

c:\>appletviewer First.java

Ques: Write a java program to create an applet which add two numbers through a add button .
[10]

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class addi extends Applet


{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b;

int x,y,z;

public void init()


{
l1 = new Label("mark-1");
t1 = new TextField(10);

l2 = new Label("mark-2");
t2 = new TextField(10);

l3 = new Label("total");
t3 = new TextField(10);

b = new Button("add");
b.addActionListener(new kk());

add(l1); add(t1);
add(l2); add(t2);
add(l3); add(t3);
add(b);
}

class kk implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
x = Integer.parseInt(t1.getText());
y = Integer.parseInt(t2.getText());
z = x+y;
t3.setText(String.valueOf(z));
}
}
}

Html file code:


<HTML>
<body>
<applet code = "addi.class" width = 100 height = 200>
</applet>
</body></HTML>

Ques: Write a java program to create an applet and perform event handling on it. [10]

import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CircleAreaApplet extends Applet implements ActionListener
{ TextField radiusField;
Button calculateButton;
Label resultLabel;
public void init()
{
radiusField = new TextField(10);
calculateButton = new Button("Calculate");
resultLabel = new Label("");
add(new Label("Enter the radius of the circle:"));
add(radiusField);
add(calculateButton);
add(resultLabel);
calculateButton.addActionListener(this);
} public void actionPerformed(ActionEvent e)
{ if (e.getSource() == calculateButton)
{ double radius = Double.parseDouble(radiusField.getText());
double area = 3.14* radius * radius;
resultLabel.setText("Area of the circle: " + area);
}
}}}
Html file code:
<HTML><body>
<applet code = "area.class" width = 100 height = 200>
</applet>
</body><HTML>

AWT
Java AWT (Abstract Window Toolkit) is an API used to create Graphical User
Interface (GUI) or Windows-based Java programs and Java AWT components are
platform-dependent, which means they are shown in accordance with the operating
system’s view. AWT is heavyweight, which means that its components consume
resources from the underlying operating system (OS). The java.awt package contains
AWT API classes such as TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List, and so on.

AWT is platform independent even after the AWT components are platform dependent
because of the points mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through
Abstract API which are platform independent. Abstract API allows Java to isolate
platform-specific details, making code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent.
Because of this, it ensures that AWT functionality remains consistent across different
environments.
Java AWT Hierarchy

• Components: AWT provides various components such as buttons, labels,


text fields, checkboxes, etc used for creating GUI elements for Java
Applications.
• Containers: AWT provides containers like panels, frames, and dialogues to
organize and group components in the Application.
• Layout Managers: Layout Managers are responsible for arranging data in
the containers some of the layout managers are BorderLayout, FlowLayout,
etc.
• Event Handling: AWT allows the user to handle the events like mouse
clicks, key presses, etc. using event listeners and adapters.
• Graphics and Drawing: It is the feature of AWT that helps to draw shapes,
insert images and write text in the components of a Java Application.

Note: Container can be added inside another container as it is type of component.

Container

The container is a component that contains other components like button, textfield, label, etc.
However, it is a subclass of the Component class.

Types of Containers in Java AWT

Panel

The panel can be defined as a container that can be used to hold other components. However, it
doesn't contain the title bar, menu bar, or border.

Window

A window can be defined as a container that doesn't contain any border or menu bar. It creates a
top-level view. However, we must have a frame, dialog, or another window for creating a window.

Frame

The frame is a subclass of Window. It can be defined as a container with components like button,
textfield, label, etc. In other words, AWT applications are mostly created using frame container.

1. import java.awt.*;
2. public class ButtonExample {
3. public static void main (String[] args) {
4.
5. // create instance of frame with the label
6. Frame f = new Frame("Button Example");
7.
8. // create instance of button with label
9. Button b = new Button("Click Here");
10.
11. // set the position for the button in frame
12. b.setBounds(50,100,80,30);
13.
14. // add button to the frame
15. f.add(b);
16. // set size, layout and visibility of frame
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. }

To compile the program using command prompt type the following commands

1. C:\Users\Anurati\Desktop\abcDemo>javac ButtonExample.java

If there's no error, we can execute the code using:

1. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample

Output:

Java AWT Dialog Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new DialogExample();
25. }
26. }

Output:
Ques: What are the uses of layout manager. Give the name of classes that represent the
layout manager . Explain any 5 layout manager. [10]

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.

There are the following classes that represent 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 a 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

o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.

Example of BorderLayout class: Using BorderLayout() constructor


FileName: Border.java

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
15. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
21. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
22. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
23.
24. f.setSize(300, 300);
25. f.setVisible(true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }

Output:

jframe.setLayout(new BorderLayout(20, 15));

This statement create gap between sections


Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One component
is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows
and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor


The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.

FileName: GridLayoutExample.java

1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class GridLayoutExample
6. {
7. JFrame frameObj;
8.
9. // constructor
10. GridLayoutExample()
11. {
12. frameObj = new JFrame();
13.
14. // creating 9 buttons
15. JButton btn1 = new JButton("1");
16. JButton btn2 = new JButton("2");
17. JButton btn3 = new JButton("3");
18. JButton btn4 = new JButton("4");
19. JButton btn5 = new JButton("5");
20. JButton btn6 = new JButton("6");
21. JButton btn7 = new JButton("7");
22. JButton btn8 = new JButton("8");
23. JButton btn9 = new JButton("9");
24.
25. // adding buttons to the frame
26. // since, we are using the parameterless constructor, therfore;
27. // the number of columns is equal to the number of buttons we
28. // are adding to the frame. The row count remains one.
29. frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
30. frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
31. frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
32.
33. // setting the grid layout using the parameterless constructor
34. frameObj.setLayout(new GridLayout());
35.
36.
37. frameObj.setSize(300, 300);
38. frameObj.setVisible(true);
39. }
40.
41. // main method
42. public static void main(String argvs[])
43. {
44. new GridLayoutExample();
45. }
46. }

Output:
1. // setting grid layout of 3 rows and 3 columns
2. f.setLayout(new GridLayout(3,3));
3. frameObj.setLayout(new GridLayout(3, 3, 20, 25));

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


FileName: FlowLayoutExample.java

1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
31. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
32. frameObj.add(b9); frameObj.add(b10);
33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. frameObj.setLayout(new FlowLayout());
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }

Output:
Example of FlowLayout class: Using FlowLayout(int align) constructor
1. / setting flow layout of right alignment
2. f.setLayout(new FlowLayout(FlowLayout.RIGHT));

frameObj.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));


Java CardLayout
The Java CardLayout class manages the components in such a manner that only one component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly Used Methods of CardLayout Class


o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card with the
given name.

Example of CardLayout Class: Using Default Constructor


The following program uses the next() method to move to the next card of the container.

FileName: CardLayoutExample1.java

1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4. import java.awt.event.*;
5.
6. public class CardLayoutExample1 extends JFrame implements ActionListener
7. {
8.
9. CardLayout crd;
10.
11. // button variables to hold the references of buttons
12. JButton btn1, btn2, btn3;
13. Container cPane;
14.
15. // constructor of the class
16. CardLayoutExample1()
17. {
18.
19. cPane = getContentPane();
20.
21. //default constructor used
22. // therefore, components will
23. // cover the whole area
24. crd = new CardLayout();
25.
26. cPane.setLayout(crd);
27.
28. // creating the buttons
29. btn1 = new JButton("Apple");
30. btn2 = new JButton("Boy");
31. btn3 = new JButton("Cat");
32.
33. // adding listeners to it
34. btn1.addActionListener(this);
35. btn2.addActionListener(this);
36. btn3.addActionListener(this);
37.
38. cPane.add("a", btn1); // first card is the button btn1
39. cPane.add("b", btn2); // first card is the button btn2
40. cPane.add("c", btn3); // first card is the button btn3
41.
42. }
43. public void actionPerformed(ActionEvent e)
44. {
45. // Upon clicking the button, the next card of the container is shown
46. // after the last card, again, the first card of the container is shown upon clicking
47. crd.next(cPane);
48. }
49.
50. // main method
51. public static void main(String argvs[])
52. {
53. // creating an object of the class CardLayoutExample1
54. CardLayoutExample1 crdl = new CardLayoutExample1();
55.
56. // size is 300 * 300
57. crdl.setSize(300, 300);
58. crdl.setVisible(true);
59. crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
60. }
61. }

Output:
When the button named apple is clicked, we get

When the boy button is clicked, we get


Again, we reach the first card of the container if the cat button is clicked, and the cycle continues.
Example of CardLayout Class: Using Parameterized Constructor
FileName: CardLayoutExample2.java

1. import java.awt.*;
2. import java.awt.event.*;
3.
4. import javax.swing.*;
5.
6. public class CardLayoutExample2 extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample2(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. c.setLayout(card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23.
24. c.add("a",b1);c.add("b",b2);c.add("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. card.next(c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample2 cl=new CardLayoutExample2();
33. cl.setSize(400,400);
34. cl.setVisible(true);
35. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
36. }
37. }
download this example

Output:

Java BoxLayout

The Java BoxLayout class is used to arrange the components either


vertically or horizontally. For this purpose, the BoxLayout class provides
four constants. They are as follows:

Note: The BoxLayout class is found in javax.swing package.

Fields of BoxLayout Class

1. public static final int X_AXIS: Alignment of the components are


horizontal from left to right.
2. public static final int Y_AXIS: Alignment of the components are
vertical from top to bottom.
3. public static final int LINE_AXIS: Alignment of the components
is similar to the way words are aligned in a line, which is based on
the ComponentOrientation property of the container. If the
ComponentOrientation property of the container is horizontal, then
the components are aligned horizontally; otherwise, the components
are aligned vertically. For horizontal orientations, we have two
cases: left to right, and right to left. If the value
ComponentOrientation property of the container is from left to right,
then the components are rendered from left to right, and for right to
left, the rendering of components is also from right to left. In the
case of vertical orientations, the components are always rendered
from top to bottom.
4. public static final int PAGE_AXIS: Alignment of the components
is similar to the way text lines are put on a page, which is based on
the ComponentOrientation property of the container. If the
ComponentOrientation property of the container is horizontal, then
components are aligned vertically; otherwise, the components are
aligned horizontally. For horizontal orientations, we have two cases:
left to right, and right to left. If the value ComponentOrientation
property of the container is also from left to right, then the
components are rendered from left to right, and for right to left, the
rendering of components is from right to left. In the case of vertical
orientations, the components are always rendered from top to
bottom.

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that


arranges the components with the given axis.

Example of BoxLayout class with Y-AXIS:

FileName: BoxLayoutExample1.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. // adding the buttons so that it can be displayed
13. add (buttons[i]);
14. }
15. // the buttons will be placed horizontally
16. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
17. setSize(400,400);
18. setVisible(true);
19. }
20. // main method
21. public static void main(String args[]){
22. BoxLayoutExample1 b=new BoxLayoutExample1();
23. }
24. }

Output:
Java AWT Example
Consider the following simple example of Java AWT in which we have shown an awt component
button by setting its placement and window frame size.

1. import java.awt.*;
public class AwtProgram1 {
2. public AwtProgram1()
3. {
4. Frame f = new Frame();
5. Button btn=new Button("Hello World");
6. btn.setBounds(80, 80, 100, 50);
7. f.add(btn); //adding a new Button.
8. f.setSize(300, 250); //setting size.
9. f.setTitle("JavaTPoint"); //setting title.
10. f.setLayout(null); //set default layout for frame.
11. f.setVisible(true); //set frame visibility true.
12. }
13.
14.
15. public static void main(String[] args) {
16. // TODO Auto-generated method stub
17.
18. AwtProgram1 awt = new AwtProgram1(); //creating a frame.
19. }
20. }

Output:

Java awt Example (extending Frame Class)


Consider the following program in which we have created a user's form GUI, which has three
fields, i.e., first name, last name, and date of birth.

1. import java.awt.*;
2. public class AwtApp extends Frame {
3.
4. AwtApp(){
5. Label firstName = new Label("First Name");
6. firstName.setBounds(20, 50, 80, 20);
7.
8. Label lastName = new Label("Last Name");
9. lastName.setBounds(20, 80, 80, 20);
10.
11. Label dob = new Label("Date of Birth");
12. dob.setBounds(20, 110, 80, 20);
13.
14. TextField firstNameTF = new TextField();
15. firstNameTF.setBounds(120, 50, 100, 20);
16.
17. TextField lastNameTF = new TextField();
18. lastNameTF.setBounds(120, 80, 100, 20);
19.
20. TextField dobTF = new TextField();
21. dobTF.setBounds(120, 110, 100, 20);
22.
23. Button sbmt = new Button("Submit");
24. sbmt.setBounds(20, 160, 100, 30);
25.
26. Button reset = new Button("Reset");
27. reset.setBounds(120,160,100,30);
28.
29. add(firstName);
30. add(lastName);
31. add(dob);
32. add(firstNameTF);
33. add(lastNameTF);
34. add(dobTF);
35. add(sbmt);
36. add(reset);
37.
38. setSize(300,300);
39. setLayout(null);
40. setVisible(true);
41. }
42. public static void main(String[] args) {
43. // TODO Auto-generated method stub
44. AwtApp awt = new AwtApp();
45. }
46. }

Output:

AWT Button

1. // importing necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. public class ButtonExample3 {
5. public static void main(String[] args) {
6. // create instance of frame with the label
7. Frame f = new Frame("Button Example");
8. final TextField tf=new TextField();
9. tf.setBounds(50,50, 150,20);
10. // create instance of button with label
11. Button b=new Button("Click Here");
12. // set the position for the button in frame
13. b.setBounds(50,100,60,30);
14. b.addActionListener(new ActionListener() {
15. public void actionPerformed (ActionEvent e) {
16. tf.setText("Welcome to Javatpoint.");
17. }
18. });
19. // adding button the frame
20. f.add(b);
21. // adding textfield the frame
22. f.add(tf);
23. // setting size, layout and visibility
24. f.setSize(400,400);
25. f.setLayout(null);
26. f.setVisible(true);
27. }
28. }

Java ActionListener Interface


The Java ActionListener is notified whenever you click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is found in java.awt.event package. It has only
one method: actionPerformed().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
1. public abstract void actionPerformed(ActionEvent e);
How to write ActionListener
The common approach is to implement the ActionListener. If you implement the ActionListener
class, you need to follow 3 steps:

1) Implement the ActionListener interface in the class:

1. public class ActionListenerExample Implements ActionListener

2) Register the component with the Listener:

1. component.addActionListener(instanceOfListenerclass);

3) Override the actionPerformed() method:

1. public void actionPerformed(ActionEvent e){


2. //Write the code here
3. }
Java ActionListener Example: On Button click
1. import java.awt.*;
2. import java.awt.event.*;
3. //1st step
4. public class ActionListenerExample implements ActionListener{
5. public static void main(String[] args) {
6. Frame f=new Frame("ActionListener Example");
7. final TextField tf=new TextField();
8. tf.setBounds(50,50, 150,20);
9. Button b=new Button("Click Here");
10. b.setBounds(50,100,60,30);
11. //2nd step
12. b.addActionListener(this);
13. f.add(b);f.add(tf);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. //3rd step
19. public void actionPerformed(ActionEvent e){
20. tf.setText("Welcome to Javatpoint.");
21. }
22. }

Output:

Java ActionListener Example: On Button click


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class Test implements ActionListener {

Button b1;
TextField t1;
Label lb1, lb3;
Frame f;

Test() {
f = new Frame("Area of a circle");

lb1 = new Label("Enter radius of a circle :");


lb1.setBounds(5, 50, 150, 30);
f.add(lb1);

t1 = new TextField();
t1.setBounds(200, 50, 150, 30);
f.add(t1);

lb3 = new Label("Result :");


lb3.setBounds(90, 140, 150, 30);
f.add(lb3);

b1 = new Button("Find ");


b1.setBounds(90, 200, 100, 30);
f.add(b1);

b1.addActionListener(this);

f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

f.setLayout(null);
f.setSize(600, 500);
f.setVisible(true);

@Override
public void actionPerformed(ActionEvent e) {

float r = Float.parseFloat(t1.getText());
float area = 0;

if (e.getSource().equals(b1)) {
area = (float) 3.14 * r * r;

lb3.setText(String.valueOf("Result : " + area));


}

public static void main(String args[]) {


Test t = new Test();
}
}
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);
Java MouseListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){
6. addMouseListener(this);
7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new MouseListenerExample();
32. }
33. }

Output:

Java MouseListener Example 2


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample2 extends Frame implements MouseListener{
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
21. public static void main(String[] args) {
22. new MouseListenerExample2();
23. }
24. }

Output:

Backward Skip 10sPlay VideoForward Skip 10s


Java MouseMotionListener Interface
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against
MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two
methods.

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);


2. public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener Example


1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionListenerExample extends Frame implements MouseMotionLi
stener{
4. MouseMotionListenerExample(){
5. addMouseMotionListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseDragged(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),20,20);
15. }
16. public void mouseMoved(MouseEvent e) {}
17.
18. public static void main(String[] args) {
19. new MouseMotionListenerExample();
20. }
21. }
Output:

Java ItemListener Interface


The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one method:
itemStateChanged().

itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.

1. public abstract void itemStateChanged(ItemEvent e);


Java ItemListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class ItemListenerExample implements ItemListener{
4. Checkbox checkBox1,checkBox2;
5. Label label;
6. ItemListenerExample(){
7. Frame f= new Frame("CheckBox Example");
8. label = new Label();
9. label.setAlignment(Label.CENTER);
10. label.setSize(400,100);
11. checkBox1 = new Checkbox("C++");
12. checkBox1.setBounds(100,100, 50,50);
13. checkBox2 = new Checkbox("Java");
14. checkBox2.setBounds(100,150, 50,50);
15. f.add(checkBox1); f.add(checkBox2); f.add(label);
16. checkBox1.addItemListener(this);
17. checkBox2.addItemListener(this);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public void itemStateChanged(ItemEvent e) {
23. if(e.getSource()==checkBox1)
24. label.setText("C++ Checkbox: "
25. + (e.getStateChange()==1?"checked":"unchecked"));
26. if(e.getSource()==checkBox2)
27. label.setText("Java Checkbox: "
28. + (e.getStateChange()==1?"checked":"unchecked"));
29. }
30. public static void main(String args[])
31. {
32. new ItemListenerExample();
33. }
34. }

Output:
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three methods.

Interface declaration
Following is the declaration for java.awt.event.KeyListener interface:

1. public interface KeyListener extends EventListener


Methods of KeyListener interface
The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description

1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.

2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.

3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

Methods inherited
This interface inherits methods from the following interface:

o java.awt.EventListener

Java KeyListener Example


In the following example, we are implementing the methods of the KeyListener interface.

KeyListenerExample.java

1. // importing awt libraries


2. import java.awt.*;
3. import java.awt.event.*;
4. // class which inherits Frame class and implements KeyListener interface
5. public class KeyListenerExample extends Frame implements KeyListener {
6. // creating object of Label class and TextArea class
7. Label l;
8. TextArea area;
9. // class constructor
10. KeyListenerExample() {
11. // creating the label
12. l = new Label();
13. // setting the location of the label in frame
14. l.setBounds (20, 50, 100, 20);
15. // creating the text area
16. area = new TextArea();
17. // setting the location of text area
18. area.setBounds (20, 80, 300, 300);
19. // adding the KeyListener to the text area
20. area.addKeyListener(this);
21. // adding the label and text area to the frame
22. add(l);
23. add(area);
24. // setting the size, layout and visibility of frame
25. setSize (400, 400);
26. setLayout (null);
27. setVisible (true);
28. }
29. // overriding the keyPressed() method of KeyListener interface where we set the text of th
e label when key is pressed
30. public void keyPressed (KeyEvent e) {
31. l.setText ("Key Pressed");
32. }
33. // overriding the keyReleased() method of KeyListener interface where we set the text of t
he label when key is released
34. public void keyReleased (KeyEvent e) {
35. l.setText ("Key Released");
36. }
37. // overriding the keyTyped() method of KeyListener interface where we set the text of the
label when a key is typed
38. public void keyTyped (KeyEvent e) {
39. l.setText ("Key Typed");
40. }
41. // main method
42. public static void main(String[] args) {
43. new KeyListenerExample();
44. }
45. }

Output:

1. String text = area.getText();


2. // splitting the string in words
3. String words[] = text.split ("\\s");
4. // printing the number of words and characters of the string
5. l.setText ("Words: " + words.length + " Characters:" + text.length());

Java Adapter Classes


Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

Pros of using Adapter classes:


o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes


Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener
ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes


Adapter class Listener interface

DragSourceAdapter DragSourceListener

DragTargetAdapter DragTargetListener

javax.swing.event Adapter classes


Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener

Java WindowAdapter Example


In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.

AdapterExample.java

Backward Skip 10sPlay VideoForward Skip 10s

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. public class AdapterExample {
6. // object of Frame
7. Frame f;
8. // class constructor
9. AdapterExample() {
10. // creating a frame with the title
11. f = new Frame ("Window Adapter");
12. // adding the WindowListener to the frame
13. // overriding the windowClosing() method
14. f.addWindowListener (new WindowAdapter() {
15. public void windowClosing (WindowEvent e) {
16. f.dispose();
17. }
18. });
19. // setting the size, layout and
20. f.setSize (400, 400);
21. f.setLayout (null);
22. f.setVisible (true);
23. }
24.
25. // main method
26. public static void main(String[] args) {
27. new AdapterExample();
28. }
29. }

Output:
Java MouseAdapter Example
In the following example, we are implementing the MouseAdapter class. The MouseListener
interface is added into the frame to listen the mouse event in the frame.

MouseAdapterExample.java

1. // importing the necessary libraries


2. import java.awt.*;
3. import java.awt.event.*;
4.
5. // class which inherits the MouseAdapter class
6. public class MouseAdapterExample extends MouseAdapter {
7. // object of Frame class
8. Frame f;
9. // class constructor
10. MouseAdapterExample() {
11. // creating the frame with the title
12. f = new Frame ("Mouse Adapter");
13. // adding MouseListener to the Frame
14. f.addMouseListener(this);
15. // setting the size, layout and visibility of the frame
16. f.setSize (300, 300);
17. f.setLayout (null);
18. f.setVisible (true);
19. }
20. // overriding the mouseClicked() method of the MouseAdapter class
21. public void mouseClicked (MouseEvent e) {
22. // creating the Graphics object and fetching them from the Frame object using getGraphics() meth
od
23. Graphics g = f.getGraphics();
24. // setting the color of graphics object
25. g.setColor (Color.BLUE);
26. // setting the shape of graphics object
27. g.fillOval (e.getX(), e.getY(), 30, 30);
28. }
29. // main method
30. public static void main(String[] args) {
31. new MouseAdapterExample();
32. }
33. }

Output:

1. public void mouseClicked(MouseEvent e) {


2. Graphics g=getGraphics();
3. g.setColor(Color.BLUE);
4. g.fillOval(e.getX(),e.getY(),30,30);
5. }
6. public void mouseEntered(MouseEvent e) {}
7. public void mouseExited(MouseEvent e) {}
8. public void mousePressed(MouseEvent e) {}
9. public void mouseReleased(MouseEvent e) {}
10.

UNIT-2
HTML
Introduction
• Web design is the process of planning, conceptualizing, and arranging content online.
• Web design is the process of planning and building the elements of the website, from structure and layout
to images, colors, fonts and graphics.
• Designing a website goes beyond aesthetics to include the website’s overall functionality
• It includes web apps, mobile apps, and user interface design.
• It has numerous components that work together to create the finished experience of a website, including
graphic design, user experience design, interface design, search engine optimization (SEO) and content
creation

Basic principles involved in developing a website


Purpose
• Good web design always caters to the needs of the user
• Each page of website needs to have a clear purpose
• The core purposes common to all websites;
➢ Describing Expertise
➢ Building Your Reputation
➢ Generating Leads
➢ Sales and After Care
Communication
• It is important to communicate clearly and make information easy to read and digest.
• Some effective tactics to include in web design include organizing information using headlines and sub
headlines, using bullet points instead of long sentences
Typefaces
• Typography commands attention and works as the visual interpretation of the brand voice
• Typefaces should be legible and only use a maximum of 3 different fonts on the website.
Colors
• Color has the power to communicate messages and evoke emotional responses
• Try to keep the color selection limited to less than 5 colors
• Complementary colors work very well, creating balance and harmony
• Pleasing color combinations increase customer engagement and make the user feel good.
Images
• Imagery is every visual aspect used within communications
• This includes still photography, illustration, video and all forms of graphics
• All imagery should be expressive and capture the spirit of the company and act as the embodiment of
their brand personality
Navigation
• Navigation is the wayfinding system used on websites where visitors interact and find what they are
looking for
• Website navigation is key to retaining visitors
• Keeping navigation simple, intuitive and consistent on every page is key
Grid based layouts
• Grids help to structure the design and keep the content organized
• The grid helps to align elements on the page and keep it clean
• The grid-based layout arranges content into a clean rigid grid structure with columns, sections that line up
and feel balanced and impose order and results in an aesthetically pleasing website.
“F” Pattern design
• people scan computer screens in an “F” pattern
• Eye-tracking studies have found that most of what people see is in the top and left areas of the screen.
• The F shaped layout mimics our natural pattern of reading in the West (left to right and top to bottom).
• An effectively designed website will work with a reader’s natural pattern of scanning the page.


Load time
• Waiting for a website to load will lose visitors
• page load time can be more effective by optimizing image sizes (size and scale), combining code into a
central CSS or JavaScript file (this reduces HTTP requests) and minify HTML, CSS, JavaScript (compressed
to speed up their load time).
Mobile friendly
• More people are using their phones or other devices to browse the web.
• It is important to consider building a website with a responsive layout where websites can adjust to
different screens.
Visual Hierarchy
• Visual hierarchy is the arrangement of elements in order of importance.
• This is done either by size, color, imagery, contrast, typography, whitespace, texture, and style.
• One of the most important functions of visual hierarchy is to establish a focal point; this shows visitors
where the most important information is.

WEBSITE
• A website can be defined as a collection of several webpages that are all related to each other and can be
accessed by visiting a homepage, by using a browser like Internet Explorer, Mozilla, Google Chrome, or
Opera.
• identified with a common domain name.
• published on web server.
• accessed using Internet address known as Uniform Resource Locator
• a website can be a personal website, a commercial website, a government website or a non-profit
organization website.

Categories of Website
➢ Static Website
➢ Dynamic Website

STATIC WEBSITE
• Static website is the basic type of website that is easy to create.
• Its web pages are coded in HTML.
• The codes are fixed for each page so the information contained in the page does not change and looks like
a printed page.

DYNAMIC WEBSITE
• Dynamic website is a collection of dynamic web pages whose content changes dynamically
• It accesses content from a database or Content Management System (CMS)
• Uses client-side scripting or server-side scripting, or both to generate dynamic content
• Uses client-side scripting or server-side scripting, or both to generate dynamic content
• Client-side scripting:
• Generates content at the client computer on the basis of user input.
• The web browser downloads the web page from the server and processes the code within the page to
render information to the user.
• In server-side scripting:
• The software runs on the server and processing is completed in the server then plain pages are sent to the
user.

Static Website Dynamic Website


• Prebuilt content is same every time the page • Content is generated quickly and changes regularly.
is loaded.
• It uses the HTML code for developing a • It uses the server side languages such as PHP,
website. SERVLET, JSP, and ASP.NET etc. for developing a
website.
• It sends the same response for every request. • It may generate different HTML for each of the
request.
• The content only changes when someone • The page contains "server-side" code it allows the
publishes and updates the file (sends it to the server to generate the unique content when the
web server). page is loaded.
• Flexibility is the main advantage of static • Content Management System (CMS) is the main
website. advantage of dynamic website.

Web Standards and W3C recommendations


W3C
• The World Wide Web Consortium (W3C) is an international industry consortium dedicated to "leading the
Web to its full potential“
• It's led by Tim Berners-Lee, the inventor of the Web.
• Founded in 1994, the W3C has more than 330 member organizations - including Microsoft, America
Online, Apple Computer, Adobe, Macromedia, Sun Microsystems, and a variety of other hardware and
software manufacturers, content providers, academic institutions, and telecommunications companies.
• The Consortium is hosted by three universities - MIT in the US, INRIA in Europe, and Keio University in
Japan. Later joined by Beihang University in China

What are Web Standards?


• Web standards are rules and guidelines established by the World Wide Web Consortium (W3C) developed
to promote consistency in the design code which makes up a web page.
• it's the guideline for the mark-up language which determines how a web page. displays in a visitor's
browser window.
• Web Standards are defined as a formal set of standards and technical specifications used to define
aspects of the world wide web.
• These are best-practice standards used by organizations to build web sites and web applications.

The advantages in adhering to these standards are:


• Web pages will display in a wide variety of browsers and computers, including new technology like
iPhones, Droids, iPads, PDA devices, mobile phones, which greatly increases the viewing audience.
• W3C Standards promote the use of "Cascading Style Sheets" (CSS) or design code which is attached to the
web page, rather than embedded in the page. The use of style sheets significantly reduces the page file
size which means not only a faster page loading time but lower hosting costs for frequently visited sites
due to using less bandwidth.
• Design features such as colors and fonts can be easily changed by just modifying one style sheet instead
of editing every individual page in a web site, reducing the costs to modify your site.
• Search Engines can access and index pages designed to web standards with greater efficiency.

Web Standards
• HTML - Hypertext Markup Language
• XML 1.0 - Extensible Markup Language
• XHTML - Extensible Hypertext Markup Language
• CSS - Cascading Style Sheets

1. HTML - Hypertext Markup Language


• HTML is the publishing language of the World Wide Web developed by Tim Berners-Lee while at
CERN.
• HTML has been developed with the vision that all manner of devices should be able to use
information on the Web: PCs with graphics displays of varying resolution and color depths, mobile
phones, hand held devices, devices for speech for output and input, computers with high or low
bandwidth, and so on.

2. XML 1.0 - Extensible Markup Language


• XML is a publishing language like HTML, but instead of having a single, fixed set of elements, it allows
you to define your own - or use a set made by someone else.
• Some applications of XML, such as XHTML and MathML, have already become W3C
Recommendations.

3. XHTML - Extensible Hypertext Markup Language


• XHTML stands for EXtensible HyperText Markup Language.
• The XHTML helps web developers to make the transition from HTML to XML.
• Using XHTML, developers can enter the XML world with all the features of it, and they can still remain
confident about the backward and future compatibility of the content.

4. CSS - Cascading Style Sheets


• Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors, spacing) to
Web documents.
• CSS describes how HTML elements should be displayed.
• Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the
process of making web pages presentable.

What are the advantages of using web standards?


• web standards are designed with forward- and backward-compatibility in mind :
• data using old versions of the standards will continue to work in new browsers, and data using
new versions of the standards will “gracefully degrade” to produce an acceptable result in older
browsers.
• Compliant documents can easily be converted to other formats, such as databases or Word documents:
• This allows for more versatile use of the information within pages.
• Greater visibility in web searches.
• The structural information present in compliant documents makes it easy for search engines to
access and evaluate the information in those documents, and they get indexed more accurately.
• Accessibility
• this means allowing the web to be used by people with disabilities, and to be understood by
people using browsers other than the usual ones e.g. voice browsers, braille browsers, hand-held
browsers with very little monitor space etc.
• Web standards offer a set of rules that every Web developer can follow, understand, and become familiar
with:
• When one developer designs a site to the standards, another will be able to pick up where the
former left off.
INTRODUCTION TO HTML

• Hypertext Markup Language


• A language that allows users to organize, improve the appearance of, and link text with data on the
internet
• Develop web pages
Example
<HTML>
<HEAD>
<TITLE> Example </TITLE>
</HEAD>
<BODY>
This is where you would include the text and images on your Web page.
</BODY>
</HTML>

HTML Tags

• Mark-up HTML elements i.e. label pieces of content such as "heading", "paragraph“
• Enclosed in angle brackets (< >)
• Come in pairs:
– Tag1: start tag or opening tag <tagname>
– Tag2: end tag or closing tag </tagname>
• The basic structure of tag is:
<tag_name> some text </tag_name>
Some Common Tags
➢ <html> :
• Encloses the complete HTML document
• Comprises of:
o Document header : <head>...</head>
o Document body: <body>...</body> tags
➢ <head> :
• document's header
• Contain other HTML tags like <title>, <link> etc.
• <title> : document title
➢ <body> :
• Document's body
• keeps other HTML tags like <h1>, <div>, <p> etc.

HTML Document Structure


• Entire document enclosed within <html> and </html> tags
• Two subparts:
– Head
• Enclosed within <head> and </head>
• more tags within, to specify title of the page, meta-information, etc.
– Body
• Enclosed within <body> and </body>
• Within the body, content is to be displayed
• Many other tags can be embedded

Structure of Web page


• All Web pages share a common structure.
• All Web pages should contain a pair of:
– <HTML>
– <HEAD>
– <TITLE>
– <BODY>

HTML Elements
• An HTML element is a component of an HTML document that tells a web browser how to structure and
interpret a part of the HTML document.
• An HTML element is defined by a starting tag
• If the element contains other content, it ends with a closing tag, where the element name is preceded by
a forward slash
• Example:
<body>
My first homepage. <b>This text is bold</b>
</body>

Attributes
• All elements can have attributes
• Attributes provide additional information about an element
• Specified in the start tag always
• Come in name/value pairs like: name="value“
– Name: the property to be set
– Value: value of the property to be set and always put within quotations.
Example
• Attribute name: align
• Value: left, center and right
• Tag: Heading
<h5 align="left"> I can align headings </h5>
<h5 align="center">This is a centered heading </h5>
<h5 align="right">This is a heading aligned to the right </h5>

Working with List

• HTML offers web authors three ways for specifying lists of information.
• All lists must contain one or more list elements
• Lists may contain −
➢ <ul> − An unordered list
➢ <ol> − An ordered list
➢ <dl> − A definition list

Unordered List
An unordered HTML list:
• It is a collection of related items that have no special order or sequence
• starts with the <ul> tag • Item
• Each list item starts with the <li> tag • Item
• Item
• The list items will be marked with bullets (small black circles) by default • Item

Ordered List
An ordered HTML list:
• Put the items in a numbered list instead of bulleted
• Starts with the <ol> tag 1. First item
2. Second item
• Each list item starts with the <li> tag 3. Third item
• The numbering starts at one and is incremented by one for each successive list element 4. Fourth item

Definition/Description List A description HTML list:


• definition list represents a term and a relevant description in the form of the list.
HTML
• HTML definition list starts and ends with dl element (i.e. <dl> and </dl>). Hypertext Markup Language
CSS
• The terms are enclosed with dt element. Cascading style sheet
• The description is enclosed with the dd element.

Example:
<HTML>
<HEAD> Output:
<TITLE> HTML Lists </TITLE>
</HEAD>
<BODY>
<h2>Unordered List</h2>
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<h2>Ordered List</h2>
<ol>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ol>
<h2>Description List</h2>
<dl>
<dt>HTML</dt>
<dd>is a markup language</dd>
<dt>Java</dt>
<dd>is a programming language and platform</dd>
<dt>JavaScript</dt>
<dd>is a scripting language</dd>
</dl>
</body>
</HTML>

Working with Table


• The HTML tables arrange data like text, images, links, other tables, etc. into rows and columns of cells
• An HTML table is defined with the <table> tag
• Each table row is defined with the <tr> tag
• A table header is defined with the <th> tag
• By default, table headings are bold and centered
• A table data/cell is defined with the <td> tag

Example:

<!DOCTYPE html> OUTPUT:


<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border = "1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>
</html>

Table Heading
• Defined using <th> tag
• Used to represent the heading row
• Can be used in any row
• Headings are centered and bold by default

<!DOCTYPE html> OUPUT:


<html>
<head>
<title>HTML Table Header</title>
</head>
<body>
<table border = "1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>
</html>

Cellpadding and Cellspacing Attributes

• Adjust the white space in table cells.


• Cellspacing: defines space between table cells
• Cellpadding: represents the distance between cell borders and the content within a cell

<html> OUTPUT:
<head>
<title>HTML Table Cellpadding</title>
</head>

<body>
<table border = "1" cellpadding = "20" cellspacing = "5">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>

</html>

Colspan and Rowspan Attributes

• Colspan: merge two or more columns into a single column


• Rowspan: merge two or more rows

<html> OUTPUT:
<head>
<title>HTML Table Colspan/Rowspan</title>
</head>

<body>
<table border = "1">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>
</html>

Working With Forms

Introduction
• HTML Forms are required, when data needs to be collected from the site visitor
• A form will take input from the site visitor and then will post it to a back-end application
• The back-end application will perform required processing on the passed data based
• <form> tag is used to create an HTML form
• Syntax −
<form>
.form elements
.</form>
attributes :
• Action Attribute
o Defines the action to be performed when the form is submitted
o The form data is sent to a web page on the server when the user clicks on the submit button
o In the example, the form data is sent to a page on the server called "/action_page.php"
o This page contains a server-side script that handles the form data:
o <form action="/action_page.php">
o If the action attribute is omitted, the action is set to the current page

• Method Attribute
o Specifies the HTTP method (GET or POST) to be used when submitting the form data
o <form action="/action_page.php" method="get">
o <form action="/action_page.php" method="post">

• Target Attribute
o Defines the action to be performed when the form is submitted
o The form data is sent to a web page on the server when the user clicks on the submit button
o In the example, the form data is sent to a page on the server called "/action_page.php"
o This page contains a server-side script that handles the form data:
o <form action="/action_page.php">
o If the action attribute is omitted, the action is set to the current page

• Name Attribute
o Each input field must have a name attribute to be submitted
o If the name attribute is omitted, the data of that input field will not be sent at all

<input> Element
• Most important form element
• Can be displayed in several ways, depending on the type attribute
Type Description

<input type="text"> Defines a one-line text input field

<input type="radio"> Defines a radio button (for selecting one of many choices)

<input type="submit"> Defines a submit button (for submitting the form)

<!DOCTYPE html> OUTPUT:


<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type = "text" name =
"first_name" />
<br>
Last name: <input type = "text" name =
"last_name" />
</form>
</body>

</html>

CSS

What is CSS?
● CSS stands for Cascading Style Sheets
● CSS describes how HTML elements are to be displayed on screen, paper, or in other media
● CSS can control the layout of multiple web pages all at once
● CSS provides a big set of pre-defined codes for styling the HTML elements
○ color
○ background-color
○ font-size
○ font-family
○ text-align
CSS Syntax

● The selector points to the HTML element you want to style.


● The declaration block contains one or more declarations separated by semicolons.
● Each declaration includes a CSS property name and a value, separated by a colon.
● Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly
braces.

What are different types using CSS?


● CSS can be applied using three ways
● Inline CSS
● Internal CSS
● External CSS

● Inline CSS
● When the CSS codes get applied directly on a tag using STYLE attribute, it is known as inline CSS
● Use the codes using key:value pair model
● Use semicolon (;) when as separator when using multiple codes
● Just like HTML, CSS is also case insensitive
Code:

OUTPUT:

Internal Style Sheet


● When we apply styling on all or selected set of elements in a web page, it is called as internal CSS
● Use <style></style> tag to create such styles

OUTPUT:

External CSS
● We can create a file having styling effects and use that file in all the web pages of a website or even in
multiple websites
● Such method of using styling is called as external CSS
● Here we need to use <link> tag to define the external CSS file name
<link href='filename.css' rel='stylesheet’>
Rel->relationship

OUTPUT:

Selectors
Selectors

Pseudo- Pseudo-
Simple Combinator Attribute
class elements
selectors selectors selectors
selectors selectors

select elements select elements


select elements based on a select elements select and style
based on an
based on name, specific based on a a part of an
relationship attribute or
id, class certain state element
between them attribute value

Simple Selectors
• Universal Selector (*)
• selects all HTML elements on the page
• Element Selector
• selects HTML elements based on the element name
• Grouping Selector
• selects all the HTML elements with the same style definitions
• ID Selector
• uses the id attribute of an HTML element to select a specific element
• CLASS Selector
• selects HTML elements with a specific class attribute
Example
ID Selector
● To define styling for specific element in the web page, first we need to define an identity to the element
using ID attribute
● Use #idname while defining styling for the element inside <style></style> tag
Class Selector:
● To define styling for group of elements in the web page, first we need to classify them CLASS attribute
● Use .idname while defining styling for the group of elements inside <style></style> tag

OUTPUT:

You might also like