Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

WT Notes Unit I

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 52

Web Technology

Computer Science & Engineering


B-Tech.(3rd Year/6th Sem)
UNIT-I

Introduction and Web Development Strategies

 Identify target user: Identify the user of the website by doing market
research.
 Make our design portable : To be successful, website design should be
portable and accessible across different browsers, operating systems, and
computer platforms. Designers should test the website in a different
environment whether they look same to all their users.
 Design for low bandwidth : Web pages in websites should be accessible
at any connection speeds. If a page is downloaded slowly then users will
leave the website before they see the content.
 Plan for clear presentation and easy access to information :
Presentation of the information on the website must be clear and easily
accessible to the user.
 Create smooth transitions: Plan to create a unified look among the
sections and pages of site. Reinforce the identifying elements of the site
and create smooth transitions from one page to another.
Any software development project, a methodology should be followed to ensure
project consistency and completeness.
History of Web and Internet
The World Wide Web is a system of interlinked hypertext documents accessed
via the Internet. Web is a huge collection of pages of information linked to each
other around the globe.
History of WWW:

 WWW was created by Sir Tim Berners Lee in 1989 at CERN in Geneva.
 In 1990 , the first text only browsers were set up and CERN scientists could
access hypertext files and other information at CERN. HTML was based on
a subset of the standard generalized markup language (SGML). To transfer
HTML documents to remote sites a new protocol was devised called HTTP
(HyperText Transfer Protocol).
 In the fall of 1991, conferences around the world started hearing about the
promise but sparks still were not flying.
 In 1993, there were only about 50 websites worldwide. A browser that
allowed users to take advantage of the web’s graphical capabilities was
developed at the National center for SuperComputing application (NCSA) .
NCSA called the browser Mosaic
Protocols Governing Web
Protocol: A protocol is a set of rules that is used to communicate applications to
each other.
OR
A protocol is the interface required for communicating the different applications.
Protocols which are a set of rules that help in governing the way a particular
technology will function for communication. In other words, it can be said that the
protocols are digital languages implemented in the form of networking algorithms.
There are different networks and network protocols, user's use while surfing.
Classifications

 HTTP: HTTP is the primary protocol used to distribute information on the


web. This protocol is used to access,send and receive Hypertext markup
language (HTML) files on the Internet. Initial HTTP 0.9 does not allow for
content typing and does not have provisions for supplying meta -
information Content Typing: To identify the type of data being transferred.
Meta Information: It is supplemental data, such as environment variables
that identify the client’s computer Current version is HTTP 1.0
 TCP/IP: It is a set of rules that an application can use to package its
information for sending across the networks of networks.
TCP: This protocol ensure the delivery of information packets across
network.
IP: This protocol is responsible logical addressing called IP address to route
information between network.
 FTP: It is used to transfer the files over networks.
 E-Mail: It is a method of exchanging digital messages across the Internet or
other computer networks.
 Telnet: Telnet lets you remotely log into another system and browse files
and directories on that remote system.
 Simple Mail Transfer Protocol(SMTP) : This protocol is used for
transferring e-mail between computers.
 Gopher: Gopher is a collection of rules implemented for searching,
retrieving as well as displaying documents from isolated sites. Gopher also
works on the client/server principle.
Writing Web Projects
Write a project mission statement: Write the specific mission statement that
you want to do.
Identify Objectives:

 Specific
 Measurable
 Attainable
 Realistic
 Time limited
Identify your target users: The matter of a website will be determined by the
users whom you want to visit the site. This is totally depend upon

 Market research
 Focus group
 Understanding intranet audiences
Determine the scope: By supporting documents and client’s approval.
Budget:

 Assumption for budgets.


 Budget categories.
 Determine hidden costs and tools.
Planning issues:

 Discuss client’s existing information system.


 Project team and developing infrastructure.
 Where the website will place.
Connecting to the Internet
Internet is a global communication system that links together thousands of
individual networks. It allows exchange of information between two or more
computers on a network. Thus internet helps in transfer of messages through
mail, chat, video & audio conference, etc. It has become mandatory for day-to-day
activities: bills payment, online shopping and surfing, tutoring, working,
communicating with peers, etc.
How Do I Connect to the Internet?

 Computer
 Connection - Phone Line, Cable, DSL, Wireless,...
 Modem
 Network Software - TCP/IP
 Application Software - Web Browser, Email,...
 Internet Service Provider (ISP)

