WT Notes UNIT 1and 2
WT Notes UNIT 1and 2
WT Notes UNIT 1and 2
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.
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.
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.
The bitwise & operator always checks both conditions whether first condition is true or false.
if-else statement
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
Example:
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
}
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.
1. arrayRefVar=new datatype[size];
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.
System.out.println(min);
}
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.
Method Description
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);
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(){
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
Example:-
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static 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
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. }
Syntax
// 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();
// 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;
}
class GFG {
public static void main(String[] args)
{
Product obj = new Product();
// 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();
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.
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.
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();
}
}
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 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.
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.
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 :
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.
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class one {
System.out.println("Geeks");
// Driver class
public class Main {
// Main function
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.
class one {
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
class A {
class B extends A {
class C extends A {
class D extends A {
public void print_D() { System.out.println("Class D"); }
// Driver Class
obj_B.print_A();
obj_B.print_B();
obj_C.print_A();
obj_C.print_C();
obj_D.print_A();
obj_D.print_D();
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. }
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
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.
//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.
//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();
}
}
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
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);
}*/
}
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();
}
}
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
• int a=50/0;//ArithmeticException
• String s=null;
System.out.println(s.length());//NullPointerException
• String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
Java try-catch/try-finally
1. Uncaught Exception
Class ExceptionExample{
Public static void main(String args[]){
Int d=0;
Int a=42;
System.out.println(a/d);
}
}
Output:
A[42]=28;
System.out.println(a/d);
}
Catch(ArithmeticException e){
System.out.println(“Division by Zero”);
}
Catch(ArrayIndexOutOfBoundsException e){
System.out.println(“ArrayIndexOutOfBoundsException”);
}
}
}
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 };
Throw
The general form of throw is shown here:
throw ThrowableInstance;
try{
throw new NullPointerException(“Demo”);
}
Catch(NullPointerException e){
System.out.println(“Inside Demo”);
Throw e;
}
}
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.
}
finally{
System.out.println("procC's finally");
}
}
Questions
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.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Multitasking
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.
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
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.
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().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs the following tasks:
FileName: Multi.java
Output:
thread is running...
FileName: Multi3.java
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.
FileName: MyThread1.java
Output:
My first thread
FileName: MyThread2.java
Output:
My new thread
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
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.
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.
1. By html file.
2. By appletViewer tool (for testing purpose).
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>
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. */
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.*;
int x,y,z;
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);
}
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
Container
The container is a component that contains other components like button, textfield, label, etc.
However, it is a subclass of the Component class.
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
1. C:\Users\Anurati\Desktop\abcDemo>java ButtonExample
Output:
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:
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.
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:
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.
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));
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
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
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:
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
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. component.addActionListener(instanceOfListenerclass);
Output:
Button b1;
TextField t1;
Label lb1, lb3;
Frame f;
Test() {
f = new Frame("Area of a circle");
t1 = new TextField();
t1.setBounds(200, 50, 150, 30);
f.add(t1);
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;
Output:
Output:
itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component.
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 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
KeyListenerExample.java
Output:
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.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
AdapterExample.java
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
Output:
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
•
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.
Web Standards
• HTML - Hypertext Markup Language
• XML 1.0 - Extensible Markup Language
• XHTML - Extensible Hypertext Markup Language
• CSS - Cascading Style Sheets
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 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>
• 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
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>
Example:
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
<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>
<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>
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="radio"> Defines a radio button (for selecting one of many choices)
</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
● 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:
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
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: