You are on page 1of 220

Department of Computer Science and Engineering

Course Code: KCS-602


Course Name: Web Technology
Faculty Name: Anuj Gupta
Email: anuj.gupta_acse@glbitm.ac.in
Department of Computer Science and Engineering
Vision

To be an institute of repute, providing globally competent and socially sensitive


professionals.

Mission

M1 : To equip with the latest technologies to be globally competitive professionals.


M2 : To inculcate qualities of leadership, professionalism, corporate understanding
and executive competence.
M3 : To imbibe and enhance human values, ethics and morals in our students.

Subject: Web Technology


Course Outcome

Subject:Web
Subject: WebTechnology
Technology
Syllabus
Unit-1
Introduction: Introduction and Web Development Strategies, History of Web and Internet, Protocols Governing Web, Writing Web Projects, Connecting to
Internet, Introduction to Internet services and tools, Introduction to client-server computing. Core Java: Introduction, Operator, Data type, Variable, Arrays,
Methods & Classes, Inheritance, Package and Interface, Exception Handling, Multithread programming, I/O, Java Applet, String handling, Event handling,
Introduction to AWT, AWT controls, Layout managers

Unit-2
Web Page Designing: HTML: List, Table, Images, Frames, forms, CSS, Document type definition, XML: DTD, XML schemes, Object Models, presenting and
using XML, Using XML Processors: DOM and SAX, Dynamic HTML

Unit-3
Scripting: Java script: Introduction, documents, forms, statements, functions, objects; introduction to AJAX, Networking : Internet Addressing,
InetAddress, Factory Methods, Instance Methods, TCP/IP Client Sockets, URL, URL Connection, TCP/IP Server Sockets, Datagram.

Unit-4
Enterprise Java Bean: Preparing a Class to be a JavaBeans, Creating a JavaBeans, JavaBeans Properties, Types of beans, Stateful Session bean, Stateless
Session bean, Entity bean
Java Database Connectivity (JDBC): Merging Data from Multiple Tables: Joining, Manipulating, Databases with JDBC, Prepared Statements,
Transaction Processing, Stored Procedures.

Unit-5
Servlets: Servlet Overview and Architecture, Interface Servlet and the Servlet Life Cycle, Handling HTTP get Requests, Handling HTTP post
Requests, Redirecting Requests to Other Resources, Session Tracking, Cookies, Session Tracking with Http Session
Java Server Pages (JSP): Introduction, Java Server Pages Overview, A First Java Server Page Example, Implicit Objects, Scripting, Standard Actions,
Directives, Custom Tag Libraries..

Subject:Web
Subject: WebTechnology
Technology
Web Development Strategies
Web development strategies refer to the approaches and plans that developers use to design, build, and
maintain websites or web applications. These strategies encompass various aspects of the development
process, including project planning, design, coding, testing, deployment, and ongoing maintenance.

Here are some key strategies commonly employed in web development:


1. Requirement Analysis 9. Performance Optimization
2. Project Planning 10. Version Control
3. Technology Stack Selection 11. Continuous Integration and
4. Responsive Design Deployment (CI/CD)
5. User Experience (UX) and User Interface (UI) Design 12. Documentation:
6. Scalability 13. Feedback and Iteration:
7. Security Measures 14. Regular Maintenance:
8. Testing 15. Community and Collaboration:

Subject: Web Technology


Web Development Strategies
Web development strategies refer to the approaches and plans that developers use to design, build, and
maintain websites or web applications. These strategies encompass various aspects of the development
process, including project planning, design, coding, testing, deployment, and ongoing maintenance.
Here are some key strategies commonly employed in web development:
1. Requirement Analysis:
• Understand the project requirements thoroughly before starting development.
• Gather information about the target audience, goals, and features.
2. Project Planning:
• Develop a detailed project plan outlining tasks, timelines, and resources.
• Break down the project into smaller milestones for better management.
3. Technology Stack Selection:
• Choose appropriate programming languages, frameworks, libraries, and tools based on project
requirements.
4. Responsive Design:
• Implement responsive web design to ensure the website works well on various devices and screen
sizes.

Subject: Web Technology


Web Development Strategies
5. User Experience (UX) and User Interface (UI) Design:
• Focus on creating an intuitive and visually appealing user interface.
• Prioritize user experience to enhance usability and satisfaction.
6. Scalability:
• Design the system architecture to be scalable, allowing for future growth in terms of users, features,
and data.
7. Security Measures:
• Implement security best practices to protect against common web vulnerabilities.
• Regularly update and patch software to address potential security risks.
8. Testing:
• Conduct thorough testing, including unit testing, integration testing, and user acceptance testing, to
identify and fix issues before deployment.
9. Performance Optimization:
• Optimize code, images, and other assets for improved website performance.
• Consider techniques such as caching and content delivery networks (CDNs).
10. Version Control:
Use version control systems (e.g., Git) to track changes and collaborate with other developers.

Subject: Web Technology


Web Development Strategies
11. Continuous Integration and Deployment (CI/CD):
• Set up CI/CD pipelines to automate testing and deployment processes, ensuring a smoother
development workflow.
12. Documentation:
• Maintain comprehensive documentation for the codebase, APIs, and system architecture to facilitate
future development and maintenance.
13. Feedback and Iteration:
• Gather feedback from stakeholders and end-users and incorporate it into the development process.
• Be prepared to iterate and make improvements based on feedback and changing requirements.
14. Regular Maintenance:
• Plan for ongoing maintenance tasks, including updates, bug fixes, and feature enhancements.
15. Community and Collaboration:
• Engage with the development community, share knowledge, and leverage open-source resources
when applicable.

These strategies may vary depending on the specific goals, scale, and nature of the web development project.
Adaptability and a focus on continuous improvement are crucial for successful web development.

Subject: Web Technology


The Internet

• Internet is a network of interconnected computers.


• It is the largest network of networks in the world.
• It uses TCP/IP protocols and packet switching .
• Every computer in internet is identified by a unique IP address.
• IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a
computer location.
• A special computer DNS (Domain Name Server) is used to give name to the IP
Address so that user can locate a computer by a name.
• Internet is accessible to every user all over the world.

Subject: Web Technology


History of the Internet
How did the Internet originate?

ARPANET
Networking project by
Pentagon’s Advanced
Research Projects
Goal: Agency (ARPA) Goal:
To allow scientists at To function if
different locations to part of network
share information were disabled

Became
functional
September 1969

Subject:
p. 69
Web Technology
History of internet
• 1968 - DARPA (Defense Advanced Research Projects Agency) of United States contracts with BBN
(Bolt, Beranek & Newman) to create ARPAnet
• ARPANET (Advanced Research Project Agency Network): Basic purpose of ARPANET was to
provide communication among the various bodies of government.
• 1970 - Initially, there were only five nodes, formally called Hosts.
• UCLA
• Stanford
• UC Santa Barbara
• U of Utah, and
• BBN
• 1972, the ARPANET spread over the globe with 23 nodes located at different countries and thus
became known as Internet.
• By the time, with invention of new technologies such as TCP/IP protocols, DNS, WWW, browsers,
scripting languages etc., Internet provided a medium to publish and access
information over the web.

Subject: Web Technology


History of the Internet

Who controls the Internet?


No one — it is a public, cooperative, and independent network
c c

Several organizations set standards

World Wide Web Consortium (W3C)


▪ Oversees research, sets standards and guidelines
▪ Mission is to contribute to the growth of the Web
▪ Nearly 400 organizations around the world are members of the W3C

Subject: Web Technology


History of web
History of WWW:
Sir Tim Berners Lee is known as father of www. He was physicist at European organization for Nuclear
Research, that is CERN.
• In early 1989, he proposed the web as a way for scientist around the world to collaborate using a global
information system based on hypertext.
• In the fall of 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 standard generalized mark-up language. To transfer document to remote
sites a new protocol was devised called HTTP.
• In the fall of 1991, conference goes around the world. People outside of the CERN were invited to join
this web community.
• 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.
• In 1994 Tim Berner Lee moved from CERN to MIT(Massachusetts institute of Technology)

Subject: Web Technology


How the Internet Works

Subject: Web Technology


How the Internet Works
1. When you turn on your computer and type a domain name in the browser search bar, your browser sends a request
to the DNS server to get the corresponding IP address. After getting the IP address, the browser forwards the
request to the respective server.
2. Once the server gets the request to provide information about a particular website, the data starts flowing. The
data is transferred through the optical fibre cables in digital format or in the form of light pulses. As the servers are
placed at distant places, the data may have to travel thousands of miles through optical fiber cable to reach your
computer.
3. The optical fiber is connected to a router, which converts the light signals into electrical signals. These electrical
signals are transmitted to your laptop using an Ethernet cable. Thus, you receive the desired information through
the internet, which is actually a cable that connects you with the server.
4. Furthermore, if you are using wireless internet using wifi or mobile data, the signals from the optical cable are first
sent to a cell tower and from where it reaches to your cell phone in the form of electromagnetic waves.
5. The internet is managed by ICANN (Internet Corporation for Assigned Names and Numbers) located in the USA. It
manages IP addresses assignment, domain name registration, etc.
6. The data transfer is very fast on the internet. The moment you press enter you get the information from a server
located thousands of miles away from you. The reason for this speed is that the data is sent in the binary form (0,
1), and these zeros and ones are divided into small pieces called packets, which can be sent at high speed.

