Java Fundamentals - Part I
Java Fundamentals - Part I
Java Fundamentals - Part I
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,
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)
Pr¡nted atSona Printers Pvt. Ltd. FB6/1 , Okhla Ph.-1 , N.D. -20 Ph.: 51616566
I
Counse Desreru
Sotrtbns to Challenge
Exerci*s)
,*:-=---_l
Table of Contents
Cycle 1
ü"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 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
Divergers Accomodators
Convergers Assim¡lators
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
*ÁñX*" ;
wz Abcut ?his t*elrse #ttr
ConvrilTroHs
1 and
k;
Construct, Demonstration
k
Beginning of a new concept
t: Additional information
-
-&p -,tt
Bold faced text Menu options, options present in dialog boxes, and
keystrokes
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
: -::: : ,, 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
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 . . .
,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
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'
i;-!á.;..é.i.ii:i:?1":i;;li¡;ij';,éiéia:;:::
I Reusability of code
I Modularity of code
f Resilience to change
I Information hiding
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.
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.
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++ 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++.
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,
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
Position Class
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.
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
r Product
r Customer
I Payment
F
The following figure shows the Customer class and its objects:
Java Frmdam€Htals
L&,"2"ffi Smwn W*rz*mrce*rzkw&s ""MAWW
t'.'t t xhesselu SB
CEPT oF OOPS
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.
c. Abstraction
,t Inheritance
:: Polymorphism
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.
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.
Abstraction (eUs\recr,:a*)
Grady Booch defined the abstraction feature as:
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,
- 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:-.
=:: 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
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.
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
- 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.
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.
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 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.
-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.
¡
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
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.
$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}
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
Nww+¿ao {-A f
a
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:
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
!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.
"f:
s section, you will learn about:
"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
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
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
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.
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
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.
ffi Hierarchical
'ffi
Multipath
Class A
Parent Class for Class B
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.
Class A
Parent Class for Classes B.
C, and D
=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.
j
i I : ,:" f$i¡
FnoM THE Expenr's Desx
The primary object-oriented methodologies are: BON, FUSION, HOOD, IBM, and
UML.
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
:::i
Canniest
1^",f E *ca, (a)
Tdaa bmreem
Noitalusoacne
?nc^rP*itar'ra'
Entiitvd
rde+ií+1 qd\
Srctaabt
abs\ra*,* óq)
\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)
Down:
2 A--is
program that can be divided into small user-defined units(6)
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.
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
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?
Sava Fundarxentals
w-
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,
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.
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.
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,
Object-Oriented
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.
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
,/'l\
;=]\
&
$ 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
_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:
ee 4 ee:ebq4¿ éqip, d blbe p@e 4 !! t!!t ¿!4e Yyj\ |'1' e ee!6.;::: ::...: ::x
-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:
The JVM forms the base for the Java platform and is convenient to use on various
hardware-based platforms.
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.
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.
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
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
{,¿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.
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.
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:
,'Y4tue '1
The groups, Integerand Floating point can store negative values. Java, unlike C/C++
does not support the concept of unsigned integers.
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:
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.
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;
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.
Arithmetic Operators
Arithmetic operators are used to compute mathematical expressions. The following
table lists the various arithmetic operators;
Operatoi
+ Adds two operands
o/o
Calculates the modulus
++ Increments a variable
Decrements a variable
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.
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-(-6)=-4
l-41 < l-61, Therefore, the result of the modult¡s operator is -4.
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,
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.
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],'
emp*ID l2l
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];
In the preceding statement, the value of the third element of the array is assigned to
the first element of the array.
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.
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
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
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,
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
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,'
)
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\) )
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 ,'
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" ;
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
'¡.- wtr\T
define the functionality of the addO method again. You can reuse the method by
just calling it.
In the preceding syntax, the void keyword specifies that the function does not return
any value. The methodName SpeCifies the name of the 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
{
' ;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.
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
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 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
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 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.
t;;.);tti.íf;'1i.#í)#.:E:::4i6i6&Ett¿e;a&::! :; ::Eltii:dÉi!;;iii;;i;E{tt;,!tF.tiifa: ,
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
á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.#:
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:
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).
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.
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.
Solution
The Java application is created using the system. out . printl-n ( ) method, To solve the
above problem, perform the following tasks:
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;
)
]
]
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í$
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 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'
'ii.
KnOwIEDGE Bwe
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.
:;::
"é"{..& 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.
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.
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.
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.
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.
IULBPC
DFINRE
ORETCDPET
ELHTGN
VPTIARE
CKESPAAGS
KRDYOESW
CNTCSUOORRT
x.ü"L# "iÉ
mv w W z* rz&mfsy & {ÉE&A# ffijwt
W LesseN 2tr
ExpeRETcENT
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 ;
3 m"¿ w W ** rzúwr*wrs%mfr w
www.niitstudent.com