0% found this document useful (0 votes)
30 views

Java Bcanotes

Uploaded by

Rohan rao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Java Bcanotes

Uploaded by

Rohan rao
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

UNIT – 1

INTERNET
Internet: Internet, a system architecture that has revolutionized communications and
methods of commerce by allowing various computer networks around the world to
interconnect. Sometimes referred to as a “network of networks,” the Internet
emerged in the United States in the 1970s but did not become visible to the general
public until the early 1990s. By 2020, approximately 4.5 billion people, or more than
half of the world’s population, were estimated to have access to the Internet. The
Internet provides a capability so powerful and general that it can be used for almost
any purpose that depends on information, and it is accessible by every individual
who connects to one of its constituent networks. It supports human communication
via social media, electronic mail (e-mail), “chat rooms,” newsgroups, and audio and
video transmission and allows people to work collaboratively at many different
locations. It supports access to digital information by many applications, including the
World Wide Web.

Web (World Wide Web): The World Wide Web—usually called the Web for short—is
a collection of different websites you can access through the Internet. A website is
made up of related text, images, and other resources. Websites can resemble other
forms of media—like newspaper articles or television programs—or they can be
interactive in a way that's unique to computers. The purpose of a website can be
almost anything: a news platform, an advertisement, an online library, a forum for
sharing images, or an educational site.
History of the Internet: The first computer networks were dedicated special-
purpose systems such as SABRE (an airline reservation system) and AUTODIN I (a
defense command-and-control system), both designed and implemented in the late
1950s and early 1960s. By the early 1960s computer manufacturers had begun to
use semiconductor technology in commercial products, and both conventional
batch-processing and time-sharing systems were in place in many large,
technologically advanced companies.
Time-sharing systems allowed a computer’s resources to be shared in rapid
succession with multiple users, cycling through the queue of users so quickly that the
computer appeared dedicated to each user’s tasks despite the existence of many
others accessing the system “simultaneously.” This led to the notion of sharing
computer resources (called host computers or simply hosts) over an entire network.
Host-to-host interactions were envisioned, along with access to specialized resources
(such as supercomputers and mass storage systems) and interactive access by
remote users to the computational powers of time-sharing systems located elsewhere.
Internet Tools and Services: The Internet covers large, international Wide Area
Networks (WAN‘s) as well as smaller Local Area Networks (LAN‘s) and individual
computers connected to the Internet worldwide. The Internet supports
communication and sharing of data, and offers vast amount of information
through a variety of services and tools.
The major Internet tools and services are:

● Electronic mail (email)


● Newsgroups
● Internet Relay Chat (IRC)
● Telnet and SSH
● File Transfer Protocol (FTP and FTPS, SFTP)
● World Wide Web (www)

Services: The type of Internet service you choose will largely depend on which
Internet service providers (ISPs) serve your area, along with the types of service they
offer. Here are some common types of Internet services.
● Dial-up: This is generally the slowest type of Internet connection, and you
should probably avoid it unless it is the only service available in your area. Dial-
up Internet uses your phone line, so unless you have multiple phone lines you
will not be able to use your landline and the Internet at the same time.
● DSL: DSL service uses a broadband connection, which makes it much faster
than dial-up. DSL connects to the Internet via a phone line but does not require
you to have a landline at home. And unlike dial-up, you'll be able to use the
Internet and your phone line at the same time.
● Cable: Cable service connects to the Internet via cable TV, although you do
not necessarily need to have cable TV in order to get it. It uses a broadband
connection and can be faster than both dial-up and DSL service; however, it is
only available where cable TV is available.
● Satellite: A satellite connection uses broadband but does not require cable or
phone lines; it connects to the Internet through satellites orbiting the Earth. As
a result, it can be used almost anywhere in the world, but the connection may
be affected by weather patterns. Satellite connections are also usually slower
than DSL or cable.
● 3G and 4G: 3G and 4G service is most commonly used with mobile phones,
and it connects wirelessly through your ISP's network. However, these types of
connections aren't always as fast as DSL or cable. They will also limit the
amount of data you can use each month, which isn't the case with most
broadband plans.
Connecting to the internet: The following are three ways to connect to the
internet:
● Connecting using Wireless Broadband (Wi-Fi)- Wi-Fi is the wireless
technology used to connect smartphones, tablets, computers and other devices
to the internet. Wi-Fi is the radio signal sent from a wireless router to a nearby
devices, which translates the signal into data you can see and use.
Note- Wi-Fi wireless technology is based on IEEE 802.11 standards which allow the
electronic device to connect to the internet.

● Connecting using an Ethernet cable- The most common use for an Ethernet
cable is connecting to a Wi-Fi router or modem to the internet entry post or
telephone line.
Connecting Procedure -

● Connect to the ethernet cable to a yellow LAN port on your modem.


● Connect the other end of the Ethernet cable to an ethernet port on your computer
or laptop.
● Make sure that the ethernet light is green and flashing next to the port you have
used on your computer.
Connecting a computer using a Dial-up- A dial up connection uses a standard phone
line and analog modem to access the internet at Data Transfer Rates (DTR) of up to 56
kbps.

● A dial up connection is the least expensive way to access the internet but it is
also slowest connection.

Connecting to Internet: Telephone, Cable, Satellite connection, Choosing an ISP we


will discuss how to connect to internet i.e. internet service providers, software and
hardware requirements, configuring internet connection etc.
Connection Types
There exist several ways to connect to the internet. Following are these connection
types available:
1.Dial-up Connection 2. ISDN 3.DSL
4. Cable TV Internet connections 5. Satellite Internet
connections 6. Wireless Internet Connections
1.Dial-up Connection- Dial-up connection uses telephone line to connect PC to the
internet. It requires a modem to setup dial-up connection. This modem works as an
interface between PC and the telephone line.There is also a communication program
that instructs the modem to make a call to specific number provided by an ISP.
Dial-up connection uses either of the following protocols:

• Serial Line Internet Protocol (SLIP)


• Point to Point Protocol (PPP)
The following diagram shows the accessing internet using modem:

2. ISDN- ISDN is acronym of Integrated Services Digital Network. It establishes the


connection using the phone lines which carry digital signals instead of analog signals.
There are two techniques to deliver ISDN services:
1. Basic Rate Interface (BRI)
2. Primary Rate Interface (PRI)

Key points:
• The BRI ISDN consists of three distinct channels on a single ISDN line: t1o
64kbps B (Bearer) channel and one 16kbps D (Delta or Data) channels.
• The PRI ISDN consists of 23 B channels and one D channels with both have
operating capacity of 64kbps individually making a total transmission rate of
1.54Mbps.
The following diagram shows accessing internet using ISDN connection:
3.DSL- DSL is acronym of Digital Subscriber Line. It is a form of broadband connection
as it provides connection over ordinary telephone lines.
Following are the several versions of DSL technique available today:
1. Asymmetric DSL (ADSL)
2. Symmetric DSL (SDSL)
3. High bit-rate DSL (HDSL)
4. Rate adaptive DSL (RDSL)
5. Very high bit-rate DSL (VDSL)
6. ISDN DSL (IDSL)
All of the above mentioned technologies differ in their upload and download speed, bit
transfer rate and level of service.
The following diagram shows that how we can connect to internet using DSL
technology:
4.Cable TV Internet Connection- Cable TV Internet connection is provided through
Cable TV lines. It uses coaxial cable which is capable of transferring data at much
higher speed than common telephone line.
Key Points:

• A cable modem is used to access this service, provided by the cable operator.
• The Cable modem comprises of two connections: one for internet service and
other for Cable TV signals.
• Since Cable TV internet connections share a set amount of bandwidth with a
group of customers, therefore, data transfer rate also depends on number of
customers using the internet at the same time.
The following diagram shows that how internet is accessed using Cable TV connection:

5. Satellite Internet Connection