Subject: Web Technology


How the Internet Works
How can you connect to the Internet?

Slow-speed High-speed
technology connection

Dial-up access modem in


DSL, cable modem,
your computer uses a
FTTP, fixed wireless, wireless modem,
standard telephone line
to connect to the Internet Wi-Fi, and satellite modems

Connection must be established each Connection is always on—


time you log on. whenever the computer is running

Subject:
p. 70
Web Technology Next
The World Wide Web
What is a Web browser?
Program that allows you to view Web pages

Internet Firefox Netscape


Explorer

Opera Safari

Subject: Web Technology


The World Wide Web

Subject: Web Technology


DNS

What is a domain name?


Text version of Internet protocol (IP)
address
▪ Number that uniquely identifies each
computer or device connected to Internet

Subject: Web Technology


The World Wide Web
What is a URL?

Unique address for a Web page


A web server delivers the Web page
to your computer

Subject: Web Technology


THE OSI MODEL
Established in 1947, the International Standards Organization (ISO) is a multinational
body dedicated to worldwide agreement on international standards.

Almost three-fourths of countries in the world are represented in the ISO.

An ISO standard that covers all aspects of network communications is the Open Systems
Interconnection (OSI) model. It was first introduced in the late 1970s.

Subject: Web Technology


THE OSI MODEL

Subject: Web Technology


Summary of layers

Subject: Web Technology


TCP/IP & its protocol…

Subject: Web Technology


TCP/IP and OSI model

25
Subject: Web Technology
Protocol Governing Web
Protocol is a set of rules that used to communicate application to each other. OR a protocol is a interface
required for communicating the different application.
Few protocols are discussed bellow:
a. HTTP
b. ICMP
c. TCP/IP
d. UDP
e. FTP
f. SMTP
HTTP:
❑ HTTP stands for HyperText Transfer Protocol.
❑ HTTP is the primary protocol used to distribute information on the web. It
is a protocol used to access the data on the World Wide Web (www).
❑ The HTTP protocol can be used to transfer the data in the form of plain text, hypertext, audio, video,
and so on.
❑ HTTP functions as a request response protocol in the client server computing model.

Subject: Web Technology


Protocol Governing Web
This protocol is known as Hypertext Transfer Protocol because of its efficiency that allows us to use in a
hypertext environment where there are rapid jumps from one document to another document.

ICMP:(Internet control message protocol)


The internet control message protocol is one of the main protocol of the internet protocol suit.
It is used by networked devices like routers to send an error message the requested service is not available
or the host or router could not be reached.

TCP
▪It is a transport layer protocol.
▪TCP stands for Transmission control protocol.
▪It is one of the main protocol in TCP/IP network where IP protocol deals with packet.
▪TCP enables two hosts to establish a connection and exchange streams of data.
▪ TCP guarantees delivery of data and also guarantee that packet will be delivered in the same order in
which they were sent.
▪TCP is connection oriented and reliable transport layer protocol.

Subject: Web Technology


Protocol Governing Web
UDP
• UDP(User datagram Protocol) is connectionless and unreliable protocol.
• It is simple unreliable transport layer protocol.
• It perform limited error checking.
• If UDP is so powerless , why would a process want to use it ?
• Answer is that , UDP is simple protocol with minimum overhead, if a process wants to send a small
message and does not much care about reliability, it can use UDP.

FTP
• FTP stands for File transfer protocol.
• FTP is a standard internet protocol provided by TCP/IP used for transmitting the files from one host to
• another.
• It is also used for downloading the files to computer from other servers
Objective of FTP
• It provides the sharing of files.
• It is used to encourage the use of remote computers.
• It transfers the data more reliably and efficiently.

Subject: Web Technology


Protocol Governing Web
SMTP
SMTP stands for Simple Mail Transfer Protocol.

SMTP is a set of communication guidelines that allow software to transmit an electronic mail over the
internet is called Simple Mail Transfer Protocol.

It is a program used for sending messages to other computer users based on e-mail addresses

Subject: Web Technology


Internet Services
Internet Services allows us to access huge amount of information such as
text, graphics, sound and software over the internet.

Four different categories of Internet Services-

Subject: Web Technology


Internet Services
Communication Services
There are various Communication Services available that offer exchange of information with individuals or groups.
The following table gives a brief introduction to these services:
S.N. Service Description
1 Electronic Mail: Used to send electronic message over the internet.

2 Telnet : Used to log on to a remote computer that is attached to internet.

3 Newsgroup : Offers a forum for people to discuss topics of common interests.

4 Internet Relay Chat (IRC) : Allows the people from all over the world to communicate in real time.

5 Mailing Lists : Used to organize group of internet users to share common information through e-mail.

6 Internet Telephony (VoIP) : Allows the internet users to talk across internet to any PC equipped to receive the call.

7 Instant Messaging : Offers real time chat between individuals and group of people. Eg. Yahoo messenger, MSN messenger.

Subject: Web Technology


Internet Services
Information Retrieval Services
There exist several Information retrieval services offering easy access to information present on the internet. The
following table gives a brief introduction to these services:

S.N. Service Description

1 File Transfer Protocol (FTP) : Enable the users to transfer files.

2 Archie : It’s updated database of public FTP sites and their content. It helps to search a file by its name.

3 Gopher : Used to search, retrieve, and display documents on remote sites.

Very Easy Rodent Oriented Netwide Index to Computer Achieved (VERONICA) :


4
VERONICA is gopher based resource. It allows access to the information resource stored on gopher’s servers.

Subject: Web Technology


Internet Services
Web Services
• Web services allow exchange of information between applications on the web. Using web services,
applications can easily interact with each other.
• The web services are offered using concept of Utility Computing.
• A Web Service is, any service that −
Is available over the Internet or private (intranet) networks
Uses a standardized XML messaging system
Is not tied to any one operating system or programming language
Is self-describing via a common XML grammar
Is discoverable via a simple find mechanism

World Wide Web (WWW)


• WWW is also known as W3.
• It offers a way to access documents spread over the several servers over the internet. These documents
may contain texts, graphics, audio, video, hyperlinks.
• The hyperlinks allow the users to navigate between the documents.

Subject: Web Technology


Other Internet Services

What is e-mail?
Short for electronic mail
The transmission of messages and files via a computer network
▪ Messages can consist of simple text or can contain attachments, such as documents,
graphics, or audio/video clips
▪ Internet access providers usually provide an e-mail program
▪ Some Web sites—such as Google Gmail, Windows Live Hotmail,
and Yahoo! Mail—provide free e-mail services
One of the original services on the Internet

Subject: Web Technology


Other Internet Services

What is an e-mail address?


Unique name that consists of a user name and domain name that
identifies the user

Subject:
p. 94 Fig. 2-27
Web Technology
Other Internet Services
How does an e-mail message travel?
Step 1. Using
e-mail software,
you create and send
message

Step 2.
Your software
contacts software on
your service Step 4.
provider’s outgoing When recipient uses
mail server e-mail software to check for
e-mail messages, the message
transfers from incoming mail
server to recipient’s computer

Step 3.
Software on outgoing mail server determines best route
for data and sends message, which travels along
Internet routers to recipient’s incoming mail server

Subject: Web Technology


Other Internet Services
What is instant messaging (IM)?
A real-time Internet communications service that notifies you when one or more people are online
and allows you to exchange messages or files

Subject: Web Technology


Other Internet Services

What is a chat?
Real-time typed conversation that takes
place on a computer
Chat room is location on server that
permits users to discuss topics of
interest

Subject: Web Technology


Other Internet Services

What is VoIP (Voice over IP)?


Enables users to speak to other users over the Internet

Subject: Web Technology


Other Internet Services
What is FTP?
File Transfer Protocol—Internet standard that allows you to upload and
download files with other computers on the Internet

Subject: Web Technology


Web Development Process

Subject: Web Technology


Client Server Computing
In the client-server architecture, when the client computer sends a request for data to the server through
the internet, the server accepts the requested process and delivers the data packets requested back to the
client. Clients do not share any of their resources.
Examples of Client-Server Model are Email, World Wide Web, etc.

How the Client-Server Model works?


Client: When we talk the word Client, it mean to talk of a person
or an organization using a particular service. Similarly in the digital
world a Client is a computer (Host) i.e. capable of receiving
information or using a particular service from the service
providers (Servers).
Servers: Similarly, when we talk the word Servers, It means a
person or medium that serves something. Similarly in this digital
world a Server is a remote computer which provides information
(data) or access to particular services.
So, it’s basically the Client requesting something and
the Server serving it as long as its present in the database.

Subject: Web Technology


Client Server Computing

Subject: Web Technology


Browser interacts with the servers
When Client sends HTML page request to
Tomcat Apache Server…

Subject: Web Technology


Browser interacts with the servers
When Client sends JSP page request to
Tomcat Apache Server…

Subject: Web Technology


Types of Client Server Computing

Subject: Web Technology


Types of Client Server Computing

Subject: Web Technology


Client Server Computing Vs Peer to Peer Computing

Difference between Client Server Computing and Peer to Peer Computing

• In client server computing, a server is a central node that services many client nodes.
On the other hand, in a peer to peer system, the nodes collectively use their resources
and communicate with each other.
• In client server computing the server is the one that communicates with the other
nodes. In peer to peer to computing, all the nodes are equal and share data with each
other directly.
• Client Server computing is believed to be a subcategory of the peer to peer computing

Subject: Web Technology


Client Server Computing Vs Peer to Peer Computing
Advantages of Client-Server model:
• Centralized system with all data in a single place.
• Cost efficient requires less maintenance cost and Data recovery is possible.
• The capacity of the Client and Servers can be changed separately.
• 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 model:


• Clients are prone to viruses, Trojans and worms if present in the Server or uploaded into the Server.
• Server is prone to Denial of Service (DOS) attacks.
• If all the clients simultaneously request data from the server, it may get overloaded. This may lead to congestion in the
network.
• Data packets may be spoofed or modified during transmission.
• Phishing or capturing login credentials or other useful information of the user are common and MITM (Man in the
Middle) attacks are common.

Subject: Web Technology


Writing Web Projects
Writing Web Projects:
Developing web project is a crucial activity and web project development differs from traditional web
projects
Phases of writing the web projects are
A. Write a project mission statement
The mission statement desribes the solution to the problem that your project is going to solve.
• What are you going to do?
• To whom we are doing it?
• How do we go about it?
B. Identify Objectives
i. Specific
ii. Measurable
iii. Attainable
iv. Realistic
v. Time limited

Subject: Web Technology


Writing Web Projects
C. Identify Target User:
The matter of a website will be determined by theusers whom you want to visit the site.
This is totally depend upon
i. Market research
ii. Focus group
iii. Understanding the audiences
D. Determine the scope: The scope of the project can change quickly.
E. Budget:
i. Assumption for budgets.
ii. Budget categories.
iii. Determine hidden costs and tools.
F. Planning issues:
Discuss client’s existing information system.
i. Project team and developing infrastructure.
ii. Where the website will place.

Subject: Web Technology


Writing Web Projects
Web Project Traditional Project
Web projects consists of an attractive Graphical User Graphical User Interface of traditional project is not good-looking as
Interface. compared to web project.
Functionality of web project is public oriented. While functionality of traditional project is defined to an organization.
New technologies such as beta technologies are used for
It is not applicable in traditional projects, mature technologies are used
providing new and cool features that client and web
in developing traditional projects.
developers wants to use.
There is no predefined standards available for web projects. Standards do exist for traditional projects that ensure quality.
Web projects are globally usable hence less secured as
Traditional projects are more secure than web projects.
compared to traditional projects.
A pricing model exists for traditional project. Various type of models
A pricing model for web project does not exist.
such as COCOMO are developed for costing.
Roles of the team members of web project are less
Team roles in traditional project are more specialized.
specialized.
After finalization of the web project, websites are alive, can
After completion, changes are not frequent in traditional project.
be changed and grow.
Cost incurred in the web project during the development of Clients takes all the expenses related to project such as cost involved
web project is not given by the clients. in designing, testing, prototyping, etc.
Project manager in web project has the full responsibility of In traditional projects, various managers at different levels have the
project. responsibility of project development.

Subject: Web Technology


JAVA Introduction

Phases:
• There are three execution phases of a program. These are written, compile and run.
• Writing a program is done by a java programmer like you and me.
• The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java
development kit (JDK). It takes Java program as input and generates bytecode as output.
• In the Run phase of a program, JVM executes the bytecode generated by the compiler.

Subject: Web Technology


JAVA Introduction

Subject: Web Technology


JAVA Terminology
1. Java Virtual Machine(JVM): We can understand that the function of Java Virtual Machine is
to execute the bytecode produced by the compiler. Every Operating System has a different
JVM but the output they produce after the execution of byte-code is the same across all the
operating systems.

2. Bytecode in the Development process: As discussed, the Javac compiler of JDK compiles the
java source code into bytecode so that it can be executed by JVM. It is saved as .class file by
the compiler.

3. Java Development Kit (JDK): As the name suggests, it is a complete Java Development Kit
that includes everything including compiler, Java Runtime Environment (JRE), java
debuggers, java docs, etc. For the program to execute in java, we need to install JDK on
our computer in order to create, compile and run the java program.

4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows
the java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet
supports, and plugins. For running the java program, a computer needs JRE.

Subject: Web Technology


JAVA Features

Subject: Web Technology


JAVA Features

Subject: Web Technology


JAVA Features

Subject: Web Technology


JAVA Features

Subject: Web Technology


JAVA Features

Subject: Web Technology


JAVA Features

Subject: Web Technology


C++ Vs
Comparison Index JAVA C++ Java
Platform-independe C++ is platform-dependent. Java is platform-independent.
nt
C++ is mainly used for system programming. Java is mainly used for application programming. It is widely used in
Mainly used for
window, web-based, enterprise and mobile applications.
C++ was designed for systems and applications It was designed with a goal of being easy to use and accessible to a
Design Goal programming. It was an extension of C programming broader audience.
language.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
C++ supports multiple inheritance. Java doesn't support multiple inheritance through class.
Multiple inheritance
It can be achieved by interfaces in java.
Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
C++ supports pointers. You can write pointer program Java supports pointer internally. However, you can't write the pointer
Pointers
in C++. program in java. It means java has restricted pointer support in java.
C++ uses compiler only. C++ is compiled and run using Java uses compiler and interpreter both. Java source code is
Compiler and the compiler which converts source code into machine converted into bytecode at compilation time. The interpreter
Interpreter code so, C++ is platform dependent. executes this bytecode at runtime and produces output. Java is
interpreted that is why it is platform independent.

Subject: Web Technology


JAVA Introduction
Comparison Index C++ Java
Call by Value and C++ supports both call by value and call by reference. Java supports call by value only. There is no call by reference in java.
Call by reference
Structure and Union C++ supports structures and unions. Java doesn't support structures and unions.
C++ doesn't have built-in support for threads. It relies Java has built-in thread support.
Thread Support
on third-party libraries for thread support.
Virtual Keyword C++ supports virtual keyword so that we can Java has no virtual keyword. We can override all non-static
decide whether or not override a function. methods by default. In other words, non-static methods are virtual
by default.
Inheritance Tree C++ creates a new inheritance tree always. Java uses a single inheritance tree always because all classes are
the child of Object class in java. The object class is the root of
the inheritance tree in java.
Object-oriented C++ is an object-oriented language. However, in C Java is also an object-oriented language. However, everything
language, single root hierarchy is not possible. (except fundamental types) is an object in Java. It is a single root
hierarchy as everything gets derived from java.lang.Object.

Subject: Web Technology


Basic Syntax

Subject: Web Technology


JAVA Identifiers

Subject: Web Technology


JAVA Syntax

Subject: Web Technology


First JAVA Program

Subject: Web Technology


First JAVA Program

Subject: Web Technology


Installing
JAVA

Subject: Web Technology


Installing
JAVA

Subject: Web Technology


Installing JAVA- set JAVA_HOME & Path

Subject: Web Technology


Installing JAVA- set JAVA_HOME & Path

Subject: Web Technology


Installing JAVA- set JAVA_HOME & Path

Subject: Web Technology


Installing JAVA- set JAVA_HOME & Path

Subject: Web Technology


Installing JAVA- set JAVA_HOME & Path

Subject: Web Technology


Data Types

Data Types in Java

Subject: Web Technology


Data Types

Subject: Web Technology


Data Types
Primitive Data Types
Primitive data types are predefined by the language and named by a keyword. There are eight primitive
data types supported by Java.
– byte
– short
– int
– long
– Float
– Double
– Boolean
– character

Subject: Web Technology


Data Types

Subject: Web Technology


Data Types
Non-Primitive / Reference Data Types
Reference variables are created using defined constructors of the classes.
They are used to access objects.
It is declared to be of a specific type that cannot be changed.
Class objects and various types of array variables come under reference data type.
The default value of any reference variable is null.
- Strings
- Class
- Arrays
- Interference

Subject: Web Technology


Operators in Java

Subject: Web Technology


Operator 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:
• Unary Operator - ++, --, ~,!
• Arithmetic Operator - >, +,-,%,/,*
• Shift Operator - <<,>>
• Relational Operator - <,>,<=,>=,==
• Bitwise Operator – bitwise OR(|): The bitwise | operator always checks both conditions whether the
first condition is true or false. Bitwise AND(&): The bitwise & operator always checks both conditions
whether the first condition is true or false.
• Logical Operator - &&(AND) 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, ||(OR) operator doesn’t check the second if the
first condition is true. It checks the second condition only if the first one is false.

Subject: Web Technology


Operator in Java
• Ternary Operator - Java Ternary operator is used as one line replacement for if-then-else
statements and is used a lot in Java programming. It is the only conditional operator which takes three
operands. (a:b)
• Assignment Operator - Java assignment operator is one of the most common operators. It is used
to assign the value on its right to the operand on its left. (=)
Examples of operator:-
public class OperatorExample{
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
Subject: Web Technology
Access Modifiers
▪ In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member.
▪ It provides security, accessibility, etc to the user depending upon the access modifier used with the
element.
▪ 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.

Subject: Web Technology


Access Modifiers

Subject: Web Technology


Keywords in Java

Subject: Web Technology


Keywords
Java keywords are also known as reserved words.
Keywords are particular words that act as a key to a code.
These are predefined words by Java, so they cannot be used as a variable, object name, or class name.
Some keywords are:-
▪ Abstract,
▪ Int,
▪ Break,
▪ byte,
▪ Class,
▪ Continue,
▪ Catch,
▪ Char,
▪ Else,
▪ If,
▪ Do, For, While, etc.

Subject: Web Technology


Variables in Java

Subject: Web Technology


Variable in Java
Variable is a data container that saves the data values during Java program execution.
Every variable is assigned a data type that designates the type and quantity of value it can hold.
A variable is a memory location name for the data.

How to declare variables?

Name- Name given to the variable.


Type- Type of data that can be stored in this variable.
Value- It is the initial value stored in the variable.

Subject: Web Technology


Variable in
Java(Cont.….)
A variable is the name of a reserved area allocated in memory. Its value can be changed.
Syntax: datatype variable_name

There are three types of variables in java


i. Local Variable
ii. Instance Variable
iii. Static Variable

• Local Variable:
A variable declared inside the body of the method is called a local variable.
Syntax: method() {
datatype variableName; // Local Variable
}

Subject: Web Technology


Variable in
Static Variable: Java(Cont.….)
A variable that is declared as static is called a static variable. Here “static” keywords is used to
declare a static variable.
Syntax: static datatype variableName; // Static variable

Instance Variable:
• A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared static.
• It is called an instance variable because its value is instance-specific and is not shared among
instances.
• Every instance has its own copy of the instance variable.
• Syntax: class {
datatype variablename; // instance variable
}

Subject: Web Technology


Variable in
Java(Cont.….)
Rules to Declare in Java:-
• A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and
two special characters such as _ underscore and $ dollar sign.
• The first character must not be a digit.
• Blank spaces cannot be used in variable names.
• Java keywords cannot be used as variable names.
• Variable names are case-sensitive.
• There is no limit on the length of a variable name but by convention, it should be
between 4 to 15 chars.
• Variable names always should exist on the left-hand side of assignment operators.

Subject: Web Technology


Variable in
Java(Cont.….)
// Example of
Variable class ABC
{
public static void main(String[] args)
{
// Declaring all the
// possible combinations of
// variable format
int _a = 10;
int $b = 20;
int C = 30;
int c = 40;

int result = _a + $b + C + c;
System.out.println("Result: " + result);
}
} //Output - 100

Subject: Web Technology


Comments in Java
Comments
Comments are descriptions of the aim and features of the program Comments. Increase the readability of
a program.

Three types of comments are there in Java:


• Single line comments: These comments start with //
Ex: // this is the comment line
• Multi-line comments: These comments start with /* and end with */
Ex: /* This is comment line*/
• Java documentation comments: These comments start with /** and end with */

These comments are useful to create an HTML file called API (application programming Interface) document.
This file contains a description of all the features of the software.

Subject: Web Technology


OOPs Concept

Subject: Web Technology


Class
Class
• Collection of objects is called class.
• It is a logical entity. It can't be physical.
• A class is a group of objects which have common
properties.
• A class can also be defined as a blueprint from which you
can create an individual object.
• Class doesn't consume any space.

A class in Java can contain:


o Fields
o Methods Syntax to declare a class:
o Constructors AccessModifier class class_name
o Blocks {
o Nested class and interface method;
constructor;
field;
}

Subject: Web Technology


Object
Object
• Object means a real-world entity such as a pen, chair,
table, computer, watch, etc.
• Any entity that has state and behaviour is known as an
object.
• It can be physical or logical.
• An Object can be defined as an instance of a class.
• An object contains an address and takes up some space in
memory.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail,
barking, eating, etc.
In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −


• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
❑ New keyword in Java: The new keyword is used to allocate memory at runtime. All objects get memory in
Heap memory area.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Subject: Web Technology


Control Structure in Java

Subject: Web Technology


Control Structure in
Java
• The execution of a block of code based on a condition is known as a control structure.
// Here, Structures means a block of code
<<Condition>>
{

}
• In general, program execution starts with a main() method, and line-by-line execution of the program
tokens places a linear/Sequential flow of Execution.
PSV main()
{
line1 // Linear Sequential flow of
execution 2
}

Subject: Web Technology


Control Structure in
Java
• The execution of a block of code based on a condition is known as a control structure.
// Here, Structures means a block of code
<<Condition>>
{

}
• In general, program execution starts with a main() method, and line-by-line execution of the program
tokens places a linear/Sequential flow of Execution.
PSV main()
{
line1 // Linear Sequential flow of
execution 2
}

Subject: Web Technology


Arrays in Java

Subject: Web Technology


Java
Arrays
• An array is a collection of similar type of elements which has a contiguous memory location.
• Java array is an object which contains elements of a similar data type.
• Array in java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on the 1st index, and so on.
• Types of Arrays in Java:
a) Single Dimensional Array
b) Multidimensional Array

Subject: Web Technology


Java Arrays(Cont…)
A. Single-Dimensional Array in Java: This is the array in which rows are fixed but columns vary.
• Syntax to declare an array in java:
i. Datatype[] arrayName;
ii. Datatype []arrayName;
iii. Datatype arrayName[];
A. Multidimensional Array in Java: Data is stored in row and columns based index(also known as matrix
form).
• Syntax to Declare multidimensional array in java
iv. Datatype[][] arrayName;
v. Datatype [][]arrayName;
vi. Datatype arrayName[][];

Subject: Web Technology


Java Arrays(Cont.…)
Single-Dimensional Arrays:
A one-dimensional array or single-dimensional array represents a row or a column of elements.
For example, the marks obtained by a student in 5 different subjects can be represented by a 1D array We
can declare a one-dimensional array and directly store elements at the time of its declaration, as:
int marks[] = {50, 60, 55, 67, 70};
We can create a 1D array by declaring the array first and then allocate memory for it by using a new
operator, as:
int marks[]; //declare marks array
marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as:
int marks [] = new int [5];

Subject: Web Technology


Java Arrays(Cont.…)
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]);
}
}

Subject: Web Technology


Classes & Object in Java

Subject: Web Technology


Class in Java
• A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
• Class is a collection of objects and it doesn’t takeany space in memory, class
is also called a
blueprint/logical.
• A class is a group of similar objects.
• A class can only be declared once. Class is not a real-world entity.
• It is just a template or blueprint or prototype.
• A class can contain any of the following variable types.
• Local variables − Variables defined inside methods, constructors, or blocks are called local variables. The
variable will be declared and initialized within the method and the variable will be destroyed when the
method has been completed.

Subject: Web Technology


Class in
Java(Cont.…)
• Instance variables − Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be accessed from inside any
method, constructor, or block of that particular class.
• Class variables − Class variables are variables declared within a class, outside any method, with the static
keyword.
• A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry(), and sleeping() are methods.

Subject: Web Technology


Class in
Java(Cont.…)
Examples of Class
Syntax to declare a class: class Student
{
access_modifier class<class_name> int id; // data member (also instance variable)
{ String name; // data member (also instance variable)
data member;
method; public static void main(String args[])
constructor; {
nested class; Student s1 = new Student();
interface; // creating an object for the Student
System.out.println(s1.id);
} System.out.println(s1.name);
}
}

Subject: Web Technology


Objects in
Java
• Object is an instant of class that executes the class. Once the object is created. It takes up space like
another variable in memory.
• Syntax:- ClassName ObjectName = new ClassName()
• If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All these
objects have a state and behavior.
• Class – Dogs
• Data members or objects– size, age, color, breed, etc.
• Methods– eat, sleep, sit and run.

Subject: Web Technology


Method in Java

Subject: Web Technology


Methods in
Java
• A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation.
• It is used to achieve the reusability of code.
• We write a method once and use it many times.
• We do not require to write code again and again.
• It also provides the easy modification and readability of code, just by adding or removing a chunk of
code.

Subject: Web Technology


Methods in
Java(Cont….)
Methods Declaration
The method declaration provides information about method attributes, such as visibility, return type,
name, and arguments.
• Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
• Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifiers:
• Public: The method is accessible by all classes when we use a public specifier in our application.
• Private: When we use a private access specifier, the method is accessible only in the classes in which it is
defined.
• Protected: When we use a protected access specifier, the method is accessible within the same package
or subclasses in a different package.

Subject: Web Technology


Methods in
Java(Cont….)
• Default: When we do not use any access specifier in the method declaration, Java uses the default
access specifier by default. It is visible only from the same package only.
• Return Type: The 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 the void keyword.
• 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 the
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name.
• Parameter List: It is the list of parameters separated by a comma and enclosed in a pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
• Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within a pair of curly braces.

Subject: Web Technology


Methods in
Java(Cont….)
• Naming in Method
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()

• Types of Method
There are two types of methods in Java:
• Predefined Method
• User-defined Method

Subject: Web Technology


Methods in
Java(Cont….)
• 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.
• Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
For Example:- public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}

Subject: Web Technology


Methods in
Java(Cont….)
• 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.
For Examples:- //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");
}

Subject: Web Technology


Methods in
Java(Cont….)
• There are several advantages to using methods in Java, including:
• Reusability: Methods allow you to write code once and use it many times, making your code more
modular and easier to maintain.
• Abstraction: Methods allow you to abstract away complex logic and provide a simple interface for others
to use. This makes your code more readable and easier to understand.
• Improved readability: By breaking up your code into smaller, well-named methods, you can make your
code more readable and easier to understand.
• Encapsulation: Methods allow you to encapsulate complex logic and data, making it easier to manage
and maintain.
• Separation of concerns: By using methods, you can separate different parts of your code and assign
different responsibilities to different methods, improving the structure and organization of your code.
• Improved modularity: Methods allow you to break up your code into smaller, more manageable units,
improving the modularity of your code.
• Improved testability: By breaking up your code into smaller, more manageable units, you can make it
easier to test and debug your code.
• Improved performance: By organizing your code into well-structured methods, you can improve
performance by reducing the amount of code that needs to be executed and by making it easier to cache
and optimize your code.

Subject: Web Technology


Inheritance in Java

Subject: Web Technology


Inheritance in
Java
• Inheritance is a mechanism in which one class acquires the property of another class.
• For example, a child inherits the traits of his/her parents. With inheritance, we can reuse the fields and
methods of the existing class.
• Hence, inheritance facilitates Reusability and is an important concept of OOPs.
• Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
• Sub Class/Child Class: Subclass is a class that inherits the other class. It is also called a derived class,
extended class, or child class.
• 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.
• Reusability: As the name specifies, reusability is a mechanism that 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.
Subject: Web Technology
Inheritance in
Java
• Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class.
• Why use inheritance in java?
1. For method overriding
2. For code reusability
3. For Data Abstraction
4. Inheritance allow for polymorphism

Subject: Web Technology


Inheritance in
Java(Cont.….)
• The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}

Examples of inheritance
• Here, Examples of inheritance are shown in the figure. 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.

Subject: Web Technology


Inheritance in
Java(Cont.….)
There are different types of Inheritance
• On the basis of class, there can be three types of inheritance in java:
I. Single Inheritance
II. Multilevel Inheritance
III. Hierarchical Inheritance
• In java programming, multiple and hybrid inheritances are supported through interface only. We will
learn about interfaces later.

Subject: Web Technology


Inheritance in
• Single Inheritance Java(Cont.….)
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. In the example given below, Dog class inherits the Animal class, so there
is the single inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11.d.eat();
12.}}

Subject: Web Technology


Inheritance in
• Multi-level Inheritance Java(Cont.….)
This type is an extension of single inheritance, in which the subclass acts as a base class for future
derivation.
• 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.

Subject: Web Technology


Inheritance in
• Hierarchical Inheritance Java(Cont.….)
• 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.

Subject: Web Technology


Inheritance in
• Multiple Inheritance Java(Cont.….)
• In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes. Note that Java does not support multiple inheritances with classes. In java, we can
achieve multiple inheritances only through Interfaces.

Subject: Web Technology


Inheritance in
• Hybrid Inheritance Java(Cont.….)
• It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve
hybrid inheritance only through interfaces.

Subject: Web Technology


Inheritance in
• Hybrid Inheritance Java(Cont.….)
• It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with classes. In java, we can achieve
hybrid inheritance only through interfaces.

Subject: Web Technology


Packages in Java

Subject: Web Technology


Packages in
• Packages in Java Java
• A package is a container of classes and interfaces A package represents a directory that contains a
related group of classes and interfaces.
• For example, when we write statements like:
import javaio*;
• Here we are importing classes of javaio package.
• Here, java is a directory name and io is another subdirectory within it.
• The ‘*’ represents all the classes and interfaces of that io subdirectory.
• We can create our own packages called user-defined packages or extend the available packages.
• User-defined packages can also be imported into other classes and used exactly in the same way as the
Built-in packages provide reusability.

Subject: Web Technology


Packages in
Java
• There are three ways to access packages from outside:
i. import package.*// we use the import keyword to access outside packages in the class. For example
java.util.*;
ii. import packageName.className.// specific class from the package will be imported into the class. For
examples-import java util.scanner;
iii.
Use a fully qualified Name.// It is generally used when two packages have the same class name. for
example- java.util.Date;
import
Notes:- java.util.Date;
if you import a package, all the classes and interfaces of that package will be imported excluding
the classes and interfaces of the sub-packages. Hence, it would help if you imported the subpackage as
well.

Subject: Web Technology


Packages in
Java(Cont.…)
• Project delivery using a package of client:-
i. Develop – java program
ii. Compile the program
iii. .class files
iv. All .class files are grouped together in a folder/directory known as a package.
v. This package is compared using .jar java files
vi. .jar files are delivered to clients.
• A package is a collection of java programs in compiled format(.class file) grouped together as a single
unit.
• Package in java can be categorized in two forms, 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.
• Here, we will have detailed learning of creating and using user-defined packages.

Subject: Web Technology


Packages in
Java(Cont.…)
// Java program to create a user-defined
// package and function to print
// a message for the users
• User-defined Packages
Users can create their own packages to package example;
store classifies, interfaces, etc. in the ur
// Class
system directory. Java uses a file
public class gfg {
system directory to store them. Just
like folders on ur computer. public void show()
{
How to create user-defined packages?
System.out.println("Hello geeks!! How are you?");
To create packages. Use package }
keyword.
public static void main(String args[])
Syntax: package packageName;
{
Examples >>> gfg obj = new gfg();
obj.show();
}
}

Subject: Web Technology


Packages in
Advantage of Java Package Java(Cont.…)
• Java package is used to categorize the classes and interfaces so that they can be easily maintained.
• Java package provides access protection.
• Java package removes naming collision.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

To Compile: javac -d . Simple.java


To Run: java mypack.Simple

Subject: Web Technology


Packages in
• Packages are used in Java in order to preventJava(Cont.…)
naming conflicts, to control access, An interface is implicitly
abstract.
• To make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
• Some of the existing packages in Java
– java.lang - bundles the fundamental classes
– java.io - classes for input and output functions are bundled in this package
• The package statement defines a name space in which classes are stored.
• omit the package statement, the class names are put into the default package, which has no name.

Subject: Web Technology


Packages in
Java(Cont.…)
• This is the general form of the package statement: –
package pkg;
• Here, pkg is the name of the package. • For example
– the following statement creates a package called MyPackage.
package MyPackage
• In a Java source file, import statements occur immediately following the package statement and before
any class definitions.
• This is the general form of the import statement.
Example: – import pkg1[.pkg2].(classname|*)

Subject: Web Technology


Interface in
Java

Subject: Web Technology


Interface in
Interface in Java
Java
• In the interface, all data members are by default public, static, and final members. All methods are public
methods by default.
• An interface is a reference type in Java. It is similar to a class, and a collection of abstract methods.
• A class implements an interface. thereby inheriting the abstract methods of the interface. Interface
Similar to a class.
• Why we use Java interface:
i. It is used to achieve abstraction.
ii. By interface, we can support the functionality of multiple inheritances.
iii. It can be used to achieve loose coupling

Subject: Web Technology


Interface in
Interface Syntax:
Java
Interface < interface-Name>
{
// declare constant fields
// By default
}
• An interface is similar to a class in several ways
– An interface can contain any number of methods.
– An interface is written in a file with a .java extension, with the name of the interface matching the name
of the file. The byte code of an interface appears in a .class file.
– Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that
matches the package name

Subject: Web Technology


Interface in
An interface is created with the followingJava(Cont.…)
syntax:
modifier interface interfaceID
{
//constants/method signatures
}
For examples,
interface A
{
int x, y;
void M1();
void M2();
}
Class is a collection of data members and methods. An abstract class is also a collection of data members
and at least one in-complete method. Now inheritance is also a collection of data members, and all
methods are in-complete (abstract).

Subject: Web Technology


Interface in
Interface different from a class
Java(Cont.…)
An interface is different from a class in several ways
– It cannot instantiate an interface.
– An interface does not contain any constructors.
– All of the methods in an interface are abstract.
– An interface cannot contain instance fields.
– An interface is not extended by a class; it is implemented by a class.

Subject: Web Technology


Interface in
Declaring Interface
Java(Cont.…)
• The interface keyword is used to declare an interface.
• Example
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import
statements public interface
NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Subject: Web Technology


Exception Handling in Java

Subject: Web Technology


Exception Handling in Java
• Exception Handling is a mechanism, in which run-time errors are detected, accepted & provided with a
solution.
• Exception is an error, that “may occur” when a java program is getting execution.
• In real-time, product manufacturing companies provide service centers so that any product being used
by a customer faces any problem, such problem is accepted and provided with a service center in the
form of a warranty or guarantee.
• Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s instructions.
• Exceptions can be caught and handled by the program.
• When an exception occurs within a method, it creates an object. This object is called the exception
object.
• It contains information about the exception, such as the name and description of the exception and the
state of the program when the exception occurred.

Subject: Web Technology


Exception Handling in Java(Cont.…)

Major reasons why an exception Occurs


• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
• Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of memory,
memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
• Error: An Error indicates a serious problem that a reasonable application should not try to catch.
• Exception: Exception indicates conditions that a reasonable application might try to catch.

Subject: Web Technology


Exception Handling in Java(Cont.…)

• Exception Hierarchy
Javaprovides some pre-defined
execution classes, using which
we can perform
exception-handling mechanisms
simply and easily.

Subject: Web Technology


Exception Handling in Java(Cont.…)

Subject: Web Technology


Exception Handling in Java(Cont.…)

Subject: Web Technology


Exception Handling in Java(Cont.…)
Types of Exception Handling

Subject: Web Technology


Exception Handling in Java(Cont.…)

1. Checked Exceptions are known exceptions during compilation time only. We provide the necessary
solution i.e., the java compiler tells the user that an exception may occur at a particular line in your
program, this is done during compilation time.
2. Unchecked exceptions are unknown exceptions, during compilation time these exceptions are not
shown by the java-compiler. i.e., the user or developer provides proper necessary solutions based on
exceptions that occurred during execution time.
The advantages of Exception Handling in Java are as follows:
Provision to Complete Program Execution.
Easy Identification of Program Code and Error-Handling Code
Propagation of Errors.
Meaningful Error Reporting.
Identifying Error Types

Subject: Web Technology


Exception Handling in Java(Cont.…)
• Java Exception Keywords
Keyword Description
try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by
try block which means we can't use catch block alone. It can be followed
by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It
is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
The "throws" keyword is used to declare exceptions. It specifies that there
throws may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.

Subject: Web Technology


Exception Handling in Java(Cont.…)
The syntax of the try-catch block:
• Java Exception Keywords
Try
{ //code that may throw exception }
catch(Exception_class_Name ref){}

The syntax of a try-finally block:


Try
{ //code that may throw exception }
finally{}
Example:
try
{ int result = 10 / 0; }
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
Subject: Web Technology
Exception Handling in Java(Cont.…)
• Java Exception Keywords: try-catch Block
Syntax: Example 1: catch ArithmeticException exception:
public class Arithmetic { public static void main(String[] args) {
try
try
{ {
//code that cause exception; int result = 30 / 0; // Trying to divide by zero
} }
catch(Exception_type e) catch (ArithmeticException e)
{ {
//exception handling code System.out.println("ArithmeticException caught!");
} }
System.out.println("rest of the code executes");
}
}

Output:
ArithmeticException caught!
rest of the code executes

Subject: Web Technology


Exception Handling in Java(Cont.…)
• Java Exception Keywords: try-catch Block
Syntax: Example 2:catch ArrayIndexOutOfBoundsException exception:
try
{
try
//code that cause exception;
{
}
int[] arr = {1, 2, 3};
catch(Exception_type e)
System.out.println(arr[5]);
{
}
//exception handling code
catch (ArrayIndexOutOfBoundsException e)
}
{
System.out.println("Array index is out of bounds!");
}

In this code, we're trying to access an index that doesn't exist in the array.
The corresponding catch block catches this exception and handles it by
printing a custom error message.

Subject: Web Technology


Exception Handling in Java(Cont.…)
How to handle Exception?
Java exception handling is managed using five keywords: try, catch, throw, throws, and finally.
Step to handle exceptions:
I. Program statements that you think can raise exceptions are contained within a try block.
II. If an exception occurs within the try block, it is thrown. Code can catch this exception(using catch
block) and handle it in some rational manner.
III. In finally, write the code which must necessarily run For example- Closing files,
and database
connection release.

Note: Finally will run mandatory irrespective run of the exception.

Subject: Web Technology


Exception Handling in Java(Cont.…)

Throw and catch


An error can throw an exception throw ;
throw<exception Object>;
• By default, exceptions result in the thread terminating after printing an error message
• However, exception handlers can catch specified exceptions and recover from an
error. catch ( e)

{
//statements that handle the exception
}

Subject: Web Technology


Exception Handling in Java(Cont.…)
Java Exception Handling Example
public class JavaExceptionExample
{
public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e){System.out.println(e);

//rest code of the program


System.out.println("rest of the code...");
}
}

Subject: Web Technology


Exception Handling in Java(Cont.…)
Throw an exception
• Example creates a subclass of Exception and throws an exception: class
MyException extends Exception { }
class MyClass
{
void oops()
{
if (/* no error occurred */)
{ /* normal processing */ } else
{ /* error occurred */ throw new MyException(); } }
//oops
}
//class MyClass

Subject: Web Technology


Multithreading in Java

Subject: Web Technology


Multithread in
Java
What is thread in Java ?
A thread in Java is the direction or
path that is taken while a program is
being executed. Generally, all the
programs have at least one thread,
known as the main thread, that is
provided by the JVM or Java Virtual
Machine at the starting of the
program's execution.

Subject: Web Technology


Multithread in
Multithreading in Java
Java
• Multi means “many” & threading means “ small logic”.
• Executing two or more methods/small logic parallel in a single java program along with the main()
method is known as multithreading.
• 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.

Subject: Web Technology


Multithread in
What is Thread?
Java(Cont.…)
A thread is a small work/task which is performed in the main program with some specific functionality
along with the main program parallel.
i.e., Light-weight process
Thread is a predefined class that is available in java.lang package.
How to create a thread in java?
i. By Extending the thread class
ii. By implementing a runnable interface

Subject: Web Technology


// Java code for thread creation by extending
// the Thread class Multithread in
class MultithreadingDemo extends Thread {
Java(Cont.…)
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Output
Thread.currentThread().getId() Thread 15 is running
+ " is running"); Thread 14 is running
}
catch (Exception e) {
Thread 16 is running
// Throwing an exception Thread 12 is running
System.out.println("Exception is caught"); Thread 11 is running
} Thread 13 is running
}
} Thread 18 is running
Thread 17 is running
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
Subject: Web Technology
}
}
Multithread in
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
Java(Cont.…)
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
Subject: Web Technology
}
Multithread in
The life cycle of a thread
Java(Cont.…)
During the lifecycle of a thread, there are many states it can
enter.
• They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead stat

Subject: Web Technology


Multithread in
Java(Cont.…)
There are various stages of the life cycle of thread as shown in the above diagram:
1. New: In this phase, the thread is created using the class “Thread class". It remains in this state
till the program starts the thread. It is also known as the born thread.
2. Runnable: On this page, the instance of the thread is invoked with a start method. The thread
control is given to the scheduler to finish the execution. It depends on the scheduler, and
whether to run the thread.
3. Running: When the thread starts executing, then the state is changed to a “running” state. The
scheduler
selects one thread from the thread pool, and it starts executing in the application.
4. Waiting: This is the state in which a thread has to wait. As there multiple threads are running
in the application, there is a need for synchronization between threads. Hence, one thread
has to wait, till the other thread gets executed. Therefore, this state is referred to as a waiting
state.
5. Dead: This is the state in which the thread is terminated. The thread is in a running state and as
soon asWeb
Subject: it completed
Technologyprocessing it is in a “dead state”.
Multithread in
Java(Cont.…)
• Multitasking
• Task means a small work on a computer, if such work is done in multiples at the same time it is known as
multitasking.
• Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
• Process-based Multitasking (Multiprocessing)
• Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
• Each process has an address in memory. In other words, each process allocates a separate memory area.
• A process is heavyweight.
• Cost of communication between the process is high.
• Switching from one process to another requires some time for saving and loading register, memory maps,
updating lists, etc.

Subject: Web Technology


Multithread in
Java(Cont.…)
2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.
• Cost of communication between the thread is low.
Java Thread Methods
The start() method of thread class is used to begin the execution of thread.
The run() method of thread class is called if the thread was constructed using a separate Runnable object
otherwise this method does nothing and returns.
The sleep() method of thread class is used to sleep a thread for a specified amount of time.
The currentThread() method of thread class is used to return a reference to the currently executing thread
object.
The join() method of thread class waits for a thread to die.
The getPriority() method of thread class is used to check the priority of the thread.

Subject: Web Technology


Multithread in
Java(Cont.…)
class EvenOddThreadsExample
{
public static void main(String[] args)
{
// Create two threads
Thread evenThread = new Thread(new EvenPrinter());
Thread oddThread = new Thread(new OddPrinter());

// Start the threads


evenThread.start();
oddThread.start();
}
}
Subject: Web Technology
Multithread in
Java(Cont.…)
class EvenPrinter implements Runnable { //Runnable interface
@Override
public void run() {
for (int i = 2; i <= 5; i += 2) {
System.out.println("Even: " + i);
try
{
Thread.sleep(500); // Sleep for 500 milliseconds
}
catch (InterruptedException e)
{
e.printStackTrace();
}}}}
Subject: Web Technology
Multithread in
Java(Cont.…)
class OddPrinter implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i += 2) {
System.out.println("Odd: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
Odd: 1
} Even: 2
} Odd: 3
Even: 4
} Odd: 5

Subject: Web Technology


INPUT/OUTPUT in Java

Subject: Web Technology


I/O in
Java I/O
Java
• (Input and Output) are used to process the input and produce the output.
• Java uses the concept of a stream to make I/O operations fast. The java.io package contains all the classes
required for input and output operations.
• We can perform file handling in Java by Java I/O API.
• Java brings various streams with its I/O package that helps the user to perform all the input-output
operations. These streams support all types of objects, data types, characters, files, etc. to fully executed
the I/O.
Stream
• Stream is nothing but the flow of data/information from a source to a destination.
• A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream

Subject: Web Technology


I/O in
Types of Stream
Java
Input Stream
Reading the data/information from source to destination is known as the input stream. Java application
uses an input stream to read data from a source; it may be a file, an array, a peripheral device, or a socket.
// In general, sources are keywords, mouse, file, etc.
For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream, etc.
Types of an input stream: 1. Byte-stream 2. Character stream
Output Stream
Writing the data/information from the source to the destination is known as output- stream.
//In general, destinations are monitor, printer, etc.
For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.

Subject: Web Technology


Subject: Web Technology
Subject: Web Technology
I/O in
Java
• In Java, 3 streams are created for us automatically. All these streams are attached to the console.
1) System.out: standard output stream is used to produce results and contains method println(), print(),
printf().
2) System.in: standard input stream is used read characters from keywords or any other input device. The
read () method is used to read data.
3) System.err: standard error stream is used to output all the errors that a program might throw. Println (),
print(), and print () functions are used to output.
For Examples:
System.out.println("simple message");
System.err.println("error message");
System.in.read();// to read data

Subject: Web Technology


I/O in
Java
Before exploring various input and output streams lets look at 3 standard or default streams that Java has
to provide which are also most common in use:

Subject: Web Technology


I/O in
Basically these 2-way streams we classified into 2 types:
Java
• Byte Stream: Byte streams are used to perform reading and writing in a java program, a byte of
information/data at a time.
• Character Stream: Character streams are used to perform reading and to write in a java program 2 bytes
of information/data at a time.
• Byte streams input stream classes: java performs different courses, using which can perform a reading of
data with input stream classes.
• Input Stream Class: This is an “Abstract class”. It contains the following method.
1. abstract int read()// this method reads a byte of data from the source and returns that as int.
2. int read(Byte [])// this method reads collections of bytes of data from the source and stores that in
byte[] of your program. It returns int i.e., no of bytes successfully read from the source.
3. Int read(byte[], int offset, int length);// this method reads a collection of byes from the source and
stores that data in byte[] starting from offset-index and length no. of an array.
4. Int available();
5. Void close();

Subject: Web Technology


I/O in
• Examples of I/O Java
Java
// Java code to illustrate print()
import java.io.*;

class Demo_print {
public static void main(String[] args)
{

// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}

Subject: Web Technology


Applet in Java

Subject: Web Technology


Applet in
Java
Applet in Java
• The applet is client-side programming.
• Applet is a special type of program that is embedded in the webpage to generate dynamic content.
• It runs inside the browser and works on the client side.
• All applets are subclasses (either directly or indirectly) of java.applet.Applet class.
• Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer.
• JDK provides a standard applet viewer tool called applet viewer.
• In general, the execution of an applet does not begin at the main() method.
• Output of an applet window is not performed by System.out.println().
• Rather it is handled with various AWT methods, such as

Subject: Web Technology


Applet in
Hierarchy of Applet Java

As displayed in the above diagram, Applet


class extends Panel. Panel class extends
Container which is the subclass of
Component. >>>>

Subject: Web Technology


Applet in
Java

• Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Subject: Web Technology


Applet in
Syntax of entire classJava
TestAppletLifeCycle extends Applet
{
Applet Life Cycle in Java>> public void init()
{
// initialized objects
}
public void start()
{
// code to start the applet
}
public void paint(Graphics graphics)
{
// draw the shapes
}
public void stop()
{
// code to stop the applet
}
public void destroy()
{
Subject: Web Technology // code to destroy the applet
Applet in
java.applet.Applet class
Java
• For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of an
applet.
1. public void init(): is used to initialize 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 stopped or the 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 the applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides a Graphics class object that can be
used for drawing ovals, rectangles, arcs, etc.
AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI (Graphical User Interface) or
window-based applications in Java.

Subject: Web Technology


Applet in
Java
import java.applet.Applet;
How to run an Applet?
import java.awt.Graphics;
There are two ways to run an applet public class First extends Applet
• By html file.
• By appletViewer tool {
(for testing purposes). public void paint(Graphics g)
//First.java >>
Simple example of Applet by html file>> {
g.drawString("welcome",150,150);
}
}

The appletviewer tool allows you to run applets without a web browser.

Subject: Web Technology


Applet in
Java

myapplet.html

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Subject: Web Technology


Applet in
Java

Subject: Web Technology


Applet in
Java

Subject: Web Technology


Applet in
Java
Types of Applet in Java
Applets are categorized into different types based on their execution context and origin.
Here are the two primary types of applets:

1) Local Applet
2) Remote Applet

Subject: Web Technology


Applet in
Java
Advantage of Applet
• There are many advantages of an applet. They are as follows:
• It works on the client side so less response time.
• Secured
• It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os, etc.
Drawback of Applet
• Plugin is required at the client browser to execute the applet.
• Applets cannot stream data directly into the browser.
• For example, applets cannot detect that a user followed a bookmark.
• Similarly, applets cannot detect that a user typed in a URL that should be followed.

Subject: Web Technology


String Handling in Java

Subject: Web Technology


String Handling in
String Handling
Java
• A string is a sequence of characters. But in Java, a string is an object that represents a sequence of
characters.
• The java.lang.String class is used to create a string object.
• An array of characters works the same as a java string.
Examples
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
• Java String class provides several methods to perform operations on string such as compare(), concat(),
split(), length(), replace(), comapreTo(), intern(), substring(), etc.
• The java.lang.String.class implements Serializable, Comparable and CharSequence interfaces.

Subject: Web Technology


String Handling in
CharSequence Interface
Java
• The CharSequence interface is used to represent the sequence of characters.
• String, StringBuffer , and StringBuilder classes implement it. It means, we can create strings in Java by
using these three classes.
• The Java String is immutable which means it cannot be changed.
• Whenever we change any string, a new instance is created.
• For mutable strings, you can use StringBuffer and StringBuilder classes.

Subject: Web Technology


String Handling in
How to create a String object?
Java
• There are two ways to create a String object:
1. By string literal
2. By new keyword
String Literal
• Java String literal is created by using double quotes. For Example: String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a
new string instance is created and placed in the pool.
For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

Subject: Web Technology


String Handling in
By New Keyword
Java
Syntax: String stringName = new String();
In such a case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
Some Java String class methods:
• char charAt(int index): It returns the char value for the particular index.
• Int length(): It returns string length.
• String substring(int beginIndex): It returns a substring for a given begin index.
• Boolean contains(CharSequnce s): It returns true or false after matching the sequence of char values.
• Boolean equals(Object another): It checks the equality of the string with the given object.
• String concat(String str): It concatenates the specified string.

Subject: Web Technology


String Handling in
By New Keyword
Java
Syntax: String stringName = new String();
In such a case, JVM will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in a heap (non-
pool).
Some Java String class methods:
• char charAt(int index): It returns the char value for the particular index.
• Int length(): It returns string length.
• String substring(int beginIndex): It returns a substring for a given begin index.
• Boolean contains(CharSequnce s): It returns true or false after matching the sequence of char values.
• Boolean equals(Object another): It checks the equality of the string with the given object.
• String concat(String str): It concatenates the specified string.

Subject: Web Technology


Event Handling in Java

Subject: Web Technology


Event Handling in
Event Handling
Java
An event can be defined as changing the state of an object or behavior by performing actions. Actions can
be a button click, cursor movement, keypress through a keyboard or page scrolling, etc.
• The java.awt.event package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events

Subject: Web Technology


Event Handling in
1. Foreground Events
Java
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of
these events are operating system failures/interrupts, operation completion, etc
Event Handling
• It is a mechanism to control the events and to decide what should happen after an event occur.
• To handle the events, Java follows the Delegation Event model.
- It has Sources and Listeners.

Subject: Web Technology


Event Handling in
Java
• Source: Events are generated from the source. There are various sources like buttons, checkboxes, lists,
menu-item, choices, scrollbars, text components, windows, etc., to generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
• To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.

Syntax:
addTypeListener()
• Example 1: For KeyEvent we use addKeyListener() to register.
• Example 2:that For ActionEvent we use addActionListener() to register.

Subject: Web Technology


Event Handling in
Flow of Event Handling
Java
i. User Interaction with a component is required to generate an event.
ii. The object of the respective event class is created automatically after event generation, and it holds all
information of the event source.
iii. The newly created object is passed to the methods of the registered listener.
iv. The method executes and returns the results.
Some Listener Interfaces:
1. KeyListener: An event that occurs due to a sequence of key presses on the keyword. keyTypes(),
keyPressed(), keyRelesed().
2. MouseWheelListener: An event that specifies that the mouse rotated in a component.
mouseWheelMoved().
3. MouseListener & MouseMotionListener: The event that occur due to the user interaction with the
mouse(Pointing Device). mousePressed(), mouseclicked(), mouseEntered(), mouseExited(),
mouseReleased().

Subject: Web Technology


AWT in Java

Subject: Web Technology


AWT in
AWT(Abstract Window Toolkit)
Java
• It is an API to develop Graphical User Interface(GUI) or window-based applications in java. It contains a
large number of classes and methods, which are used for creating and managing GUI.
• A graphical user Interface (GUI) offers interaction via some graphical components.
• For Example, our underlying operating System also offers GUI via a window, frame, Panel, Button,
TextField, TextArea, Listbox, Comobox, Label, Checkbox, etc.
• GUI provides results to the end user in response to raised events GUI is entirely based on events.
• Java AWT components are platform-dependent i.e. components are displayed according to the view of
the operating system.
Examples of GUI-based applications:
Airline Ticketing System, ATM, Mobile Applications

Subject: Web Technology


AWT in
Java AWT Hierarchy
Java(Cont.…)

Subject: Web Technology


AWT in
Java AWT Hierarchy
Java(Cont.…)
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT, there are
classes for each component as shown in the above diagram. In order to place every component in a
particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain other components like buttons, text fields, labels,
etc. The classes that extend the Container class are known as containers such as Frame, Dialog, and Panel.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Subject: Web Technology
AWT in
Window
Java(Cont.…)
A window is a rectangular area that is displayed on the screen. In the different windows, we can execute a
different programs and display different data. A window must have either a frame, dialog or another
window.
Frame
A Frame is a top-level window with a title and a border. The size of the frame includes any area designated
for the border. Frame encapsulates window. It has a title bar, menu bar, borders, and another window.
Panel
The panel provides space in which an application can attach any other components, including other panels.
Canvas
The canvas component represents a blank rectangular area of the screen which the application can draw

Subject: Web Technology


AWT in
Java(Cont.…)
• Java AWT components are platform-dependent i.e., components are displayed according to the view of
the operating system. Java AWT calls the native platform(OS) subroutine for creating API components
like TextField, CheckBox, Button, etc.
• The java.awt.packge provides classes for AWT API such as TextField, Label, TextArea, RadiaButton,
CheckBox, etc.
• Useful Methods of component class are listed below:
Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by default
false.

Subject: Web Technology


AWT in
How to create AWT
Java(Cont.…)
To create AWT, we need a frame. Here are two ways to create GUI using frame
- By extending the Frame class (inheritance)
- By Creating the object of the frame class (association)

Subject: Web Technology


AWT in
import java.awt.*; Java(Cont.…)
public class AWTExample1 extends Frame // extending Frame class to our class AWTExample1
{
AWTExample1() // initializing using constructor {
Button b = new Button("Click Me!!");// creating a button
b.setBounds(30,100,80,30); // setting button position on screen
add(b); // adding button into frame
setSize(300,300); // frame size 300 width and 300 height
setTitle("This is our basic AWT example"); // setting the title of Frame
setLayout(null); // no layout manager
setVisible(true); // now frame will be visible, by default it is not visible
}
public static void main(String args[]) // main method {
AWTExample1 f = new AWTExample1(); // creating instance of Frame class
}}

Subject: Web Technology


AWT in
Java AWT Controls
Java(Cont.…)
Every user interface considers the following three main aspects:
• UI elements: These are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex which we will
cover in this tutorial.
• Layouts: They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter.
• Behavior: These are events that occur when the user interacts with UI elements. This part will be
covered in the Event Handling chapter.
Every Awt controls inherits properties from the class of the component.
1. Label: A Label object is a component for placing text in a container.

Subject: Web Technology


AWT in
Useful label class constructors are given below:
Java(Cont.…)
• Label: Construct an empty label.
Syntax: label I=new Label();
• Label(String text): Constructs a new label with the specified string of text, left justified.
Syntax: label I new label(“this is a label.LEFT);
2. Button: The button is a control component that has a label and generates an event when pressed. This
class creates a labeled button.
Button class constructors:
• Button():
• Button(String text)

Subject: Web Technology


AWT in
3.
Java(Cont.…)
list: The list component presents the user with a scrolling list of text items. The list represents a list of
text items. The list can be configured so that the user can choose either one item or multiple items.
List class constructors:
• List(): Create a new scrolling list. For example Syntax; List li = new List();
• List(int rows): Creates a new scrolling list initialized with the specified number of visible lines.
• List(int rows, Boolean multipleMode)
4. Text Field
5. Text Area
6. Choice
7. Images
8. Scroll Bar

Subject: Web Technology


AWT in
Java AWT Layout Manager
Java(Cont.…)
• The layout means the arrangement of components within the container or placing the component at a
particular position within the container.
• The task of lay-outing the controls is done automatically by the layout manager.
• Layout Manager: The layout manager automatically positions all the components within the container. If
we do not use a layout manager then also the components are positioned by the default layout manager.
• Java provides us with various layout managers to position the controls. The properties like size, shape,
and arrangement vary from one layout manager to another layout managers.
• The layout manager is associated with every container object.
• Each layout manager is an object of the class that implements the Layout Manager.

Subject: Web Technology


AWT in
Java(Cont.…)
AWT layout Manager classes are listed below:
1. Border Layout: The Border layout arranges the component to fit in the five regions: east, west, north
south, and center.
Syntax: BorderLayout()(no gap between components), BorderLayout(int hgap, int vgap)(specified
horizontal and vertical gap.
2. CardLayout: The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
Syntax: CardLayout()
3. FlowLayout: FlowLayout is the default layout. It layout the component in a directional flow.
Syntax: FlowLayout()
4. GridLayout: The GridLayout manages the component in form of a rectangular grid.
Syntax: GridLayout()
5. GridBagLayout: This is the most flexible layout manager class.
Syntax: GridBagLayout()
Subject: Web Technology
AWT in
Characteristics
Java(Cont…)
• It is a set of native user interface components.
• It is very robust in nature.
• It includes various editing tools like graphics tools and imaging tools.
• It uses native window-system controls.
• It provides functionality to include shapes, colors, and font classes.
Advantages
• It takes very less memory for the development of GUI and executing programs.
• It is highly stable as it rarely crashes.
• It is dependent on the operating system so performance is high.
• It is easy to use for beginners due to its easy interface.

Subject: Web Technology


AWT in
Disadvantages
Java(Cont…)
• The buttons of AWT do not support pictures.
• It is heavyweight in nature.
• Two very important components trees and tables are not present.
• Extensibility is not possible as it is platform dependent

Subject: Web Technology


Subject: Web Technology

You might also like