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

Java Fundamentals - Part I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 135

$ludent 0uide

ililT
Java Fundamentals

Student Guide
r

Th¡s product or docuÁent ¡s protected by copyright and distributed under licenses restricting its use, copying,
distribution and decompilation. Please view "Mark of Authentic¡ty" label to establish proper ¡icensed usage. No
part of th¡s document may be copied, reproduced, pr¡nted, d¡stributed, modified, removed, amended ¡n any
form by any means whether electronic, mechanical, digital, optical, photographic or otherwise without prior
written authorization of NIIT and its authorized licensors, if any.

Information in this document is subject to change by NIIT without not¡ce. The names of companies, products,
people, characters, and/or data mentioned herein are fictit¡ous and are in no way intended to represent any
real individual, company, entity, services, product or event, unless othenyise noted,

All products are registered trademarks of their respective organ¡zaüons.


All software is used for educational purposes only,

Disclaimer: The documents and graphics on this courservare ould include technical inaccuracies or
typographical errors/translation errors. Changes are period¡cally added tD the informaüon herein. NIIT may
make improvements and/or changes herein at any Ume. MIT makes no representaüons about the accuracy of
the information contained ¡n the courseware and graphts ¡n thÉ coürservare for any purpose. All documents
and graphics are provided "as is". NIIT hereby disda¡firs all rarrar¡ties and cond¡tions with regard to this
information, including all implied warrant¡6 and conditbrE d merdlantab¡l¡ty, fitness for any particular
purpose, title and non-infringement. In any event, I{IIT mdlor its laceftsor(s)/$pplier(s) shall not be liable to
any party for any direct, indirect, specjal or oüler consequential damages for any use of the
courseware/translated courseware, the informatbn, or on ary other hyp€r l¡nked web site, including. without
limitation, any lost profits, bus¡ness interruption. lrs of progr-ans or other data on your information handling
system or otherw¡se, even if NIIT is expressly advised of the posiulity of sldl damages.

Due to the dynamic nature of the ¡nternd, the tiRls and ñ€b r#rences rnentioned in this document may be
(are) subject to changes, for which NIIT shat nd hoad ily respofls¡b¡l¡ty.

N
e..l

at

O
é
q)

IEB/DOBAI-l/lava Fundamentals (Part 1)/Q4M2SG-o5-M01-V02


Copyright @NIIT. All rights resenred.

Pr¡nted atSona Printers Pvt. Ltd. FB6/1 , Okhla Ph.-1 , N.D. -20 Ph.: 51616566

I
Counse Desreru

From the Experts Desk

Sotrtbns to Challenge
Exerci*s)

,*:-=---_l
Table of Contents

Cycle 1

l,-esson 1A - Introduction to Object-Oriented Programming


for Object-Oriented Prcgramming
H--r-.e;ng '.....'...........1A.3
OOPS with Procedural Programming.. ..........'.'....'.... 14.4
OliEü (}bnted Programming.............. .1A.7
leq¡añ3qEs of Object-Oriented Programming......'......'.. '.'.'.....' 1A.7
@mifr'.g the Applications of Object-Oriented Programming............. .'....'.... 1A'10
3nrcs arrd Objects ................... 1A.12
........1A.15
-:rry
iesson 18 - ConcePt of OOPS
F:¡h¡es d Object-Oriented Programming.............. .................. 18.3
l-gcslaLjon ........18.3
¡us?c€fl .............18.4
:nrrúeftsrrae".... ..'....' 18.5
o?úilrirrrgr:rls¡n. ..,.,. 18,13
by ........18.14

ü"csÉon IC - Collaborate
müpre..........
-}.Fr<?€r,tÉd Analysis and Design
........1c.3
...'.............. 1C.3
ü;aror-s -rrc of Inheritence.... ..'.. 1C'6
rruÉ?c Cesses ancj Methods '..'... 1C'9
{
F.rn tt= Erperfs Desk.,,....,.. 1C.lO
I qh;F. .... 1C.10
I mf¡,. ...'...1C.12
Cycle 2

Lesson 2A - Introduction to Java


Java Programming Language.. ..............2A.3
Need for Java.............. .................2A.3
Java Architecture................ ...'....'.24.8
Java Architecture Security.., .'......24.10
Declaring Variables and Literals 24.13
Using Various Data Types ...........2A.13
Defining Variables and Uterals.... ............"........24.16
Manipulating Variables....... ".'.....24.18
Arrays..,...,.........
Using ...'.2A.21
...........
Arrays '.' '.. ' 2A.2t
Arrays...........
Accessing ..""""'.'24'24
Summary .....'..2A.25

Lesson 28 - Classes and Objects


Structure of Java Application .'.............. 28.3
Creating Classes and Objects ........28.3
Adding Methods to a Class .'..'.'..'.'28'7
Defining Constructors ..........'.""...28.9
Access Specifiers and Modifiers............... 2B'tL
Access Soecifiers.................. ,..'.'28'IL
Modifiers..............;......
Types of Permitted "..'..28.14
Compifing anApplication............. ........28.17
Demonstration: Crcating a Java Application 28'19
Problem Statement .....,..............28.19
Solution......... .......28.19
Summary ...."..28'21

Lesson 2C - Collaborate
Knowledge Byte........... .......2C.3
Evolution and Need for Java '......'..2C.3
Garbage Collection in JVM........... .........'."'.'...'...2C'4
Setting the CLASSPATII ".............'2C.5
I

i
i
l
AeeurTp*xs Cet*nse
PnOUOGUE

Description
-1is course, Developing Object Based Applications in Java, focuses on the features of
:-e Object-briented Prógramming (OOP). This course begins with basic concepts of
fOp añd then moves orito prográmming in Java language and advanced concepts of
.lava, such as packages and streams, Applets, Threads and exception handling.
-'re course consists of three sub modules:
1. Java Fundamentals
2. Programming in Java
3. Packages and Streams
In this book, the first sub module, Java Fundamentals, is covered' This sub module
:rovides an introduction to the Object-Oriented Programming System (OOPs),
advantages of OOPs, application of OOPs, and concept of classes and objects' It
cescribei the various features of OOPs: Encapsulation, Abstraction, Inheritance, and
polymorphism. This sub module also deals with the basics of Java programm¡ng
anguage such as variables, literals, access specifiers, and modifiers.

Rationale
java is an Object-oriented language that enables you to create real world applications.
The code reuiability feature oÍ :ava enables the software developers to upgrade the
existing applications without re-rewriting the entire code of the application'

Prerequisites
-le students undergoing this sub module are recommended to have the following
;<ills:
ft Fundamentals of Programming.

Objectives
dfter completing this sub module, students will be able to:
I Describe the concept and features of object-oriented programming.
ü Declare and work with variables, literals, and arrays.
ü Create classes and objects and add methods to a class'
I ldentify the various types of access specifiers.
I Imolement the d¡fferent conditional statements and looping statements'

.\i:,
W Pass arguments to methods and create nested classes and add asseftions in
Java.
W Use unary, bit-w¡se, shift, instanceof operator, and ident¡fy the operators
precedence.

ir ír.:Mgw
MernoDolocY

Learning Architecture Based on collaborative


Constructivism (LACC)
Introduction
as one of
3-oadly, almost all teaching-learning interactions/modes can be classified
:-e following:
M Interactions, where the teacher or external resource Creates the learning
exDerience
the
; Interactions, where the teaCher or external resource creates Or cOnstructS
learning, in collaboration with the learners'
x situations, where the learners create their own learning experiences
modes, would
lry learning architecture, which can suitably integrate all of the above
:eideal.Methodologies,inthepast,havemainlyfocusedonthefirstmodeof
-te¡-action. The last two'or these possible modes, which encompass the theory of
sltuated cognition and collaborative constructivism, provide the
most challenging task
'or the design of a new methodology'
..IIT',s breakthrough LACC methodology builds in learning components that enable all
:. the above interactions, to address the various stages of experiential learning and
:atering to multiple learner types.

Stages in ExPeriential Learning


l::crding to David A Kolb*, experiential learning involves four principal stages:
ü concrete exoeriences- (cE) - Learner's personal involvement through
concrete exPeriences
Reflective observation- (RO) - Learner reflects on experience and looks for
meaning
Active exoerimentation- IAE) - Learner applies this meaning to form a
logical
co"c|Lrs'torT, expefinrents with similar problems, which leads to new concrete
exoerience
Abstract conceotualization- (AC't - Learner experiments with similar
a.oblems, which leads to new concrete exper¡ence
Learner TYPes
styles are
The cElAC and AEIRO dimensions are polar opposites as far as learning
concerned and depending on the preference of an individual's learning styles/stages'
four distinct types of leamers are possible'

Divergers Accomodators

Convergers Assim¡lators

ffi Diveroers or the imaginative learners,


'ffi Assimilators or the analytic learners,
W Converoers or the precision learners and
W Accommodators or the dynamic learners'
the -
NIIT's LACC methodology has Learning ComponenG, that are oriented towards
possible
four stages of experieníiil tearning and hence is highly suitable to all
types/profiles of lea rners'

Learning ComPonents
NIIT's IACC methodology has the following learning components:
ffi CONSTRUCT: The learning begins with this component'here. An instructor who is a
subject matter expert is required to lead the students This component
intróduces the learner to new concepts and thereby constructing his/her
knowledge base, The instructor brings in concrete experiences for the
learner
éxplanations and demonstrations. These two sessions are meant to
through
proviáe the required foundation for the student to be able to move to the
subsequent stages of learning.
coLLABoMTE: The next learning component makes it possible for the
w learner
to have contextual familiarity on the subject through collaborative learning. Here

*whzry
the learner is provided with a mentor/direction/ and stimulus for reflective
observation. The learner is provided with a rich choice of tools like case studies,
scenario/problem statements and best practices to reflect on the concepts learnt
in the previous sessions and apply his/her understanding in the larger context.
I EXPERIMENT: Here, the learner is exposed to active experimentation. The
learner experiments his/her understanding of the concepts and observations to
form a logical conclusion leading to better learning effectiveness and experience.
I APPLY: This learning component provides the environment for learners to
develop conceptual clarity. Here the learner learns, refers, compares, thinks and
applies their entire knowledge spectrum and create solutions for a real life case
study. The tools used to provide such learning are project, information search
and analysis skills (ISAS) and reference reading (RR).

Required Resources
-rs -ethodology requires the following resources for delivery:
t Online Classroom: Room having networked computer nodes for all students:
Leaming Components like CONSTRUCT, EXPERIMENT and APPLY (Projects) are
executed in such a resource.
I Adeouate Environment: To execute components like COLLABOMTE and APPLY
ireference reading and ISAS)

crIn
*Reference

I Kolb, D. (1984a). Experiential learning: Experience as the source of learning and


devélopment. Englewood Cliffs, Nl: Prentice-Hall.
ü Kolb, D. (1984b). Leaming Styles Inventory. Boston: McBer & Co.
* R Dangwal INIITI& S Mitra tNIITl. Learning Styles and Perceptions of self,
Internátional Education, e-Journal, volume 4, number 4 (Dec 2000) ISSN 1327-
9548, Australia (2000)
I Children and the Internet: Experiments with minimally invasive education in
India, Sugata Mitra [NIIT]and Vivek Rana[NIIT], The British Journal of
Ed ucationa I Tech nology, 32,2,pp 221-232 (200 1 )
3 Minimally Invasive Edugation: A progress report on the "Hole-in-the-wall"
experiments, S. Mitra [NIIT], The Brit¡sh loumal of EducationalTechnology,34,
3, pp367-37 1 (2003)

*ÁñX*" ;
wz Abcut ?his t*elrse #ttr
ConvrilTroHs
1 and

k;
Construct, Demonstration

k
Beginning of a new concept

t: Additional information
-
-&p -,tt

Tips and tricks


-

ür _ -irrrtér Programming code

-s¡: F Arial font Programming syntax


Italicized text Introduction of a new term

Bold faced text Menu options, options present in dialog boxes, and
keystrokes

From the Expert's Desk

W
''!l*!. & i.t, : " ¡:.. Th¡s "l¡^,'; r*e.9
lt¿ .s t.lo O.7"\

LrlrJLessoru 1A
"J
InrnoDucrloru T0 Oa¡ECT-
OnTENTET} PnOERAMMTNG

Obiectlves
i- : s lesson, you will learn to:
Apprec¡ate the need for object-oriented programming
Compare OOPS with procedural programming
identify the advantages of object-oriented programming
identify the applications of object-oriented programming
Identify classes and objects

Visit the student website at www.niitstudent.com to enhance your learning


experience

'-l 3nw a {l ryn 4 *. tr* rá r"¡t" v¿ E# 2"&",3


a&"2 3w w m ffi sÁ *&a r***rxY"a| s
F
N==o FoR 0e:=cr-OnreruTED
Pnoe RAMMING

: -::: : ,, e world, the need of the hour is to develop simple and speedy
l:,:-- :e instantly
'!'r applied
svp,rsu to
Lv varied
vqr rcu requirements.
I ELlurr errenLS, This
r nrs has
nas resulted in tr
In the
-:-:^: and sometimes, comprex software systems. However, arthough
:' :': software system is a reality, there are ways to ensure that this
::: ^ct become a stumbring brock to the smooth functioninq of the

*: 'ying this complexity is to split the software system into its


.-:s and arrange the parts in a hierarchy. This is váry simirar
:-: oyees of an organization can be grouped according to thetofunctions
tne way
--J then arranged In a hierarchy.
=:: l'iented Programming (oop) came into effect, procedurar programmrng
:-:;rams r¡,rifla^
l--^r:mc written h,,.,^i^^
by using !L^
the procedurar
-.-^--r programming
-:: ons. These functions can be executed anywhere withinapproaéh consist
the program. A
:"" :-Jgram contains the instructional steps that are performed to carrv out
ll|r r :]

'- ":: :-! :f a procedural program are interdependent


and, therefore, difficult to
:'?-i :-: 'rom another. These interdependent functions cannot n" reusáJ ¡n oif.r*.
- - *-. * -' :-' 3 result, even for a
similar task across programs, the entire function has
- -.:::=_ This made program development a complex task.
- : -; : 'ou nave a program, EmployeeDetails, coded in procedural
:-::: :-e details of employees of a bank. The program has a function,language
'
-"'l: : : :-at prlnts the details of each bank employée. This function
can be called
: -=' "3m different parts of the same program. If you want to print the details
-a: : ' cf a different organization, such as Railway Reservation by using the
- 1 -- -:-==s
-r, printDetails, then you have to recode it in another program.
':::
*:-:- :--a< :ata in procedural programming is visible and accessible throughout the
ng ¡t easy to manipulate the data from anywhere in the pro{ram.
' : -: es of procedural languages are coBol (common Business oriented
;- trascal and BASIC (Beginner's All purpose
:::: ,.,as too simple and proved insufficient symbolic Instruction code).
for programming comprex
: : -= coBoL was used primarily for documentation and data handlinq. All
--v -^guages lack support for OOp.

..¿ &'¡¡ í¿ 3i a ¿ r ¡,¡J z¿,r q.'q * r z g;. n,i,i¡ il;.,::i


of the object-
The limitations of the procedural programming led to the evolution
the prográm is broken into independent chunks known as
oriented approach. In OOP
objects, w'nicn can be integrated to create a complete program'

For example, in ooPS you can have an Employee object that


keeps the details. of
employees of any orgañization, The same Employee object_can. also have functions to
printiñ"ru emptóyeá details. Any program can reuse this Employee object.
programmer to
Thus, objects can be reused across various programs. This enables a
deveiop án application in a relatively shorter durat¡on'
user-
ooP enables you to consider a real-world entity as an object. o.oP combines objects can
defined data and instructions into a single entity called an obje.ct. In OOP,
placed in libraries. OOP also offers some bu¡it-¡n libraries' These libraries consist of
be programs' A major
á rEt-oioO¡"cts and pre-defined functions and can be used by all
reusability of code because it saves the effort required to
advantage of OOP is the
defined in libraries'
rewrite the same code for every program using the functions

Compaiing OOPS with Procedural Programming


YoucanuseVar¡ousprogrammingmethodo|ogiestocreatean.app|icatio.nora
program. Eacn prográr*ing meihodology coñsists of its own features that
can be
various ap-plications. Tñe commonly used programming
used for creating
methodologies include :

ffi Procedural Programm¡ng

W Object-oriented programming (OOP)

Procedural Programm¡ng
program ¡nto a se
The procedural programming methodology involves dividing a large
perform specific tasks' In this methodology' i
of subprocedures or subprograms that
óne or more units or modules. These modules can be user-
órog;r is divided ¡nto from libraries'
defined or can be taken
are also
A module can cons¡st of single or multiple procedures. These.procedures
programming
known as functions, routinei, subroutines, or methods in various
languages.

Aprocedura|programcanconsistofmu|tip|e|eve|sorScopes.Aprocedurecanbe
defined independently or within another procedure. The level of
the procedure . . .

in the procedure also exhibit


¡ó;;¿r on tr'" ¿er¡nit¡án. Similarly, the
procédure
data
of a
available
higher or outer scope cannot access thr
various levels or r.op"r. The
data within the procedure that has lower or inner scope'

,r: WTl
!"k,4 3 mw a zxruúm{**r2t.erffi
W
: srocedure or a subprogram is a set of commands that can be executed
-¡ependently. In a program following procedural methodology, each step of a
-i-rcrogram is linked to the previous step.
=:'example, in a program that needs to accept, display, and print data, you can
: .'de the program into subprograms. You can create three subprograms that accept
:=:a, display data, and print data, respectively. Each subprogram performs a defined
'--ction while the combined action of subprograms makes a complete program.
-- procedural programming, you can use a subprogram at multiple locations within a
:-:gram to perform a specific task.
-- s enables you to reuse the program code as and when required in a program,
¡':hout rewriting the entire code, as shown in the following figure:

Variable A
Variable B
Variable C

Procedure 1
(Accept Data)
Accept Valre nf A
Accept value of g

Frccedure 2
(Display Data)
aisplay value of A
Oisplay vól$e of g

C=4,+B
trrccedure 3
{Print Data)
Frir¡t Valus trf A
Print Value {rf g
Print ValÍ3 nf C

Proced u ra I P rog ra m m i ng
*-e preceding figure displays a program that consists of three procedures/ Accept
)=:a. Display Data, and Print Data. Data is accepted in the Accept Data procedure,
: s: ayed in the Display Data procedure, and printed in the Print Data procedure.
:-:.:edural programming is used for developing simple applications. The languages
:-:: *se the procedural programming methodology include Pascal and C languages.
-::-':: cí rhe benefits of the procedural programming methodology are:
; Easy to read program code

3 É,¿ qr T i;{,*|ttw p nt *:,.¿ !:r./t,"'*,


'ffi Easy maintainable program code as various procedures can be debugged in
isolation
W Code is more flexible as you can change a specific procedure that gets
implemented across the program
The features of procedural programming methodology are:
W Large programs are divided into smaller programs.

W Most of the data is shared as global that can be accessed from anywhere within
the program.
In the procedural programming approach, portions of the code are so interdependent
that the code in one application cannot be reused in another. For example, the module
used to calculate the salary of the employees in a bank management system cannot
be used to calculate the salary of the employees in an educational institute. You need
to create a separate module to calculate the salary of the employees in an educational
institute,
When you need to reuse the procedural program in another application, a change in
the application results in rewriting a large poftion of the code. This results in
decreased productivity and increased maintenance cost of the application. This was
one of the reasons that led tothe evolution of the object-oriented approach'

Object-oriented Prog ram m¡ ng


A large application consists of component objects, which interact with each other.
These components can be used to develop various applications. This is referred to as
the object-oriented approach to develop an appl¡cat¡on.
For example, SelveYourMoney bank needs to calculate the salaries of its employees.
The salary is calculated on the basis of the base salary of an employee, number of
leaves taken by the employee in excess to the leaves allowed in a month, and
dearness and housing allowance. The organization consists of various types of
employees, such as regular, contract, and waged.

Smith, a programmer, develops a code to calculate the employees'salaries by using


an object-oriented programming language. This code is reused for employees at all
levels. Reusability of code enables Smith to use the same code for employees at all
levels.

i;-!á.;..é.i.ii:i:?1":i;;li¡;ij';,éiéia:;:::

h&"ffi Saww W*xsn&m*r*effiqffi&% {#tW


As discussed earlier, object-oriented programming enables you to reuse various
connponents of a program across programs. Reqsability of code not only saves
time,
¡t¡t also the effoft of the programming team' i

Advantages of Object-Oriented Programming


COp emulates the real world in a software system. The real world consists of
objects
ürat can be categorized in different classes. Some of the advantages of object-
criented programming include:
I Real-world programming

I Reusability of code

I Modularity of code

f Resilience to change
I Information hiding

Real World Programming

Consider the scenario to setup a business establishment w¡th a basic


structure' Over a
period of time, you keep acoing the various objects required to- extend the entire
establishment. Similarly in OOP, you create a basic structure of a program and
keep
extending the functionality of the program as per the requirements. The object-
oriented ápproach models the reai world more accurately than the conventional,
procedural aPProach'

ReusabilitY of Code

In the object-oriented approach, you build classes, which can be used by several
applicatiois. The concept can be explained by using the following analogy'
processes, the
As a strategic intervention of revamping their existing products and
*unag"ru-nt of BeautylnFitness has det¡ded to automate their existing systems using
a staggered approach. The automated sales system is the first process to be

3"p,,7
axlw Tnwm ffiumd,wruz*qztw\w

I

T
implemented. The system enables the management to analyze the sales data and
build strategies for the products. In addition, the automated system also tracks
salesperson-wise data to provide incentives to the high performers.

Over a period of time, the management decides to extend the functionality of the
automated system to the purchase department. In addition, the various modules to be
added for the system must take care of the finance and Personnel depaftments.

In this scenario, one of the most common entities is the employee of the organization.
In the existing automated system, the programmer has already created a component
that stores the details of an employee. Therefore, the programmer need not recreate
the entire component again. The employee component of the sales automation system
can be used to track the details of the employees across depaftments, including the
payroll division of the Personnel department.

In the Personnel department, the automated system needs to keep track of


employees. In addition to the regular employees, the Personnel department needs to
keep track of the contract employees who join the organization temporarily for a
specific period.

To store the employee details, the system again requires the employee component.
However, to store the details of the contract employees, the programmer can extend
the functionality of the existing employee component and make the desired changes in
the existing component.
The finance department needs to make payments against various payouts, salaries,
and wages of the employees. In this module too, the programmer can reuse the
existing components, such as, employee and contract employees.
The reuse of the components once created not only reduces the effott of recreating
the components, but also reduces the chances of introduction of errors in various
modules, After integrating all the modules, a consolidated system can be created that
has various components reused across the modules.

The benefit of reusability translates to savings in time and effort, which in turn results
in cost effectiveness.

Modularity of Code
Another advantage of object-oriented programming is its modularity. It means that an
object can be maintained independently of other objects. All these objects are
independent of each other and are maintained separately. You can make modifications
in the required object without affecting the functionality of other objects.

3"&"& Smwn Tuaszúwrn*mtaTw r#Jw&w


application authenticates your login ID and provides the access is completely hidden
from you.

Identifying the Applications of Object-Oriented


Programming
Object-oriented programming has applications in several domains, such as business
management, home computing, and accounts management. These applications can be
Character User Interface (CUI) or Graphical User Interface (GUI)

Character User Interface (CUI) based Applications

CUI is an interface used to interact with a computer. A user working on CUI needs to
type commands on the command-line to interact with the computer Input commands
can be long and complex, CUI is not user-friendly because a user needs to remember
all the commands and the syntax of the commands. The most common examples of
CUl-based applications are DOS and UNIX.

C++ for GUI Applications

C++ is an OOP language that enables you to create GUI applications. For example,
C++ is used to develop banking software, inventory control, and payroll systems. The
hardware simulations for Personal Digital Assistant (PDA) tools are also peformed by
using C++.

Graphical User Interface (GUI) based Applications

Errors induced due to typing long commands often discourage the user and affect the
productivity and efficiency of the user. GUI is a method of interacting with a computer
by directly manipulating graphical images in addition to text. Various applications are
written to run in graphical user environments, such as Microsoft Windows and Linux.
In a GUl-based program, various events take place by clicking a button on the screen/
moving the mouse, or pulling down a menu, Object-oriented programming hides the
data and processing methods, which inform the system that an event has occurred,

GUI can be programmed using object-oriented programming methodology, which uses


various objects. The objects communicate with each other by sending messages to
each other. An object receiving a message responds to the message sent by another
object by executing one of its pre-defined functions. An object represents each
element of the GUL IT determines the attributes and the behavior of each element of
GUI. A window of GUI has various attributes, such as size and position.

h#",#"{3 3 ry"w'e W w {z *e YYz ry,site| %l il;1' Ltt


For example, if a user closes a window, object-oriented programming system sends a
message to the window that executes an algorithm to remove the image on the
screen.

Computer Aided Designing/Manufactur¡ng (CAD/CAM)

The concept of OOP is applied for designing and implementing various software
systems for computer graphics, such as computer Aided Designing (cAD) and
ómputer Aided Manufácturing (CAM). The concept of OOP is used to create graphical
and numerical building blocks that can be assembled to form portable, flexible, and
cost effective solutions for various real life problems'

Games

Computer games might be considered as a type of abstract simulation. All the


adventure games, sports games, and the space games are modeling some type of
objects present in the real world. Most of the things, such as landscapes, creatures,
and buildings that are depicted in games are related to the real world and can be
classified as'Objects'according to their properties and features. You can organize a
game into a collection of "things," when you apply OOP techniques to the design' This
is possible because things can be translated easily into objects in an OOP
environment.

In a hypothetical adventure game, the player controls a character around a fantasy


world and fights creatures, collects treasure, and so on'

Position Class

Main Class It*m Clasx

Treasure Class Key Class

Class Hierarchy for a Hypothet¡cal Adventure Game

a xtzv 3 r¡qr n ffi z*vz úm nz q. vckmtw h&^.3.3.


3

The advantages of OOP will become evident when you develop new games. You can
follow the OOP design of an existing game, and reuse many of the objects to develop
new games.

Classes and Objects


A class defines the structure and behavior of an object or a set of objects. For
example, peacock, sparrow, and kingfisher are categorized as birds because all of
them share some common characteristics, such as they are covered with feathers,
have hollow bone structures, and have the ab¡l¡ty to fly. Similarly, the various entities
that have similar attributes comorise a class.
For example, in a university, all the students have similar attributes. They have a
student ID, name, date of birth, gender, and address. Therefore, to automate the
student management system of the university, you can create a Students class that
consists of the attributes needed to store the student details.

Objects are the basic building blocks of Object Oriented Programming (OOP). The
concept of the object-oriented methodology is based on objects. You create
independent entities that can be reused across various programs, Objects display the
following characteristics :
W State: The state of an object is indicated by a set of attributes and the values of
these attributes. For example, when you design an online shopping site for
books, each book, which is an object in the program, has its size, number of
pages/ type of binding, and its shipping details.

W Behavior: The behavior of an object refers to a change of its state over a period
of time. For example, in the online shopping site, when you place an order for a
book, the status of the book might change from available to sold out. The
changed state of a book is its behavior.
W ldentity: Each object has a unique identity, iust as each person has a unique
identity. For example, multiple books consist of the same size, number of pages,
type of binding, and shipping details. However, each book has its distinct
identity, for example the book number. The book number identifies a book
among other books.
An object is an instance of a class. A class in object-oriented methodology is a
collection of various attributes, such as data and methods. You can access the data of
a class by using its methods.

Consider a pay phone where you put in a coin and then dial the number that you want
to call. The pay phone exhibits a certain kind of behavior, that is, when you drop a
coin and dial a number, it connects you to the person you want to talk to at the other
end of the line. The order in which the operations are carried out is important, The pay
phone behaves in this manner because of the existence of a state. One state of the

::: ::a¡tt t.:., i á;¿i.i, ¿:r¡;ii: ;:: ¡: :,,


i, ¿ ;; ; ¿::; ¿ L r:: :::i::::: ,:::::::::.: : : aaa a:a,a, a, a;.;t.;t ,:.',:.. :::::..:,:t.a:a:

ft"&"3"X kwwm W*urz&nrm*mtm&u . it;:Wi"tV


1 A4& 4
flme b üat a cailer ¡nserts a coin but the number is not diared and in the other
! ¡ a¡frr b inserted as welt as the numbei i, ¿iul"¿.
stab af.d behavior together, comprise.the properties of
pPqgtt_y of the object pay phone could be object. For exampre,
ihe amount or-an
monáy or the number of
s b be lnserted.

Boodr, the famous author who has written many


books on oops has defined a
ty as:

iilrercnt or distinct characteristic, trait, quatity or feature


that contributes to
úrg an object uniquely that object."

do not exist in isoration. They interact with other objects


and react to these
ons. These interactions take place through messages.
Grady Booch has
behavior as:
r is how an object acts and reacts, in terms of its state changes and message

ilentity of an object distinguishes it from ail other objects. In


rc' its identity wilr be the seriar number assigned to ií the case of the pay
uv tná'má-nuracturer.
l objects may have the same behavior, may or may
not have the same state but
have the same identity, The identity-of
H.. ou¡e.f n"u"i .nunges in its
"n
al people have described techniques for identifying
-ofcrasses. According to one of
[ijl?,the: :"^:t :.1,:
"r""il'::
ns.
nou _q" T s rl, h d e,scri ptío.n
The nou ns rep reselicu nái¿-ái"'.lurr"r.
iñ ;;d ñ . rh e n, yo u

example, in an ouilet, there can be severar counters,


each one manned by a singre
upp.oá.né, unv .á,nt"., dependins
ff#::,,'.?'Ii:
the :,:j::r:: ?^.,,?Íil
product the customer wishes ;ljy_,_t:I:r.
to purchase. The saresp".ron í#i!'á;:f,";5'"n
düct and accepts the payment from the customer. The
di'fferent ciasses that can be
ntified are:
I Counter
I Salesperson

r Product

r Customer
I Payment
F
The following figure shows the Customer class and its objects:

Classes and Objeds


In this lesson, you learned:
r An object is a software package consisting of variables and methods.
I Various programming methodologies that can be used are:
o Procedural programming
o Object-oriented programming
r The procedural programming methodology involves dividing a large program
into a set of subprocedures or subprograms that perform specific tasks.-
r The-procedural programming methodology allows code reusability in large
applications.
I An object is defined as an instance of a class.
r In the.object-oriented approach, classes are designed such that they can be
reused.

r The areas of gngtic_atjon of the object-oriented programming include cul, GUI,


Games, and CAD/CAM-based programs.
f 9Ujgct oriented programming offers features such as Reusability, Resilence,
Modularity, and Information hiding.

Java Frmdam€Htals
L&,"2"ffi Smwn W*rz*mrce*rzkw&s ""MAWW
t'.'t t xhesselu SB
CEPT oF OOPS

üús lesson, you will |earn to:


d Identify the features of object-oriented programming
E Encapsulation
t Abstraction
t Inheritance
t Polymorphism

Sava Fumdam*ntx|'*
1:#WÉpéi¿ñ,ni;;¿;.i!+.a:++#z#:w#ffiñ)F;qE ffiÑFÉlt::.ffiw!)e-xffiffiffi
LW"2 Sawa Ywnúamentals &tWffi
'..1{ ¡J \
- :-.ll+ . ,.,-'
íI- i.+-'-
1

t o{/

FeRruREs oF Oe:ecr-OnrrNTED
PnocnnMMING

-:_ect-Oriented Programming (OOP) is used to build OOPS. Objects are the basic
: - cing block of Object-Oriented Programming System (OOPS). The real world objects
-=,e two characteristics: state and behavior. Forexample, human beings have state,
as name, color, age, and height and behaviorsuch as walking, dancing, and
'-:l
,::ctng. All the objects in OOPS are based on real world having a specific state and
: =-avior.

I I pS consists of the followinq features:


': Enca osu lation

c. Abstraction
,t Inheritance
:: Polymorphism

Encapsulation f ¿vr.r,;p.,,v 1,,;


".i"i'')
!':cy Booch, a famous authorwho has written many books on OOPS has defined the
=- :apsulation feature as:
'l^.capsulation is the process of hiding all of the details of an obiect that do not
:: ^:ribute to its essential characteristics."
object are hidden from the
=-:apsulation implies that the non-essential details of an
-s:: and an access is provided to its essential details. Therefore, encapsulation is also
:: ed information hiding. For example, when you plug in the cord of a vacuum cleaner
:-: switch it on, the vacuum cleaner starts functioning. An end-user need not know
:-: ,vorking principle of a vacuum cleaner to convert electricity into suction power.
--: switch of the vacuum cleaner encapsulates the complex process of conversion of
=::tricity into suction power. The complexity of an object is hidden as a result of
- - ^^^^..t^+i^^
= ,dPSuloLlUll.

l:rr puter games also use the feature of encapsulation. The user only needs to know
-:¡; to play the game. However, the complex working of game is hidden from the
, s3r.

-- ob¡ect-oriented methodology, need of encapsulation arises because the emphasis is


:^ designing classes in such a manner that the classes share data and methods

3 n'¿ a V s¿ rz qJ
ffi rv:¿ r* nf; & 4n 3-{A.:}
r

among themselves. Encapsulation is the feature that provides security to the data and
the methods of a class.
An Anytime money(ATM) that you use to withdraw money also has an encapsulated
function. You inseft an ATM card in the machine and provide the pin code' The only
access that you have to the ATM is to provide the pin code for your account and not to
the process of validating the password. If the pin code is correct, you can make the
desired transaction. The backend transaction process is encapsulated. In addition, if
you try to access another account, access is denied, as you are not authorized to
access any account other than your account.

Accessing an ATM Machine

Abstraction (eUs\recr,:a*)
Grady Booch defined the abstraction feature as:

"An Abstraction denotes the essential characteristics of an object that distinguishes it


from all other kinds of objects and thus provides crisply defined conceptual
boundaries, relative to the perspective of the viewer."

Abstraction refers to the attributes of an object that clearly demarcates it from other
objects. For example, while developing an online shopping site for books, you use
objects of various items, such as books, compact disks (CDs), and cassettes. All these
objects have a well-defined set of attributes that distinguish these objects from each
other. For example, a book has page numbers, type of binding, and subject. However,

::::7.:;::;;:;.^ n d¡n-¡é ü9 t9:ee!!::r:i n;; d ¡ ró aá ; +;


^ ^6
3"W"& 3m qá
x W a* {e * mr,\z * {*te& # #tW*WW
'w ffi.&&&
I : has type of media, such as audio or visual, duration, and storage capacity of the
_:D

--e concept of abstraction is implemented in object-oriented programming by creating


: isses. All the attributes of the objects of the classes are defined in the class.
-:,.,ever/ you cannot store any data in a class because creating a class does not
: :cate any memory space to the class. To store data, you need to create objects of
:-: class, which have memory allocated as soon as it is created. Classes form the
:=-rplates for creating objects.

-- :ddition to the well-defined characteristics of an object, abstraction enables you to


:-rr,ide a restricted access to data. You come across hundreds of advertising
--sssages every day through magazines or newspapers. You do not read, understand,
:-: respond to all of these because these are not of your interest. Instead, you
::-centrate only on messages that are of your specific interest. For example, if you
.,a-t to buy a refrigerator, you will concentrate on the advertisements featuring
-:'igerators. You will not concentrate on the advertisements of other products, such
:s , acuum cleaner, washing machine, and air conditioner.
-- :cject-oriented programming, abstraction means ignoring the non-essential details
:':'r object and concentrating on its essential details, As discussed earlier, in an ATM,
:-: user is not required to know the entire process of a transaction and how the data
s:cred. However, the program provides a restricted access to the user's account.

- larly, when you want to send e-mail messages/ you should know the processes of
-: ng e-mail messages and sending it to the receiver. However, it is not necessary
:-'/ou to know the entire process of sending the e-mail messages across the
-::,!ork.
-: nplement abstraction, you also use the encapsulation feature, Encapsulation hides
:-: irrelevant details of an object and abstraction makes only the relevant details of
:- rbject visible. For example, the operation of a washing machine is hidden or
=-:apsulated from the user. The details, like switching on and off the washing
--:1¡ne are the only details relevant for the user to know. This is implemented by
::s:raction. Rest of the working of the washing machine is encapsulated from the
-s:-.

I n heritance l tr*, '" ' '' , )


-- object-oriented methodology, inheritance enables you to extend the functionality of
:- existing class. You create a class that inherits the attributes and behavior of
;-:ther class. In addition, the new class can consist of a few new attributes and
::-aviors that are specific to the class. In terms of classes and objects, attributes
-:'3r to the data and behavior refers to the methods.

=:: example, you might have the Student class that consists of the basic
:-aracteristics of students, such as name, date of birth, and gender, You can extend
:-e functions of the student class to a day scholar, who in addition to characteristics of

,7 a v a¡ ? e.L'¿t rJ.'¿¡ t'í'4 "¿i t"r"/; trt tr ti lr.:7r..1:i

I I
1^, :,'. 1'. i":.:r ¡'r.,gr¡''il;l üf"i:,;i'ir'.r
"J
r"-

the Student class contains its own features, such as locker number and residential
address.

Inheritance enables you to add new features and functionality to an existing class
without modifying the existing class. Inheritance also enables you to share data and
methods among multiple classes.

Superclass and Subclass

In inheritanc e, a superclass or parentclass is the one from which another class


inherits attributes and behavior. Asubclass or child class is a class that inherits
attributes and behavior from a superclass. For example, an Air ticket can be of two
types, Confirmed and Requested. It also has various attributes, such as flight number,
date, time, and destination. Both types of air tickets inherit these common attributes.
The Confirmed ticket will however have a seat number while a Requested ticket will
have a status attribute.

The following figure shows the concept of superclass and subclass:

Attribtáes:
FligkNualer
Date
Tihe
Dectin*ion

ctass:
Requested T¡cket
lnherhed áttrlbstes: Inherited AttributBE:
Slightl{umber FligbtNumber
Date Date
Tim* Time
Destinaúisx Destination

Superclass and Subclass

9W"ffi Swzaw ffiatm&mrrt*mYe\s ffi:W.


has the following characteristics :

I A subclass is a specialized form of the superclass.


I A subclass can inherit the propefties and methods of its parent or superclass.

- A subclass may have some additional and unique features in addition to the
features inherited from its superclass.
implement inheritance in object-oriented programming, various relationships exist
the various classes of the program.

ips Between Classes


and objects are related to and ¡nteract with each other. In object-oriented
ng, objects peform actions in response to messages from other objects
the receiving object's behavior. This approach specifies the relationships
classes based on the behavior of individual class.

various relationships that can exist between the various classes of a program are:
r Kind-of
I Is-a
I .-)
Part-of
I Has-a 4

Íhd-Of Relationship
TE Knd-of relationship is used at the class level to describe the relationship between
¡ superclass and a subclass. A subclass can inherit the attributes of a superclass.
, a subclass is a type of suPerclass.

3E!f Sava Fundarnentals Ls'v


F@-

In the ticketing example discussed earlier, the subclasses, such as confirmed ticket
and requested tickets are the kind of tickets. The following figure depicts the kind-of
relationship between the confirmed ticket and ticket classes:

Crnfirmsd
Ticket Tick*t

Kind-Of Relationship

Is-A Relationship

The relationship between objects of superclass and subclass is referred to as an is-a


relationship. For example, in the tickeüng system, a ticket class is a superclass and
confirmed ticket is a subclass. A confirmed ticket for New York is an object of the
confirmed ticket class. The relationship between these three reads as the ticket for
New York is a confirmed ticket, which in tum is a kind of ticket.

The following figure depicts the Is-a relationship between the three classes:

Gonfirmed
Ticket
Ticket frr
l\ley¡ York

Is-A Relat¡onsh¡D

Part-Of Relationship

When a class is an element of another class, it depicts the paft-of relationship. For
example, while developing a program, you might real¡ze that you need to store
address of various entities, such as students, customérs, and organization. You might
further realize that the address consists of various sub-attributes, such as address line
1, address line 2, city, state, country, and zip code. To reuse the entire set of these
attributes, you can create a class that consists of the required attributes. You can use
this class as an element of the classes where you need to store address. The address
class exhibits the paft-of relationship with respect to the class in which it is included.

lt!taltl:41¿;;;;;:t7,:;::¿:2?)t:aitj;;:;;:::;:.::t:;:i:2:a.;!:;¿:::at:t ;.a|,;:¿;t::::;::t ):!: |:!.|!!| y|p9 !,49'61¿686én

hw"& Ta,aw #a3{aúmm*mtals #ttW&W


a*?w@&
r
I

-he foltowing figure shows the part-of relationship between the Address and Student
M -l^-^^-,
I
-ld55e>.

Address Student

I
Part-Of Relat¡onsh¡P

l-las-A Relationship

-he has-a relationship is reverse of the part-of relationship. When a class consists of
another class as its eiement, it depicts the has-a relationship, For example, when you
nclude the address class in the student class, the relationship between the student
:nd address class reads as the student class has an address. The has-a relationship is
also known as aggregation or composition.

-he following figure shows the has-a relationship between the Student Detail and
.A.ddress classes:

Address

Has-A Relat¡onsh¡P

:'r a program, You create various classes that exhibit various relationships among
:nem, The tyPe of relationships among classes result in different types of inheritance.

Types of Inheritance
-he animal kingdom has many exampres of inheritance, Consider the example of the
animal kingdom. One of the basic attributes of all members of the animal kingdom is
:rat they cln move, Aves, terrestrial animais, and aquatic anim.als inherit these
"eatures and have their own specialized attributes, In addition, flying animals, such
as
:ats and archaeopteryx, inherit the attribute of birds and land animals' Similarly'
ámphib¡ans, such as salámanders and frogs, inherit the attributes of land animals and
aquatic animals.

YLtr.Y; 3 aq n F z*n rJ, m rn * {rkí21 ffi 3"W.%

¡
1*
!'
i e.".Fr ':' '
The following figure illustrates the hierarchy of inheritance among the various classes
in the animal kingdom.

W6,
have w¡ñgs hav€ te€th añd lungs hav* grll*

E
+ JJ
lr"*"*"ñ;l f^-,"-.***l

háve wings áfld teéth have hngs and gillá

Animal Hierarchy
Similarly, in object-oriented programming, you can create a hierarchy of inheritance
among various classes. This hierarchy not only enables programmers to reuse the
existing code, but also to extend the functionality of the existing program.

{tt tf¡ ,;4 *rÍír#


'v,N&u

tA^ e-.( -a'( el"^f *, y xt


",^la
UJ'1¿13 **, ¡"1[ ¡irr];"Q.$
¡l

$r\tg ¡.n;\1áb
For example, in an organization, if you need to include a new category of employees,
such as contract employees, you can inherit the attributes of the existing employee
dass to the contract employee class and add the attributes for the contract
employees.

Similar to the animal kingdom hierarchy, classes in a program can have following
types of inheritance:
I Single inheritance
I Multiple inheritance

Single Inheritance

In single inheritance, subclass is derived from only one superclass. The subclass or the
child class inherits the attributes of the parent class or super class. The foHowing
figure displays the single inheritance:

$ub ülass
{child}

The Single Inheritance

In the Animal Hierarchy figure, the animal category classes, such as Birds, Land
Animals, and Fish are example of single inheritance because these classes have
inherited the characteristics from one superclass, Animal.
For example, classes called Even numbers, Odd numbers, and Prime numbers is
derived from the class Numerals,

ñuen Numbers
S¡ngle Inheritance

rWWffi 3 ww w Y a*ra& w {ffi e {zg.ffig #. aw.lh

Nww+¿ao {-A f
a

6r¡c¡^ -> \ c\,,stl e*.trtu yr*rr"*q{


\t I
cr.i é -> qvjr t a^:.a dA p,,;r+t f, q¡-- Ff'¡r'¿""g{a {*.rfi*"r.-
Multiple Inheritance

In multiple inheritance, a subclass is derived from more than one super class. The
subclass or the child class inherits various attributes from its suoerclasses. For
example, in the parent-child relationship, a child inherits characteristics of mother and
father. The following figure displays multiple inheritance:

Super clóss Super Class


(Pa rent 1 ) {Pa rent2 )

Sub Class
(chird)

Multiple Inheritance
In the Animal Hierarchy figure, the animal category classes, such as Flying Animals
and Amphibians are examples of multiple inheritance. The Flying Animal class has
inherited characteristics from two parent classes, Birds and Land Animals. The
Amphibian class has inherited properties from two parent classes, Land Animals and
Fish.

Consider an example of an organization with the name, Global Courier Company. The
organization is a Courier Company as well as Insurance Company. Therefore, the
Global Courier Company class inherits the characteristics of the Courier Company and
Insurance Company classes. The Global Courier Company is a subclass and Courier
Company and Insurance Company are superclass. The type of inheritance involved in
this scenario is multiple inheritance.
The following figure shows multíple inheritance:

Insurance Compar¡y

Global Courier

Multiole Inheritance

2w,3"& 3 azs a F w rzrS mrYz* mtat 6 r. wEzT


Polymorphism
is derived from two Latin words-Poly, which means many, and morph,
means forms. Any thing that exists in more than one form is known as a
You might have noticed that a person assumes different roles in different
, For example, a person assumes various roles when he interacts with the
of his family. He is a fatherto his children, child to his parents, and husband
his wife. Although, the person is same, he behaves differently with the family
as per his relation with the member.

object-oriented methodology. polymorphism is the feature that enables you to


ilgn a different meaning or usage to an entity in different contexts, The entity can
a variable, method, or an object. Polymorphism enables an entity to have more
rn one form depending upon the context in which it is used. Polymorphism enables
entity to be used as a general category for different types of actions.

!e,\narh-s *) eampr-la
-
q"k\ -? €,^LJJ
Qta{ ,r-* e*'"}oÁshca
In this lesson, you learned:
W Encapsulation- Hides the implementation details of an object and therefore hides
its complexity.
W Abstraction- Focuses on the essential features of an object.
W Inheritance- Creates a hierarchy of ciasses and helps in reuse of attributes and
methods of a class.
W The relationship among the classes can be classified as:
o Kind-of
o Is-a
o Part-of
o Has-a
W A superclass shares its attributes and behavior with its child classes.
W A subclass inherits its attributes and behavior from parent classes.
m There are two types of inheritance:
o Single inheritance- A class inherits attributes from only one superclass.
o Multiple inheritance- A class inherits attributes from two or more
superclasses.
W Polymorphism- Assigns a different meaning or usage to an entity in different
contexts.

hw,L4 3 aw m Y xayzú a rvt e YÉee, 6 üwffi


ril-l
-i&"'LessoN tC
CoLLABORATE

3;;; Snqn '#mn4.mmz*mt¿nt* L1*" i,"


Kn¡owr-EDGE Bvre

"f:
s section, you will learn about:

I 3:ject-Oriented Analysis and Design


I "
arious Types of Inheritance
Jbstract Classes and Methods

Object-Oriented Analysis and Design


:r.e:-oriented analysis and design (OOAD) consists of object-oriented analysis and
rn-t,::-criented design, In object-oriented analysis the emphasis is on the
'riü':s:gation of a problem based on the requirements, For example, the
5*--.:'r'curMoney, Inc. bank requires a new automated bank management system. In
m_e::-oriented analysis, the end users and the developers of the system analyze the
reg,- -=ments of the new system.

"rr:-= rbject-oriented design, the emphasis is on defining the software objects and
1;ru i3 collaborate these objects to fulfill the requirements of the new system to be
r¿.= :3ed. For example, in the bank management system, the Customer class needs
r: -=,e various attributes, such as Customer_ID and Customer_Name and methods,
- :- 3s get_CustlDQ and set_CustlD0 to enable a customer to perform automated
-. -g transaction,
T- Scftware Development Life Cycle (SDLC) is a set of phases that divides the entire
-:::ss of building a large program or application into smaller and more manageable
-- = Each phase has defined inputs, involves application of tools and techniques, and
;:-:-ates a specific output, Each stage of the SDLC requires documentation, in
a:: : l:l to the development and planning of the software,
r := je of the SDLC consists of well-defined activities and methods needed to perform
:*:-s tasks, such as:
g Collecting information about the software that needs to be developed
* Documenting the retrieved information
Creating design documents

lmplementing and coding the software


Testing the software

i:;.".. f '";'"")a '':;i:;r.;r:,; :8.í:; 3


W Deploying the software
sDLC of any
According to Grady Booch, James Rumbaugh, and Ivar Jacobson, the
software intensive system includes the following four phases:

W Inception -1 (rr^^*)
W Elaboration
ffi Construction

W Transition

Inception (rr,u.e,lo\
in Incept¡on
This is the first phase of the sDLC process. The various activities involved
stage are:
ffi understanding the problem and the methods for solving it.
W Specifying the scope, objectives, and requirements of the software system'
ffi Specifying the estimates of the resources needed'
W Planning a schedule of the various stages in the project'

Elaboration

This is the second phase of the sDLC process. The architecture of the
system is
are also.explained and
defined at this stage. ihe requiremenis of the system
The various activities involved in Elaboration stage are:
documented in this stage.
phase
W Elaborating the system specification obtained from the inception

W Analyzing the Problem

ffi Describing the system's requirements by creating a model of the system

W Analyzing the requirements for the project

W Developing the Project Plan

kü"& 3 mv¿ m F a* númuvt * {zt"m$ * #¡W'#ffi

1a¿**$':'*- **'!=l-"dt
/ r.J.
arttbr t<r
' -? at <pr¡<r,,
S co?e/
is the third phase of the SDLC process. This stage involves the following

Elaborating the solution specification obtained from the elaboration phase


.:
I Building and developing the software system

"l Completing implementation and testing of the software system

-t Extending the functions of the system based on test résults

sition
is the last phase of the SDLC process. The software is handed over to the end-
er and is tested for defects. Defects identified are then documented and corrected.

Th transition stage of a software system involves the following activities:


I Integ rating different modules.

I Delivering the integrated modules.


I Deploying the integrated modules.
I Correcting problems in the deployed modules.

Yq¡ can compare the various stages of software development with the construction of
¡ house. You need to follow the similar stages as that of software development for the
g¡struction process.

lr the inception phase, you build a vision of why you want a house and what kind of
hse it should be. You discuss the same with-your family members, start arranging
fu finance, land, personnel, and outline various modules to monitor the progress of
üre project.
h the elaboration phase, you complete a detailed analysis of each and every aspect of
üre house. You call an architect, get a blueprint of the house to be prepared, verify it,
d for modifications, and finally give acceptance to the architect to staft construction.
h the construction phase, the construction team takes over. Engineers, contractors
lrd other skilled perconnel get busy in the process of translating the blueprint into
realrty. As the construction progresses, you keep checking the functionality of various
ftahrres, such as the electrical wiring, landscaping, and water connection. In case you

3E? Saxra fwczá*r*ent"afs Lü"5

Dli/n-;.1o -Jre5a
{d"1}!^r-+
**ffifr*&
P*

find something not satisfying your requirements, you immediately ask for changes b
prevent inconveniences later.

In the transition phase, you move into your newly built house. In case you find an
unexpected probiem, such as a problem with the drainage system, you immediately
call a plumber and get the problem rectified. A period of maintenance now stafts
where repairs and modifications are carried out as and when problems are detected.

Various Types of Inher¡tance


Inheritance is the propefty that enables a class or an object to acquire the attributes
and methods of another class. For example, FixedAccount, CurrentAccount, and
SavingsAccount are the three subclasses of the Account class. The Account class has
the actount number and balance attributes, which are inherited by the FixedAccount'
CurrentAccount, and SavingsAccount subclasses. The Account class is known as the
superclass or base class and the FixedAccount, CurrentAccount, and SavingsAccount
classes are known as the subclasses or the derived classes. You have already learned
about single and multiple inheritance. The other types of inheritance are:
ffi Multilevel
W Hybrid

ffi Hierarchical
'ffi
Multipath

3"ü"ffi 3 mw m W as'nrT mtvi w ffiteTffi, #)wtt,


.t/ &g I
Iultilevel fnheritance
','!t multile.vel inheritance, a class is derived from an inherited class. As a result,
the
Gived class inherits features from other derived classes. ror example, Grandparents
'büte base class' The Parents class is a derived class that inherits features from
the
ke class. The Children class inherits the attributes and rnethods of the parents ctáss
rrd the Grandparents class.

Class A
Parent Class for Class B

M u ltilevel In herita nce

Sava Fux***rnen*alg;
Hybrid Inheritance
In hybrid inheritance, a derived class exhibits two or more than two types of
inheritance. For example, a derived class inherits attributes and methods of two or
more base classes, which is multiple inheritance. One of the base classes is derived
from a single parent class, which is single inheritance.

Hierarch ical Inher¡tance


More than one subclass can be derived from a single base class in hierarchical
inheritance.

Class A
Parent Class for Classes B.
C, and D

Hierarchica I In herita nce

¿fr.o Sava Fundamentals ffixtrlt


l{ ultipath Inheritance
v-:ipath inheritance is a combination of multiple and hierarchical inheritance, In
D -- tiple inheritance, a child class is a derived class that inherits attributes and
l0 -:thods of two or more base classes. The base classes are derived from a single
:?-ent class in hierarchical inheritance.
I
I :- ihe following figure, the two paths of inheritance for the D class are: A, B, and D,
:-: A, C, and D.

Abstract Classes and Methods


\n abstract c/ass is a class that cannot be instantiated. It contains methods that have
-c implementation. The methods having no implementation in the abstract class are
abstract methods. An abstract method is implemented in the subclass instead
=¿lled
:f being implemented in the abstract class. An abstract class is always inherited by
3ther classes.

=or example, you are not able to see the instance of the food you eat. You are only
:ble to see the instances of various food items, such as mango, apple, and chocolates.
rhe food represents the abstract concept of the things that we eat.

?437"f: 3 n w ¿n.'ú utz &m r:*, m rzt mTn 3-{:"ry

.'.n- í: *. r-: ;' ,

j
i I : ,:" f$i¡
FnoM THE Expenr's Desx

ffi What are the examples of the object-oriented programming languages?

The examples of the object-oriented programming languages are: Simula, C++,


Python, Smalltalk, CLOS, and Java.
W What are the primary object-oriented methodologies used currentlyT

The primary object-oriented methodologies are: BON, FUSION, HOOD, IBM, and
UML.

W How did object-orientation evolve?

The object-orientation evolved with the evolution of Simula that provided


features, such as objects, classes, and inheritance. Simula was the first object-
oriented programming language. Simula 1 was a simulation language and
Simula 67 was referred to as Simula. Smalltalk was another language having
various features, such as classes, inheritance, and graphical user environment.
ffi Class B inherits features from its base class, class A. Class C is a sub class of
class B and inherits features from class B. How many times will the features of
class A appear in class C?

The following figure shows the class heirarchy for classes A, B, and C.

CIass Hierarchy

hü"3-w 3m u¿
m T
T u* a4 mzzz * r*t m4 s ''rywLTtr

C",V B\r¡e- **¡ arlCl'¡ { u '' ,' "a


Class B inherits features from its base class, Class A. These features occur only
once in Class B. Class C inherits features from its base class, Class B' The
features inherited by Class C include the features that Class B inherited from
Class A. Thér,efor€, the features of Class A appear only once in Class C'

eww Sana Fean&a*tentar* LT"IL

thrrcQ"ra -" Pen- ****"


7F

:::i

1. Match the followino:


a. Java i. Structured Programming Language
".-.-*ii. Procedural Programming Language
c.C iii, Object-oriented Programming
d. LISP iv. Imperative Programming Language
e. FORTRAN v. Functional Programming Language
2. Make words from the jumbled letters in the box given below and match them
with their description :
a. An object is an ,,-1,i¡*rtrof a class.
b. The attribgte of a class is represented by ___.
c. ¿¡¿ge!¿JiüÉeature of objectioriented programming i-also called
informationhiding, , i r
d. An objec! of class has a unique l&,*-f rrv .

e. R¡bs{r¡ottass is not instantiated,

Canniest
1^",f E *ca, (a)
Tdaa bmreem

Noitalusoacne
?nc^rP*itar'ra'
Entiitvd
rde+ií+1 qd\
Srctaabt
abs\ra*,* óq)

#"*.k2. 3 av n F a¿ rs$awnxrzLtnts ti,tWíT

\v r*bleJ-yre¡r.¡dñp3
3. Solve the following crossword:

Across:
i. Type of Inheritance in which there is one base class and one sub
class (6)

lv, The characteristic of an object that refers to a change of the state


of the object over a period of time (8)

69 an example of procedural programmins (5)

Down:
2 A--is
program that can be divided into small user-defined units(6)

5 The type of inheritance in which there is more than one level of


inheritance. ( 10)

e,wEY{ 7nnrm ffiwra{A'em4ntffit# 3"ü.3"m


Sawa F*ndanr*.mt"ele wwr
Lessem 3B
FHRTMENT

Swwm Wa¿m&mwremtffig#
f.n*1 Lne ExeRcrsEs
,i'&J
Exercise 1
5,'stem Solutions Inc. recruits its employees through two processes: External
iecruitment process and Employee Referral process. In the External Recruitment
:-!cess, the applicants submit their personal and professional information for a
:osit¡on in the company. The applicants that are shott-listed are interviewed and the
-terviewer records the results of the interview, such as test scores/ rating, and
::rsonal information of the applicant. In the Employee Referral process, employees
-efer the candidates for the given positions. Identify the various classes and their
What are the various conventions that the class names follow?
=::ributes.
Exercise 2
S..¡nOvens Company, an oven manufacturing company manufactures a large number
-.f ovens. An oven possesses ceftain features and attributes and must behave in a
:ertain manner. The company documents these attributes as a blueprint, which is
,sed to manufacture the oven.
a. What is this blueprint called in an object-oriented programming language?
Identify the class and objects and the various attributes ofan object ofthe
class.
b, The manufacturer does not want that a user should tamper with the
electrical wiring in the oven, and hence must be hidden from the user.
Identify the feature of object-oriented programming that best describes
the feature of data or information hiding.
c. A person operating the oven need not know the details of how the oven
works. The person just needs to know how to switch on and off an oven,
and change the temperature settings. Identify the feature of OOPS that
allows the user to ignore the irrelevant details of working of an oven and
concentrate on the essentials.
d. All ovens have certain common attributes and functionality, For example,
every oven has a door, Different companies add various additional
features to the basic functionality of an oven. Identify a sub class of the
Oven class. Identify the property of OOPS, in which the existing features
of a class can be reused by another class and what is its advantage.

; !¿ií7 r,:;in¡,t e !:ti.:::, ii,i E:7 Xt; ;:j;,1


Exercise 3
ldentify the types of inheÉtance in the following figures:

Andrewsons
Institub of
Medical
Sciences

F¡gurc 7

Savw f*znúame*tals
Motcr Bike Motor Sike Truck

Fsure 2

rxéicisi,e r
identify the relationships between the various classes depicted in the following
f ig u res:
a.t.

l';lachine

b.

Car

C0rrputer

, ?t'ql'T
d.

FmplsyeelS

Exercise 5
A passenger of FlyHigh Airlines can travel by two types of ticket reservations,
Confirmeá ticket and Requested ticket. The Airline reservation has various
attributes,
Both types of classes ¡nherit these
such as flight number, dáte, time, and destination.
Confirmed ticket class would however have a seat number
common aitributes. T'he
*fr¡1" u Requested ticket would have a status attribute. Draw the class hierarchy
Jiug.ut for ttre three classes depicting the inherited attributes of the sub classes and
their individual attributes.

!
.r.-'. í¡
"j
:X Lt ": ?: . | "^""{.} r. ",',", h" É
" i. A Y,
'!
a

HOUT ASSIGNMENT

Which language is an Object Oriented Programming language?


a. BASIC
b. coBoL
c. FORTRAN
@ Java
z. Which option is correct about the procedural programming approach?
@ In the procedural programming approach, portions of the code are so
interdependent that the code in one application cannot be reused in
another.
b. In the procedural programming approach, portions of the code can be
reused.
c. The procedural programming language provides the advantage of
information hiding.
d. The procedural programming language provides the advantage of real
world programming.
3. Which feature of Object Oriented Programming language ensures data security
in a program?

O Information Hiding
b. Resuability of code
c. Resilience to change
d. Modularity of code
4. Which option is correct about the classes and objects in OOPS?

$ Ob¡ects are the basic building blocks of OOP.


b. Objects are the basic building blocks of procedural programing
methodology.
c. class is an instance of an object.
d. The objects can exist in isolation.
5. Which option is correct about the objects in object oriented programming
language?
Two objects may have the same behavior, may or may not have the
same state but will never have the same identity.
b. Two objects will never have the same identity, behavior, and state.
Two objects may have the same identity, behavior, and state.

T:WZTtr "", e:" 4; ..:i,.;.i";.


"r:!li,
d. Two objects may have the same identity, may or may not have the
same state but will never have the same behavior
6. Which option is correct about the objects in Object Oriented Programming
language?

@ fne identity of an object can be changed in its lifetime.


b. The identity of an object never changes in its lifetime.
c. The behavior of an object distinguishes it from all other objects.
d. The behavior of an object refers to a change of its behavior over a
period of time.
7. In single inheritance, a subclass is derived from
@ onty one superclass.
b. Two superclasses.
c. Three superclasses.
I
I d. Four superclasses.
1l
I
8. Inmu|tip|einheritance,asubc|assisderivedfrom-_'
a. Only one superclass.
b. Two superclasses.
c. Three superclasses,
14
@,i More than one super class.
9. A computer has a monitor then what is the kind of relationship depicted
between the Computer and Monitor class,
a. Kind-of
b. Is-a
c. Part-of
(l) Has-a
10. Which option is correct about inheritance?
a. Inheritance does not allow you to share data and methods among
multiple classes.
Inheritance enables you to,add new features and functionality to an
existing class without modifying the existing class.
c. In inheritance, a subclass is also called a parent class,
d. In inheritance, a superclass is also called a child class.

kffi"ffi Tmw* Wq**&mmwrz4*4s


w
IwrnepucTuelu
hess*F* Re.
TC) #*v*

In this lesson, you will learn about:


Éil Concepts of Java programming language
Éil Vat'iables
Éil ArraYs

Sava Fundarxentals
w-

2.&,W Sawm Funúarsz*.rztals i&jWú


.v &4^ a
IÁv* Pi¡

lava is an object-oriented programming language that was designed to meet the need
'or a platform independent language. Java is used to create applications that can run
on a single computer as well as a distributed network. Java is both a language and a
rechnology used to develop stand-alone and Internet-based applications.

With the increasing use of the Internet, Java has become a widely used programming
anguage, Java software works everywhere, from the smallest devices, such as
.nicrowave ovens and remote controls to Supercomputers' Java programs are
ndependent of the type of computer, telephone, television, or the operating system
these devices run on. The lava programs work on any type of compatible device that
supports Java,

Need for Java


The Java language contains built-in support for the World Wide Web (WWW), which is
a service of the Internet to retrieve information in the form of Web pages. The primary
motive behind developing Java language was the need for a portable and
platform-independenl language that could be used to produce code that would run on
a variety of Control Processing Unit(CPU) under different environments. You can use
Java to bevelop network-orieñted programs because networking features are built-in
features in Java.
you can use Java to wr¡te a variety of applications. A few types of Java applications
are:

W Applications that use Character User Interface (CUI): Applications are


executable programs that are controlled by the operating system' These
applications haúe an access to the system resources, such as file systems and
can read and write to files on local computers'
W Applications that use Graphical User Interface (GUI): These applications are
used in the W¡ndows environment, In GUI, you interact with the application in
graphical mode.
ffi Applets: Applets are small executable programs that run on a Web page. These
piograms require a Java-enabled browser, such as Internet Explorer or Netscape
Navigator. Applets have limited access to system resources'
W Servlets: Servlets are the programs that are used to extend the functionality of
Web servers.

,::'wffi1r J mv *, F a¿n úa {ffi w q21 t},9 4á ?.k,3


W Packages: Packages are collections of classes that can be reused by applications
and applets.
Most programming languages are platform dependent. Applications developed by
using such programming languages can run only on those types of hardware and
software platforms on which the applications are compiled. Compilation of an
application refers to conversion of the program instructions, written in a programming
language, to the language that the computer can understand,

Java is a platform independent language that enables you to compile an application on


one platform and execute it on any platform. This saves your effort to write and
compile the same application for different platforms.

Computers connected to the Internet run on different operating systems and hardware
platforms. The applications running on these computers can be Web-based or
Internet-based. Internet applications are distributed, which means two or more
applications running on different computers communicate with each other by
exchanging messages and data.

You use Java programming language to develop an Internet-based application that


can be accessed by programmers working on various types of computers.

In addition, you can download a file or an executable program on a computer


connected to the Internet. Any program downloaded through the Internet can perform
some malicious task on the local computer if the local computer does not implement
security checks. Java provides a solution to all these problems. Java applet, which is a
program embedded within a Web page, when downloaded from the Internet on a
computer cannot access the file system on the local computer. Java provides a.run
time environment, which implements various security checks on Java applets and does
not allow them to peform any malicious task.

Characteristics of Java
Simple Solutions Systems Inc, is a software development organization, which has
branches across the globe. The organization needs to develop an automated
application within a short duration. The application must enable the employees to
obtain information about the benefits and opportunities offered by the organization.
The organization also wants a Web-based application for the recruitment system that
enables an individual from any country to apply for a job. The applicants across the
globe might use any type of operating system, such as Windows, Linux, or Solaris.
The system should be reliable enough to handle error-causing conditions, such as
viruses.

2"&,.4 ?as¿w #**ndar**cata\g {.6}WAW


The choice for having a programming language that fulfills all these requirements is
Java because it exhibits the following characteristics:
X Simple
& object-or¡ented
& Compiled and interpreted
ffi Portable

ffi Distributed

ffi Secure

Simple

A lava programmer does not need to know the internal details of Java as to how
memory is allocated to data because in Java, the programmer does not need to handle
memory manipulation. Java is a simple language that can be learned easily even if
you have just stafted programming. It was designed to be easy for the programmer to
learn and use effectively. The syntax for various Java statements is easy to
understand,

One of the major problem areas in most of the object-oriented


languages, such as C++, ¡s to handle memory allocation,
Programme¡s need to explicitly handle memory in the program
for its opt¡mum utilization. To handle memory allocation, they
use pointers that enable a program to refer to memory
location of the computer. However, Java does not support
pointers and consists of the built-in functionality to manage

Object-Oriented

Java supports the object-oriented approach to develop programs, It supports various


features of an object-oriented language, such as abstraction, encapsulation,
inheritance, and polymorphism. To implement the object-oriented language, the entire
code of the program must be written within a class. The lava language does not
suppoft stand-alone statements. Even the most basic program in Java must be within
a class.

,7zW'?,18W Smwm Famümffie,nte.&# 7.&..%


f

Compiled and Interpreted

The Java programs are first compiled and then interpreted. While compiling, the
compiler software checks for the errors in the program and lists all the errors on the
screen. Afteryou have made the program error-free and have recompiled it, the
compiler converts the program into computer language.

The Java compiler compiles the code to a Bytecode that is understood by Java. Wher
you compile a Java source code file (.java), the Java compiler generates the Bytecode
which is a compiled Java program with a .class extension, The Java Virtual Machine
(JVM) then interprets this Bytecode into the computer code and runs it. While
interpreting the interpreter software reads and executes the code line by line. The
Java interpreter can execute Java code directly on any computer on which a JVM has
been installed.
The lava compiler is written in Java and the interpreter is
written in C programming language

Poftable

Portability refers to the ability of a program to run on any platform without changing
the source code of the program. The programs developed on one computercan run or
another computer, which might have a different platform. Java enables the creation o;
cross-platform programs by compiling the programs into an intermediate
representation called Java Bytecode. Bytecode is the result of compiling a Java
program. You can execute this code on any platform,

The Java compiler reads lava language source (.java) files, translates them into Java
Bytecode, and saves the Bytecode into class (,class) files. The compiler generates a
class file for each class in the source,

Converting a Java program into Bytecode makes a Java program portable because any
computer installed with the JVM for the platform on which it is running can interpret
the Bytecode. The IVM is the interpreter of the Bytecode, which reads the Bytecode
line by line and executes it.

If the operating system of the computer changes/ you only need to install the IVM for
the new operating system without requiring any changes ¡n the source code of the
Java program. Therefore, other people can use the programs that you write in Java
even if they have different computers with different operating systems.

ye",ffi 7mvm Tan*mq,n*s2Yn.s ttii¡W717


IVM is not platform independent. Each platform iee7s to ttave
its own JVM to run a Java application. The Bytecode supports
connection to multiple databases.

The following figure shows how the Java Bytecode and the IVM together make Java
programs portable on different platforms:

ryl
fr Java $ource Code I

--- ,f--
4___g::__J
ÉffiJéva
{
\-Try-/\
I

u**- .:. " *.


f, eytecode fite
{ (.class nte)
I

,/'l\
;=]\

\j:_/ \.:' - ffi\


uNrx tuacrntostr
*-T-*lf,
f,wi.uows lfi I

&
$ UNIX | [ Macintosh
$ tt/indows | I

il Máchine
| fl uacirine I f M€chine
t_:gsj
I

t__eg!Lj q___jga_J
Java portability with Mult¡ple Platforms

The preceding figure displays how a Java application is portable across platforms. The
Java compiles and converts the source code of a Java application available in a .java
file to a Bytecode file (.class file). The same .class file can'be interpreted by the :úV of
a specific platform, such as Windows, UNIX, or Macintosh.

Distributed

Java is used to develop applications that can be distributed among various computers
on the network. Java is designed for the distributed environment of tne Internet

ryiwÉrr 3 av n W *zm* myrz e rkV.e\%: ?"e..7


because it supports the various Internet protocols, such as Transmission Control
Protocols and Internet Protocol (TCP/IP).

_Java applications can open and' access remote objects on the Internet in the same
manner as they can open and access objects in a local network. Java contains a
package, Remote Method Invocation (java.rmi), which is used to build distributed and
client-server based applications.

Secure

lava has built-in security features that verify that the programs do not perform any
destructive task, such as accessing the files on a remote system. Java does not allor
the use of explicit pointers, which áre used to referto the memory locátions in a C++
program. All references to the memory are symbolic references, which means that the
programs cannot access memory locations w¡thout proper authorization.

When you access a program over the Internet, it is susceptible to attacks from the
virus programs. In Java, the compiled Bytecode is strongly type checked. Any change
made in the Bytecode are flagged as errors and the program does not execute. This
ensures the security of the lava program over the Internet.

In addition, if Java applets are downloaded from the Internet, they perform
operations, such as accessing files and read/write function, from the host computer
from where you run the applet. Applets cannot access the resources on the local
computer.

An applet can only communicate with the remote server from which you download the
applet. It cannot make connection with other remote computers.
Host computer is the remote computer where the application is
stored. You run the application from the host computer over a
network by using a computer, which is termed as the local
computer.

iñ;r;óñiié¿iiñ
Various components of the Java architecture are:

W Java programming language


W Java class file
ffi Java Viftual Machine (JVM)
W Java {1¡plication Programming Interface (API)

ee 4 ee:ebq4¿ éqip, d blbe p@e 4 !! t!!t ¿!4e Yyj\ |'1' e ee!6.;::: ::...: ::x

2e"& 3*wa f*,tnda{w*,ntals wfrtr.t


because it supports the various Internet protocols, such as Transmission Control
Protocols and Internet Protocol (TCP/IP).

-Java applications can open and access remote objects on the Internet in the same
manner as they can open and access objects in a local network. Java contains a
package, Remote Method Invocation (java.rmi), which is used to build distributed and
client-server based applications.

Secure

Java has built-in security features that verify that the programs do not perform any
destructive task, such as access¡ng the files on a remote system. JaVa does not allow
the use of explicit pointers, which are used to referto the memory locations in a C++
program. All references to the memory are symbolic references, which means that the
programs cannot access memory locations without proper authorization.

When you access a program over the Internet, it is susceptible to attacks from the
virus programs. In Java, the compiled Bytecode is strongly type checked. Any changes
made in the Bytecode are flagged as errors and the program does not execute. This
ensures the security of the Java program over the Internet.

In addition, if Java applets are downloaded from the Internet, they peform
operations, such as accessing files and read/write function, from the host computer
from where you run the applet. Applets cannot access the resources on the local
computer.

An applet can only communicate with the remote server from which you download the
applet. It cannot make connection with other remote computers.
Host computer is the remote computer where the application is
stored. You run the application from the host computer over a
network by using a computer, which is termed as the local
computer.

Java Architecture
Various components of the Java architecture are:
W Java programming language
ffi Java class file
ffi Java Viftual Machine (JVM)
W Java Application?rognamming Interface (API)
Java Programming Language and class File

Java programs are saved with an extension, .java. A .java file is compiled to generate
the .class file, which contains the Bytecode. The JVM convefts the Bytecode contained
in the .class file to machine object code. The JVM needs to be implemented for each
platform running on a different operating system.

The following figure shows the relationship among various components of the lava
prog ram ming environment:

lav¡ File Syter0de

The Java programming env¡ronment

Java Virtual Machine (JVM)

The JVM forms the base for the Java platform and is convenient to use on various
hardware-based platforms.

Components of the JVM


IVM for different platforms uses different techniques to execute the Bytecode. The
major components of JVM are:
ffi Class loader

W Execution engine
ffi lust In Time (JIT) compiler

Class Loader

The c/ass loader loads the class files, which are required by a program running in the
memory. The classes are loaded dynamically when required by the running program.
A JVM can have following types of class loaders:

W Primordial Class Loader: Loads the Java API classes required by the running
Java program.
W Class Loader Objects: Loads the classes ütne Java application program' An
application can create class loaders at runtime for loading the classes of the
application.

3 mzx m W *q nú mwm *rz:t mTw ZP".W


*:"ffi&TK
Fr_

Execution Engine

The Java execution engine is the component of the IVM that runs the Bytecode one
line after another. The execution engines implemented by different vendors use
different techniques to run the Bytecode, The Java execution engine converts the
Bytecode to the machine object code and runs it.

JIT Compiler

The JIT compiler is used for compiling the Bytecode into executable code. The JVM
runs the JIT compiled code without interpreting because the JlT-compiled code is in
the machine code format. Running the JIT- compiled code is faster than running the
interpreted code because it is compiled and does not require to be run, line after line.

Java Application Programm¡ng Intedace (ApI)

The Java API is a collection of software components that provide capabilities, such as
GUI. The related classes and interfaces of the lava ApI are grouped into packages.

The following figure shows how the Java API and the JVM forms the platform for the
Java programs on top of the hardware:

| :aua crogram I
(.:ava)
| |
t_____=______l
ffiFI
l.------------
,-\
-*Java\.
L*_eL_l
ffi
R:*9
Hardware
I
L__J i

Components of Java platform

Java Architecture Security


Java architecture also consists of a few security features that make lava a secure
programming language. The architecture consists of the following security features:
W Compiler level security

.: 1 !. P?A 4l;Ét:;li::V::te:\rt4.6.a!6\é|;i Z:! rr?!1!.!p.

lí:¡ lWtt¿A
1y: ffi***
w Bytecode verifier
w Class loader

W Sandbox model

The following figure shows the various levels of security implemented on Java
programs:

&ut*rq*t¡ L*1rs* 2r
Svtecsde vprifi*r

*ewrlfY U*u*, *\
Cl¿ss lnader

*erarr*rÍ L*v** 4:
Sandbrx M*del

Security Levels ín Java Arch¡tedure

Compiler Level Security

one of the problem areas in earlierobject-oriented languages, such as c++, wasthe


availability of pointers. Pointers enable a program to access memory directly, which
might result in improper usage of memory. The problem of memory usage is resolved
in Java, as it does not support pointers at the program level. Java prevents errors that

I:::::::: i': ;;;:;


"t't:
tí:;iww 3 m'sr m W axffi qáa frw *rzq. e6w 2.&*23

{,¿r-J* "'Ye/*&
arise due to improper memory usage, reducing the compile-time errors, In addition,
Java employs typecasting between data types that implies that when one type of data
is assigned to another type of variable, an automatic type conversion takes place.
Typecasting in Java ensures that there is no data loss in the result or output of a Java
code.
At times, you might need to compare incompatible data, such
as a text and a number. To compare such data, you need to
convert data of one type to another, such as text to number or
number to text. Conversion of data from one type to another is

Bytecode Verifier

The Bytecode verifier checks the Bytecode before it runs on a computer. It ensures
that the Bytecode does not violate access restrictions, such as read/write operat¡ons'
and verifies that the Bytecode does not forge pointers. The Bytecode is verified in two
phases:

W In the first phase, the verifier checks for the structure of the .class file,
W The second phase occurs when the Bytecode is run. The Bytecode verifier checks
the validity of classes, variables, and methods used in a program.
Native APIs are the application programming interfaces of the
operating system on which the Java application is executed.

Class Loader

The c/ass loader determines how and when an applet will use classes in a running Java
environment. In a Java environment, there can be many class loaders and each class
loader can create its own run-time environment. The class loader loads all the applets
and their references.

Sandbox Model

lhe sandbox model is implemented in the Java applets container, such as Web
browsers. The sandbox model determines the limitations of Java applets that they can
only access the resources of the host computer and cannot access the files on the
local computer. Java applications do not employ this security model and are allowed to
read from and write to files on the local computers.

7.&"ñ"4 Zmr¿m Wzxrz&amav2te*& 'f"1W


Dec¡-aRING VnnrnBLEs AND
LITERALSI

Wi '.:aa:), aaa,!aa

Java supports some basic programming elements, such as data types, keywords,
literals, and variables, Keywords are the reserved words for Java programming
language, which cannot be used as names forvariables, class, or method.

Using Various Data Types


The data stored in memory of the computer can be of many types. For example, a
person's age is stored as a numeric value and an address is stored as alphanumeric
characters. Data types are used to define the operations possible on variables and the
storage method.
Java is a strictly typed language, which means that lava gives impoftance to type
checking. Expressions and variables in Java can be of different types, such as int,
char, or string, Type checking is one of the impoftant steps in compilation of a
program. The data stored in the memory of a computercan be of differenttypes. The
various data types in Java are:
ffi Primitive or the simple data types
ffi Abstract or the derived data types

Primitive Data Types


The buift-in data types in Java are known as the primitive or the simple data types.
There are eight primitive data types in Java, which are fufther grouped in the following
categories:
W Integer type: Can store whole number values. The size of the values of the
variables depends upon the chosen integer data type, The four integer data
types are:
o byte
. shoÉ
o int
o lono

':azm' 3 ms¿ n W z* ru ú. r¿ rr? {& r'tt.& ffi


É . 2,á,^,?i""3
F-_-_--

W Floating point type: Can store fractional numbers. The two types of floating
point type are:
o float
o double
ffi Boolean type: Can store only the true and false values. Boolean data type is
reouired when a condition has to be checked. The true orfalse value of the
expression or the condition determines further execution of the Java program.
W Charactertype: Can store symbols, such as letters and numbers. In character
type, there is one data type, char.

The following table lists the primitive data types with their size and range, grouped in
four categories:

GróiuB Data Type SÍZe Pe,nge' üátáattt


'',
: .,ri llr:,: ,. ,

,'Y4tue '1

Integer byte One byte -27 to 27-! (signed) 0

short Two _2ts ¡o 2rs _1 0


byte

int Four -237 to 23r_! 0


byte

long Eight -263 to 263-r 0


byte

Floating float Four 3.4e-038 tO 3.4u*038 0.0


point byte

double Eight 1.7e-308 tO 1.7"*308 0.0


byte

Boolean boolean One bit true or false false

Cha racter char Two a single character null


byte

The groups, Integerand Floating point can store negative values. Java, unlike C/C++
does not support the concept of unsigned integers.

7.&,"lt4 3 xt¿ * W z* rzú m r"n * rztmZn i;t'?{i{t


Abstract data types
The abstract data types include the data types derived from the primitive data types
and have more functions than primitive data types. For example, String is an abstract
data type that can store letters, digits, and other characters, such as /, O, :,:, $, and
#. You cannot perform calculations on a variable of the String data type even if the
data stored in it has digits, However, String provides methods for concatenating two
strings, searching for one string within another, and extracting a part of a string.

Keywords ava¡lable in Java

The keywords are the reserved words for a language, which express the language
features, Keywords cannot be used for naming purpose of variables, constants, or
classes.

Java is a case sensitive language and the keywords should be written in lowercase
only. The keywords with all or some letters in uppercase can be treated as variable
name but that should be avoided. The following table lists the Java keywords:

Abstract boolean break byte

case catch cnar CIASS

Const continue default oo

Double etse extends final

Finally float for goto

If implements Impott instanceof

Int interface long native

New pacKage private protected

Public return short static

Strictfp super switch synchron ized

This throw throws tra nsient

Try void volatile while

;:,MÉA'tr 3 mw m ffi ¿zvzúarzz*q"eYwIs ?.Ét.b%


Defining Variables and Literals
A variable is used to store and manipulate data or values in programs. Avariable is
the name that refers to a memory location where some data value is stored. You can
assign different values to a variable during program execution. Java allocates memory
to each variable that you use in your program. If the name, number, is used to refer
to an area in memory in which a value is stored, number is a variable.
Each variable that is used in a program must be declared. For example, if the variable,
number, is to be used for storing an integer value, the variable, number, must be
declared and it should be of the type int.

Naming Conventions for Variables

A program refers to a variable by using its name. Ceftain rules and conventions
govern the naming of variables. These rules are enforced by a programming language.
A program does not compile if you have not followed the rules of the language.
Conventions help to improve the readability of the program, but following them is not
mandatory. The naming conventions for a variable in Java are;
r& The name of a variable needs to be meaningfui, short, and without any
embedded space or symbol, such as ?,l, #, @, o/o, &, {}, fl, i, i, ", and /.
W. A variable name must be unique.
W A variable name must begin with a letter, an underscore (-), or the dollar
symbol ($), which can be followed by a sequence of letters or digits (0 to 9), '$',
or '_',
'ffi A variable name should not start with a digit.
. A variable name should not contain embedded white spaces. You can use an
underscore for spacing purpose.
o A variable name should not consist of a keyword.
o A variable name in Java is case sensitive. There is a difference between
uppercase and lowercase names. For example, age is not same as Age'

Types of Variables

The area or the region of a program where a variable can be accessed is known as
variable scope. The various types of variables on the basis of the variable scope in
Java are:
ffi Class variables: Are accessible within a class and its objects. The class variables
are declared inside the class before their use.

:.+ .3_ *. 3 *'q r^z #a¡ n rJ a rt* e *?. al n i: ffi2T3'


'l
I

w Instance variables: Are declared inside a class and are created when the class is
instantiated. Objects give different values to instance variables as per the
specific requirements of the object of that class type.
W Local variables: Are declared inside a method. Theirscope is within the block of
code in which they are defined. They are local to the block of code and are not
accessible outside the method.
W Static variables: Are allocated memory only once but are globally accessible to
all instances of a class. Therefore, when an instance of a class is destroyed, the
static variable is not destroyed and is available to other instances of that class.
w Automatic variables: Are accessible within the function in which they are
declared. The automatic variables are created when a function is called and are
destroyed when you exit the function.

Declaring Variables

The declaration of a variable informs the compiler about the variable name, data type,
and the scope of a variable. A variable has to be declared before you access it. The
following syntax shows how to declare a variable:
<type> <variablename>; // Single varj-abfe of gÍven type.
<type><variablelname,variable2name.....variable n name> // ltultiple
variables of given type.
In the preceding syntax, you need to initialize variables before you use them. The
Java compiler initializes the class data variables to default values when an object is
created. You can assign values to a variable during declaration or after declaration of
the variable before first use of the variable. For example, you can use the following
statement to declare the variables, numl, and num2 to calculate the sum of two
numbers:
int num1, num2;

The following syntax shows how to assign values to a variable:


<type> <variablename>=<vafue>; / / During declaration.
<variablename):(value) // After decl-aration.
For example, you can use the following statement to assign values to the variables,
num1, and num2 to calculate the sum of two numbers:
int num1, ntm2; // Declaration of variables'
numl : 5; // Assigning values to the variables.
num2:10;
You can also assign the same value to more than one variable in a single statement.
The following statement shows the assignment of the same value to more than one
variable:
^ _L_^_ ? .

iij . ! '. '! :: . ; : : ; :, - ,: | . 1 : ::: | . !: . ::: : ' . ' :' : : ' .

i&1 €gy.&
,:a' &a& @
3*wm Yeanúmrrq*ffita&s 2fi^"27
In the preceding command, integer value 3 is first assigned to variable c, then to b
and finally to a.

Literals in Java
Literals are the values to be stored in variables and constants. A literal contains a
sequence of characters, such as digits, alphabets, or any other symbol that represents
the value to be stored. The various types of literals in Java are:
ffi Integer literals: Are numeric type values. The numerical values can be
reoresented in octal and hexadecimal notation. The octal notation of a number is
prefixed by zero and hexadecimal numbers are prefixed by 0x. For example,
n=0123 is integer literal in octal notation, n=0x456 is integer literal in
hexadecimal notation, and n=2 is decimal notation for an integer literal,

ffi Floating point literals: Are numeric values with fractional paft. For example,
x=7 .9 is a floating point literal.
ffi Character literals: Are represented in single quotation marks. For example, x='k'
is a character literal.

ffi String literals: Are enclosed in double quotation marks. For example, x="James"
is a string literal.
W Boolean literals: Are the literals having value, true or false. For example,
x= false is a Boolean literal.

Manipulati ng Variables
To manipulate data and variables in Java, you use operators, which accept one or
more operands or arguments and produce an output. The operators used to
manipulate variables are assignment and arithmetic operators.

Assignment Operator
You use the assignment operator (=) to assign a value to a variable. The following
syntax is used for the assignment operator:
op1- : op2;

In the preceding syntax, the assignment operator assigns the value of right operand,
op2 to the left operand, op1. The data type of the variable is compatible with data
type of the value assigned to the variable.

7.&""zffi Yat¿w ?an*aryt*ntw\s l,WLí.f


I

Arithmetic Operators
Arithmetic operators are used to compute mathematical expressions. The following
table lists the various arithmetic operators;

Operatoi
+ Adds two operands

Subtracts one operand from another.

Multiplies two operands

Divides two operands

o/o
Calculates the modulus

++ Increments a variable

Decrements a variable

Basic Arith metic Operators

In Java, you perform the basic mathematical operations, such as addition, subtraction,
multiplication, and division using +, -, x, and / operators.
The addition operator (+) is used to add two ¡ntegers and concatenate two string
values' For example, you have two numbers, 4 and 5. To add these numberr, yo,Ls"
the following statement:
4+5
In the preceding statement, you use the, +, operator to concatenate the two
values to
produce a result 9.

In addition to the numbers, you can use the + operator to concatenate two str¡ng
values' For example, the expression, ab + cd, produces the result, abcd.

,{'W&$V ?awm Fayndaryiernte\# a&,,9#


Modulus Operator

The modulus operator (9o) returns the remainder of a divisjon as a result of a division
operation. You can apply the modulus operator on both integer and floating-point
values.

The following examples show the results of modulus operator on two operands:

* L5 o/o 6:

15-6=9
9-6=3
3 < 6. Therefore, the result of the modulus operator is 3.
I 9.6 o/o 4.2:
9.6-4.2=5.4
5.4-4.2=L.2
L.2 < 4.2, Therefore, the result of the modulus operator is 1.2,
J -10 Vo 3:

-10 + 3 = -7 (To reduce the magnitude of -10 by 3, you add 3 to -10)


-7+3=-4
-4+3=-!
l-11 < 3. Therefore, the result of the modulus operator is -1.
s -!00/o-6: .

-10-(-6)=-4
l-41 < l-61, Therefore, the result of the modult¡s operator is -4.

24.20 f,ava fundamentals ffirg##


You might come across a situation where you need to store similar Wpe of values for a
large number of data items. For example, to store the marks of all the students of a
university, you need to declare thousands of variables. In addition, each variable
name needs to be unique, as perthe variable naming rules. It is practically impossible
for a person to ¡'emember the name of each variable. To avoid such situations, you
can use arrays. An array is a group of variables of the same data type and referred to
Dy a common name.

An array is a contiguous block of memory locations referred by a common name. For


example, to store the marks of 5000 students, you can declare an array, marks, of
size 5000 and can store the marks of as many students.

An array consists of a name and the number of elements of the array. You can refer to
a specific array element by the array name and the element number, which is known
as the index number.

Creating Arrays

The length of an array is fixed at the time of its creation. An array represents related
entities having the same data type in contiguous or adjacent memory locations. The
related data items form a group and are referred to by the same name. For example,
the automated employee management system of SimpleSystemsSolutions Inc. might
need an array of integers to hold the IDs of the employees. The following command
shows an array named employee:
employee l5l ;
The complete set of values is known as an array and the individual entities are called
as elements of the array. A specific value in an array is indicated by writing the array
name and placing the index of the desired element in square brackets. The index is
also known as subscript and the array may be called as a collection of subscripted
elements of the same data type. The advantage of using array lies in the fact that you
can refer to a large number of elements by just specifying the subscript preceded by
the array name. Arrays make it easy to do calculations in a loop, such as determining
the total number of values stored in an array,

i;'?áXÁry 3 aaa a W e3 ffi {3 m rvi * ffitffiE%, x&"3"9


F---

The various types of arrays in Java are:


W One-dimensional arrays
W Multi-dimensional arrays

One-dimens¡onal Arrays

One-dimensional array is a list of variables of the same data type. The following
syntax shows how to declare a one-dimensional array:
type arr [] ,'
In the preceding syntax/ type is the data type of the array. All the elements of the
array contain variables of the same data type as the array. For example, you have an
array that contains the names of the various designations offered by
SimpleSystemsSolutions Inc. for its employees. The following syntax shows how to
declare a one-dimensional string array:
af ri nn ¡laci n¡¡+i nn,,_types
f r¡naa l1ñ l .
[10],.
In the preceding syntax, the designation_types array is declared that can store 10
designation types in it.

Allocating Memory to Arrays

You use the new operator to allocate memory to an array. The following syntax shows
how to allocate memory to a one-dimensional array:
arr = ner^7 type Isize] ,.

You can use the following statement to allocate memory to an array having 3
elements:
Emp_ID : b3y/ string [3],'

rtt i,t a i;:1:);;; :;::ti::i:t:::!::::1

ke"?"x Sawa Frs*&azw*r*Eals wlw&,


The SimpleSolutionsSystem Inc. needs to store the employee IDs in an array,
emp-ID[]. The following figure shows how memory locations are allocated to the
emp_ID[] array;

emp*ID l2l

Memory Allocation to Arrays

M ulti-dimens¡onal Arrays
In addition to one-dimensional arrays, you can create multi-dimensional arrays. To
declare multi-dimensional arrays/ you need to specify multiple square brackets after
the array name. For example, the following syntax displays the declaration of a two
dimensional array:
r-+L
¿rr -..r-rñr-'1
Iluf Lf yf tLL L I -=w
Itr intt3l [];
-

In a multi-dimensional array, you need to allocate memory for only the first
dimension, as shown in the preceding syntax. You can allocate the remaining
dimensions separately. The following code snippet manually allocates memory to the
second dimension:
muftiDim[0] : new int[4]t
multiDim[1] = new ínt[4];
multiDim[2] : new int[4];
In addition, when you allocate memory to the second dimension of a
multi-dimensional array, you need not allocate the same number to each dimension.
You can use the following code snippet to create a multi-dimensional arra;z in which
the sizes of the second dimension are not eoual:
i-r *_.r+rñr*,' _ rrr
LrvrrLf Ll - -eh, intt3] tI;
multiDim[0] = new ínt [1];
ñ,,1finimrlr - ñóil int[2];
mul-LiDim[2] = new int[4];

:u'MYYW Smww Wanúmcw*.tttwfrs m&"ffiffi


Accessing Arrays
You need to access various elements of an array to assign, retrieve, and manipulate
the values stored in the array

Assigning Values to the Elements of an Array


To access a specific array, you need to specify the name of the array and the index
number of the element. The index position of the first element in the array is 0. For
example, the following statement assigns the value "ceneraf Manager" to the first
element of the array, des i gnat i or_:vpes i j :
designation types l0l -"Genera: Mar.ager";
You can use the following code snippet to assign values to different elements of the
given array:
String designation_types, _ ;
designation types: new Scringl3l;
designation typesl0l: "General Manager";
designation types l1l: "Assistant Manager",'
designation typesl2l= "Managing Di,rector";
You can declare and allocate memory to a user-defined array in a-single statement.
The following syntax shows how to declare an array and allocate the array in a single
statement:
tYPe arrLl = new:YPelsizel,'
You can use the following code snippet to declare and initialize arrays in the same
statement:
String Designation_typesil : r" Generaf Manager", "Assistant Manager",
"Managing Director" ] ;

Accessing values from var¡ous elements of an array


Similar to assigning values to array elements, you can access values from elements in
the array by referring to the element by its index number. The following statement is
used to access and display an element stored at a specific index position:
nacinn:f i¡n r¡'naciñl-^aci¡n:f i^n f \,ñeS[2]-
'" "JF

In the preceding statement, the value of the third element of the array is assigned to
the first element of the array.

3&"24 3atra ft¿.*úwm*,nteAfi tr;:wztT


In this lesson, you learned:
W Java is both a language and a technology used to develop desktop and
Internet-based applications known as Java applications and applets.
W The various characteristics of Java programming language are:
¡ Simple
¡ Object-oriented
o Compiled and interpreted
o Portable
o Distributed
¡ Robust
. Secure
ffi Various components of the Java architecture are:
¡ Java programming language
. Java class file
o Java Virtual Machine
. Java Application Programming Interface (API).
ffi The JVM converts the Bytecode contained in the .class file to machine object
code.

w The various data types defined in Java are:


o Integers: Include byte, short, int, and long data types
o Floating-point numbers: Include double and float data types.
o Characters: Include char, data type.
o Boolean: Include boolean, data type.
w The built-in or the intrinsic data types in Java are known as the primitive or the
simple data types.
w The abstract data types include the data types derived from the primitive data
types.

ffi The keywords are the reserved words for a language, which express the
language features.

w A variable is the basic storage unit in Java. It is the name that refers to a
memory location where some data value is stored.

Tmww Wzxn#ar{e*{2tffi&# ¿.,é4., ¿.3


#:Wb{'{
I The various types of variables are:
o Class variables
o Instance variables
o Local variables
o Static variables
.. Automatic variables
You use operators in Java to manipulate data and variables. The various
operators are assignment and arithm-etic operators.
r An array is a group of variables of the same data type and refer"red to by a
common name. A specific element of an array can be accessed by its index.
array is a block of memory locations.

2¡'.m Java Fundarnentals


w Java is both a language and a technology used to develoo desktop and
Internet-based applications known as Java applications and applets.
w The various characterístics of Java programming language are:
. S¡mple
o Object-oriented
o Compiled and interpreted
o Portable
o Distributed
¡ Robust
t Secure
W Var¡ous components of the Java architecture are:
r Java programming language
. Java class t¡te
o Viftual Machine
Java
. Application Programming Interface (ApI)
Java
w The JVM converts the Bytecode contained in the .class file to machine object
code.

w The various data types defined in Java are:


. Integers: Include bvte, short, int, and long data types
r Floating-point numbers: Include double and float data types.
rCharacters: Include char, data type.
. Boolean: Include boolean, data type.
w The built-in or the intrinsic data types in Java are known as the primitive or the
simple data types.
W The abstract data types ínclude the data types derived from the primitive data
types.
ffi The keywords are the reserved words for a language, which express the
language features.

ffi A variable is the basic storage uh¡t ¡n Java. It is the name that refers to a
memory location where some data value is stored.

?,A.27
s The various Vpes of variables are:
o Class variables
. Instance variables
o Local variables
. Static variables
. Automatic variables
n You use operators in Java to manipulate data and variables. The various
operatorc are asslgnment and arithmetic operators.
3 An array is a group of variables sf the same data type and referred to by a
common name. A specific element of an array can be accessed by its index.
array is a block of memory locations.

Java fundamentals
W hessom kB
Cmsses AF*n On¡EcTs

ectives
In this lesson, you will learn about:
d Structure of a Java program
F Access specifiers and mbd¡f¡ers
5 Creating a Java application

Have you reg¡ster

at;;:at;i:.:t!;;::t;i::,t;;Á,:,;:l:iii;;:::.rt;::i;:i:!;:.i:::;..t;:n::t;;;::t.!t;,.;!i..:;:a::;:
'3
* q "* Y ¿¿'* rÁ * t"rz r,g
s lq
v¿"6. ¿
"!: '. ".
zffi"4 S*wa Y*r*áatnt,en*e*8
o SrnucruRE or Jnva
A
-
- t-t
r ¡
AppucATroN
f- a-l
-l
-l

In Java, you can either create a stand-alone application or a networked application. A


stand-alone application uses resources of a local computer. A networked application
uses the resources available over a network. For example, a networked application is
allowed to read from or write to files on remote computers.

Classes and objects form the basis of the structure of a Java application. A lava
application cons¡sts of a class, in which you declare the data members and methods.
An object is an instance of a class, and it encapsulates the methods and data
members of a class. Objects can be reused across programs,

Creating Classes and Objects


A class defines user-defined objects and their characteristics. Any concept that you
need to implement in a Java program is encapsulated within a class. A class defines
the attributes and methods of objects of the same type sharing common
characteristics. For example, when you create an online shopping site for books, each
book is an instance of the Books class. All books have attributes, such as the number
of pages, type of binding, and title. In addition, the books have various common
methods, such as being selected, being bought, and being sold. The state of each
book is independent of the state of another book.
The main components of a class are:
I Data members (attributes)
S Methods

Classes contain statements that include the declaration of data members, which
specify the type of data to be stored, Methods of a class contain a set of executable
statements that gives a desired output. Methods define the action to be carried out on
the data members of the class. The class block orthe class body is included within a
set of braces, {}, which indicate the start and end of the class.

ti'#lNY
The following figure shows the members of the Book class:

String title;
float price;
int pages;

void getQ;
void showO:

Methods

Members of the Book Class

Creating Classes in Java

Various data members and methods of a class are defined inside a class. The
statements written in a Java class must end with a semicolon, ;. The following syntax
shows how to declare a class:
class CfassName
l
/ /DecIaraLion of data members
/ /DecLaraLion of methods
l
In the preceding syntax, the word class is a keyword in lava used to declare a class
and className is the name given to the class. This name is required to create objects
of the class.
The preceding syntax consists of a few statements that are prefixed with double slash,
//. These sta[ements are considered as comment entries by the compiler. The
time. It is the
Compiler ignores these statements and these are not executed at run
best practice to include comment entries to describe the code.

You can also declare an empty class that does not contain any data members and
methods. For example, consider a class, Organization, which does not have data
members and methods. The following syntax shows the declaration of an empty class,
Organization, without any data members and methods:
class Organizatron
{
// No data members and methods
l

:. Y.:"""'
You can use the following code snippet to declare the Employee class that defines
various data members, such as employeeName, employeelD, and
em ployeeDesignation.

cJ-ass Employee
I
String empf oyeeName.'
j-nt emp]oyeeID.'
String employeeDesignation,'
)

Creating Objects of Classes

An object is an instance of a class and has a unique identity. The identity of an object
distinguishes it from other objects. Classes and objects are closely linked to each
other. While an object has a unique identity, a class is an abstraction of the common
properties of various objects. To create an object, you need to perform the following
steps:

1. Declaration: Declares a variable that holds the reference to the object. The
following syntax shows how to declare an object of the class:
cf ass_name obj ect_name,'
2. Instantiation or creation: Creates an object of the specified class, When you
declare an object, memory is not allocated to it. Therefore, you cannot store
data in the data members of the object. To allocate memory to the object, you
need to use the new operator. The new operator allocates memory to an
object and returns a reference to that memory location in the object variable.
The following syntax shows how to create an object:
obj ect_name= new cfass_name ( ) ,'
r'l
\.n 54¿vt,-r. ; i:rr'e ütc*:r*:5
-
ga+t¡ l '.'4re¿ {rrr t' 'i .' 'rr 'l
fttttlo"¡ c'<¿C)
! ,' ,' :,,t.!, E rqu\) )

'i-'r.c- ir""'-J'l '= )!'(v a¡;|'tr1"7'oVC)',


,v""rl I I

'4,WlY 3 ;,u.,,,; a V: as'¡: # t* rz' v r* *.t x a+


r¿
The following figure shows how an object is created and reference is assigned to t.€
memory allocated for the object:
wt Yt
fi oecra'e el
Ernproye*
--.& J:.:,"J:?,
a I
I

4_________J "
Cre¿te
el = new ---+
E rn plnyee{)

Creating an Object

You can use the following statement to declare and instantiate an object, e1, of the
Employee class in a single statement:
Employee e1= new Employee O;
You can use the following code snippet to create objects for four employees of an
organization:
Employee el :new lmployee O ;
Employee e2 =new Employee O ;
Employee e3 :new Employee O;
Empf oyee e4 :new Employee O ,'

Accessing Data Members of a Class

You need to assign values to data members of the object before using them, You c¿-
access the data members of a class outside the class by specifying the object name
followed by the dot operator and the data member name. The following syntax shovrs
how to access the data members of a class outside the class:
obj ect_name . data_member_name
In the preceding syntax, ob¡ ect_name refers to the name of the object and
dara_member_name refers to the name of the data variable inside the object that yo-
want to access.

,l l{lIT
You can use the following code snippet to access data members of the
Employee class,
assign values to
such as employeeName]employeeiD, and employeeDesignation and
them through objects, e1 and e2:
e1 . employeeName:" John" ;
e2 . emmployeeName="AndY" i

e1 . employeelD:1;
eZ . emp-Lovee LD=¿ i
el.empfoyeeDesignation : "Manaqer" ;
e2.ernployeeDesignation : "Director" ;

Adding Methods to a Class


Inaprogram,referringtomu|tipledata.membersofac|asscanbeatedioustask.InYou
á¿J¡tioni".céssing ¿aía mem¡ers directly overrules the concept of encapsulation' in
."n c."it" a methbd that can be used to access the data members' Using methods
a Java program provides the following advantages:

Reusability: Enables you to reuse the whole code or a paft of it. A function
W or a
in the ..
task ¡s encapsulated in a method that can be accessed from anywhere
program. The practice of reusing a method is also called "write once, use many"'
at various
The following figure shows the reusability of code by calling a method
places in a Program:

MEth0d
tl
illt
I 2
tl Fraqram

1_____*________J
|

Access¡ng Methods

ffi Reduce complexity: Reduces complexity in a code having hundreds of lines' A


|argeandcomplexcodeisdividedintoprocedures,whichareimp|ementedas
methods.
ffi Data Hiding: Hides the implementation details of an object' When you call a
how that
method from another location in the code, you do not need.to know of the
the data members
method is being executed. The programmercan access
eiample, you have a method, addo that is
class by executing methods. For
a class. When you call the addg method at
;;;¡ rd add two ñumbers defined in
name' You need not
a different location in the code, you call the method by its

'¡.- wtr\T
define the functionality of the addO method again. You can reuse the method by
just calling it.

Adding Methods to Classes


The management of SimplesystemsSolutions Inc. performs various functions, such as
adding, deleting, and modifying the details of its employees, The automated solution
of the organization consists of various methods for performing these functions.
The following syntax shows how to define a method:
void methodName ( )

// Mo1 hnri l¡ndr¡

In the preceding syntax, the void keyword specifies that the function does not return
any value. The methodName SpeCifies the name of the method.

Declaring the main g Method

A Java program consists of the main O method that calls the methods defined in a
class. You can create a number of classes in a Java program. The Java compiler
compiles all the classes in an application but to execute a program, you need to
include a mainO method in the program. The following syntax shows how to declare
the main O method:
nrrl-,1i¡ efrf i¡ ¡¡niA main(String[] args)
{
/ / Code for main () method
]

In the preceding syntax, the method header contains three words public, static, and
void. The implications of these three words are:
W public: The public keyword indicatesthatthe method can be accessed from any
object in a Java program,
W static: The static keyword is used with the main O method that associates the
method with its class. You need not create an obiect of the class to call the
main ( ) methOd.
'ffi void: The void keyword signifies that the maín O method returns no value.

The main O method can be declared in any class, but the name of the file and the
class name in which the main O method is declared should be the same. The file must

¡"'mtlr
have the .java extension. For example, if the main O method is declared in class
Employee, the name of the file should be Employee. j ava.

The main g method accepts a single argument in the form of an array of elements of
type String as shown in the following command:
public static vc' j ::.a':: (S--:'ng arr [ ] )
In the preceding statement, the method header shows one argument in parentheses.
The argument implies that when the class Employee is executed, an array of strings is
sent to the program that helps in program initialization. Strings are a sequence of
characters. ar:.- is the array containing the string values,
An argument is a variable that you need to pass to a method
for providing an input value to the method.

Defining Constructors
You might have observed that to initialize the data members of a class, you need to
assign values to each data member. However, it might turn out to be a tedious task if
you need to initialize a large number of data members. In Java, you can create
constructors of the classes that automatically initialize the data members of the class
when you create an object.

A constructor is a method with the same name as the class name. A constructor of a
class is automatically invoked every time an instance of a class is created.
Constructors do not have a return type,

For example, to calculate the interest on the balance amount in the account of a
customer you can create an Account class. You can use the following code snippet to
add a constructor, Accc:inr O of the class to initialize the values of the data members
of the Account class.
cfass Accou:r--
{
int prlnclpai; / / Data members of the cfass
int interesrRa:e;
int time;
AccountO // Ccost-ructor method
{
principal : 10000; / / initiafization of data members
ínteresLRace : 5;
time= 2;
]
void interest O // method decfaration
{

..: | 1:.::':::- aar 1:l :.1:t-.:.a:,:.:!':l::. :::::: ::.;;

' ;2
&iWiáHW ¡';n q {: A; r,.t} ?a í:,:'1 4. 7:
"t+i
!* r'fi; ai:.13 .. :.4
float amou¡¡: (principal*interestRate*tine) /100,' // method
accessing the data members of the class
]
l
In the preceding code snippet, each time an object of the Account class is created, the
constructor is invoked and the object data members are initialized to the default
values as specified in the constructor. Constructors have the following characteristics:
I A constructor has the same name as the class itself.
t There is no retum type for a constructor. A constructor returns the instance of
the class instead of a value.
I A constructor is used to assign values to the data members of each object
created from a class.

28.1ü Java Fundarnentals sttrtr?


3 Accrss SPecrrrERs AND
HoorrrERs
hr-
Classes enable an object to access data variables or methods of another class. For
example, in a banking appfication you might need to hide information, such as
customer balance, from unauthorized access by other classes of the application'
Within the Account dass, the meürods access the information, but outside the class
you need to resüict access to üis information'

Java provides access specrñers and modifiers to decide which part of the class, such as
data members ar¡d rnetilods will be accessible to other classes or objects and how the
data members are r¡sed in oüter classes and objects.

Access Specifiers
An access specifrer aontrols tñe access of class members and variables by other
objects. The varbr"¡s tyoes of access specifiers in Java are:
W public

W private

W protected

t friendly or pactage

The public Access SPecifier

Class members witfr publE specifiercan be accessed anywhere in the same class,
package in whkh the dass is created, or a package other than the one in which the
class is dedared. Yot¡ can use a public class, data member, or a methOd from any
object in a Java progñrn.
A pckage is a collection of classes'

The pui-:: keytrrord is used to declare a member as public. The following statement
shows how to dedare a data member of a class as public:
nrhl'e <i=-= -.::> <;=l:--: ::a::e>.'

3,í¡* .'3"
&:I*lT 1t,
F
I
"I
'a

The class Account defines the show O method and various data members, such as
name and account number. All the classes in the program can access the various

f details of a customer, such as name and account number. Therefore, these data
members and the method are declared public. The showl¡ method is used to display
the account number and customer name of a customer.
You can use the following code snippet to define a class, Accounr that contains public
data variables and method:
public class Account
{
public int account_no; / / Data members are accessibfe outside the class
public String name;
public void showO //¡tethod declaration
{
System.out.println("Name :"+ name) ;,//Statement of the
method
System.out.println("Account number of this customer is: "+
account_no) ;
]
)

In the example of a library, the books that are access¡ble by general public are
declared public.

The private Access Specifier


The private access specifier provides most restricted level access. A data member of a
class declared private is accessible at the class level only in which it is defined. You
can use the private access specifier to declare members that should be available to
the class within which they are declared. The private keyword is used to declare a
member as private.
In Java, you implement the concept of encapsulatio+,by
using the private keyword.

The following syntax shows how to declare a data memberof a class asprivare:
private ffoat <variabfeName>; / / private data member of ffoat tvpe
private methodNane O; / / PrivaLe method
The Account class defines the show O method and the various data members, such as
balance and age. These members are to be accessed only by the objects of the same
class. Therefore, these methods are declared private. You can use the following code
snippet that shows the Account class with private data variables, such as age and
bafance i

kw"kx 3 wza -m Y a.a ra# m nz * w,t m& w ffi|W*&ry


.Y ffi&& 6
class Account
{
prlvate int accounL_no; // Data members converted to private to
encapsulate data
private String name;
private int age;
privat.e ffoat balance;
public void showO // Method can be cafled from outside the class to
access the data members
{
System.out.println ("Age :,'+ age) i
System.out.println("Balance of this customer is: "+
bal-ance) ;
)
]

In the preceding code sn¡ppet, the objects of Account class can call the show o
method, but objects of other classes cannot access or invoke the private members of
Account class,

The protected Access Specifier

The variables and methods that are declared protected are accessible only to the
subclasses of the class in which they are declared. The protecreo keyword is used to
declare a member as protected.

The following statement shows how to declare a member as protected:


protected <data type> <name of the variable);
In an airline reservat¡on application, you can create the Ticket class that cons¡sts of
various data members, such oS flightNumber, date, tíme, 3fld destination, you can
derive the confirmedricket subclass from the ricker class that consists of an
additional data member, searNumber. you can declare the data members of the
Ticket class as protected, which can be accessed by the confirmedTicker subclass.
You can,use the following code snippet to define the ricret class that has protected
data variables:
public class Tícket
{
ñr^ró^+^A i nr f I i nhr\r,rm]¡ar' / /protected data members accessib_Le to
'áJrr-r.¿ cr-asses
protected String date
nróté.f
r! vé.'l (l- ri n¡
eev uvs + i ma
nrofF.fad Sfrinn doc1- in¡f in¡.
protected void showData o
t
/ / Code bodv
l
]

t;;.);tti.íf;'1i.#í)#.:E:::4i6i6&Ett¿e;a&::! :; ::Eltii:dÉi!;;iii;;i;E{tt;,!tF.tiifa: ,

ffiW Sazaw YÍtm*mm*rz%mTw x&"93


In the preceding code snippet various data members and methods are declared
protected.

The friendly or package Access Specifier

If you do not specify any access specifier, the scope of data members and methods is
friendly. Java provides a large number of classes, which are organized into groups in a
package. A class, variable, or method that has friendly access is accessible only to the
classes of a package.

The data members, such as pageNumbers 3ñd price, and the showData0 method of
the eooks class are not given access specifiers. The following code snippet shows the
Books class that has friendly access specifier:
cfass Books
{
int pageNumbers; / / Tine defaul-t friendly access is provided to the data
members
float price;
void showData o
{
// Code bodv
]
I

In Java, friendly is not a keyword. It is a term that is used


for the access level when no access specifier has been
specified, You cannot declare a class, variable, or method
with the friendly specifier.

Types of Permitted Modifiers


Modifiers determine or define how the data members and methods are used in other
classes and objects. The main difference between access specifiers and modifiers is
that access specifiers define the accessibility of the data members in a class and the
modifiers determine how these methods are used and modified by other classes. The
various modifiers permitted in Java are:
W static
ffi final
* abstract
& native

á6áúfu¿.É&!:^+*:+*üj2,1#KáiÉ:#trp-gseE@e4|e:e.4.4Y.*w*iaááM)táidñw9@F.ry::.}3!:!.1*::i;Á6aá86ffiñ@t@*:n:zi::i.#:

HW.Z& Smwm Wwv.z&m#e*.ffike4% ffiffiv


f# synchronized

stát¡c
The static keyword is used with methods, variables, and inner classes. The static
keyword is used to define chss variables and methods that belong to a class and not
to any pafticular instance of the class.
A static method associates the data members with a class and not the objects of the
class, Therefore, all the objects of a class share the same static data members and
methods. Non-static methods are those, which are associated with objects, and as a
result the values of the data members differ for different objects. You cannot access
non-static data members and methods from a static method.
For example, in an online shopping application, you can keep track of the number of
books sold by keeping static counter data member in the Books class that ¡ncrement
each time a book is sold.

final
fhe finat keyword is used with methods, variables, and classes. The final modifier
indicates that the data member cannot be modified. For example, consider a variable
that has been assigned a value. If the variable has been declared fina1, you cannot
modify the value of the variable and if you try to do so, it will cause run-time errors' A
variable declared final is initialized at the time it is declared.

The f ínal- modifier does not allow. the class to be inherited. It is used to create classes
that serve as a standard, and you do not want anybody to modify the methods in a
subclass and use them in a different manner. The f inar modifier has the following
cha racteristics:

W A finaf method cannot be modified in the subclass.

ffi A final class cannot be inherited'


W All the methods and data members in a f inal class are implicitly final.
A class can be declared as final if you do not want the
class to be subclassed.

3'*'* a* *ffit& # AW"Lffi


4WW F z*'*z # m {T4 *
abstract
The abstract keyword is used to declare classes that only define common propefties
and behavior of other classes. An abstract class is used as a base class to derive
specific classes of the same type. For example, you can create an abstract Books class
that contains the common data members, such as title, page numbers, and type of
binding for all the books.

native
Íhe native modifier is used only with methods. It is used to inform the compiler that
the method has been coded in a programming language otherthan Java, such as C or
C++. The natj-ve keyword with a method indicates thatthe method lies outside the
Java Runtime Environment (JRE).

The following syntax shows how to declare a native modifier:


public native void nativeMethod(varI, var2, .) ;

The native method makes a program platform-


dependent. In addition, writing native methods must be
avoided. They are used when you have an existing code
in another language and do not want to rewrite the code
in Java.

synchronized

The synchronized modifier is used for methods. The synchronized modifier controls
the access to a block of code in a multithreaded programming environment. A thread
is a unit of execution within a process. Java supports multithreaded programming and
each thread defines a separate path of execution.

In a multithreaded program, you need to synchronize various threads. As a result of


synch.ronization, only one thread can access a shared resource when two or more
threads need access to the resource at the same time. For example, if multiple
threads need to print a document, only one thread can access the printer as the result
of synchronization.

:!: :! ei: F9 d a a i d;; ; i;t;|ái;

kffi.zü 3 p, u¡ * W sa ** m r* * rz{*fr '* ffiwyt


CouprlrNc AN AppLrcATroN
-:n properties
rEss to derive
Books class
: and type of
After you create an application, you need to compile it before executing it. When you
compile the application, the compiler checks for the compile-time errors. The
successful compilation of the application results in the Bytecode generation of the
application, which is a .class file. The following application consists of the basic
structure of a Java application and should be written in a text editor appl¡cation, such
tire :ompiler that as Notepad:
.i,,i ..........re, such aS C or class Hello
rrs outside the {
public static void main(String args[])
{
/* Output of the String */
Syst.em.out.println("Welcome to the Exciting World of Java"),.
]
]

To complete and execute the application, you need to perform the following steps:
e*rsting code 1. Compile the application,
the code
2. Execute the application,

Compiling an Application
'er controls To compile an application/ you need to save the code with a file name that is exactly
t. A thread the same as that of the class name, with a .java extension. In this case the file name
u mming and should be sello. j ava.

To compile the .java file, you need to perform the following steps:
ls
a result of
IIVIE Or more 1. Open the command window.
rt - tiple
'r-
:s the result 2. Set the PATH variable to the bin directory of the installation directory, as
follows:

C:\j2sdk1.4. r_O2\bin
3. Change to the directory where you have saved the .java file. You can also give
the complete path of the .java file while compiling it.

;:l;.$$,ff'{ :,' Hl1'{"


4. Compile the application by using the following command at the command
prompt.
javac Hello.java
Execute the Bytecode by using the following command:
java Hello

Executing the Application

3 ¡"* q'rz F t¿ gz4 x {rz r¿ i\E aE o.;


ffiW
w
Problem Statement
You need to create an Account class that consists of various data members, such as
account number, name, age, and balance. The application must initialize the data
members to default values when an object of the Account class is created. In addition,
the application must display the data stored in the object.

Solution
The Java application is created using the system. out . printl-n ( ) method, To solve the
above problem, perform the following tasks:

1. Code the application.

2. Compile and execute the application.

1. Code the Application

You need to write the code to create an application that consists of the Account class.
The class must conta¡n a constructor that initializes the data members of the class.
You also need to define the shownata ( ) method that displays the data stored in the
object. In addition, you need to define the rnain ( ) method that creates an object of
the Account class and executes the showoata O method.

You can use the following code to create the Account class and save it as
Account. java file:
cfass Account
{
private int account_no; / / Data members converted to private to
encapsulate data
private Strj-ng name;
private int age,'
private float balance;
publíc Account o
{
duuOUnE_nO : I;
name = "Susan Ward";
age : 35;
bafance = 500;
)

ffiW Twwm W**n&mnzwr'*Km&*


p.U"3.*
publ-ic void showData O / / Vetnoa can be ca11ed from outside the cfass to
access the data members
{
. printl-n ( "Account Number
System. out : rr+ :¡¡nrrnl- nn\'
System.out.príntIn ("Name : "+ name)
q\rql- éñ ñri ñ1- l ñ lrlAdó : rr+ rñó\ .
^rrl-
vg9.r!+r¡94|gYv,'

System.out.printfn ("Balance of this customer is : "+


balance) ;
]
nrrhli¡ cl-¡f i¡ r¡nid main (String args [ ] )
{
Account ac : new Account O ;
ac. sho!,¡Data (

]
]

2. Compile and Execute the Application

The command to compile the Account application is:


javac Account.java
The command to execute the Hello application is:
java Account

i*:Yiil:Y,r¡.9t:9.49.,91r!::::!!.::)li:i#*1::!.P99g.r!9!!!enAi94p.4lpi€.pq9!e@p@vá.dÁná;+^Rj:+wg/9!.Frg)g94iasgtílnñ:@:F/fsdddddtí$

.xffi"n& 3 mza w W q* ra & * {ve *{EE ffiá # #,ffiff


:..4.:a

W A class includes data members and methods. Methods can include expressions
that evaluate a value.
W Creating a class includes declaration of class members. Data members of same
type can be declared in a single line.
W You can declare a class without data variables and methods.
W A class with only data members is of no practical use.
W You can interact directly with data members inside the class only.

W Object creation includes declaration of class object variable and assignin g


memory to object variable.
W You can access data members outside the class through class objects.
W A constructor is invoked on every creation of an object of a class type. The
constructor can be used to initialize data members of newly created object.
W There are two types of constructors the default constructor and the overloaded
constructor.
W A constructor returns no value and has the same name as the class itself.
W A Java application requires a mainO method to start execution.

W The Java interpreter first of all looks for the maino method. The class name and
the file name in which the mainO method is declared are same.
W You can use access specifiers to restrict the access to class members by other
classes.

W There are private, public, and protected access specifiers. Private access
specifier gives the most restricted access among all the access specifiers.
W Class members with public specifier can be accessed anywhere in the same
class, same package, or a different package.
W A modifier determines the use of the data members and methods in other
classes and objects.

W The various modifiers available in Java are static, final, abstract, native, and
synchronized.

'p^&";2n
ffi you must set the PATH variable of the operating system to the bin directory of
the installation directory.
ffi You need to use the javac fileName.java command to compile the fileName.java
file.
ffi You need to use the java fileName to execute the fileName'class file'

&&.&w. 3m vm W a*rs**sz:s *,ffiHm*w


Ce*-;-*ECIRATE

3 mw n Y q* rs &w r¿z *ratm E s


w.ü"k 3 mw n W t"á rz*m ryz. *rq*.mfr * &tffiEY
il!"

'ii.

KnOwIEDGE Bwe

In this section, you will learn about:


ffi Evolution and Need for Java
W Garbage Collection ín Java Virtual Machine (JVM)
W Setting the CLASSPATH
W Significance of the Java class file
Evolution and Need for Java
Initially, Java was not developed forthe Internet programming. The Java designers
later added the functions such as distributed, security, and portability that make
Internet programming simpler to develop using Java. You can use Java to develop
network-oriented programs because networking features are built-in in lava.
In 1991, a team of software developers at Sun Microsystems, USA, was designing a
language for consumer electronic devices. The development team headed by James
Gosling wanted to design a portable language using which programs that could run on
computers with different platforms. The team aimed at programming the devices from
different manufacturers so that the devices could be controlled by a single remote
control. They also wanted the language to be simple so that anyone can learn it in less
time. The team considered C++ as the model language for designing Java language.
The team deprecated various ambiguous features from this new language, Initially,
this developed language was called Oak, but was later renamed to Java.

Yeár Development
1990 Sun Microsystems developed software
to manipulate electronic devices.
1991 A new language named Oak was
introduced using the most popular
object-oriented language C++.
1993 The WWW appeared on the Internet
that transformed the text-based
Internet into graphical Internet.
r994 Sun Microsystems team developed a
Web browser called HoUava to locate
and run applet programs on the
Internet.

'"jt"'
iQ:W6"Wtr 3 #. i,f & {: !,:t iZ 4:}, # f ",n,*.tt" ?,:* | * rá
Y:i€iÍt: :
i
1995 Oak was renamed as Java.

1996 Java was established as an


Object-oriented program ming language.

Garbage Collection in JVM


Garbage collection is a good way to free programmers from the burden of having to
explicitly free the allocated memory. On execution, a Java program creates and uses
different objects, Each object within a program uses some amount of system
resources, such as the system memory during the run time. Garbage collection is the
process that is used to free the memory of the objects that are no longer in use.
When a program stops referencing an object, it is not required any more and can be
deleted. The space that ¡s used by the object is released for use by another objects. In
this way, garbage collection serves as a mode for memory recycling where the space
occupied by one object is recycled so that it is made available for subsequent new
objects.
The garbage collection feature implies that the new objects are created and all the
unreferenced objects are deallocated from the memory. The different approaches used
for detecting garbage objects are:
W Reference-Counting Collectors
W Tracing Collectors
W Compacting Collectors
Reference-Co u nti ng Col lectors
Reference-counting garbage collectors store the references of the objects used within
a program. When an object is created, the reference count of the object is set to one.
When you reference the object, the reference count of the object is incremented by
one. When a reference to an object goes out of scope or is assigned a new value, the
reference count of the object is decremented.
An object that has a reference count of zero is not referenced in a program and is a
garbage object. When the object is identified as garbage, the reference count of all the
objects that it refers to is decremented. Therefore, garbage collection of one object
can lead to creation of more garbage objects.
The garbage collection method can be executed in small parts within a program and
the program need not be interrupted for a long time. An overhead occurs whenever
the counters are incremented or decremented.

:;::
"é"{..& 3 ;.2 "¿ ia F u¿ t' *A n tat * t zY ¡zÍ * ffi|ww
Tracing Collectors
In this technique, a set of roots is defined from the location where the objects are
traced. An object is reachable if there are objects that reference it, The objects that
are not reachable are considered garbage objects since they are not referenced and
are not accessed within a program. The tracing collectors mark the objects that are
reachable. At the end of the trace, all unmarked objects are identified as garbage.
Tracing Collector is also known as the mark-and-sweep algorithm, The mark phase
marks all the referenced objects. The sweep phase garbage collects the unreferenced
objects.

Compacting Collectors
Compacting collectors reduce the fragmentation of memory by moving all the free
space to one side during garbage collection. The free memory is then available to be
used by other objects. All references to the shifted objects are then updated to refer
to the new memory locations.

Setting the CLASSPATH


The CLASSPATH environment variable instructs the IVM class loader to find the classes
that are directly or indirectly invoked, including the system classes. CLASSPATH is the
environment variable, which shows the Java compiler, javac.exe, the location where
the class files are stored. You can set the CLASSPATH variable using two methods,
either using the -classpath option with Software Development Kit (SDK) tool or by
setting the CLASSPATH environment variable. The -classpath option is used when
the SDK tools are called, such as java, javac, and javadoc. The following syntax shows
how to set the CLASSPATH with an SDK tool:
C:) sdktool -classpath (classpathl);(classpath2). . .

The following syntax shows how to set the classpath using the classpath environment
variable:
C: ) set CLASSPAfH=<classpathl>;<classpath2>. . .
In the preceding syntax, semi-colons separate the multiple entries in classpath. The
classpath variable finds the path where the class files are stored while compiling the
Java program using the javac compiler.
The class files or classes can be stored either in directories or in archive files. The
syntax to import a class, bank, of the app.bankrnfo package is:
C:) java -classpath C:\Mlprogs\Utility app.bankrnfo.bank
In the preceding syntax, when you execute the Java program impofting the bank
class, the JVM uses the classpath settings to determine the location of the package
and class.

3, ;r,:'¡¡ :¡:¡ "{ t:,42 t3'*, r*, t:ffi.t :¿Ét:;


'rwx-tr
If the class required is stored in a jar or zip archive file, you need to specify the name
of the archive file as well. For example, if the class, bank, is contained in a jar file,
then the following syntax shows how to set the classpath variable:
C:) java -classpath C:\Mlprogs\Utility\bankdetails.jar app.banklnfo.baal
The following syntax shows how to specify multiple entries in classpath:
_C : ) j ava -classpath C : \Mtprogs\Utility ; C : \My.progs\!,{'app ;

Significance of the Java Class File


The Java class file contains the Java Bytecode. The class files are platform
independent therefore you can run a Java program by loading the class file on any
system with the Java Runtime Environment (JRE). The following command shows how
to view the contents of a class file:
javap -c (class_filenane)
The lavap command prints the instructions that consist of the Java bytecode, for each
of the methods in a class.

?_ü.q Smww #s*ffi*mrzu*vaknfrx ffiwf


Fno¡¡ THE Expent's Drsx

Best Practices
Declaring Class Variables as private and Methods as
public
You should declare all the class variables as private because data should always
remain hidden from the objects of other classes. Methods should be declared as public
because the methods provide an interface to the objects of the other classes.

Declaring Arrays
Arrays can range from a higher minimum numberto a higher maximum number, such
as 45 to 90 but it is more efficient to begin arrays with an element 0 because it takes
up less memory in the computer to store arrays that begin with 0.
If you write a Java program having the for loop that starts from array element 45 to
element 90, the compiler will still allocate the memory to the array starting from
elements 0 to array element 44.

i Declaring Class Variables


You can follow Hungarian notation to declare variables in lava. The conventions
followed in the Hungarian notation are:
W The first letter of the variable should indicate the data type used. you can use
the letters, i, f, and b to indicate an integer, float, or a boolean variable. For
example, iAge, fPrice, and bResult.
w The variable name should be meaningful. For example, iAge is an integer
variable to store the age of a student.
W In case the variable name consists of multiple words, the first letter of each
word should be capitalized, for example iTotalMarks and fPriceOfCommodity.

Tips and Tricks


Displaying Text in a Java Program
You can also use the drawSrrins O method to display text in addition to the
System.out.printlnO method in Java. The drawstrinSO method requires three

tV\W$gW 3 ww m'{. * w rim r* *r*t *á n É.{:;,v


arguments. The first argument represents the string to be displayed on an applet. The
second and third arguments represent the x and y coordinates of the string to be
displayed.

Setting CLASSPATH
cLAsspATH is an environment variable that enables the Java compiler javac.exe to
locate class files to be imported. You can use the sET cr,AssPArs= to set the
cLAsspATH variable. The following syntax shows how to set crassPAr¡¡ in Java:
SET CLASSPATH= g ; \j2sdk1. 4. 1_02\bin

FAQs
W Why is Java considered ideal for network communication?
Java is considered ideal for network communication because it is a platform
independent language. Java enables an application to be executed on any
network. The built-in classes of Java support TCP/IP and UDP protocols used for
network communication. Java suppotts the Client-Server model for network
communication,
ffi What will happen if the data type of a variable and the value assigned to the
variable are different?
If the data type of a variable and the value assigned to the variable are different
then compilation error occurs. If an integer variable is assigned a character
value, the ASCil value of the assigned character is displayed as an output. The
following code shows assigning a character value to an integer variable.
.lál- :f \/ñaf
^l:ca
n"l-.]
yuvrru i¡ ef af i^ rr¡id m¡in lQf rinc ¡ [l l

{
i-! .,- lLl.

System, out.print (x) ;


]
]

In the preceding code, the ASCII value of the character b is displayed as 98.
Similarly, if you assign a float or a double value to a character variable, an error
message is displayed. The following code shows assigning a double value to a
character variable:
class datatype{
nrrl-'l i¡
yqvrre cl- ¡l- i¡ r¡nid main lSr rino : ll l

{
char x: 5.5;
System. out.print (x) ;
]
]

"É.{:.'&". j Av m E, * rZ # m {:r:É
q.Í r.24;.#l # #"jW{gE
Java is a strongly typed language and it allows the values of the spec¡fic data
types, which are compatible with the type of variable.
w Do all arguments sent to a Java applicat¡on have to be strings?
Yes, all the arguments sent to a Java application have
to be string. If you use
some other data type, such as int, you need to convert the value to string.
w can two variables have the same letters but different capitatization, as in
variableName and VariableName?
No, Java is a case-sensitive language. It differentiates the two variables,
variableName and VariableName.

t
i

2.ü"',#

L-
2. Match the following:
a. Variables i. Reseryed words
b. Literals ii. Basic storage unit
c. Keywords iii. Sequence of characters
3. Make words from the jumbled letters in the box given below and match them
with their description,
a. Class members that can be accessed by the subclasses of the class in
which they are declared.
b. Class members that are accessible to all the classes of a package by
default.
c. Class members that can be accessed only by the objects of the same
class.
d. Class members that can be accessed anywhere in the same class.
e. This method of the String class is used to find the length of a string.
f . Collection of classes that can be reused.

S. Are the reserved words for a language.


h. A method with the same name as the class name.

IULBPC
DFINRE
ORETCDPET
ELHTGN
VPTIARE
CKESPAAGS
KRDYOESW
CNTCSUOORRT

x.ü"L# "iÉ
mv w W z* rz&mfsy & {ÉE&A# ffijwt
W LesseN 2tr
ExpeRETcENT

WW 3 mzs w W a*sz rS m rm * szYnfr x x.w"z


.1-4".;í.nli#rr",:1.*{."t"4{,1;prtí*1,:i
W
Exercise 1
ServeYourMoney bank offers sevices to its various customerc. The bank has various
branches all over the country and therefore each of the branches has a unique id. The
bank stores üre detaits of its customers, such as customer name, account number,
address, phone number, and e-mail address. In addition, the bank stores the varióus
details of its employegs, guch as employee name, employee id, address, phone
number, and e-mail id. The bank offers its customers with a choice of aécbunts, such
as savings and current acount. Ask the students to identify the various classes and
their attributes.

Exercise 2
Write a program to perform arithmetic addition, subtraction, multiplication and
division on two numbers, 12 and 5.

Exercise 3
Write a program to display the name, address, and position of three applicants using
arrays. Create and initialize the arrays, and display the values stored in the array.

Éi,*ii;,ffijÁeÁ;i;i;iii***ea")
WW Tav* Yxlr.ú*ret**ka4s #.w,3
1. Which of the following is correct extension of a lava file?
a. .jav
b. .java
c. .IAVA
d. .class
2. The lava compiler reads the Java source file and converts it to a file having an
extension:
a. . class
b. .java
c. .prg
d. ,file
JVM stands for:
a. lava Virtual Machine
b. Java Virtual Model
c. lava Virtual Mechanism
d. Java Virtual MethodologY
4. JIT stands for:
a. Java In Time
b. lust In Time
c. Java Is Tested
d. Java Is Time saving
5. What is the maximum number of dimensions an array can accept:
a. 266
b. 255
c. 256
d. 2s0
6. Identify the correct code snippet to declare a class :

a. Cl-ass EmploYee
{
String emPloYeeName;
int empfoyeelD;
String emPloYeeDesignation;
]
b. class Employee
{
String emPloYeeName"
int employeelD;
String emPloYeeDes ignation ;

7.W^4 3 *zc m Y L4 rzú mm *, rat :a*&r; ffijWf


C. CLASS Employee
{
String employeeName;
int employeelD;
String employeeDes ignation ;
l
d-c1ass Employee details
{
String employeeName,.
int empfoyeelDt
String employeeDesignation ;
i
7. Identify the correct code sn¡ppet to declare the main O method :

€|- public void static main(String[] args)


{
// Code for maino nethod
l
b. public main(String[] args)
{
// Coae for rnain0 method
)

C. public static void main(String[] args)


{
/ / Code for main O method
)

d. public static void main(StringO args)


{
/ / Code for main O method
l
8. which of the following characteristic is supported by consFtrctors in Java:
a. A constructor has the same name as the class itself.
b. A constructor has a return type.
c. A constructor does not retum the instane of the dass instead of a value.
d. A constructor ¡s not used to ass¡gn values to the data members of each
object created from a class.
9. Which of the following is the default access specif¡er in Java?
a. publ¡c
b. private
c. friendly
d. protected

EW Java T*snáarrzemte*e kw"%


10. Which of the following is a type of permitted modifier:
a. public
b. static
c. private
d. protected

3 m"¿ w W ** rzúwr*wrs%mfr w
www.niitstudent.com

You might also like