What Can I Do on the Internet?

 Send and receive email messages.


 Download free software with FTP (File Transfer Protocol).
 Post our opinion to a Usenet newsgroup.
 Surf the World Wide Web.
 And much, much more.
 There is no charge for most services.

Introduction to Internet services and tools


Internet Services allows us to access huge amount of information such as text,
graphics, sound and software over the internet. Following diagram shows the four
different categories of 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.
Telnet
2
Used to log on to a remote computer that is attached
to internet.
Newsgroup
3
Offers a forum for people to discuss topics of
common interests.
Internet Relay Chat (IRC)
4
Allows the people from all over the world to
communicate in real time.
Mailing Lists
5
Used to organize group of internet users to share
common information through e-mail.
Internet Telephony (VoIP)
6
Allows the internet users to talk across internet to
any PC equipped to receive the call.
Instant Messaging
7
Offers real time chat between individuals and group
of people. Eg. Yahoo messenger, MSN messenger.
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.
Archie
2
It’s updated database of public FTP sites and their
content. It helps to search a file by its name.
Gopher
3
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.

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 the concept of Utility Computing.
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.
Video Conferencing
Video conferencing or Video teleconferencing is a method of communicating by
two-way video and audio transmission with help of telecommunication
technologies.
Modes of Video Conferencing
Point-to-Point

This mode of conferencing connects two locations only.

Multi-point

This mode of conferencing connects more than two locations through Multi-point
Control Unit (MCU).

How does the Internet work?


If we need to conclude this section, we can say that it starts with protocols and
finish in architecture. The most dominant parts are listed in the following section:
● Protocols – standardized rules that define how computers communicate
and exchange data
● IP address – unique number used to identify computers on the Internet
● Domain name – structured naming system to locate computers on the
Internet
● URL – uniform naming scheme that specifies unique addresses of
Internet resources
● Client and server – computing architecture used by most Internet
services
Client-Server Definition
Client-server denotes a relationship between cooperating programs in an
application, composed of clients initiating requests for services and servers
providing that function or service.


Terminologies :-
The terminologies in distributed client/server architecture’s are as follows-

1. Applications Programming Interface (API) –It is a set of functions, and it


calls programs that allow clients as well as servers to intercom with each
other.
2. Client / User –This is a network information provider that is typically a
computer system or workstation that can query databases and/or other
information from a server.
3. Middleware –It is a set of drivers, API’s and/or other software which
improves the connection among a client application with a server.
4. Relational Database –This is a type of database in which information
access is limited to a selection of rows that meet all search criteria.
5. Server –This is also a computer, typically a high-powered system and
workstation or a minicomputer or a mainframe, which gives information to
the network client to manipulate.
6. Structured Query Language (SQL) –This is the developed language IBM
(International Business Machines) and ANSI standardized to address,
produce, update, and query RDB’s (relational databases).

Characteristics of Client Server Computing


The salient points for client server computing are as follows:

 The client server computing works with a system of request and response.
The client sends a request to the server and the server responds with the
desired information.
 The client and server should follow a common communication protocol so
they can easily interact with each other. All the communication protocols
are available at the application layer.
 A server can only accommodate a limited number of client requests at a
time. So it uses a system based to priority to respond to the requests.
 Denial of Service attacks hindera servers ability to respond to authentic
client requests by inundating it with false requests.
 An example of a client server computing system is a web server. It returns
the web pages to the clients that requested them.
Difference between Client Server Computing and Peer to Peer
Computing
The major differences between client server computing and peer to peer
computing are as follows:

 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.
Advantages of Client Server Computing
The different advantages of client server computing are −

 All the required data is concentrated in a single place i.e. the server. So it is
easy to protect the data and provide authorization and authentication.
 The server need not be located physically close to the clients. Yet the data
can be accessed efficiently.
 It is easy to replace, upgrade or relocate the nodes in the client server
model because all the nodes are independent and request data only from
the server.
 All the nodes i.e clients and server may not be build on similar platforms yet
they can easily facilitate the transfer of data.
Disadvantages of Client Server Computing
The different disadvantages of client server computing are −

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

What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle)
in the year 1995. James Gosling is known as the father of Java. Before Java, its
name was Oak. Since Oak was already a registered company, so James Gosling
and his team changed the Oak name to Java.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!
Why to Learn java Programming?
Java is a MUST for students and working professionals to become a great
Software Engineer specially when they are working in Software Development
Domain. I will list down some of the key advantages of learning Java
Programming:

 Object Oriented − In Java, everything is an Object. Java can be easily


extended since it is based on the Object model.
 Platform Independent − Unlike many other programming languages
including C and C++, when Java is compiled, it is not compiled into platform
specific machine, rather into platform independent byte code. This byte
code is distributed over the web and interpreted by the Virtual Machine
(JVM) on whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral
object file format, which makes the compiled code executable on many
processors, with the presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation
dependent aspects of the specification makes Java portable. Compiler in
Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write
programs that can perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
 Interpreted − Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
 High Performance − With the use of Just-In-Time compilers, Java enables
high performance.
 Distributed − Java is designed for the distributed environment of the
internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it
is designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.

Java "Hello, World!" Program


// Your First Program
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Output
Hello, World!

Note: If you have compiled the exact code, you need to save the file as
HelloWorld.java. It's because the name of the class and file name should match in
Java. Also, some online compilers only accept the class named Main.
Things to take away

 Every valid Java Application must have a class definition (that matches the
filename).
 The main method must be inside the class definition.
 The compiler executes the codes starting from the main function.
Components Of Java Programming Language
A Java Programmer writes a program in a human-readable language called
Source Code. Therefore, the CPU or Chips never understand the source code
written in any programming language.
These computers or chips understand only one thing, which is called machine
language or code. These machine codes run at the CPU level. Therefore, it would
be different machine codes for other models of CPU.
However, you need to worry about the machine code, as programming is all about
the source code. The machine understands this source code and translates them
into machine understandable code, which is an executable code.
All these functionalities happen inside the following 3 Java platform components:
Java Development kit (JDK)
JDK is a software development environment used for making applets and Java
applications. The full form of JDK is Java Development Kit. Java developers can
use it on Windows, macOS, Solaris, and Linux. JDK helps them to code and run
Java programs. It is possible to install more than one JDK version on the same
computer.

Why use JDK?

Here are the main reasons for using JDK:

 JDK contains tools required to write Java programs and JRE to execute
them.
 It includes a compiler, Java application launcher, Appletviewer, etc.
 Compiler converts code written in Java into byte code.
 Java application launcher opens a JRE, loads the necessary class, and
executes its main method.
Java Virtual Machine (JVM):

Java Virtual Machine (JVM) is an engine that provides a runtime environment to


drive the Java Code or applications. It converts Java bytecode into machine
language. JVM is a part of the Java Run Environment (JRE). In other
programming languages, the compiler produces machine code for a particular
system. However, the Java compiler produces code for a Virtual Machine known
as Java Virtual Machine.
Why JVM?

Here are the important reasons of using JVM:

 JVM provides a platform-independent way of executing Java source code.


 It has numerous libraries, tools, and frameworks.
 Once you run a Java program, you can run on any platform and save lots of
time.
 JVM comes with JIT (Just-in-Time) compiler that converts Java source code
into low-level machine language. Hence, it runs faster than a regular
application.

Java Runtime Environment (JRE)


JRE is a piece of software that is designed to run other software. It contains the
class libraries, loader class, and JVM. In simple terms, if you want to run a Java
program, you need JRE. If you are not a programmer, you don't need to install
JDK, but just JRE to run Java programs.
Why use JRE?

Here are the main reasons of using JRE:

 JRE contains class libraries, JVM, and other supporting files. It does not
include any tool for Java development like a debugger, compiler, etc.
 It uses important package classes like math, swing, util, lang, awt, and
runtime libraries.
 If you have to run Java applets, then JRE must be installed in your system.

Different Types of Java Platforms


There are four different types of Java programing language platforms:
1. Java Platform, Standard Edition (Java SE): Java SE's API offers
the Java programming language's core functionality. It defines all the
basis of type and object to high-level classes. It is used for
networking, security, database access, graphical user interface (GUI)
development, and XML parsing.
2. Java Platform, Enterprise Edition (Java EE): The Java EE platform
offers an API and runtime environment for developing and running
highly scalable, large-scale, multi-tiered, reliable, and secure network
applications.
3. Java Programming Language Platform, Micro Edition (Java
ME): The Java ME platform offers an API and a small-footprint virtual
machine running Java programming language applications on small
devices, like mobile phones.
4. Java FX: JavaFX is a platform for developing rich internet
applications using a lightweight user-interface API. It user hardware-
accelerated graphics and media engines that help Java take
advantage of higher-performance clients and a modern look-and-feel
and high-level APIs for connecting to networked data sources.

To understand Java programming language, we need to understand some basic


concept of how a computer program can run a command and execute the action.

Operator in Java

Operator in Java is a symbol which is used to perform operations.


Java supports following Operators:

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators
Assume integer variable A holds 10 and variable B holds 20, then

The Relational Operators


There are following relational operators supported by Java language.Assume
variable A holds 10 and variable B holds 20, then
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60
and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Assume integer variable A holds 60 and variable B holds 13 then −

The Logical Operators


The following table lists the logical operators Assume Boolean variables A holds
true and variable B holds false, then
The Assignment Operators
Following are the assignment operators supported by Java language −

Miscellaneous Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists
of three operands and is used to evaluate Boolean expressions. The goal of the
operator is to decide, which value should be assigned to the variable. The
operator is written as −
variable x = (expression) ? value if true : value if false
instanceof Operator
This operator is used only for object reference variables. The operator checks
whether the object is of a particular type (class type or interface type). instanceof
operator is written as −
( Object reference variable ) instanceof (class/interface type)

Data type
There are two data types available in Java −
 Primitive Data Types
 Reference/Object Data Types

Primitive Data Types

There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the
eight primitive data types in detail.
 byte

 Byte data type is an 8-bit signed two's complement integer


 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50
 short

 Short data type is a 16-bit signed two's complement integer


 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short
is 2 times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

 int

 Int data type is a 32-bit signed two's complement integer.


 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless
there is a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000

 long

 Long data type is a 64-bit signed two's complement integer


 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L

 float

 Float data type is a single-precision 32-bit IEEE 754 floating point


 Float is mainly used to save memory in large arrays of floating point
numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f

 double

 double data type is a double-precision 64-bit IEEE 754 floating point


 This data type is generally used as the default data type for decimal
values, generally the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4

 boolean

 boolean data type represents one bit of information


 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example: boolean one = true

 char

 char data type is a single 16-bit Unicode character


 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'

 Reference Datatypes

 Reference variables are created using defined constructors of the classes.


They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Puppy, etc.
 Class objects and various types of array variables come under reference
data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or
any compatible type.
 Example: Animal animal = new Animal("giraffe");
Variable

Local Variable

A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.
A local variable cannot be defined with a "static" keyword.

Instance Variable

A variable declared inside the class but outside the body of the method, is called
instance variable. It is not declared as static.It is called instance variable because its
value is instance specific and is not shared among instances.

Static variable

A variable which is declared as static is called a static variable. It cannot be local.


You can create a single copy of a static variable and share among all the instances
of the class. Memory allocation for static variables happens only once when the
class is loaded in the memory.
Example to understand the types of variables in java
1class A{
2 int data=50;//instance variable
3 static int m=100;//static variable
4 void method(){
5 int n=90;//local variable
6 }
7}
Arrays
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set
of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.

Declaring Array Variables


Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −

 It creates an array using new dataType[arraySize].


 It assigns the reference of the newly created array to the variable
arrayRefVar.

Methods & Classes


Java is an Object-Oriented Language. As a language that has the Object-Oriented
feature, Java supports the following fundamental concepts −
Object − Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as behaviors – wagging the
tail, barking, eating. An object is an instance of a class.
An object has three characteristics:
 State: represents the data (value) of an object.
 Behavior: represents the behavior (functionality) of an object such as
deposit, withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The
value of the ID is not visible to the external user. However, it is used
internally by the JVM to identify each object uniquely.

Class − A class can be defined as a template/blueprint that describes the


behavior/state that the object of its type support.

 Polymorphism
If one task is performed in different ways, it is known as polymorphism. For
example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something; for example, a cat speaks
meow, dog barks woof, etc.

 Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example phone call, we don't know the internal processing.In Java, we
use abstract class and interface to achieve abstraction.
 Inheritance
When one object acquires all the properties and behaviors of a parent object,
it is known as inheritance. It provides code reusability. It is used to achieve
runtime polymorphism.

 Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.

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


blueprint from which objects are created. It is a logical entity. It can't be physical.
Class contains the following

Syntax to declare a class:


class <class_name>{
field;
method;
}

Method in Java
In general, a method is a way to perform some task. Similarly, the method in
Java is a collection of instructions that performs a specific task. It provides the
reusability of code. We can also easily modify code using methods. In this
section, we will learn what is a method in Java, types of methods, method
declaration, and how to call a method in Java.

What is a method 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. The method is executed only when we call or invoke it.
The most important method in Java is the main() method.

Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.

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 specifier:

 Public: The method is accessible by all classes when we use 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 protected access specifier, the method is
accessible within the same package or subclasses in a different package.
 Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only.
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It
must be corresponding to the functionality of the method. Suppose, if we are
creating a method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in
the pair of parentheses. It contains the data type and variable name. If the method
has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to
be performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and
start with a lowercase letter. If the method name has more than two words, the
first name must be a verb followed by adjective or noun. In the multi-word
method name, the first letter of each word must be in uppercase except the first
word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the
same class, it is known as method overloading.

Types of Method
There are two types of methods in Java:

Predefined Method
 User-defined Method

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.
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.

Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object.Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.
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 which 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 which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

extends Keyword
extends is the keyword used to inherit the properties of a class.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.

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

Output:
barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which
again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java
1class Animal{
2 void eat(){System.out.println("eating...");}
3}
4class Dog extends Animal{
5 void bark(){System.out.println("barking...");}
6}
7class BabyDog extends Dog{
8 void weep(){System.out.println("weeping...");}
9}
10class TestInheritance2{
11 public static void main(String args[]){
12 BabyDog d=new BabyDog();
13 d.weep();
14 d.bark();
15 d.eat();
16}}

Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.

File: TestInheritance3.java
1class Animal{
2 void eat(){System.out.println("eating...");}
3}
4class Dog extends Animal{
5 void bark(){System.out.println("barking...");}
6}
7class Cat extends Animal{
8 void meow(){System.out.println("meowing...");}
9}
10class TestInheritance3{
11 public static void main(String args[]){
12 Cat c=new Cat();
13 c.meow();
14 c.eat();
15 //c.bark();//C.T.Error
16}}

Output:
meowing...
eating...

Important points about interface

 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.
 You cannot instantiate an interface. An interface does not contain any
constructors.
 All the methods are public and abstract. And all the fields are public, static,
and final.An interface cannot contain instance fields.
 An interface is not extended by a class; it is implemented by a class. A class
can extend only one class, but implement many interfaces at a time .
 An interface can extend multiple interfaces.
 An interface is implicitly abstract. You do not need to use
the abstract keyword while declaring an interface.
 An interface can extend another interface, in a similar way as a class can
extend another class

Exception Handling

An exception is an unexpected event that occurs during program execution. It


affects the flow of the program instructions which can cause the program to
terminate abnormally.

An exception can occur for many reasons. Some of them are:

 Invalid user input


 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

Java Exception hierarchy


Here is a simplified diagram of the exception hierarchy in Java.

As you can see from the image above, the Throwable class is the root class in the
hierarchy.
Note that the hierarchy splits into two branches: Error and Exception.
Java Exception Types
The exception hierarchy also has two branches: RuntimeException and
IOException.
1. RuntimeException
A runtime exception happens due to a programming error. They are
also known as unchecked exceptions.
These exceptions are not checked at compile-time but run-time. Some of
the common runtime exceptions are:

 Improper use of an API - IllegalArgumentException


 Null pointer access (missing the initialization of a variable) -
NullPointerException
 Out-of-bounds array access - ArrayIndexOutOfBoundsException
 Dividing a number by 0 – ArithmeticException

You can think about it in this way. “If it is a runtime exception, it is your
fault”.

The NullPointerException would not have occurred if you had checked


whether the variable was initialized or not before using it.

An ArrayIndexOutOfBoundsException would not have occurred if you


tested the array index against the array bounds.

2. IOException
An IOException is also known as a checked exception. They are checked
by the compiler at the compile-time and the programmer is prompted to
handle these exceptions.
Some of the examples of checked exceptions are:

 Trying to open a file that doesn’t exist results in


FileNotFoundException
 Trying to read past the end of a file

Java Exception Handling

We know that exceptions abnormally terminate the execution of a program.This is


why it is important to handle exceptions. Here's a list of different approaches to
handle exceptions in Java.
 try...catch block
 finally block
 throw and throws keyword