Satellite Internet connection offers high speed connection to the internet. There are two
types of satellite internet connection: one way connection or two way connection.
In one way connection, we can only download data but if we want to upload, we need
a dialup access through ISP over telephone line.
In two way connection, we can download and upload the data by the satellite. It does
not require any dialup connection.

The following diagram shows how


internet is accessed using satellite internet connection:
6.Wireless Internet Connection

Wireless Internet Connection makes use of radio frequency bands to connect to the
internet and offers a very high speed. The wireless internet connection can be obtained
by either WiFi or Bluetooth.
Key Points:

• Wi Fi wireless technology is based on IEEE 802.11 standards which allow the


electronic device to connect to the internet.
• Bluetooth wireless technology makes use of short-wavelength radio waves and
helps to create personal area network (PAN).

Internet Service Providers (ISP)- An Internet Service Provider is an organization that


provides a myriad of service for accessing using or participating in the Internet. ISP can
be organized in various forms, such as commercial community owned, non-profit or
otherwise privately owned.
Role of ISP- An ISP is a company that provides web access to both business and
consumers. It may also provide other services such as email services, domain
registration, web hosting and browser services.
Internet Service Provider (ISP) is a company offering access to internet. They offer
various services:
• Internet Access
• Domain name registration
• Dial-up access
• Leased line access
ISP Types

ISPs can broadly be classified into six categories as shown in the following diagram:
ACCESS PROVIDERS- They provide access to internet through telephone lines, cable
wi-fi or fiber optics.
MAILBOX PROVIDER- Such providers offer mailbox hosting services. It implements
email servers to send, receive, accept and store email for other organizations or end
users on their behalf.
HOSTING ISPS- Hosting ISPs offers e-mail, and other web hosting services such as
virtual machines, clouds etc.
VIRTUAL ISPS- Such ISPs offer internet access via other ISP services. It is known as
affinity ISP is an ISP that resells the resources of existing ISPs under another brand
name.
FREE ISPS- Free ISPs do not charge for internet services.
Choosing an Internet service provider
Now that you know about the different types of Internet service, you can do some
research to find out what ISPs are available in your area. If you're having trouble
getting started, we recommend talking to friends, family members, and neighbors
about the ISPs they use. This will usually give you a good idea of the types of Internet
service available in your area.
Most ISPs offer several tiers of service with different Internet speeds, usually measured
in Mbps (short for megabits per second). If you mainly want to use the Internet for
email and social networking, a slower connection (around 2 to 5Mbps) might be all you
need. However, if you want to download music or stream videos, you'll want a faster
connection (at least 5 Mbps or higher). You'll also want to consider the cost of the
service, including installation charges and monthly fees. Generally speaking, the faster
the connection, the more expensive it will be per month. Although dial-up has
traditionally been the least expensive option, many ISPs have raised dial-up prices to
be the same as broadband. This is intended to encourage people to switch to
broadband. We do not recommend dial-up Internet unless it's your only option.

Introduction to Internet Services- 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. Service
N. 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.
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.
4 Very Easy Rodent Oriented Netwide Index to Computer
Achieved (VERONICA)
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 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.

Audio and 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).

Email Concept-
Email provides a great way of communicating with friends, colleagues, business
associates and the like. But with email comes certain responsibilities such as
knowing how to protect yourself and others from viruses, understanding etiquette,
dealing with spam and more.
Email
Email is a service which allows us to send the message in electronic mode over the
internet. It offers an efficient, inexpensive and real time mean of distributing information
among people.
E-Mail Address
Each user of email is assigned a unique name for his email account. This name is
known as E-mail address. Different users can send and receive messages according
to the e- mail address.E-mail is generally of the form username@domainname. For
example, [email protected] is an e-mail address where webmaster is
username and tutorialspoint.com is domain name.
• The username and the domain name are separated by @ (at) symbol.
• E-mail addresses are not case sensitive.
• Spaces are not allowed in e-mail address.
E-mail Protocols are set of rules that help the client to properly transmit the
information to or from the mail server. Here in this tutorial, we will discuss various
protocols such as SMTP, POP, and IMAP.
Advantages
E-mail has prooved to be powerful and reliable medium of commmunication. Here are
the benefits of E-mail:

• Reliable- Many of the mail systems notify the sender if e-mail message was
undeliverable.

• Convenience- There is no requirement of stationary and stamps. One does not


have to go to post office. But all these things are not required for sending or
receiving an mail.
• Speed- E-mail is very fast. However, the speed also depends upon the
underlying network.

• Inexpensive- The cost of sending e-mail is very low.

• Printable- It is easy to obtain a hardcopy of an e-mail. Also an electronic copy of


an e-mail can also be saved for records.
• Global- E-mail can be sent and received by a person sitting across the globe.

• Generality- It is also possible to send graphics, programs and sounds with an e-


mail.
Disadvantages
Apart from several benefits of E-mail, there also exists some disadvantages as
discussed below:

• Forgery- E-mail doesn’t prevent from forgery, that is, someone impersonating
the sender, since sender is usually not authenticated in any way.
• Overload- Convenience of E-mail may result in a flood of mail.

• Misdirection- It is possible that you may send e-mail to an unintended recipient.

• Junk- Junk emails are undesirable and inappropriate emails. Junk emails are
sometimes referred to as spam.
• No Response- It may be frustrating when the recipient does not read the e-mail
and respond on a regular basis.
E-mail System
E-mail system comprises of the following three components:
Mailer- It is also called mail program, mail application or mail client. It allows us to
manage, read and compose e-mail.
Mail Server- The function of mail server is to receive, store and deliver the email. It is
must for mail servers to be Running all the time because if it crashes or is down, email
can be lost.
Mailboxes- Mailbox is generally a folder that contains emails and information about
them.

Secure Email-
Note-
• The Secure Email service does not automatically insert the email into the official
medical record.
• Secure email that is sent to Stanford's mailing list service (@lists.stanford.edu)
must be sent to a secure mailing list. Otherwise, it will be rejected.See How to
Set up a Secure Mailing List for more information.
• Secure: can occur anywhere in the subject line of your message but always
include the colon. Secure: is not case sensitive — you can use any combination
of upper and lower case letters
• Email with "Secure:" anywhere in the subject line is routed through the Secure
Email server unless it is going to a trusted domain (e.g., a Stanford Email
account, @stanfordchildrens.org, @stanfordhealthcare.org). Trusted domains
receive secure email directly without having to verify identity.
• Any email containing High Risk Data must include Secure: somewhere in the
subject line, however it is recommended, and good practice, to include secure: in
the subject line of any message that contains Moderate Risk Data as well. While
your intended recipient may have an @stanford.edu, @stanfordchildrens.org, or
@stanfordhealthcare.org address, you do not know where the message will be
automatically forwarded or manually resent after being read by the original
recipient.
• Do not put sensitive data in the subject line because the subject line is not
secured.
• If you reply to a secure email, your reply will be sent securely provided that
"Secure:" is somewhere in the subject line. You do not need to remove the "RE:"
from the subject line.
To send secure email:
1. If you are sending a message using a desktop client such as Outlook or Apple
Mail, verify that your client is configured correctly. See Configuring Your Email
Program to check your settings. The Secure Email settings are the same as
those for regular email.
If you are sending a message using webmail, your settings are correct so no
action is required.
2. Put Secure: anywhere in the subject line of the message and then continue
typing your subject line. (Be sure to include the colon.)
Example subject line: Secure: Regarding Your Appointment
3. Compose your message and send it as you would normally.
To receive secure email-
1. You can receive a secure message in almost any email client. A secure message
is received in your inbox with the encrypted attachment named
message_zdm.html.
2. To read a secure email, click the message_zdm.html attachment. Next, click the
Read Message button on the page that opens in your Web browser.
3. If you're a first-time user, you'll be asked to register. You'll have to provide your
name and set a password. Another email message will be sent to you to verify
that you are the owner of the email address.
4. If you are a registered user, you'll just need to provide your password and
authenticate. When the authentication process completes, the secure email will
be displayed in your Web browser.
UNIT- 2
CORE JAVA
Introduction- Java is an object-oriented programming language with its runtime
environment. It is a combination of features of C and C++ with some essential additional
concepts. Java is well suited for both standalone and web application development and
is designed to provide solutions to most of the problems faced by users of the internet
era.
What is Java-
• Java is an object-oriented programming language developed by Sun
Microsystems, and it was released in 1995.
• James Gosling initially developed Java in Sun Microsystems (which was later
merged with Oracle Corporation).
• Java is a set of features of C and C++. It has obtained its format from C, and
OOP features from C++.
• Java programs are platform independent which means they can be run on any
operating system with any processor as long as the Java interpreter is available
on that system.
• Java code that runs on one platform does not need to be recompiled to run on
another platform; it's called write once, run anywhere(WORA).
• Java Virtual Machine (JVM) executes Java code, but it has been written in
platform-specific languages such as C/C++/ASM, etc. JVM is not written in Java
and hence cannot be platform independent, and Java interpreter is a part of JVM.
Where Java use- Earlier Java was only used to design and program small computing
devices, but it was later adopted as one of the platform-independent programming
languages, and now according to Sun, 3 billion devices run Java.
Java is one of the most important programming languages in today's IT industries.
• JSP - In Java, JSP (Java Server Pages) is used to create dynamic web pages,
such as in PHP and ASP.
• Applets - Applets are another type of Java programs that are implemented on
Internet browsers and are always run as part of a web document.
• J2EE - Java 2 Enterprise Edition is a platform-independent environment that is a
set of different protocols and APIs and is used by various organizations to
transfer data between each other.
• JavaBeans - This is a set of reusable software components that can be easily
used to create new and advanced applications.
• Mobile - In addition to the above technology, Java is widely used in mobile
devices nowadays, many types of games and applications are being made in
Java.
Type of Java Application-
• Web Application - Java is used to create server-side web applications.
Currently, Servlet, JSP, Struts, JSF, etc. technologies are used.
• Standalone Application - It is also known as the desktop application or window-
based application. An application that we need to install on every machine or
server such as media player, antivirus, etc. AWT and Swing are used in java for
creating standalone applications.
• Enterprise Application - An application that is distributed in nature, such as
banking applications, etc. It has the advantage of high-level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise
applications.
• Mobile Application - Java is used to create application software for mobile
devices. Currently, Java ME is used for building applications for small devices,
and also Java is a programming language for Google Android application
development.
Feature of Java-
• Object-Oriented - Java supports the features of object-oriented programming.
Its object model is simple and easy to expand.
• Platform independent - C and C++ are platform dependency languages hence
the application programs written in one Operating system cannot run in any other
Operating system, but in platform independence language like Java application
programs written in one Operating system can able to run on any Operating
system.
• Simple - Java has included many features of C / C ++, which makes it easy to
understand.
• Secure - Java provides a wide range of protection from viruses and malicious
programs. It ensures that there will be no damage and no security will be
broken.
• Portable - Java provides us with the concept of portability. Running the same
program with Java on different platforms is possible.
• Robust - During the development of the program, it helps us to find possible
mistakes as soon as possible.
• Multi-threaded - The multithreading programming feature in Java allows you to
write a program that performs several different tasks simultaneously.
• Distributed - Java is designed for distributed Internet environments as it
manages the TCP/IP protocol.
Popular Java Editor-
• Notepad - On Windows machine, you can use any simple text editor like
Notepad (Recommended for this tutorial), TextPad.
• Netbeans - is a Java IDE that is open source and free which can be downloaded
from http://www.netbeans.org/index.html
• Eclipse - is also a java IDE developed by the Eclipse open source community
and can be downloaded from http://www.eclipse.org/

Java Operator- Java operators are symbols that are used to perform mathematical or
logical manipulations. Java is rich with built-in operators.
There are many types of operators available in Java such as:
• Arithmetic Operators-
Operator Meaning Work
+ Addition To add two operands.
- Subtraction To subtract two operands.
* Multiplication To multiply two operands.
/ Division To divide two operands.
% Modulus To get the area of the
division of two operands.

• Unary Arithmetic Operators-


Example Description
val = a++; Store the value of "a" in "val" then
increments.
val = a--; Store the value of "a" in "val" then
decrements.
val = ++a; Increments "a" then store the new value
of "a" in "val".
val = --a; Decrements "a" then store the new value
of "a" in "val".

• Relational Operators-
Operator Meaning
== Is equal to
!= Is not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
• Logical Operators-
Operator Meaning Work
&& Logical AND If both operands are true then only "logical AND
operator" evaluate true.
|| Logical OR The logical OR operator is only evaluated as true
when one of its operands evaluates true. If either or
both expressions evaluate to true, then the result is
true.
! Logical Not Logical NOT is a Unary Operator, it operates on
single operands. It reverses the value of operands,
if the value is true, then it gives false, and if it is
false, then it gives true.

• Conditional Operators
Operato Meaning Work
r
& Binary There are two types of AND operators in Java: the logical &&
AND and the binary &. Binary & operator work very much the same
Operator as logical && operators works, except it works with two bits
instead of two expressions. The "Binary AND operator"
returns 1 if both operands are equal to 1.
| Binary OR Like "AND operators ", Java has two different "OR" operators:
Operator the logical || and the binary |. Binary | Operator work similar to
logical || operators works, except it, works with two bits
instead of two expressions. The "Binary OR operator" returns
1 if one of its operands evaluates as 1. if either or both
operands evaluate to 1, the result is 1.
^ Binary It stands for "exclusive OR" and means "one or the other", but
XOR not both. The "Binary XOR operator" returns 1 if and only if
Operator exactly one of its operands is 1. If both operands are 1, or
both are 0, then the result is 0.
~ Binary
Compleme
nt Operator
<< Binary Left
Shift
Operator
>> Binary
Right Shift
Operator
>>> Shift right
zero fill
operator
• Assignment Operators- The Java Assignment Operators are used when you
want to assign a value to the expression. The assignment operator denoted by
the single equal sign =.
o Compound Assignment Operators-
Operator Meaning
+= Increments then assigns
-= Decrements then assigns
*= Multiplies then assigns
/= Divides then assigns
%= Modulus then assigns
<<= Binary Left Shift and assigns
>>= Binary Right Shift and assigns
>>>= Shift right zero fill and assigns
&= Binary AND assigns
^= Binary exclusive OR and assigns
|= Binary inclusive OR and assigns

• Instanceof Operator
• Member Selection or Dot Operator

DataType- Data Types available in Java are:


• Primary Data Type
Java supports eight primitive data types: byte, short, int, long, float, double, char
and boolean.
These eight data types are further classified into four groups:
o Integer,
o Relational Numbers(Floating point)
o Characters
o Boolean(Conditional).
• Non-Primitive Data Types
Classes, Interface, Arrays, etc.
Integer- Integer is the whole number without any fractional point. It can hold whole
numbers such as 196, -52, 4036, etc. Java supports four different types of integers,
these are:
Type Contains Default Size Range
byte Signed integer 0 8 bit or -27 to 27-1 or
1 byte -128 to 127
short Signed integer 0 16 bit or -215 to 215-1
2 bytes or
-32,768 to
32767
int Signed integer 0 32 bit or -231 to 231-1
4 bytes or
-2147,483,648
to
2147,483,647
long Signed integer 0 64 bit or -263 to 263-1
8 bytes or
-
9223,372,036,
854,755,808 to
9223,372,036,
854,755,807

Float- It is used to hold whole numbers containing fractional part such as 36.74, or -
23.95 (which are known as floating point constants). There are two types of floating
point storage in java. These are:
Type Contains Default Size Range
float IEEE 754 0.0f 32 bit or ±1.4E-45 to
floating point 4 bytes ±3.40282347E
single- +38F
precision
double IEEE 754 0.0 64 bit or ±439E-324 to
floating point 8 bytes ±1.797693134
double- 8623157E+308
precision

Character- It is used to store character constants in memory. Java provides a character


data type called char whose type consumes a size of two bytes but can hold only a
single character.
Type Contains Default Size Range
char Unicode \u0000 16 bits or 0 to 216-1 or
character 2 bytes \u0000 to
unsigned \uFFFF

Conditional- Boolean type is used to test a particular condition during program


execution. Boolean variables can take either true or false and is denoted by the
keyword boolean and usually consumes one byte of storage.
Type Contains Default Size Range
boolean true or false false 1 bit true or false
Variable- A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary + able" which
means its value can be changed.
Types of Variables
There are three types of variables in Java:

• local variable
• instance variable
• static variable
1) 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 "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.

Java Array- Normally, an array is a collection of similar type of elements which has
contiguous memory location.
• 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.
• Unlike C/C++, we can get the length of the array using the length member. In
C/C++, we need to use the sizeof operator.
• In Java, array is an object of a dynamically generated class. Java array inherits the
Object class, and implements the Serializable as well as Cloneable interfaces. We
can store primitive values or objects in an array in Java. Like C/C++, we can also
create single dimentional or multidimentional arrays in Java.
• Moreover, Java provides the feature of anonymous arrays which is not available
in C/C++.

Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
• Random access: We can get any data located at an index position.
Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow
its size at runtime. To solve this problem, collection framework is used in Java
which grows automatically.
Types of Array in java
There are two types of array.

• Single Dimensional Array


• Multidimensional Array
Single Dimensional Array in Java
Syntax-

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];
Instantiation of an Array in Java

arrayRefVar=new datatype[size];

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java

1. dataType[][] arrayRefVar; (or)


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

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

Decision Making statements

o if statements
o switch statement

Loop statements

o do while loop
o while loop
o for loop
o for-each loop

Jump statements

o break statement
o continue statement
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided. There are two types of
decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given
below. Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.

if(condition) {

statement 1; //executes when condition is true

}
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is evaluated
as false.
Syntax:

if(condition) {

statement 1; //executes when condition is true

else{

statement 2; //executes when condition is false

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

if(condition 1) {

statement 1; //executes when condition 1 is true

else if(condition 2) {

statement 2; //executes when condition 2 is true


}

else {

statement 2; //executes when all the conditions are false

}
4. Nested if-statement:
In nested if-statements, the if statement can contain a if or if-else statement inside another
if or else-if statement.
Syntax of Nested if-statement is given below.

if(condition 1) {

statement 1; //executes when condition 1 is true

if(condition 2) {

statement 2; //executes when condition 2 is true

else{

statement 2; //executes when condition 2 is false

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the
variable which is being switched. The switch statement is easier to use instead of if-else-
if statements. It also enhances the readability of the program.
Points to be noted about switch statement:

• The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.

switch (expression){

case value1:

statement1;

break;

case valueN:

statementN;

break;

default:

default statement;

}
Loop Statements:
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.

1.for loop

2.while loop

3.do-while loop
1. for loop- In Java, for loop is similar to C and C++. It enables us to initialize the
loop variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
for(initialization, condition, increment/decrement) {

//block of statements

}
The flow chart for the for-loop is given below.

Syntax-

for(data_type var : array_name/collection_name){

//statements

2. Java while loop- The while loop is also used to iterate over the number of
statements multiple times. However, if we don't know the number of iterations in
advance, it is recommended to use a while loop. Unlike for loop, the initialization
and increment/decrement doesn't take place inside the loop statement in while
loop.
It is also known as the entry-controlled loop since the condition is checked at the start of
the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
The syntax of the while loop is given below.

while(condition){

//looping statements

}
The flow chart for the while loop is given in the following image.
3. Java do-while loop- The do-while loop checks the condition at the end of the
loop after executing the loop statements. When the number of iteration is not
known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance.
The syntax of the do-while loop is given below.

do

//statements

} while (condition);
The flow chart of the do-while loop is given in the following image.

Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the other
part of the program. There are two types of jump statements in Java, i.e., break and
continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch statement.
However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only
be written inside the loop or switch statement.

Syntax-

public class BreakExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 0; i<= 10; i++) {

System.out.println(i);

if(i==6) {

break;
}

}
Continue statement- Unlike break statement, the continue statement doesn't break the
loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the
loop immediately.
Consider the following example to understand the functioning of the continue statement
in Java.

public class ContinueExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

if(j == 4) {

continue;

System.out.println(j);

Class- A class is a user defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by
convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
5. Interfaces (if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more
than one interface.
6. Body: The class body surrounded by braces, {}.

Object- It is a basic unit of Object-Oriented Programming and represents the real-life


entities. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of:
1. State: It is represented by attributes of an object. It also reflects the properties of
an object.
2. Behavior: It is represented by methods of an object. It also reflects the response
of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Objects correspond to things found in the real world. For example, a graphics program
may have objects such as “circle”, “square”, “menu”. An online shopping system might
have objects such as “shopping cart”, “customer”, and “product”.

Method- In general, a method is a way to perform some tasks. 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.

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.
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. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method runs in the background
that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
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.
We have defined the above method named findevenodd(). It has a parameter num of type
int. The method does not return any value that's why we have used void. The method
body contains the steps to check the number is even or odd. If the number is even, it
prints the number is even, else prints the number is odd.
Once we have defined a method, it should be called. The calling of a method in a program
is simple. When we call or invoke a user-defined method, the program control transfer to
the called method.

Inheritance- Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs (Object
Oriented programming system). 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. Moreover, you can
add new methods and fields in your current class also. Inheritance represents the IS-A
relationship which is also known as a parent-child relationship.
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
class Subclass-name extends Superclass-name

//methods and fields

}
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Java Package- A java package is a group of similar types of classes, interfaces and sub-
packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Package- Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces. Packages are used for:
• Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
• Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
• Providing controlled access: protected and default have package level access
control. A protected member is accessible by classes in the same package and
its subclasses. A default member (without any access specifier) is accessible by
classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding).

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some
of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

User-defined packages- These are the packages that are defined by the user. First we
create a directory myPackage (name should be same as the name of the package). Then
create the MyClass inside the directory with the first statement being the package names

Interface- An interface in Java is a blueprint of a class. It has static constants and


abstract methods. The interface in Java is a mechanism to achieve abstraction. There
can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java. In other words, you can say that
interfaces can have abstract methods and variables. It cannot have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Declaration in Java-
Syntax: interface <interface_name>{
// declare constant fields

// declare methods that abstract

// by default.

}
Exception Handling- The Exception Handling in Java is one of the powerful mechanism
to handle the runtime errors so that the normal flow of the application can be maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition. In Java, an exception is an event
that disrupts the normal flow of the program. It is an object which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to
handle exceptions. Let's consider a scenario:

Types
1) Checked Exception- The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For example,
IOException, SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception- The classes that inherit the RuntimeException are known as
unchecked exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error- Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Multithreading- Multithreading in Java is a process of executing multiple threads


simultaneously. A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process. Also, context switching
between threads takes less time.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
1. It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn't affect other threads if an exception occurs
in a single thread.
Multitasking- Multitasking is a process of executing multiple tasks simultaneously. We
use multitasking to utilize the CPU. Multitasking can be achieved in two ways:
• 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
registers

• , memory maps, updating lists, etc.


2) Thread-based Multitasking (Multithreading)
• Threads share the same address space.
• A thread is lightweight.

I/o in Java- Java I/O (Input and Output) is used to process the input and produce the
output. Java uses the concept of a stream to make I/O operation 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.
Stream- A stream is a sequence of data. In Java, a stream is composed of bytes. It's
called a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
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.
Here is a list of the various print functions that we use to output statements:
o print(): This method in Java is used to display a text on the console. This
text is passed as the parameter to this method in the form of String. This
method prints the text on the console and the cursor remains at the end of
the text at the console. The next printing takes place from just here.
o println(): This method in Java is also used to display a text on the
console. It prints the text on the console and the cursor moves to the start
of the next line at the console. The next printing takes place from the next
line.
o printf(): This is the easiest of all methods as this is similar to printf in C.
Note that System.out.print() and System.out.println() take a single
argument, but printf() may take multiple arguments. This is used to format
the output in Java.
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.This stream also uses all the 3 above-mentioned functions to output the
error data:
1. print()
2. println()
3. printf()

Java Applet- An applet is a Java program that runs in a Web browser. An applet can be
a fully functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following −
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not define
main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet
is downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the applet
to a child playing in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.
Life Cycle of an Applet
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.
Advantage of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.

String Handling- In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. Java String class provides a
lot of methods to perform operations on strings such as compare(), concat(), equals(),
split(), length(), replace(), compareTo(), intern(), substring() etc.

String Handling- Strings, which are widely used in Java programming, are a sequence
of characters. In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world!'.
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray); System.out.println(
helloString );
}
}

Java Networking- Java Networking is a concept of connecting two or more computing


devices together so that we can share resources.
Java socket programming provides facility to share data between different computing
devices.
Advantage of Java Networking
1. Sharing resources
2. Centralize software management

The java.net package supports two protocols,

TCP: Transmission Control Protocol provides reliable communication between the


sender and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.

UDP: User Datagram Protocol provides a connection-less protocol service by allowing


packet of data to be transferred along two or more nodes
Java Networking Terminology-
1) IP Address- IP address is a unique number assigned to a node of a network e.g.
192.168.0.1 . It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol- A protocol is a set of rules basically that is followed for communication. For
example:
• TCP
• FTP
• Telnet
• SMTP
• POP etc.
3) Port Number- The port number is used to uniquely identify different applications. It
acts as a communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address- MAC (Media Access Control) address is a unique identifier of NIC
(Network Interface Controller). A network node can have multiple NIC but each with
unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable
but slow. The example of connection-oriented protocol is TCP. But, in connection-less
protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.
6) Socket- A socket is an endpoint between two way communications.
Visit next page for Java socket programming.

What is an Event?
Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user
interface components. For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the page are the activities
that causes an event to happen.
Types of Event
The events can be broadly classified into two categories:
• Foreground Events - Those events which require the direct interaction of
user.They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting an
item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user are
known as background events. Operating system interrupts, hardware or software
failure, timer expires, an operation completion are the example of background
events.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should happen
if an event occurs. This mechanism have the code which is known as event handler that
is executed when an event occurs. Java Uses the Delegation Event Model to handle the
events. This model defines the standard mechanism to generate and handle the
events.Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
• Source - The source is an object on which event occurs. Source is responsible for
providing information of the occurred event to it's handler. Java provide as with
classes for source object.
• Listener - It is also known as event handler.Listener is responsible for generating
response to an event. From java implementation point of view the listener is also
an object. Listener waits until it receives an event. Once the event is received , the
listener process the event an then returns.
The benefit of this approach is that the user interface logic is completely separated from
the logic that generates the event. The user interface element is able to delegate the
processing of an event to the separate piece of code. In this model ,Listener needs to be
registered with the source object so that the listener can receive the event notification.
This is an efficient way of handling the event because the event notifications are sent only
to those listener that want to receive them.
Steps involved in event handling
• The User clicks the button and the event is generated.
• Now the object of concerned event class is created automatically and information
about the source and the event get populated with in same object.
• Event object is forwarded to the method of registered listener class.
• the method is now get executed and returns.
Points to remember about listener
• In order to design a listener class we have to develop some listener
interfaces.These Listener interfaces forecast some public abstract callback
methods which must be implemented by the listener class.
• If you do not implement the any if the predefined interfaces then your class can not
act as a listener class for a source object.
Callback Methods
These are the methods that are provided by API provider and are defined by the
application programmer and invoked by the application developer. Here the callback
methods represents an event method. In response to an event java jre will fire callback
method. All such callback methods are provided in listener interfaces.
If a component wants some listener will listen to it's events the the source must register
itself to the listener.

Introduction to AWT-
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
• Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
• The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• The AWT tutorial will help the user to understand Java GUI programming in simple
and easy steps.
• Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.

Hierarchy of AWT-

Java AWT Hierarchy- The hierarchy of Java AWT classes are given below, all the
classes are available in java.awt packag.
Component class- Component class is at the top of AWT hierarchy. It is an abstract
class that encapsulates all the attributes of visual component. A component object is
responsible for remembering the current foreground and background colors and the
currently selected text font.
Container- Container is a component in AWT that contains another component like
button, text field, tables etc. Container is a subclass of component class. Container
class keeps track of components that are added to another component.
Panel- Panel class is a concrete subclass of Container. Panel does not contain title bar,
menu bar or border. It is container that is used for holding components.
Window class- Window class creates a top level window. Window does not have
borders and menubar.
Frame- Frame is a subclass of Window and have resizing canvas. It is a container that
contain several different components like button, title bar, textfield, label etc. In Java,
most of the AWT applications are created using Frame window. Frame class has two
different constructors,
1. Label A Label object is a component for placing text in a container.
2. Button This class creates a labeled button.

3. Check Box A check box is a graphical component that can be in either an


on (true) or off (false) state.

4. List The List component presents the user with a scrolling list of text
items.
5. Choice A Choice control is used to show pop up menu of choices.
Selected choice is shown on the top of the menu.

Layout- In Java, Layout Managers is used for arranging the components in order.
LayoutMananger is an interface which implements the classes of the layout manager.
1. java.awt.BorderLayout- BorderLayout is used, when we want to arrange the
components in five regions. The five regions can be north, south, east, west and
the centre. There are 5 types of constructor in Border Layout. Types-
• public static final int NORTH
• public static final int SOUTH
• public static final int EAST
• public static final int WEST
• public static final int CENTER

2. Java.awt.FlowLayout- Flow Layout is used, when we want to arrange the


components in a sequence one after another. Types-
• FlowLayout()
• FlowLayout(int align)
• FlowLayout(int align, inthgap, intvgap)

3. Java.awt.GridLayout- Grid Layout is used, when we want to arrange the


components in a rectangular grid. Types-
• GridLayout()
• GridLayout(int rows, int columns)
• GridLayout(int rows, int columns, inthgap, int vgap)

4. Java.awt.CardLayout- Card Layout is used, when we want to see only one


component at a time.Types-
• CardLayout()
• CardLayout(inthgap, intvgap)
5. javax.swing.BoxLayout- Box Layout is used, when we want to arrange the
components vertically or horizontally.BoxLayout(Container c, int axis)is the only
constructor in the Box Layout

Menus in Java- We started this chapter by introducing the most common components
that you might want to place into a window, such as various kinds of buttons, text fields,
and combo boxes. Swing also supports another type of user interface element, the pull-
down menus that are familiar from GUI applications. A menu bar on top of the window
contains the names of the pull-down menus. Clicking on a name opens the menu
containing menu items and submenus. When the user clicks on a menu item, all menus
are closed and a message is sent to the program. a typical menu with a submenu.

A menu with a submenu-

1. Menu Building- Building menus is straightforward. You first create a menu bar:

[JMenuBar menuBar = new JMenuBar();]

A menu bar is just a component that you can add anywhere you like. Normally, you want
it to appear at the top of a frame. You can add it there with the set JMenuBar method:

[frame.setJMenuBar(menuBar);]

For each menu, you create a menu object:

[JMenu editMenu = new JMenu("Edit");]

You add the top-level menus to the menu bar:

menuBar.add(editMenu);
• JMenu(String label)
constructs a menu with the given label.
• JMenuItem add(JMenuItem item)
adds a menu item (or a menu).
• JMenuItem add(String label)
adds a menu item with the given label to this menu and returns the item.
• JMenuItem add(Action a)
adds a menu item with the given action to this menu and returns the item.
• void addSeparator()
adds a separator line to the menu.
• JMenuItem insert(JMenuItem menu, int index)
adds a new menu item (or submenu) to the menu at a specific index.
• JMenuItem insert(Action a, int index)
adds a new menu item with the given action at a specific index.
• void insertSeparator(int index)
adds a separator to the menu.
• void remove(int index)
• void remove(JMenuItem item)
removes a specific item from the menu.
• JMenuItem(String label)
constructs a menu item with a given label.
• JMenuItem(Action a)
constructs a menu item for the given action.
• void setAction(Action a)
sets the action for this button or menu item.
• void setJMenuBar(JMenuBar menubar)
sets the menu bar for this frame.
2. Icons in Menu Items- Menu items are very similar to buttons. In fact, the
JMenuItem class extends the Abstract Button class. Just like buttons, menus can
have just a text label, just an icon, or both.

[JMenuItem cutItem = new JMenuItem("Cut", new ImageIcon("cut.gif"));]

3. Checkbox and Radio Button Menu Items- Checkbox and radio button menu
items display a checkbox or radio button next to the name.

[JCheckBoxMenuItem readonlyItem = new JCheckBoxMenuItem("Read-only");

optionsMenu.add(readonlyItem);]
4. Pop-Up Menus- A pop-up menu is a menu that is not attached to a menu bar but
that floats somewhere.

[JPopupMenu popup = new JPopupMenu();

You then add menu items in the usual way:

JMenuItem item = new JMenuItem("Cut");

item.addActionListener(listener);

popup.add(item);]

5. Keyboard mnemonics- You can supply a mnemonic letter only in the constructor
of a menu item, not in the constructor for a menu. Instead, to attach a mnemonic
to a menu, you call the setMnemonic method:

JMenu helpMenu = new JMenu("Help");

helpMenu.setMnemonic('H');

6. Enabling and Disabling Menu Items- Occasionally, a particular menu item


should be selected only in certain contexts. To enable or disable a menu item, use
the setEnabled method:

[saveItem.setEnabled(false);]

7. Toolbars- A toolbar is a button bar that gives quick access to the most commonly
used commands in a program .

[JToolBar bar = new JToolBar();

bar.add(blueButton);]

8. Tooltips- A disadvantage of toolbars is that users are often mystified by the


meanings of the tiny icons in toolbars. To solve this problem, user interface
designers invented tooltips. A tooltip is activated when the cursor rests for a
moment over a button.

[exitButton.setToolTipText("Exit");]

Images- You have already seen how to build up simple drawings by painting lines and
shapes. Complex images, such as photographs, are usually generated externally, for
example, with a scanner or special image-manipulation software. (itis also possible to
produce an image, pixel by pixel, and store the result in an array. This procedure is
common for fractal images, for example.) Once images are stored in local files or
someplace on the Internet, you can read theminto a Java application and display them
on Graphics objects. As of Java SE 1.4, reading an image is very simple. If the image is
stored in a local file, call

[String filename = "...";

Image image = ImageIO.read(new File(filename));

Otherwise, you can supply a URL:

String urlname = "...";

Image image = ImageIO.read(new URL(urlname));]

Window with tiled graphics image-

1. javax.imageio.ImageIO
• staticBufferedImage read(File f)
• staticBufferedImage read(URL u)
reads an image from the given file or URL.
2. java.awt.Graphics
• booleandrawImage(Image img, int x, int y, ImageObserver observer)
draws an unscaled image. Note: This call may return before the image is drawn.
• booleandrawImage(Image img, int x, int y, int width, intheight, ImageObserver
observer) draws a scaled image. The system scales the image to fit into a region
with the given width and height. Note: This call may return before the image is
drawn.
• void copyArea(int x, int y, int width, int height, int dx, intdy)

Graphics- The Graphics class is the abstract base class for all graphics contexts that
allow an application to draw onto components that are realized on various devices, as
well as onto off-screen images. A Graphics object encapsulates state information needed
for the basic rendering operations that Java supports.

1. public abstract void drawString(String str, int x, int y): is used to draw the
specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with
the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill
rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw
oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle,
int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color
to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font
to the specified font.
Unit 3 : Java Swing

Creating a Swing Applet and Application: Swing-based applets are similar to AWT-based
applets, but with an important difference: A Swing applet extends JApplet rather than Applet.
JApplet is derived from Applet. Thus, JApplet includes all of the functionality found in Applet
and adds support for Swing. JApplet is a top-level Swing container, which means that it is not
derived from JComponent. Because JApplet is a top-level container, it includes the various panes
This means that all components are added to JApplet’s content pane in the same way that
components are added to JFrame’s content pane.

Swing applets use the same four life-cycle methods i.e init( ), start( ), stop( ), and destroy( ). Of
course, you need override only those methods that are needed by your applet. Painting is
accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally
override the paint( ) method.

All interaction with components in a Swing applet must take place on the event dispatching
thread, This threading issue applies to all Swing programs.

Example:

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Programming using Panes/ Swing Containers: Swing component is an independent
control, such as button, label, text field, etc. They need. a container to display themselves. Swing
components are derived from JComponent class. JComponent provides the functionality
common for all components. JComponent inherits the AWT class Container and Component.
Thus, a Swing component and AWT component are compatible with each other.

These are divided into two parts:

a. Top-Level Containers
b. Lightweight Containers

Top-Level Containers: A top-level container, as the name suggests, lies at the top of the
containment hierarchy. The top-level containers are JFrame, JApplet, and JDialog. These
containers do not inherit JComponent class but inherit the AWT classes’ Component and
Container. These containers are heavyweight components. The most commonly used containers
are JFrame and JApplet.

Each top-level container defines a set of panes. JRootPane is a special container which extends
JComponent and manages the appearance of JApplet and JFrame objects. It contains a fixed set
of panes, namely, glass pane, content pane, and layered pane.
• Glass pane: A glass pane is a top-level pane which covers all other panes. By default, it
is a transparent instance of JPanel class. It is used to handle the mouse events affecting
the entire container.

• Layered pane: A layered pane is an instance of JLayeredPane class. It holds a container


called the content pane and an optional menu bar.

• Content pane: A content pane is a pane which is used to hold the components. All the
visual components like buttons, labels are added to content pane. By default, it is an
opaque instance of JPanel class and uses border layout. The content pane is accessed via
getContentPane () method of JApplet and JFrame classes.

Lightweight Containers: Lightweight containers lie next to the top-level containers in the
containment hierarchy. They inherit. JComponent. One of the examples of lightweight container
is JPanel. As lightweight container can be contained within another container, they can be used
to organize and manage groups of related components.

Pluggable Look and Feel:

Swing is GUI Widget Toolkit for Java. It is an API for providing Graphical User Interface to
Java Programs. Unlike AWT, Swing components are written in Java and therefore are
platform-independent. Swing provides platform specific Look and Feel and also an option for
pluggable Look and Feel, allowing application to have Look and Feel independent of
underlying platform.

Initially there were very few options for colors and other settings in Java Swing, that made the
entire application look boring and monotonous. With the growth in Java framework, new
changes were introduced to make the UI better and thus giving developer opportunity to
enhance the look of a Java Swing Application.

“Look” refers to the appearance of GUI widgets and “feel” refers to the way the widgets
behave.
1. CrossPlatformLookAndFeel: this is the “Java L&F” also known as “Metal” that looks
the same on all platforms. It is part of the Java API (javax.swing.plaf.metal) and is the
default.
2. SystemLookAndFeel: here, the application uses the L&F that is default to the system it is
running on. The System L&F is determined at runtime, where the application asks the
system to return the name of the appropriate L&F.
3. Synth: the basis for creating your own look and feel with an XML file.
4. Multiplexing: a way to have the UI methods delegate to a number of different look and
feel implementations at the same time

Example: UIManager.setLookAndFeel("fully qualified name of look and feel");

Label: The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a user
cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create a label,
we need to create the object of Label class.

Label Fields: The java.awt.Component class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Example: public class Label extends Component implements Accessible

Text fields: The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed), the event is
sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It can also be done
using ActionEvent; if the ActionEvent is enabled on the text field, then the ActionEvent may be
fired by pressing return key. The event is handled by the ActionListener interface.

Syntax: public class TextField extends TextComponent

Buttons: A button is basically a control component with a label that generates an event when
pushed. The Button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

Toggle Buttons: A JToggleButton is a two-state button. The two states are selected and
unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the
user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is
used to select a choice from a list of possible choices. Buttons can be configured, and to some
degree controlled, by Actions. Using an Action with a button has many benefits beyond
directly configuring a button.

Constructors in JToggleButton:

1. JToggleButton(): Creates an initially unselected toggle button without setting the text or
image.
2. JToggleButton(Action a): Creates a toggle button where properties are taken from the
Action supplied.
3. JToggleButton(Icon icon): Creates an initially unselected toggle button with the specified
image but no text.
4. JToggleButton(Icon icon, boolean selected): Creates a toggle button with the specified
image and selection state, but no text.
5. JToggleButton(String text): Creates an unselected toggle button with the specified text.
6. JToggleButton(String text, boolean selected): Creates a toggle button with the specified
text and selection state.

Radio Buttons: The JRadioButton class is used to create a radio button. It is used to choose
one option from multiple options. It is widely used in exam systems or quiz. It should be added
in ButtonGroup to select one radio button only.
View ports: A viewport represents a polygonal (normally rectangular) area in computer
graphics that is currently being viewed. In web browser terms, it refers to the part of the
document you're viewing which is currently visible in its window (or the screen, if the document
is being viewed in full screen mode).

Scroll Panes: A JScrollPane provides a scrollable view of a component. When screen real
estate is limited, use a scroll pane to display a component that is large or one whose size can
change dynamically. Other containers used to save screen space include split panes and tabbed
panes. The code to create a scroll pane can be minimal.
Scroll Bar: A vertical or horizontal bar commonly on the far right or bottom of a
window that allows you to move the window viewing area up, down, left, or right. Most people
today are familiar with scroll bars because of the need to scroll up and down on almost every
Internet web page.

Lists: List in Java provides the facility to maintain the ordered collection. It contains the index-
based methods to insert, update, delete and search the elements. It can have the duplicate
elements also. We can also store the null elements in the list.

The List interface is found in the java.utl package and inherits the Collection interface. It is a
factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and
backward directions. The implementation classes of List interface are ArrayList and LinkedList,
Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The
Vector class is deprecated since Java 5.

Combo Box: A combo box is a combination of a text field and a drop-down list from
which the user can choose a value. If the text-field portion of the control is editable, the user
can enter a value in the field or edit a value retrieved from the drop-down list. You use the
JComboBox class to create combo boxes.
Progress Bar: A progress bar is a graphical control element used to visualize the progression
of an extended computer operation, such as a download, file transfer, or installation. Sometimes,
the graphic is accompanied by a textual representation of the progress in a percent format.

Menus and Toolbars:

• Menus typically are displayed as one-word strings clustered in a row at the top of the
integrated development environment (IDE) or a tool window. Menus also can be
displayed as the result of a right-click event, and are referred to as shortcut menus in that
context. When clicked, menus expand to display one or more commands. Commands,
when clicked, can carry out tasks or launch submenus that contain additional commands.
Some well-known menu names are File, Edit, View, and Window.
• Toolbars typically are rows of buttons and other controls, such as combo boxes, list
boxes, text boxes, and menu controllers. All toolbar controls are associated with
commands. When you click a toolbar button, its associated command is activated.
Toolbar buttons usually have icons that suggest the underlying commands, such as a
printer for a Print command. In a drop-down list control, each item in the list is associated
with a different command. A menu controller is a hybrid in which one side of the control
is a toolbar button and the other side is a down arrow that displays additional commands
when clicked.

Layered Panes: A layered pane is a Swing container that provides a third dimension for
positioning components: depth, also known as Z order. When adding a component to a layered
pane, you specify its depth as an integer. The higher the number, closer the component is to the
"top" position within the container.
Tabbed Panes: The JTabbedPane class is used to switch between a group of components
by clicking on a tab with a given title or icon. It inherits JComponent class.

Split Panes: JSplitPane is used to divide two components. The two components are divided
based on the look and feel implementation, and they can be resized by the user. If the minimum
size of the two components is greater than the size of the split pane, the divider will not allow
you to resize it.

The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using JSplitPane.VERTICAL_SPLIT.
When the user is resizing the components the minimum size of the components is used to
determine the maximum/minimum position the components can be set to.
Layouts: Layout Manager in UNIT 2

Windows: The class Window is a top level window with no border and no menubar. It uses
BorderLayout as default layout manager. (UNIT 2)

Dialog Boxes: The JOptionPane class is used to provide standard dialog boxes such as
message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to
display information or get input from the user. The JOptionPane class inherits JComponent class.

Example:
import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Inner Frame:

JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many


features of a frame which includes displaying title, opening, closing, resizing, support for menu
bar, etc.
Constructors for JInternalFrame

1. JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non-
maximizable JInternalFrame with no title
2. JInternalFrame(String t) :creates a new non- closable, non- resizable, non- iconifiable,
non- maximizable JInternalFrame with a title specified
3. JInternalFrame(String t, boolean resizable) :creates a new non- closable, non-
iconifiable, non- maximizable JInternalFrame with a title and resizability specified
4. JInternalFrame(String t, boolean resizable, boolean closable) : creates a new non-
iconifiable, non- maximizable JInternalFrame with a title, closability and resizability
specified
5. JInternalFrame(String t, boolean resizable, boolean closable, boolean
maximizable) :creates a new non- iconifiable JInternalFrame with a title, closability,
maximizability and resizability specified
6. JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable,
boolean iconifiable) : creates a new JInternalFrame with a title, closability,
maximizability, iconifiability and resizability specified
UNIT-4 (JDBC)

JDBC Connectivity Model:


JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as −
• Java Applications
• Java Applets
• Java Servlets
• Java ServerPages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture: The JDBC API supports both two-tier and three-tier processing models
for database access but in general, JDBC Architecture consists of two layers −
• JDBC API − This provides the application-to-JDBC Manager connection.
• JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application –
The JDBC API provides the following interfaces and classes.
• DriverManager − This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
• Driver − This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
• Connection − This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
• Statement − You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
• ResultSet − These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its
data.
• SQLException − This class handles any errors that occur in a database application.
JDBC-ODBC Bridge: The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:

• easy to use.
• can be easily connected to any database.

Disadvantages:

• Performance degraded because JDBC method call is converted into the ODBC
function calls.
• The ODBC driver needs to be installed on the client machine.

Java.Sql Package: We have relational databases, from which at many times we need to
access the data. For various data processing related matters from RDDBMS we have java.sql
package. The various classes in the package.
• Date: It gives time in milliseconds. It is a wrapper type. It provides sql with dates. The
class is declared as:
public class Date extends Date
The class methods are inherited from date class.

• DriverManager: The class is designed for managing the various JDBC drivers. The
class is declared as follows:
public class DriverManager extends Object
The class methods are inherited from Object class.

• DriverPropertyInfo: The class keeps an account for managing the various properties of
JDBC drivers which are required for making a secure connection. The class is declared
as follows:
public class DriverPropertyInfo extends Object
The class methods are inherited from Object class.

• SQLPermission: The class manages the various SQL related permissions which are
provided to the accessing objects. The class is declared as follows:
public final class SQLPermission extends BasicPermission
The class methods are inherited from BasicPermission class.

• Time: It is wrapper class around java.util. The class provides time related information.
The class is declared as follows:
public class Time extends Date
The class methods are inherited from Date class.