1. Java try...catch block

The try-catch block is used to handle exceptions in Java.


1class Main {
2 public static void main(String[] args) {
3 try {
4 // code that generate exception
5 int divideByZero = 5 / 0;
6 System.out.println("Rest of code in try block");
7 }
8 catch (ArithmeticException e) {
9 System.out.println("ArithmeticException => " + e.getMessage());
10 }
11 }
12}

Output
ArithmeticException => / by zero
In the example, we are trying to divide a number by 0. Here, this code
generates an exception.
To handle the exception, we have put the code, 5 / 0 inside the try block.
Now when an exception occurs, the rest of the code inside the try block is
skipped.
The catch block catches the exception and statements inside the catch block
is executed.
If none of the statements in the try block generates an exception, the catch
block is skipped.
2. Java finally block
In Java, the finally block is always executed no matter whether there is an
exception or not.
The finally block is optional. And, for each try block, there can be only one
finally block.
1class Main {
2 public static void main(String[] args) {
3 try {
4 // code that generates exception
5 int divideByZero = 5 / 0;
6 }
7
8 catch (ArithmeticException e) {
9 System.out.println("ArithmeticException => " + e.getMessage());
10 }
11 finally {
12 System.out.println("This is the finally block");
13 }
14 }
15}

Output
ArithmeticException => / by zero
This is the finally block
In the above example, we are dividing a number by 0 inside the try block.
Here, this code generates an ArithmeticException.
The exception is caught by the catch block. And, then the finally block is
executed.

3. Java throw and throws keyword


The Java throw keyword is used to explicitly throw a single exception.When
we throw an exception, the flow of the program moves from the try block to
the catch block.
Example: Exception handling using Java throw
1class Main {
2 public static void divideByZero() {
3 // throw an exception
4 throw new ArithmeticException("Trying to divide by 0");
5 }
6 public static void main(String[] args) {
7 divideByZero();
8 }
9}
Output
Exception in thread "main" java.lang.ArithmeticException: Trying to divide
by 0
at Main.divideByZero(Main.java:5)
at Main.main(Main.java:9)

In the above example, we are explicitly throwing the ArithmeticException


using the throw keyword.
Similarly, the throws keyword is used to declare the type of exceptions that
might occur within the method. It is used in the method declaration.
Example: Java throws keyword
1import java.io.*;
2class Main {
3 // declaring the type of exception
4 public static void findFile() throws IOException {
5 // code that may generate IOException
6 File newFile = new File("test.txt");
7 FileInputStream stream = new FileInputStream(newFile);
8 }
9 public static void main(String[] args) {
10 try {
11 findFile();
12 }
13 catch (IOException e) {
14 System.out.println(e);
15 }
16 }
17}
Output

java.io.FileNotFoundException:
test.txt (The system cannot find the file specified)

Multi Thread programming


Any application can have multiple processes (instances). Each of this process can
be assigned either as a single thread or multiple threads.

What is Single Thread?


A single thread is basically a lightweight and the smallest unit of processing. Java
uses threads by using a "Thread Class".
There are two types of thread – user thread and daemon thread (daemon threads
are used when we want to clean the application and are used in the background).
When an application first begins, user thread is created. Post that, we can create
many user threads and daemon threads.
1package demotest;
2public class GuruThread
3{
4 public static void main(String[] args) {
5 System.out.println("Single Thread");
6 }}
What is Multithreading in Java?
MULTITHREADING in Java is a process of executing two or more threads
simultaneously to maximum utilization of CPU. Multithreaded applications execute
two or more threads run concurrently. Hence, it is also known as Concurrency in
Java. Each thread runs parallel to each other. Mulitple threads don't allocate
separate memory area, hence they save memory. Also, context switching between
threads takes less time.
1package demotest;
2public class GuruThread1 implements Runnable
3{
4 public static void main(String[] args) {
5 Thread guruThread1 = new Thread("Guru1");
6 Thread guruThread2 = new Thread("Guru2");
7 guruThread1.start();
8 guruThread2.start();
9 System.out.println("Thread names are following:");
10 System.out.println(guruThread1.getName());
11 System.out.println(guruThread2.getName());
12 }
13 @Override
14 public void run() {
15 }
16}

Advantages of multithread:

 The users are not blocked because threads are independent, and we can
perform multiple operations at times
 As such the threads are independent, the other threads won't get affected if