• Timestamp: It is wrapper class around java.util. The class allows JDBC API to identify
as TIMESTAMP value. The class is declared as follows:
public class Timestamp extends Date
The class methods are inherited from Date class.

• Types: The class defines various SQL constants. The class is declared as follows:
public class Types extends Object
The class methods are inherited from Object class.
Connectivity of Remote Database: here are 5 steps to connect any java application with
the database using JDBC. These steps are as follows:

• Register the Driver class


• Create connection
• Create statement
• Execute queries
• Close connection

Register the Driver class: The forName() method of Class class is used to register the driver
class. This method is used to dynamically load the driver class.

• public static void forName(String className)throws ClassNotFoundException

Create connection: The getConnection() method of DriverManager class is used to establish


connection with the database.

• public static Connection getConnection(String url)throws SQLException


• public static Connection getConnection(String url,String name,String password) thr
ows SQLException

Create statement: The createStatement() method of Connection interface is used to create


statement. The object of statement is responsible to execute queries with the database.

• public Statement createStatement()throws SQLException

Execute queries: The executeQuery() method of Statement interface is used to execute queries
to the database. This method returns the object of ResultSet that can be used to get all the records
of a table.

• public ResultSet executeQuery(String sql)throws SQLException

Close connection: By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the connection.

• public void close()throws SQLException


Navigating through Multiple rows retrieved from a Database: The object of
ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the
first row.

But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:

• Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,


ResultSet.CONCUR_UPDATABLE);

Commonly used Methods -


UNIT-5 Java Servlets

Servlet Basic: Servlet technology is used to create a web application (resides at server side
and generates a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed these
disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

Important Points:

• Servlet is a technology which is used to create a web application.


• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web page.

Servlet API Basic: Servlet API consists of two important packages that encapsulate all the
important classes and interface, namely:

• javax.servlet
• javax.servlet.http

The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.

Interfaces in javax.servlet package

• Servlet

• ServletRequest

• ServletResponse

• RequestDispatcher

• ServletConfig

• ServletContext

• SingleThreadModel

• Filter

• FilterConfig

• FilterChain

• ServletRequestListener

• ServletRequestAttributeListener

• ServletContextListener
• ServletContextAttributeListener

Classes in javax.servlet package

• GenericServlet

• ServletInputStream

• ServletOutputStream

• ServletRequestWrapper

• ServletResponseWrapper

• ServletRequestEvent

• ServletContextEvent

• ServletRequestAttributeEvent

• ServletContextAttributeEvent

• ServletException

• UnavailableException

Interfaces in javax.servlet.http package

• HttpServletRequest

• HttpServletResponse

• HttpSession

• HttpSessionListener

• HttpSessionAttributeListener

• HttpSessionBindingListener

• HttpSessionActivationListener

• HttpSessionContext (deprecated now)

Classes in javax.servlet.http package


• HttpServlet

• Cookie

• HttpServletRequestWrapper

• HttpServletResponseWrapper

• HttpSessionEvent

• HttpSessionBindingEvent

• HttpUtils (deprecated now)

Life cycle of a Servlet:


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the below diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.
1. Servlet Class is loaded: The classloader is responsible to load the servlet class. The servlet
class is loaded when the first request for the servlet is received by the web container.

2. Servlet Instance is created: The web container creates the instance of a servlet after loading
the servlet class. The servlet instance is created only once in the servlet life cycle.

3. init() method is invoked: The web container calls the init method only once after creating the
servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4. Service method is invoked: The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it follows the first three steps as
described above then calls the service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

5. destroy() method is invoked: The web container calls the destroy method before removing
the servlet instance from the service. It gives the servlet an opportunity to clean up any resource
for example memory, thread etc. The syntax of the destroy method of the Servlet interface is
given below:

public void destroy()

Running Servlet:

Six Steps to Running Servlet


Once Tomcat is installed and configured, you can put it to work. Six steps take you from writing
your servlet to running it. These steps are as follows:

1. Create a directory structure under Tomcat for your application.

2. Write the servlet source code. You need to import the javax.servlet package and the
javax.servlet.http package in your source file.

3. Compile your source code.

4. Create a deployment descriptor.

5. Run Tomcat.

6. Call your servlet from a web browser.


Debugging Servlets:

It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of


client/server interaction, making errors likely but hard to reproduce.

Here are a few hints and suggestions that may aid you in your debugging.

1. System.out.println()

2. Message Logging

3. Using JDB debugger

4. Using Comments

5. Clients and Server Headers

Thread Safe Servlets:

By default, servlets are not thread-safe. The methods in a single servlet instance are usually
executed numerous times simultaneously up to the available memory limit. Each execution
occurs in a different thread, though only one servlet copy exists in the servlet engine.

HTTP Redirect:

URL redirection, also known as URL forwarding, is a technique to give more than one URL
address to a page, a form, or a whole Web site/application. HTTP has a special kind of response,
called a HTTP redirect, for this operation.

Redirects accomplish numerous goals:

• Temporary redirects during site maintenance or downtime

• Permanent redirects to preserve existing links/bookmarks after changing the site's URLs,
progress pages when uploading a file, etc
Cookies:

HTTP cookies (also called web cookies, Internet cookies, browser cookies, or simply cookies)
are small blocks of data created by a web server while a user is browsing a website and placed on
the user's computer or other device by the user’s web browser. Cookies are placed on the device
used to access a website, and more than one cookie may be placed on a user’s device during a
session.
Cookies serve useful and sometimes essential functions on the web. They enable web servers to
store stateful information (such as items added in the shopping cart in an online store) on the
user’s device or to track the user's browsing activity (including clicking particular
buttons, logging in, or recording which pages were visited in the past). They can also be used to
save for subsequent use information that the user previously entered into form fields, such as
names, addresses, passwords, and payment card numbers.
Authentication cookies are commonly used by web servers to authenticate that a user is logged
in, and with which account they are logged in. Without the cookie, users would need to
authenticate themselves by logging in on each page containing sensitive information that they
wish to access. The security of an authentication cookie generally depends on the security of the
issuing website and the user's web browser, and on whether the cookie data
is encrypted. Security vulnerabilities may allow a cookie's data to be read by an attacker, used to
gain access to user data, or used to gain access (with the user's credentials) to the website to
which the cookie belongs (see cross-site scripting and cross-site request forgery for examples).
Tracking cookies, and especially third-party tracking cookies, are commonly used as ways to
compile long-term records of individuals' browsing histories.

Introduction of Java Server Pages (JSP):

• It stands for Java Server Pages.


• It is a server side technology.
• It is used for creating web application.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform independent web
pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the client’s request.

Introduction to RMI:
RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in
one system (JVM) to access/invoke an object running on another JVM.

RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.

Client-Server Application using RMI:

In an RMI application, we write two programs, a server program (resides on the server) and
a client program (resides on the client).

• Inside the server program, a remote object is created and reference of that object is made
available for the client (using the registry).

• The client program requests the remote objects on the server and tries to invoke its
methods.
The following diagram shows the architecture of an RMI application.

• Transport Layer − This layer connects the client and the server. It manages the existing
connection and also sets up new connections.

• Stub − A stub is a representation (proxy) of the remote object at client. It resides in the
client system; it acts as a gateway for the client program.

• Skeleton − This is the object which resides on the server side. stub communicates with
this skeleton to pass request to the remote object.

• RRL(Remote Reference Layer) − It is the layer which manages the references made by
the client to the remote object.

Working of RMI:

• When the client makes a call to the remote object, it is received by the stub which
eventually passes this request to the RRL.

• When the client-side RRL receives the request, it invokes a method called invoke() of
the object remoteRef. It passes the request to the RRL on the server side.
• The RRL on the server side passes the request to the Skeleton (proxy on the server)
which finally invokes the required object on the server.

• The result is passed all the way back to the client.

You might also like