one thread meets an exception.
Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
 Runnable − After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task. A thread transitions back to
the runnable state only when another thread signals the waiting thread to
continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is waiting
for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

Java I/O Streams

In this tutorial, we will learn about Java input/output streams and their types.
In Java, streams are the sequence of data that are read from the source and written
to the destination.
An input stream is used to read data from the source. And, an output stream is
used to write data to the destination.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
For example, in our first Hello World example, we have used System.out to print a
string. Here, the System.out is a type of output stream.
Similarly, there are input streams to take input.
We will learn about input streams and output streams in detail in the later tutorials.

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:

1. System.in: This is the standard input stream that is used to read characters
from the keyboard or any other standard input device.
2. System.out: This is the standard output stream that is used to produce the
result of a program on an output device like the computer screen.
3. System.err: This is the standard error stream that is used to output all the
error data that a program might throw, on a computer screen or any standard
output device.

Types of Streams
Depending upon the data a stream holds, it can be classified into:

 Byte Stream
 Character Stream
Byte Stream
Byte stream is used to read and write a single byte (8 bits) of data.All byte stream
classes are derived from base abstract classes called InputStream and OutputStream.
InputStream:
InputStream is an abstract class of Byte Stream that describe stream
input and it is used for reading and it could be a file, image, audio, video,
webpage, etc. it doesn’t matter. Thus, InputStream read data from source
one item at a time.

OutputStream:
OutputStream is an abstract class of Byte Stream that describes stream
output and it is used for writing data to a file, image, audio, etc. Thus,
OutputStream writes data to the destination one at a time.
Difference between InputStream and OutputStream

InputStream OutputStream
1. It is an abstract class that describes Stream Input. 1. It is an abstract class that describes Stream Output.

2. InputStream Read data from the source once at a 2. InputStream Write data from the source once at a
time. time.

3. Output Stream consists of methods which perform:


3. InputStream consist of method which performs:
 Write a byte to current Outputstream : public
 Read next byte of data from the input stream void write(int)throws IOException
and return -1 at the end of the file: public
abstract int read()throws IOException
 Write array of byte to current output
stream : public void write(byte[])throws
 Close current InputStream: public int
IOException
available()throws IOException
 Flushes the current OutputStream: public
 Returns an estimate of the number of bytes void flush()throws IOException
that can be read from the current input
stream: public void close()throws IOException
 Close current Output Stream. : public void
close()throws IOException

4. Types of InputStream are: 4. Types of OutputStream are:

 FileInputStream  FileOutputStream
 ByteArrayInputStream  ByteArrayOutputStream
 FilterInputStream  FilterOutputStream
 ObjectInputStream  ObjectOutputStream

In these types the most important and mostly used In these types the most important and mostly used
type is FileInputStream. type is FileOutput Stream.

Character Stream
In Java, characters are stored using Unicode conventions (Refer this for details).
Character stream automatically allows us to read/write data character by character.
Though it has many classes, the FileReader and the FileWriter are the most popular
ones. FileReader and FileWriter are character streams used to read from the source
and write to the destination respectively
Stream class Description

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReader This output stream is used to translate character to byte.

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.


FileWriter This is used to output stream that writes to file.

Java Applet

An applet is a Java program that can be embedded into a web page. It runs inside
the web browser and works at client side. An applet is embedded in an HTML page
using the APPLET or OBJECT tag and hosted on a web server.

Important points :

1. All applets are sub-classes (either directly or indirectly)


of java.applet.Applet class.
2. 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.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather
it is handled with various AWT methods, such as drawString().

Four methods in the Applet class gives you the framework on which you build any
serious applet −

 init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
 start − This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing the
applet after having gone off to other pages.
 stop − This method is automatically called when the user moves off the page
on which the applet sits. It can, therefore, be called repeatedly in the same
applet.
 destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not
normally leave resources behind after a user leaves the page that contains the
applet.
 paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.

A "Hello, World" Applet

Following is a simple applet named HelloWorldApplet.java −


1import java.applet.*;
2import java.awt.*;
3public class HelloWorldApplet extends Applet {
4 public void paint (Graphics g) {
5 g.drawString ("Hello World", 25, 50);
6 }
7}

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

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.

Events are handled


A source generates an Event and send it to one or more listeners registered with the
source. Once event is received by the listener, they process the event and then
return. Events are supported by a number of Java packages,
like java.util, java.awt and java.awt.event.

Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.
Example of Event Handling
1import java.awt.*;
2import java.awt.event.*;
3import java.applet.*;
4import java.applet.*;
5import java.awt.event.*;
6import java.awt.*;
7public class Test extends Applet implements KeyListener
8{
9 String msg="";
10 public void init() {
11 addKeyListener(this);
12 }
13 public void keyPressed(KeyEvent k){
14 showStatus("KeyPressed");
15 }
16 public void keyReleased(KeyEvent k) {
17 showStatus("KeyRealesed");
18 }
19 public void keyTyped(KeyEvent k){
20 msg = msg+k.getKeyChar();
21 repaint();
22 }
23 public void paint(Graphics g){
24 g.drawString(msg, 20, 40);
25 }
26}

Important Event Classes and Interface


Event Classes Description Listener Interface
generated when
button is pressed,
ActionEvent menu-item is ActionListener
selected, list-item is
double clicked

generated when
mouse is dragged,
moved,clicked,presse
MouseEvent MouseListener
d or released and also
when it enters or exit
a component
generated when input
KeyEvent is received from KeyListener
keyboard

generated when
ItemEvent check-box or list item ItemListener
is clicked

generated when value


TextEvent of textarea or TextListener
textfield is changed

generated when
MouseWheelEven
mouse wheel is MouseWheelListener
t
moved

generated when
window is activated,
WindowEvent deactivated, WindowListener
deiconified, iconified,
opened or closed

generated when
component is hidden, ComponentEventListene
ComponentEvent
moved, resized or set r
visible

generated when
component is added
ContainerEvent ContainerListener
or removed from
container

generated when scroll


AdjustmentEvent AdjustmentListener
bar is manipulated

generated when
FocusEvent component gains or FocusListener
loses keyboard focus

AWT stands for Abstract Window Toolkit.

It is a platform-dependent API to develop GUI (Graphical User Interface) or window-based


applications in Java. It was developed by Sun Microsystem In 1995. It is heavy-weight in
use because it is generated by the system’s host operating system. It contains a large
number of classes and methods, which are used for creating and managing GUI.
Java AWT Hierarchy

Characteristics
 It is a set of native user interface components.
 It is very robust in nature.
 It includes various editing tools like graphics tool 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 development of GUI and executing programs.
 It is highly stable as it rarely crashes.
 It is dependent on operating system so performance is high.
 It is easy to use for beginners due to its easy interface.
Disadvantages
 The buttons of AWT does 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

AWT Classes

The AWT framework contains many classes and interfaces using which we
can create GUIs. The AWT package is java.awt. Some of the frequently used
AWT classes are listed below:
Various classes in java.awt package are arranged in a hierarchy as shown
below:
Component and Container

The Component is the abstract root class for many GUI control classes.
Container is a sub class of Component class. The Component and various
Container classes are arranged in a hierarchy as shown below:
Component

Component is the abstract class that encapsulates all the properties of a


visual component. Except for menus, most of the GUI components are
inherited from the Component class.

Container

Container is a sub class of the Component class which can be used to hold
other components. A Container object can hold other Containers also. A
Container is responsible for laying out (positioning) the components.

Panel

Panel class is a concrete sub class of the Container class. A Panel object is a
window without title bar, menu bar and border. Panel is the super class of
Applet class and is capable of holding other components or containers.

Window

Window is a sub class of Container class. A Window creates a top-level


container which can hold other components or containers.

Frame

Frame is a concrete sub class of Window class. The Frame encapsulates a


window. Frame contains a title bar, menu bar, borders and resizable corners.
To create stand alone applications in Java, we generally use Frame.

Canvas

Canvas class is derived from the Component class. A Canvas encapsulates a


blank window on which we can draw.

Frame Class

The Frame class is used to create standard windows. Following are two
Frame class constructors:

Frame()
Frame(String title)

Following are some of the frequently used methods of Frame class:

void setSize(int width, int height) – Used to specify the width and height of
the frame window.

void setSize(Dimension reference) – Used to specify the dimensions of the


frame window.

Dimension getSize() – Returns the dimensions of the frame window.

void setVisible(boolean visibleFlag) – Makes the frame window visible or non-


visible based on the boolean parameter.

void setTitle(String title) – Used to set the title of the frame window.

You might also like