Top Banner
ililT $ludent 0uide
135
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Java Fundamentals - Part I

ililT$ludent 0uide

Page 2: Java Fundamentals - Part I

Java Fundamentals

Student Guide

Page 3: Java Fundamentals - Part I

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. Nopart of th¡s document may be copied, reproduced, pr¡nted, d¡stributed, modified, removed, amended ¡n anyform by any means whether electronic, mechanical, digital, optical, photographic or otherwise without priorwritten 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 anyreal 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 ortypographical errors/translation errors. Changes are period¡cally added tD the informaüon herein. NIIT maymake improvements and/or changes herein at any Ume. MIT makes no representaüons about the accuracy ofthe information contained ¡n the courseware and graphts ¡n thÉ coürservare for any purpose. All documentsand graphics are provided "as is". NIIT hereby disda¡firs all rarrar¡ties and cond¡tions with regard to thisinformation, including all implied warrant¡6 and conditbrE d merdlantab¡l¡ty, fitness for any particularpurpose, title and non-infringement. In any event, I{IIT mdlor its laceftsor(s)/$pplier(s) shall not be liable toany party for any direct, indirect, specjal or oüler consequential damages for any use of thecourseware/translated courseware, the informatbn, or on ary other hyp€r l¡nked web site, including. withoutlimitation, any lost profits, bus¡ness interruption. lrs of progr-ans or other data on your information handlingsystem 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.

IEB/DOBAI-l/lava Fundamentals (Part 1)/Q4M2SG-o5-M01-V02Copyright @NIIT. All rights resenred.

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

N

e..l

at

Oéq)

I

Page 4: Java Fundamentals - Part I

Counse Desreru

From the Experts Desk

Sotrtbns to ChallengeExerci*s)

,*:-=---_l

Page 5: Java Fundamentals - Part I

{

I

I

Table of Contents

Cycle 1

l,-esson 1A - Introduction to Object-Oriented ProgrammingH for Object-Oriented Prcgramming '.....'...........1A.3--r-.e;ng OOPS with Procedural Programming.. ..........'.'....'.... 14.4

OliEü (}bnted Programming.............. .1A.7leq¡añ3qEs of Object-Oriented Programming......'......'.. '.'.'.....' 1A.7

@mifr'.g the Applications of Object-Oriented Programming............. .'....'.... 1A'103nrcs arrd Objects ................... 1A.12

-:rry ........1A.15

iesson 18 - ConcePt of OOPSF:¡h¡es d Object-Oriented Programming.............. .................. 18.3

l-gcslaLjon ........18.3¡us?c€fl .............18.4:nrrúeftsrrae".... ..'....' 18.5o?úilrirrrgr:rls¡n. ..,.,. 18,13

by ........18.14

ü"csÉon IC - Collaboratemüpre.......... ........1c.3

-}.Fr<?€r,tÉd Analysis and Design ...'.............. 1C.3

ü;aror-s -rrc of Inheritence.... ..'.. 1C'6rruÉ?c Cesses ancj Methods '..'... 1C'9

F.rn tt= Erperfs Desk.,,....,.. 1C.lOqh;F. .... 1C.10

mf¡,. ...'...1C.12

Page 6: Java Fundamentals - Part I

Cycle 2

Lesson 2A - Introduction to JavaJava Programming Language.. ..............2A.3

Need for Java.............. .................2A.3Java Architecture................ ...'....'.24.8Java Architecture Security.., .'......24.10

Declaring Variables and Literals 24.13Using Various Data Types ...........2A.13Defining Variables and Uterals.... ............"........24.16Manipulating Variables....... ".'.....24.18

Using Arrays..,...,......... ...'.2A.21Arrays ........... '.' '.. ' 2A.2tAccessing Arrays........... ..""""'.'24'24

Summary .....'..2A.25

Lesson 28 - Classes and ObjectsStructure of Java Application .'.............. 28.3

Creating Classes and Objects ........28.3Adding Methods to a Class .'..'.'..'.'28'7Defining Constructors ..........'.""...28.9

Access Specifiers and Modifiers............... 2B'tLAccess Soecifiers.................. ,..'.'28'ILTypes of Permitted Modifiers..............;...... "..'..28.14

Compifing an Application............. ........28.17Demonstration: Crcating a Java Application 28'19

Problem Statement .....,..............28.19Solution......... .......28.19

Summary ...."..28'21

Lesson 2C - CollaborateKnowledge Byte........... .......2C.3

Evolution and Need for Java '......'..2C.3Garbage Collection in JVM........... .........'."'.'...'...2C'4Setting the CLASSPATII ".............'2C.5

Page 7: Java Fundamentals - Part I

I

!

iil

Page 8: Java Fundamentals - Part I

AeeurTp*xs Cet*nse

Page 9: Java Fundamentals - Part I

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 offOp 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' Itcescribei the various features of OOPs: Encapsulation, Abstraction, Inheritance, andpolymorphism. This sub module also deals with the basics of Java programm¡ng

anguage such as variables, literals, access specifiers, and modifiers.

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

Objectivesdfter 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:,

Page 10: Java Fundamentals - Part I

W Pass arguments to methods and create nested classes and add asseftions inJava.

W Use unary, bit-w¡se, shift, instanceof operator, and ident¡fy the operatorsprecedence.

ir ír.:Mgw

Page 11: Java Fundamentals - Part I

MernoDolocY

Learning Architecture Based on collaborativeConstructivism (LACC)

Introduction

3-oadly, almost all teaching-learning interactions/modes can be classified as one of

:-e following:

M Interactions, where the teacher or external resource Creates the learning

exDerience

; Interactions, where the teaCher or external resource creates Or cOnstructS the

learning, in collaboration with the learners'

x situations, where the learners create their own learning experiences

lry learning architecture, which can suitably integrate all of the above modes, would

: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

Page 12: Java Fundamentals - Part I

Learner TYPes

The cElAC and AEIRO dimensions are polar opposites as far as learning styles are

concerned and depending on the preference of an individual's learning styles/stages'

four distinct types of leamers are possible'

Divergers

Convergers

Accomodators

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'

NIIT's LACC methodology has Learning ComponenG, that are oriented towards the -

four stages of experieníiil tearning and hence is highly suitable to all possible

types/profiles of lea rners'

Learning ComPonents

NIIT's IACC methodology has the following learning components:

ffi CONSTRUCT: The learning begins with this component' An instructor who is a

subject matter expert is required to lead the students here. 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

through éxplanations and demonstrations. These two sessions are meant to

proviáe the required foundation for the student to be able to move to the

subsequent stages of learning.

w coLLABoMTE: The next learning component makes it possible for the learner

to have contextual familiarity on the subject through collaborative learning. Here

*whzry

Page 13: Java Fundamentals - Part I

the learner is provided with a mentor/direction/ and stimulus for reflectiveobservation. The learner is provided with a rich choice of tools like case studies,scenario/problem statements and best practices to reflect on the concepts learntin the previous sessions and apply his/her understanding in the larger context.

EXPERIMENT: Here, the learner is exposed to active experimentation. Thelearner experiments his/her understanding of the concepts and observations toform a logical conclusion leading to better learning effectiveness and experience.

APPLY: This learning component provides the environment for learners todevelop conceptual clarity. Here the learner learns, refers, compares, thinks andapplies their entire knowledge spectrum and create solutions for a real life case

study. The tools used to provide such learning are project, information searchand 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)

I

I

crIn

Page 14: Java Fundamentals - Part I

*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 ofEd 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

Page 15: Java Fundamentals - Part I

ConvrilTroHs1 and

k; Construct, Demonstration

k Beginning of a new concept

- t:

-&p-

-,tt

Additional information

ürTips and tricks

_ -irrrtér Programming code

-s¡: F Arial font Programming syntax

Page 16: Java Fundamentals - Part I

Introduction of a new termItalicized text

Bold faced text Menu options, options present in dialog boxes, andkeystrokes

From the Expert's Desk

W''!l*!. & i.t, : " ¡:.. Th¡s "l¡^,'; r*e.9

Page 17: Java Fundamentals - Part I

lt¿ .s t.lo O.7"\

"JLrlrJ Lessoru 1AInrnoDucrloru T0 Oa¡ECT-OnTENTET} PnOERAMMTNG

Obiectlvesi- : s lesson, you will learn to:

Apprec¡ate the need for object-oriented programmingCompare OOPS with procedural programmingidentify the advantages of object-oriented programmingidentify the applications of object-oriented programmingIdentify classes and objects

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

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

Page 18: Java Fundamentals - Part I

a&"2 3 w w m ffi sÁ *&a r***rxY"a| s

Page 19: Java Fundamentals - Part I

N==o FoR 0e:=cr-OnreruTED

=:: l'iented Programming (oop) came into effect, procedurar programmrngl--^r:mc r¡,rifla^ h,,.,^i^^ !L^ -.-^--r

- : -; : 'ou nave a program, EmployeeDetails, coded in procedural language' :-::: :-e details of employees of a bank. The program has a function,-"'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: : ' ==s cf a different organization, such as Railway Reservation by using the- 1 -- -:- -r, printDetails, then you have to recode it in another program.

'::: :- :ata in procedural programming is visible and accessible throughout the*:-:- -a< ng ¡t easy to manipulate the data from anywhere in the pro{ram.

: : -= coBoL was used primarily for documentation and data handlinq. All--v -^guages lack support for OOp.

F

:""

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.

'!'r svp,rsu Lv vqr rcu I ELlurr errenLS, r nrs nas resulted In tr-:-:^: 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 to tne way:-: oyees of an organization can be grouped according to the functions--J then arranged In a hierarchy.

:-:;rams written by using the procedurar programming approaéh consist-:: ons. These functions can be executed anywhere within the program. A:-Jgram contains the instructional steps that are performed to carrv out

' : -: es of procedural languages are coBol (common Business oriented;- trascal and BASIC (Beginner's All purpose symbolic Instruction code).:::: ,.,as too simple and proved insufficient for programming comprex

Pnoe RAMMING

: -::: : ,, e world, the need of the hour is to develop simple and speedyl:,:-- :e instantly applied to varied requirements. This has resulted in the

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

Page 20: Java Fundamentals - Part I

The limitations of the procedural programming led to the evolution of the object-

oriented approach. In OOP the prográm is broken into independent chunks known as

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.

Thus, objects can be reused across various programs. This enables a programmer to

deveiop án application in a relatively shorter durat¡on'

ooP enables you to consider a real-world entity as an object. o.oP combines user-

defined data and instructions into a single entity called an obje.ct. In OOP, objects can

be placed in libraries. OOP also offers some bu¡it-¡n libraries' These libraries consist of

á rEt-oioO¡"cts and pre-defined functions and can be used by all programs' A major

advantage of OOP is the reusability of code because it saves the effort required to

rewrite the same code for every program using the functions defined in libraries'

Compaiing OOPS with Procedural Programming

YoucanuseVar¡ousprogrammingmethodo|ogiestocreatean.app|icatio.noraprogram. Eacn prográr*ing meihodology coñsists of its own features that can be

used for creating various ap-plications. Tñe commonly used programming

methodologies include :

ffi Procedural Programm¡ng

W Object-oriented programming (OOP)

Procedural Programm¡ng

The procedural programming methodology involves dividing a large program ¡nto a se

of subprocedures or subprograms that perform specific tasks' In this methodology' i

órog;r is divided ¡nto óne or more units or modules. These modules can be user-

defined or can be taken from libraries'

A module can cons¡st of single or multiple procedures. These.procedures are also

known as functions, routinei, subroutines, or methods in various programming

languages.

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

¡ó;;¿r on tr'" ¿er¡nit¡án. Similarly, the data available in the procedure also exhibit

various levels or r.op"r. The procédure of a higher or outer scope cannot access thr

data within the procedure that has lower or inner scope'

3 mw a W zxruúm{**r2t.erffi!"k,4,r: WTl

Page 21: Java Fundamentals - Part I

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

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

Variable AVariable BVariable C

Procedure 1

(Accept Data)Accept Valre nf AAccept value of g

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

C=4,+B

trrccedure 3{Print Data)

Frir¡t Valus trf APrint Value {rf gPrint ValÍ3 nf C

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

Page 22: Java Fundamentals - Part I

'ffi Easy maintainable program code as various procedures can be debugged inisolation

W Code is more flexible as you can change a specific procedure that getsimplemented 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 withinthe program.

In the procedural programming approach, portions of the code are so interdependentthat the code in one application cannot be reused in another. For example, the moduleused to calculate the salary of the employees in a bank management system cannotbe used to calculate the salary of the employees in an educational institute. You needto create a separate module to calculate the salary of the employees in an educationalinstitute,

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 indecreased productivity and increased maintenance cost of the application. This wasone 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 asthe 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 ofleaves taken by the employee in excess to the leaves allowed in a month, anddearness and housing allowance. The organization consists of various types ofemployees, such as regular, contract, and waged.

Smith, a programmer, develops a code to calculate the employees'salaries by usingan object-oriented programming language. This code is reused for employees at alllevels. Reusability of code enables Smith to use the same code for employees at alllevels.

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

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

{#tW

Page 23: Java Fundamentals - Part I

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'

As a strategic intervention of revamping their existing products and processes, the

*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

'¡I

I

T

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

Page 24: Java Fundamentals - Part I

implemented. The system enables the management to analyze the sales data andbuild strategies for the products. In addition, the automated system also trackssalesperson-wise data to provide incentives to the high performers.

Over a period of time, the management decides to extend the functionality of theautomated system to the purchase department. In addition, the various modules to beadded 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 componentthat stores the details of an employee. Therefore, the programmer need not recreatethe entire component again. The employee component of the sales automation systemcan be used to track the details of the employees across depaftments, including thepayroll division of the Personnel department.

In the Personnel department, the automated system needs to keep track ofemployees. In addition to the regular employees, the Personnel department needs tokeep track of the contract employees who join the organization temporarily for aspecific 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 extendthe functionality of the existing employee component and make the desired changes inthe 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 theexisting components, such as, employee and contract employees.

The reuse of the components once created not only reduces the effott of recreatingthe components, but also reduces the chances of introduction of errors in variousmodules, After integrating all the modules, a consolidated system can be created thathas various components reused across the modules.

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

Modularity of Code

Another advantage of object-oriented programming is its modularity. It means that anobject can be maintained independently of other objects. All these objects areindependent of each other and are maintained separately. You can make modificationsin the required object without affecting the functionality of other objects.

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

Page 25: Java Fundamentals - Part I

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

Identifying the Applications of Object-OrientedProgrammingObject-oriented programming has applications in several domains, such as businessmanagement, home computing, and accounts management. These applications can beCharacter 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 totype commands on the command-line to interact with the computer Input commandscan be long and complex, CUI is not user-friendly because a user needs to rememberall the commands and the syntax of the commands. The most common examples ofCUl-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. Thehardware simulations for Personal Digital Assistant (PDA) tools are also peformed byusing C++.

Graphical User Interface (GUI) based Applications

Errors induced due to typing long commands often discourage the user and affect theproductivity and efficiency of the user. GUI is a method of interacting with a computerby directly manipulating graphical images in addition to text. Various applications arewritten 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 thedata and processing methods, which inform the system that an event has occurred,

GUI can be programmed using object-oriented programming methodology, which usesvarious objects. The objects communicate with each other by sending messages toeach other. An object receiving a message responds to the message sent by anotherobject by executing one of its pre-defined functions. An object represents eachelement of the GUL IT determines the attributes and the behavior of each element ofGUI. 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

Page 26: Java Fundamentals - Part I

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

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

The concept of OOP is applied for designing and implementing various softwaresystems for computer graphics, such as computer Aided Designing (cAD) andómputer Aided Manufácturing (CAM). The concept of OOP is used to create graphicaland 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 theadventure games, sports games, and the space games are modeling some type ofobjects 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 fantasyworld and fights creatures, collects treasure, and so on'

Main Class

Treasure Class Key Class

Class Hierarchy for a Hypothet¡cal Adventure Game

Position Class

It*m Clasx

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

Page 27: Java Fundamentals - Part I

3

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

Classes and ObjectsA class defines the structure and behavior of an object or a set of objects. Forexample, peacock, sparrow, and kingfisher are categorized as birds because all ofthem 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 entitiesthat have similar attributes comorise a class.

For example, in a university, all the students have similar attributes. They have astudent ID, name, date of birth, gender, and address. Therefore, to automate thestudent management system of the university, you can create a Students class thatconsists of the attributes needed to store the student details.

Objects are the basic building blocks of Object Oriented Programming (OOP). Theconcept of the object-oriented methodology is based on objects. You createindependent entities that can be reused across various programs, Objects display thefollowing characteristics :

W State: The state of an object is indicated by a set of attributes and the values ofthese attributes. For example, when you design an online shopping site forbooks, each book, which is an object in the program, has its size, number ofpages/ type of binding, and its shipping details.

W Behavior: The behavior of an object refers to a change of its state over a periodof time. For example, in the online shopping site, when you place an order for abook, the status of the book might change from available to sold out. Thechanged state of a book is its behavior.

W ldentity: Each object has a unique identity, iust as each person has a uniqueidentity. For example, multiple books consist of the same size, number of pages,type of binding, and shipping details. However, each book has its distinctidentity, for example the book number. The book number identifies a bookamong other books.

An object is an instance of a class. A class in object-oriented methodology is acollection of various attributes, such as data and methods. You can access the data ofa class by using its methods.

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

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

ft"&"3"X

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

kwwm W*urz&nrm*mtm&u . it;:Wi"tV1 A4& 4

Page 28: Java Fundamentals - Part I

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

object. For exampre,pPqgtt_y of the object pay phone could be ihe amount or monáy or the number ofs b be lnserted.

the famous author who has written many books on oops has defined a

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 andons. These interactions take place through messages. Gradybehavior 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 the case of the payrc' its identity wilr be the seriar number assigned to ií uv tná'má-nuracturer.

l objects may have the same behavior, may or may not have the same state butH.. have the same identity, The identity-of

"n ou¡e.f n"u"i .nunges in its

al people have described techniques for identifying crasses. According to one of[ijl?, : :"^:t "r""il':: :.1,: _q" T s rl, h d e,scri ptío.n

-of iñ ;;d ñ . rh e n, yo uthe nou ns. The nou ns rep reselicu nái¿-ái"'.lurr"r.

example, in an ouilet, there can be severar counters, each one manned by a singre

ff#::,,'.?'Ii: :,:j::r:: ?^.,,?Íil ;ljy_,_t:I:r. upp.oá.né, unv .á,nt"., dependinsthe product the customer wishes to purchase. The saresp".ron í#i!'á;:f,";5'"ndüct and accepts the payment from the customer. The di'fferent ciasses that can bentified are:

Boodr,ty as:

react to theseBooch has

I Counter

Salesperson

Product

Customer

Payment

IrrI

Page 29: Java Fundamentals - Part I

F

The following figure shows the Customer class and its objects:

Classes and Objeds

Page 30: Java Fundamentals - Part I

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 programmingo Object-oriented programming

r The procedural programming methodology involves dividing a large programinto a set of subprocedures or subprograms that perform specific tasks.-

r The-procedural programming methodology allows code reusability in largeapplications.

I An object is defined as an instance of a class.

r In the.object-oriented approach, classes are designed such that they can bereused.

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

Page 31: Java Fundamentals - Part I

L&,"2"ffi Smwn W*rz*mrce*rzkw&s""MAWW

Page 32: Java Fundamentals - Part I

xhesselu SBCEPT oF OOPS

üús lesson, you will |earn to:Identify the features of object-oriented programmingEncapsulationAbstractionInheritancePolymorphism

dEttt

t'.'t t

Sava Fumdam*ntx|'*

Page 33: Java Fundamentals - Part I

1:#WÉpéi¿ñ,ni;;¿;.i!+.a:++#z#:w#ffiñ)F;qE ffiÑFÉlt::.ffiw!)e-xffiffiffi

LW"2 Sawa Ywnúamentals &tWffi

Page 34: Java Fundamentals - Part I

I- - :-.llí i.+-'- +t o{/

'..1{ 1. ,.,-' ¡ \J

i

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,

'-:l as name, color, age, and height and behaviorsuch as walking, dancing, and,::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."

=-:apsulation implies that the non-essential details of an object are hidden from the-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

FeRruREs oF Oe:ecr-OnrrNTED

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

Page 35: Java Fundamentals - Part I

r

among themselves. Encapsulation is the feature that provides security to the data andthe methods of a class.

An Anytime money(ATM) that you use to withdraw money also has an encapsulatedfunction. You inseft an ATM card in the machine and provide the pin code' The onlyaccess that you have to the ATM is to provide the pin code for your account and not tothe process of validating the password. If the pin code is correct, you can make thedesired transaction. The backend transaction process is encapsulated. In addition, ifyou try to access another account, access is denied, as you are not authorized toaccess 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 itfrom all other kinds of objects and thus provides crisply defined conceptualboundaries, relative to the perspective of the viewer."

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

3"W"&

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

aá ^6

; +;

#tW*WW'w ffi.&&&3 m qá x W a* {e * mr,\z * {*te& #

Page 36: Java Fundamentals - Part I

I : _:D

has type of media, such as audio or visual, duration, and storage capacity of the

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

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

lr.:7r..1:i

Page 37: Java Fundamentals - Part I

r"-

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

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

Superclass and Subclass

In inheritanc e, a superclass or parentclass is the one from which another classinherits attributes and behavior. Asubclass or child class is a class that inheritsattributes and behavior from a superclass. For example, an Air ticket can be of twotypes, 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 willhave a status attribute.

The following figure shows the concept of superclass and subclass:

Superclass and Subclass

Attribtáes:FligkNualerDateTiheDectin*ion

ctass:Requested T¡cket

lnherhed áttrlbstes:

Slightl{umberDateTim*Destinaúisx

Inherited AttributBE:

FligbtNumberDateTimeDestination

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

Page 38: Java Fundamentals - Part I

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 thefeatures inherited from its superclass.

implement inheritance in object-oriented programming, various relationships existthe various classes of the program.

ips Between Classes

and objects are related to and ¡nteract with each other. In object-orientedng, objects peform actions in response to messages from other objects

the receiving object's behavior. This approach specifies the relationshipsclasses based on the behavior of individual class.

rIII

various relationships that can exist between the various classes of a program are:

Kind-of

Is-a

Part-of .-)

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

Page 39: Java Fundamentals - Part I

F@-

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

CrnfirmsdTicket Tick*t

Kind-Of Relationship

Is-A Relationship

The relationship between objects of superclass and subclass is referred to as an is-arelationship. For example, in the tickeüng system, a ticket class is a superclass andconfirmed ticket is a subclass. A confirmed ticket for New York is an object of theconfirmed ticket class. The relationship between these three reads as the ticket forNew 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:

GonfirmedTicket

Ticket frrl\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. Forexample, while developing a program, you might real¡ze that you need to storeaddress of various entities, such as students, customérs, and organization. You mightfurther realize that the address consists of various sub-attributes, such as address line1, address line 2, city, state, country, and zip code. To reuse the entire set of theseattributes, you can create a class that consists of the required attributes. You can usethis class as an element of the classes where you need to store address. The addressclass exhibits the paft-of relationship with respect to the class in which it is included.

hw"&lt!taltl:41¿;;;;;:t7,:;::¿:2?)t:aitj;;:;;:::;:.::t:;:i:2:a.;!:;¿:::at:t ;.a|,;:¿;t::::;::t

Ta,aw #a3{aúmm*mtals):!: |:!.|!!| y|p9 !,49'61¿686én

#ttW&Wa*?w@&

Page 40: Java Fundamentals - Part I

M

I

rI

I

I

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

Address

Part-Of Relat¡onsh¡P

l-las-A Relationship

-he has-a relationship is reverse of the part-of relationship. When a class consists ofanother 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

:'r a program, You:nem, The tyPe of

Has-A Relat¡onsh¡P

create various classes that exhibit various relationships amongrelationships among classes result in different types of inheritance.

Types of Inheritance

-he animal kingdom has many exampres of inheritance, Consider the example of theanimal 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.

Student

YLtr.Y;

¡1*i e.".Fr

!' ':' '

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

Page 41: Java Fundamentals - Part I

The following figure illustrates the hierarchy of inheritance among the various classesin the animal kingdom.

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

have hngs and gillá

{tt tf¡ ,;4 *rÍír#'v,N&u

tA^ e-.( -a'( el"^f *, y xt ",^laUJ'1¿13 **, ¡"1[ ¡irr];"Q.$

¡l

$r\tg --, ¡.n;\1áb

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

háve wings áfld teéth

Animal Hierarchy

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

Page 42: Java Fundamentals - Part I

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 employeedass to the contract employee class and add the attributes for the contractemployees.

Similar to the animal kingdom hierarchy, classes in a program can have followingtypes of inheritance:

Single inheritance

Multiple inheritance

Single Inheritance

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

$ub ülass{child}

The Single Inheritance

In the Animal Hierarchy figure, the animal category classes, such as Birds, LandAnimals, and Fish are example of single inheritance because these classes haveinherited the characteristics from one superclass, Animal.

For example, classes called Even numbers, Odd numbers, and Prime numbers isderived from the class Numerals,

I

I

ñuen Numbers

S¡ngle Inheritance

aw.lhrWWffi

6r¡c¡^ -> \ c\,,stl\t I

cr.i é -> qvjr t a^:.a

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

yr*rr"*q{a

Nww+¿ao {-A fe*.trtu

dA p,,;r+t f, q¡-- Ff'¡r'¿""g{a {*.rfi*"r.-

Page 43: Java Fundamentals - Part I

Multiple Inheritance

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

Multiple Inheritance

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

Consider an example of an organization with the name, Global Courier Company. Theorganization is a Courier Company as well as Insurance Company. Therefore, theGlobal Courier Company class inherits the characteristics of the Courier Company andInsurance Company classes. The Global Courier Company is a subclass and CourierCompany and Insurance Company are superclass. The type of inheritance involved inthis scenario is multiple inheritance.

The following figure shows multíple inheritance:

Multiole Inheritance

Super clóss(Pa rent 1 )

Super Class{Pa rent2 )

Sub Class(chird)

Insurance Compar¡y

Global Courier

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

Page 44: Java Fundamentals - Part I

Polymorphismis 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 aYou might have noticed that a person assumes different roles in different

, For example, a person assumes various roles when he interacts with theof 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 familyas per his relation with the member.

object-oriented methodology. polymorphism is the feature that enables you toilgn a different meaning or usage to an entity in different contexts, The entity cana variable, method, or an object. Polymorphism enables an entity to have morern one form depending upon the context in which it is used. Polymorphism enablesentity to be used as a general category for different types of actions.

!e,\narh-s -

*) eampr-laq"k\ -? €,^LJJQta{ ,r-* e*'"}oÁshca

Page 45: Java Fundamentals - Part I

In this lesson, you learned:

W Encapsulation- Hides the implementation details of an object and therefore hidesits complexity.

W Abstraction- Focuses on the essential features of an object.

W Inheritance- Creates a hierarchy of ciasses and helps in reuse of attributes andmethods of a class.

W The relationship among the classes can be classified as:

o Kind-ofo Is-ao Part-ofo 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 differentcontexts.

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

Page 46: Java Fundamentals - Part I

ril-l

-i&"'LessoN tCCoLLABORATE

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

Page 47: Java Fundamentals - Part I
Page 48: Java Fundamentals - Part I

"f:

I

I

Kn¡owr-EDGE Bvre

s section, you will learn about:

3:ject-Oriented Analysis and Design

" 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 andrn-t,::-criented design, In object-oriented analysis the emphasis is on the'riü':s:gation of a problem based on the requirements, For example, the5*--.:'r'curMoney, Inc. bank requires a new automated bank management system. Inm_e::-oriented analysis, the end users and the developers of the system analyze thereg,- -=ments of the new system.

"rr:-= rbject-oriented design, the emphasis is on defining the software objects and1;ru i3 collaborate these objects to fulfill the requirements of the new system to ber¿.= :3ed. For example, in the bank management system, the Customer class needsr: -=,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, ina:: : 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

Page 49: Java Fundamentals - Part I

W Deploying the software

According to Grady Booch, James Rumbaugh, and Ivar Jacobson, the sDLC of any

software intensive system includes the following four phases:

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

ffi Construction

W Transition

Inception (rr,u.e,lo\

This is the first phase of the sDLC process. The various activities involved in Incept¡on

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

defined at this stage. ihe requiremenis of the system are also.explained and

documented in this stage. The various activities involved in Elaboration stage are:

W Elaborating the system specification obtained from the inception phase

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ü"&

1a¿**$':'*- **'!=l-"dt/ r.J.

S co?e/ -? arttbr t<r' at <pr¡<r,,

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

Page 50: Java Fundamentals - Part I

is the third phase of the SDLC process. This stage involves the following

Elaborating the solution specification obtained from the elaboration phase

Building and developing the software system

Completing implementation and testing of the software system

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:

Integ rating different modules.

Delivering the integrated modules.

Deploying the integrated modules.

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 theg¡struction process.

lr the inception phase, you build a vision of why you want a house and what kind ofhse it should be. You discuss the same with-your family members, start arrangingfu 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, contractorslrd other skilled perconnel get busy in the process of translating the blueprint intorealrty. As the construction progresses, you keep checking the functionality of variousftahrres, such as the electrical wiring, landscaping, and water connection. In case you

3E? Saxra fwczá*r*ent"afs

Dli/n-;.1o -Jre5a

.: I

"l-t

IIII

{d"1}!^r-+ **ffifr*&

Lü"5

Page 51: Java Fundamentals - Part I

P*

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

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

Various Types of Inher¡tanceInheritance is the propefty that enables a class or an object to acquire the attributesand 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 thesuperclass or base class and the FixedAccount, CurrentAccount, and SavingsAccountclasses 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

Hierarchical

Multipath

#)wtt,.t/ &g I

ffi

'ffi

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

Page 52: Java Fundamentals - Part I

Iultilevel fnheritance

','!t multile.vel inheritance, a class is derived from an inherited class. As a result, theGived 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 theke class. The Children class inherits the attributes and rnethods of the parents ctássrrd the Grandparents class.

M u ltilevel In herita nce

Class A

Parent Class for Class B

Sava Fux***rnen*alg;

Page 53: Java Fundamentals - Part I

Hybrid Inheritance

In hybrid inheritance, a derived class exhibits two or more than two types ofinheritance. For example, a derived class inherits attributes and methods of two ormore base classes, which is multiple inheritance. One of the base classes is derivedfrom 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 hierarchicalinheritance.

Hierarchica I In herita nce

¿fr.o

Class AParent Class for Classes B.C, and D

L '-*

Sava Fundamentals ffixtrlt

Page 54: Java Fundamentals - Part I

Dl0

I

I

l{ ultipath Inheritance

v-:ipath inheritance is a combination of multiple and hierarchical inheritance, In-- tiple inheritance, a child class is a derived class that inherits attributes and

-:thods of two or more base classes. The base classes are derived from a single:?-ent class in hierarchical inheritance.

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

=¿lled abstract methods. An abstract method is implemented in the subclass instead

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

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

I

I : ,:" f$i¡ij

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

Page 55: Java Fundamentals - Part 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.

What are the primary object-oriented methodologies used currentlyT

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

How did object-orientation evolve?

The object-orientation evolved with the evolution of Simula that providedfeatures, such as objects, classes, and inheritance. Simula was the first object-oriented programming language. Simula 1 was a simulation language andSimula 67 was referred to as Simula. Smalltalk was another language havingvarious features, such as classes, inheritance, and graphical user environment.

Class B inherits features from its base class, class A. Class C is a sub class ofclass B and inherits features from class B. How many times will the features ofclass A appear in class C?

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

CIass Hierarchy

W

W

ffi

hü"3-w

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

3 m u¿ m T u* T a4 mzzz * r*t m4 s ''rywLTtr

Page 56: Java Fundamentals - Part I

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

eww

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

Sana Fean&a*tentar* LT"IL

Page 57: Java Fundamentals - Part I

7F

1. Match the followino:a. Java

c.C

:::i

i. Structured Programming Language".-.-*ii. Procedural Programming Language

iii, Object-oriented Programmingd. LISP iv. Imperative Programming Languagee. FORTRAN v. Functional Programming Language

2. Make words from the jumbled letters in the box given below and match themwith 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 rd. An objec! of class has a unique l&,*-f rrv .

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

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

Noitalusoacne?nc^rP*itar'ra'Entiitvdrde+ií+1 qd\Srctaabtabs\ra*,* óq)

#"*.k2.

\v r*bleJ-yre¡r.¡dñp3

3 av n F a¿ rs$awnxrzLtnts ti,tWíT

Page 58: Java Fundamentals - Part I

3. Solve the following crossword:

Down:

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

lv, The characteristic of an object that refers to a change of the stateof the object over a period of time (8)

69

--is

an example of procedural programmins (5)

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

5 The type of inheritance in which there is more than one level ofinheritance. ( 10)

Across:

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

Page 59: Java Fundamentals - Part I

Sawa F*ndanr*.mt"ele wwr

Page 60: Java Fundamentals - Part I

Lessem 3BFHRTMENT

Swwm Wa¿m&mwremtffig#

Page 61: Java Fundamentals - Part I
Page 62: Java Fundamentals - Part I

f.n*1,i'&J

Lne ExeRcrsEs

Exercise 15,'stem Solutions Inc. recruits its employees through two processes: Externaliecruitment 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

=::ributes. What are the various conventions that the class names follow?

Exercise 2S..¡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 oftheclass.

b, The manufacturer does not want that a user should tamper with theelectrical wiring in the oven, and hence must be hidden from the user.Identify the feature of object-oriented programming that best describesthe feature of data or information hiding.

c. A person operating the oven need not know the details of how the ovenworks. The person just needs to know how to switch on and off an oven,and change the temperature settings. Identify the feature of OOPS thatallows the user to ignore the irrelevant details of working of an oven andconcentrate on the essentials.

d. All ovens have certain common attributes and functionality, For example,every oven has a door, Different companies add various additionalfeatures to the basic functionality of an oven. Identify a sub class of theOven class. Identify the property of OOPS, in which the existing featuresof 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

Page 63: Java Fundamentals - Part I

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

F¡gurc 7

AndrewsonsInstitub of

MedicalSciences

Savw f*znúame*tals

Page 64: Java Fundamentals - Part I

Motcr Bike Motor Sike Truck

rxéicis i,e r Fsure 2

identify the relationships between the various classes depicted in the followingf ig u res:

a.t.

l';lachine

Car

C0rrputer

b.

, ?t'ql'T

Page 65: Java Fundamentals - Part I

d.

FmplsyeelS

Exercise 5A passenger of FlyHigh Airlines can travel by two types of ticket reservations,

Confirmeá ticket and Requested ticket. The Airline reservation has various attributes,

such as flight number, dáte, time, and destination. Both types of classes ¡nherit these

common aitributes. T'he Confirmed ticket class would however have a seat number

*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,

Page 66: Java Fundamentals - Part I

'!a

z.

HOUT ASSIGNMENT

Which language is an Object Oriented Programming language?

a. BASICb. coBoLc. FORTRAN

@ Java

Which option is correct about the procedural programming approach?

@ In the procedural programming approach, portions of the code are sointerdependent that the code in one application cannot be reused inanother.

b. In the procedural programming approach, portions of the code can bereused.

c. The procedural programming language provides the advantage ofinformation hiding.

d. The procedural programming language provides the advantage of realworld programming.

Which feature of Object Oriented Programming language ensures data securityin a program?

O Information Hiding

b. Resuability of code

c. Resilience to change

d. Modularity of code

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

c. class is an instance of an object.

d. The objects can exist in isolation.

Which option is correct about the objects in object oriented programminglanguage?

Two objects may have the same behavior, may or may not have thesame state but will never have the same identity.

Two objects will never have the same identity, behavior, and state.

Two objects may have the same identity, behavior, and state.

3.

4.

5.

b.

T:WZTtr "", e:" 4; ..:i,.;.i";. "r:!li,

Page 67: Java Fundamentals - Part I

I

I

1lI

d. Two objects may have the same identity, may or may not have thesame state but will never have the same behavior

6. Which option is correct about the objects in Object Oriented Programminglanguage?

@ 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 aperiod of time.

7. In single inheritance, a subclass is derived from

@ onty one superclass.

b. Two superclasses.

c. Three superclasses.

d. Four superclasses.

Inmu|tip|einheritance,asubc|assisderivedfrom-_'a. Only one superclass.

b. Two superclasses.

c. Three superclasses,14

@,i More than one super class.

A computer has a monitor then what is the kind of relationship depictedbetween 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 amongmultiple classes.

Inheritance enables you to,add new features and functionality to anexisting class without modifying the existing class.

In inheritance, a subclass is also called a parent class,

In inheritance, a superclass is also called a child class.

8.

9.

c.

d.

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

Page 68: Java Fundamentals - Part I

whess*F* Re.IwrnepucTuelu TC) #*v*

In this lesson, you will learn about:

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

Sava Fundarxentals

Page 69: Java Fundamentals - Part I

w-

i&jWú.v &4^ a2.&,W Sawm Funúarsz*.rztals

Page 70: Java Fundamentals - Part I

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 systemthese devices run on. The lava programs work on any type of compatible device thatsupports Java,

Need for JavaThe 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 primarymotive behind developing Java language was the need for a portable andplatform-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-infeatures in Java.

you can use Java to wr¡te a variety of applications. A few types of Java applicationsare:

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

IÁv*

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

Page 71: Java Fundamentals - Part I

W Packages: Packages are collections of classes that can be reused by applicationsand applets.

Most programming languages are platform dependent. Applications developed byusing such programming languages can run only on those types of hardware andsoftware platforms on which the applications are compiled. Compilation of anapplication refers to conversion of the program instructions, written in a programminglanguage, to the language that the computer can understand,

Java is a platform independent language that enables you to compile an application onone platform and execute it on any platform. This saves your effort to write andcompile the same application for different platforms.

Computers connected to the Internet run on different operating systems and hardwareplatforms. The applications running on these computers can be Web-based orInternet-based. Internet applications are distributed, which means two or moreapplications running on different computers communicate with each other byexchanging messages and data.

You use Java programming language to develop an Internet-based application thatcan be accessed by programmers working on various types of computers.

In addition, you can download a file or an executable program on a computerconnected to the Internet. Any program downloaded through the Internet can performsome malicious task on the local computer if the local computer does not implementsecurity checks. Java provides a solution to all these problems. Java applet, which is aprogram embedded within a Web page, when downloaded from the Internet on acomputer cannot access the file system on the local computer. Java provides a.runtime environment, which implements various security checks on Java applets and doesnot allow them to peform any malicious task.

Characteristics of Java

Simple Solutions Systems Inc, is a software development organization, which hasbranches across the globe. The organization needs to develop an automatedapplication within a short duration. The application must enable the employees toobtain information about the benefits and opportunities offered by the organization.The organization also wants a Web-based application for the recruitment system thatenables an individual from any country to apply for a job. The applicants across theglobe 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 asviruses.

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

Page 72: Java Fundamentals - Part I

The choice for having a programming language that fulfills all these requirements isJava 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 howmemory is allocated to data because in Java, the programmer does not need to handlememory manipulation. Java is a simple language that can be learned easily even ifyou have just stafted programming. It was designed to be easy for the programmer tolearn and use effectively. The syntax for various Java statements is easy tounderstand,

Object-Oriented

Java supports the object-oriented approach to develop programs, It supports variousfeatures of an object-oriented language, such as abstraction, encapsulation,inheritance, and polymorphism. To implement the object-oriented language, the entirecode of the program must be written within a class. The lava language does notsuppoft stand-alone statements. Even the most basic program in Java must be withina class.

,7zW'?,18W

One of the major problem areas in most of the object-orientedlanguages, such as C++, ¡s to handle memory allocation,Programme¡s need to explicitly handle memory in the programfor its opt¡mum utilization. To handle memory allocation, theyuse pointers that enable a program to refer to memorylocation of the computer. However, Java does not supportpointers and consists of the built-in functionality to manage

Smwm Famümffie,nte.&# 7.&..%

Page 73: Java Fundamentals - Part I

f

Compiled and Interpreted

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

The Java compiler compiles the code to a Bytecode that is understood by Java. Wheryou compile a Java source code file (.java), the Java compiler generates the Bytecodewhich 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. Whileinterpreting the interpreter software reads and executes the code line by line. TheJava interpreter can execute Java code directly on any computer on which a JVM hasbeen installed.

Poftable

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

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

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

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

The lava compiler is written in Java and the interpreter iswritten in C programming language

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

Page 74: Java Fundamentals - Part I

IVM is not platform independent. Each platform iee7s to ttaveits own JVM to run a Java application. The Bytecode supportsconnection to multiple databases.

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

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

Distributed

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

rylfr Java $ource Code I

4___g::__J--- ,f--

Éffi{ Jéva \\-Try-/

I

u**- .:. " *.f, eytecode fite

I

{ (.class nte) i

;=]\,/'l\ ffi\\j:_/ \.:' -f,wi.uows lf, uNrx

lfi tuacrntostr

I*-T-*&

$ tt/indows | $ UNIX | [ Macintosh I

il Máchine | fl uacirine I f M€chine I

t__eg!Lj t_:gsj q___jga_J

Java portability with Mult¡ple Platforms

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

Page 75: Java Fundamentals - Part I

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

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

Secure

lava has built-in security features that verify that the programs do not perform anydestructive task, such as accessing the files on a remote system. Java does not allorthe 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 theprograms cannot access memory locations w¡thout proper authorization.

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

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

An applet can only communicate with the remote server from which you download theapplet. It cannot make connection with other remote computers.

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

Host computer is the remote computer where the application isstored. You run the application from the host computer over anetwork by using a computer, which is termed as the localcomputer.

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

Page 76: Java Fundamentals - Part I

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

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

Secure

Java has built-in security features that verify that the programs do not perform anydestructive task, such as access¡ng the files on a remote system. JaVa does not allowthe 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 theprograms cannot access memory locations without proper authorization.

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

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

An applet can only communicate with the remote server from which you download theapplet. It cannot make connection with other remote computers.

Host computer is the remote computer where the application isstored. You run the application from the host computer over anetwork by using a computer, which is termed as the localcomputer.

Java ArchitectureVarious 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)

Page 77: Java Fundamentals - Part I

Java Programming Language and class File

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

The following figure shows the relationship among various components of the lavaprog 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 varioushardware-based platforms.

Components of the JVM

IVM for different platforms uses different techniques to execute the Bytecode. Themajor 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 thememory. 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 runningJava program.

W Class Loader Objects: Loads the classes ütne Java application program' Anapplication can create class loaders at runtime for loading the classes of theapplication.

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

Page 78: Java Fundamentals - Part I

Fr_

Execution Engine

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

JIT Compiler

The JIT compiler is used for compiling the Bytecode into executable code. The JVMruns the JIT compiled code without interpreting because the JlT-compiled code is inthe machine code format. Running the JIT- compiled code is faster than running theinterpreted 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 asGUI. 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 theJava programs on top of the hardware:

| :aua crogram I

| (.:ava)

|t_____=______lffiFI ,-\l.------------ -*Java\.L*_eL_l R:*9ffiI Hardware

iL__JComponents of Java platform

Java Architecture SecurityJava architecture also consists of a few security features that make lava a secureprogramming 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¿A1y: ffi***

Page 79: Java Fundamentals - Part I

Bytecode verifier

Class loader

W Sandbox model

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

Security Levels ín Java Arch¡tedure

Compiler Level Security

one of the problem areas in earlierobject-oriented languages, such as c++, wastheavailability of pointers. Pointers enable a program to access memory directly, whichmight result in improper usage of memory. The problem of memory usage is resolvedin Java, as it does not support pointers at the program level. Java prevents errors that

tí:;iww

w

w

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

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

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

t

{,¿r-J* "'Ye/*&

I:::::::: i': "t't:

;;;:;

3 m'sr m W axffi qáa frw *rzq. e6w 2.&*23

Page 80: Java Fundamentals - Part I

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

Bytecode Verifier

The Bytecode verifier checks the Bytecode before it runs on a computer. It ensuresthat 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 twophases:

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 checksthe validity of classes, variables, and methods used in a program.

Native APIs are the application programming interfaces of theoperating 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 Javaenvironment. In a Java environment, there can be many class loaders and each classloader can create its own run-time environment. The class loader loads all the appletsand their references.

Sandbox Model

lhe sandbox model is implemented in the Java applets container, such as Webbrowsers. 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 thelocal computer. Java applications do not employ this security model and are allowed toread from and write to files on the local computers.

At times, you might need to compare incompatible data, suchas a text and a number. To compare such data, you need toconvert data of one type to another, such as text to number ornumber to text. Conversion of data from one type to another is

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

Page 81: Java Fundamentals - Part I

WiDec¡-aRING VnnrnBLEs ANDLITERALSI

'.:aa:), aaa,!aa

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

Using Various Data TypesThe data stored in memory of the computer can be of many types. For example, aperson's age is stored as a numeric value and an address is stored as alphanumericcharacters. Data types are used to define the operations possible on variables and thestorage method.

Java is a strictly typed language, which means that lava gives impoftance to typechecking. 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 aprogram. The data stored in the memory of a computercan be of differenttypes. Thevarious 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 followingcategories:

W Integer type: Can store whole number values. The size of the values of thevariables depends upon the chosen integer data type, The four integer datatypes are:

o byte. shoÉo into lono

':azm' 3 ms¿ n W z* ru ú. r¿ rr? {& r'tt.& É ffi . 2,á,^,?i""3

Page 82: Java Fundamentals - Part I

F-_-_--

W Floating point type: Can store fractional numbers. The two types of floatingpoint type are:

o floato double

ffi Boolean type: Can store only the true and false values. Boolean data type isreouired when a condition has to be checked. The true orfalse value of theexpression or the condition determines further execution of the Java program.

W Charactertype: Can store symbols, such as letters and numbers. In charactertype, there is one data type, char.

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

GróiuB Data Type SÍZe Pe,nge' üátáattt'', : ,r llr:,: ,. , . i

,'Y4tue '1

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

short Twobyte

_2ts ¡o 2rs _1 0

int Fourbyte

-237 to 23r_! 0

long Eightbyte

-263 to 263-r 0

Floatingpoint

float Fourbyte

3.4e-038 tO 3.4u*038 0.0

double Eightbyte

1.7e-308 tO 1.7"*308 0.0

Boolean boolean One bit true or false false

Cha racter char Twobyte

a single character null

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

Page 83: Java Fundamentals - Part I

Abstract data types

The abstract data types include the data types derived from the primitive data typesand have more functions than primitive data types. For example, String is an abstractdata 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 thedata stored in it has digits, However, String provides methods for concatenating twostrings, 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 languagefeatures, Keywords cannot be used for naming purpose of variables, constants, orclasses.

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

3 mw m ffi ¿zvzúarzz*q"eYwIs

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 ?.Ét.b%

Page 84: Java Fundamentals - Part I

Defining Variables and LiteralsA 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 canassign different values to a variable during program execution. Java allocates memoryto each variable that you use in your program. If the name, number, is used to referto 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 bedeclared 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 conventionsgovern 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 notmandatory. The naming conventions for a variable in Java are;

r& The name of a variable needs to be meaningfui, short, and without anyembedded 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 dollarsymbol ($), 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 anunderscore 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 asvariable scope. The various types of variables on the basis of the variable scope inJava are:

ffi Class variables: Are accessible within a class and its objects. The class variablesare declared inside the class before their use.

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

Page 85: Java Fundamentals - Part I

'lI

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 thespecific requirements of the object of that class type.

Local variables: Are declared inside a method. Theirscope is within the block ofcode in which they are defined. They are local to the block of code and are notaccessible outside the method.

Static variables: Are allocated memory only once but are globally accessible toall instances of a class. Therefore, when an instance of a class is destroyed, thestatic variable is not destroyed and is available to other instances of that class.

Automatic variables: Are accessible within the function in which they aredeclared. The automatic variables are created when a function is called and aredestroyed 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. Thefollowing syntax shows how to declare a variable:<type> <variablename>; // Single varj-abfe of gÍven type.<type><variablelname,variable2name.....variable n name> // ltultiplevariables of given type.

In the preceding syntax, you need to initialize variables before you use them. TheJava 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 ofthe variable before first use of the variable. For example, you can use the followingstatement to declare the variables, numl, and num2 to calculate the sum of twonumbers: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 onevariable:^ _L_^_ ? .

W

W

w

i&1 €gy.&,:a' &a& @

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

3*wm Yeanúmrrq*ffita&s 2fi^"27

Page 86: Java Fundamentals - Part I

In the preceding command, integer value 3 is first assigned to variable c, then to band 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 representsthe value to be stored. The various types of literals in Java are:

ffi Integer literals: Are numeric type values. The numerical values can bereoresented in octal and hexadecimal notation. The octal notation of a number isprefixed by zero and hexadecimal numbers are prefixed by 0x. For example,n=0123 is integer literal in octal notation, n=0x456 is integer literal inhexadecimal 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 VariablesTo manipulate data and variables in Java, you use operators, which accept one ormore operands or arguments and produce an output. The operators used tomanipulate variables are assignment and arithmetic operators.

Assignment Operator

You use the assignment operator (=) to assign a value to a variable. The followingsyntax 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 datatype of the value assigned to the variable.

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

Page 87: Java Fundamentals - Part I

I

Arithmetic Operators

Arithmetic operators are used to compute mathematical expressions. The followingtable 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 stringvalues' For example, you have two numbers, 4 and 5. To add these numberr, yo,Ls"the following statement:4+5In the preceding statement, you use the, +, operator to concatenate the two values toproduce a result 9.

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

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

Page 88: Java Fundamentals - Part I

Modulus Operator

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

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

* L5 o/o 6:

15-6=9

9-6=33 < 6. Therefore, the result of the modulus operator is 3.

I 9.6 o/o 4.2:

9.6-4.2=5.45.4-4.2=L.2L.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.

ffirg##24.20 f,ava fundamentals

Page 89: Java Fundamentals - Part I

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

An array is a contiguous block of memory locations referred by a common name. Forexample, to store the marks of 5000 students, you can declare an array, marks, ofsize 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 toa specific array element by the array name and the element number, which is knownas the index number.

Creating Arrays

The length of an array is fixed at the time of its creation. An array represents relatedentities having the same data type in contiguous or adjacent memory locations. Therelated data items form a group and are referred to by the same name. For example,the automated employee management system of SimpleSystemsSolutions Inc. mightneed an array of integers to hold the IDs of the employees. The following commandshows an array named employee:employee l5l ;

The complete set of values is known as an array and the individual entities are calledas elements of the array. A specific value in an array is indicated by writing the arrayname and placing the index of the desired element in square brackets. The index isalso known as subscript and the array may be called as a collection of subscriptedelements of the same data type. The advantage of using array lies in the fact that youcan refer to a large number of elements by just specifying the subscript preceded bythe array name. Arrays make it easy to do calculations in a loop, such as determiningthe total number of values stored in an array,

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

Page 90: Java Fundamentals - Part I

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 followingsyntax 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 thearray contain variables of the same data type as the array. For example, you have anarray that contains the names of the various designations offered bySimpleSystemsSolutions Inc. for its employees. The following syntax shows how todeclare a one-dimensional string array:af ri nn ¡laci n¡¡+i nn f r¡naa l1ñ l .,,_types [10],.

In the preceding syntax, the designation_types array is declared that can store 10designation types in it.

Allocating Memory to Arrays

You use the new operator to allocate memory to an array. The following syntax showshow 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 3elements:Emp_ID : b3y/ string [3],'

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

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

Page 91: Java Fundamentals - Part I

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

Memory Allocation to Arrays

M ulti-dimens¡onal Arrays

In addition to one-dimensional arrays, you can create multi-dimensional arrays. Todeclare multi-dimensional arrays/ you need to specify multiple square brackets afterthe array name. For example, the following syntax displays the declaration of a twodimensional array:r-+ -..r-rñr-'1 -=w intt3l [];¿rr L Iluf Lf yf tLL L I - Itr

In a multi-dimensional array, you need to allocate memory for only the firstdimension, as shown in the preceding syntax. You can allocate the remainingdimensions separately. The following code snippet manually allocates memory to thesecond dimension:muftiDim[0] : new int[4]tmultiDim[1] = new ínt[4];multiDim[2] : new int[4];In addition, when you allocate memory to the second dimension of amulti-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 whichthe sizes of the second dimension are not eoual:i-r *_.r+rñr*,' _ -eh, intt3] tI;LrvrrLf Ll - rrr

multiDim[0] = new ínt [1];ñ,,1finimrlr - ñóil int[2];mul-LiDim[2] = new int[4];

emp*ID l2l

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

Page 92: Java Fundamentals - Part I

Accessing ArraysYou need to access various elements of an array to assign, retrieve, and manipulatethe 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 indexnumber of the element. The index position of the first element in the array is 0. Forexample, the following statement assigns the value "ceneraf Manager" to the firstelement 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 thegiven 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 singlestatement:tYPe arrLl = new:YPelsizel,'

You can use the following code snippet to declare and initialize arrays in the samestatement: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 inthe array by referring to the element by its index number. The following statement isused 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 tothe first element of the array.

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

Page 93: Java Fundamentals - Part I

In this lesson, you learned:

W Java is both a language and a technology used to develop desktop andInternet-based applications known as Java applications and applets.

W The various characteristics of Java programming language are:

¡ Simple¡ Object-orientedo Compiled and interpretedo Portableo Distributed¡ Robust. Secure

ffi Various components of the Java architecture are:

¡ Java programming language. Java class fileo Java Virtual Machine. Java Application Programming Interface (API).

ffi The JVM converts the Bytecode contained in the .class file to machine objectcode.

The various data types defined in Java are:

o Integers: Include byte, short, int, and long data typeso Floating-point numbers: Include double and float data types.o Characters: Include char, data type.o Boolean: Include boolean, data type.

The built-in or the intrinsic data types in Java are known as the primitive or thesimple data types.

The abstract data types include the data types derived from the primitive datatypes.

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

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.

w

w

w

ffi

w

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

Page 94: Java Fundamentals - Part I

I The various types of variables are:

o Class variableso Instance variableso Local variableso Static variables.. Automatic variables

You use operators in Java to manipulate data and variables. The variousoperators are assignment and arithm-etic operators.

An array is a group of variables of the same data type and refer"red to by acommon name. A specific element of an array can be accessed by its index.array is a block of memory locations.

r

2¡'.m Java Fundarnentals

Page 95: Java Fundamentals - Part I

w

w

Java is both a language and a technology used to develoo desktop andInternet-based applications known as Java applications and applets.

The various characterístics of Java programming language are:. S¡mpleo Object-orientedo Compiled and interpretedo Portableo Distributed¡ Robustt Secure

Var¡ous components of the Java architecture are:

r Java programming language. Java class t¡teo Java Viftual Machine. Java Application Programming Interface (ApI)

The JVM converts the Bytecode contained in the .class file to machine objectcode.

The various data types defined in Java are:

. Integers: Include bvte, short, int, and long data typesr Floating-point numbers: Include double and float data types.r Characters: Include char, data type.. Boolean: Include boolean, data type.

The built-in or the intrinsic data types in Java are known as the primitive or thesimple data types.

The abstract data types ínclude the data types derived from the primitive datatypes.

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

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

W

w

w

w

W

ffi

ffi

?,A.27

Page 96: Java Fundamentals - Part I

s The various Vpes of variables are:

o Class variables. Instance variableso Local variables. Static variables. Automatic variables

You use operators in Java to manipulate data and variables. The variousoperatorc are asslgnment and arithmetic operators.

An array is a group of variables sf the same data type and referred to by acommon name. A specific element of an array can be accessed by its index.array is a block of memory locations.

n

3

Java fundamentals

Page 97: Java Fundamentals - Part I

Whessom kBCmsses AF*n On¡EcTs

ectivesIn this lesson, you will learn about:

d Structure of a Java programF Access specifiers and mbd¡f¡ers5 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 v¿"6. s ¿ lq

"!: '. ".

Page 98: Java Fundamentals - Part I

zffi"4 S*wa Y*r*áatnt,en*e*8

Page 99: Java Fundamentals - Part I

o SrnucruRE or Jnva-A r AppucATroN-

¡- t-tf a-l

-l-l

In Java, you can either create a stand-alone application or a networked application. Astand-alone application uses resources of a local computer. A networked applicationuses the resources available over a network. For example, a networked application isallowed to read from or write to files on remote computers.

Classes and objects form the basis of the structure of a Java application. A lavaapplication 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 datamembers of a class. Objects can be reused across programs,

Creating Classes and ObjectsA class defines user-defined objects and their characteristics. Any concept that youneed to implement in a Java program is encapsulated within a class. A class definesthe attributes and methods of objects of the same type sharing commoncharacteristics. For example, when you create an online shopping site for books, eachbook is an instance of the Books class. All books have attributes, such as the numberof pages, type of binding, and title. In addition, the books have various commonmethods, such as being selected, being bought, and being sold. The state of eachbook 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, whichspecify the type of data to be stored, Methods of a class contain a set of executablestatements that gives a desired output. Methods define the action to be carried out onthe 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

Page 100: Java Fundamentals - Part I

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 CfassNamel

/ /DecIaraLion of data members/ /DecLaraLion of methodsl

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

Compiler ignores these statements and these are not executed at run time. It is thebest 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 datamembers 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 methodsl

:. Y.:"""'

Page 101: Java Fundamentals - Part I

You can use the following code snippet to declare the Employee class that definesvarious data members, such as employeeName, employeelD, andem ployeeDesignation.

cJ-ass EmployeeI

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 objectdistinguishes it from other objects. Classes and objects are closely linked to eachother. While an object has a unique identity, a class is an abstraction of the commonproperties of various objects. To create an object, you need to perform the followingsteps:

1. Declaration: Declares a variable that holds the reference to the object. Thefollowing 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 youdeclare an object, memory is not allocated to it. Therefore, you cannot storedata in the data members of the object. To allocate memory to the object, youneed to use the new operator. The new operator allocates memory to anobject 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 -

! ,' ,' :,,t.!, E rqu\) fttttlo"¡ c'<¿C) )

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

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

r¿'4,WlY

Page 102: Java Fundamentals - Part I

The following figure shows how an object is created and reference is assigned to t.€memory allocated for the object:

Creating an Object

You can use the following statement to declare and instantiate an object, e1, of theEmployee class in a single statement:Employee e1= new Employee O;

You can use the following code snippet to create objects for four employees of anorganization: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 namefollowed by the dot operator and the data member name. The following syntax shovrshow 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 anddara_member_name refers to the name of the data variable inside the object that yo-want to access.

wt Ytfi oecra'e Ernproye* --.& J:.:,"J:?, Ia I el 4_________J "

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

,l l{lIT

Page 103: Java Fundamentals - Part I

You can use the following code snippet to access data members of the Employee class,

such as employeeName]employeeiD, and employeeDesignation and assign values to

them through objects, e1 and e2:

e1 . employeeName:" John" ;e2 . emmployeeName="AndY" i

e1 . employeelD:1;eZ . emp-Lovee LD=¿ iel.empfoyeeDesignation : "Manaqer" ;

e2.ernployeeDesignation : "Director" ;

Adding Methods to a Class

Inaprogram,referringtomu|tipledata.membersofac|asscanbeatedioustask.Iná¿J¡tioni".céssing ¿aía mem¡ers directly overrules the concept of encapsulation' You

."n c."it" a methbd that can be used to access the data members' Using methods in

a Java program provides the following advantages:

W Reusability: Enables you to reuse the whole code or a paft of it. A function or a

task ¡s encapsulated in a method that can be accessed from anywhere in the ..

program. The practice of reusing a method is also called "write once, use many"'

The following figure shows the reusability of code by calling a method at various

places in a Program:

ffi

ffi

MEth0dtlltil

I Fraqram 2 |tl1_____*________J

Access¡ng Methods

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

|argeandcomplexcodeisdividedintoprocedures,whichareimp|ementedasmethods.

Data Hiding: Hides the implementation details of an object' When you call a

method from another location in the code, you do not need.to know how that

method is being executed. The programmercan access the data members of the

class by executing methods. For eiample, you have a method, addo that is

;;;¡ rd add two ñumbers defined in a class. When you call the addg method at

a different location in the code, you call the method by its name' You need not

'¡.- wtr\T

Page 104: Java Fundamentals - Part I

define the functionality of the addO method again. You can reuse the method byjust calling it.

Adding Methods to Classes

The management of SimplesystemsSolutions Inc. performs various functions, such asadding, deleting, and modifying the details of its employees, The automated solutionof 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 returnany 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 aclass. You can create a number of classes in a Java program. The Java compilercompiles all the classes in an application but to execute a program, you need toinclude a mainO method in the program. The following syntax shows how to declarethe main O method:nrrl-,1i¡ efrf i¡ ¡¡niA

{

/ / Code for main ( )

]

In the preceding syntax, the method header contains three words public, static, andvoid. The implications of these three words are:

W public: The public keyword indicatesthatthe method can be accessed from anyobject in a Java program,

W static: The static keyword is used with the main O method that associates themethod with its class. You need not create an obiect of the class to call themain ( ) 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 theclass name in which the main O method is declared should be the same. The file must

main(String[] args)

method

¡"'mtlr

Page 105: Java Fundamentals - Part I

have the .java extension. For example, if the main O method is declared in classEmployee, 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 oftype 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 issent to the program that helps in program initialization. Strings are a sequence ofcharacters. ar:.- is the array containing the string values,

An argument is a variable that you need to pass to a methodfor providing an input value to the method.

Defining ConstructorsYou might have observed that to initialize the data members of a class, you need toassign values to each data member. However, it might turn out to be a tedious task ifyou need to initialize a large number of data members. In Java, you can createconstructors of the classes that automatically initialize the data members of the classwhen you create an object.

A constructor is a method with the same name as the class name. A constructor of aclass 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 acustomer you can create an Account class. You can use the following code snippet toadd a constructor, Accc:inr O of the class to initialize the values of the data membersof the Account class.

cfass Accou:r--{

int prlnclpai; / / Data members of the cfassint 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::. :::::: ::.;;

' ¡';n q ;2 {: A; r,.t} ?a í:,:'1 4. 7: "t+i

!* r'fi;&iWiáHWai:.13 .. :.4

Page 106: Java Fundamentals - Part I

float amou¡¡: (principal*interestRate*tine) /100,' // methodaccessing the data members of the class]

l

In the preceding code snippet, each time an object of the Account class is created, theconstructor is invoked and the object data members are initialized to the defaultvalues 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 ofthe class instead of a value.

I A constructor is used to assign values to the data members of each objectcreated from a class.

28.1ü Java Fundarnentals sttrtr?

Page 107: Java Fundamentals - Part I

3 Accrss SPecrrrERs AND

hr- HoorrrERs

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 ascustomer balance, from unauthorized access by other classes of the application'Within the Account dass, the meürods access the information, but outside the classyou 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 thedata members are r¡sed in oüter classes and objects.

Access SpecifiersAn access specifrer aontrols tñe access of class members and variables by otherobjects. 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 theclass is dedared. Yot¡ can use a public class, data member, or a methOd from anyobject 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 statementshows how to dedare a data member of a class as public:

nrhl'e <i=-= -.::> <;=l:--: ::a::e>.'

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

Page 108: Java Fundamentals - Part I

FI"I

'a

fThe class Account defines the show O method and various data members, such asname and account number. All the classes in the program can access the variousdetails of a customer, such as name and account number. Therefore, these datamembers and the method are declared public. The showl¡ method is used to displaythe account number and customer name of a customer.

You can use the following code snippet to define a class, Accounr that contains publicdata variables and method:public class Account{public int account_no; / / Data members are accessibfe outside the classpublic String name;

public void showO //¡tethod declaration{

System.out.println("Name :"+ name) ;,//Statement of themethodSystem.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 aredeclared public.

The private Access Specifier

The private access specifier provides most restricted level access. A data member of aclass declared private is accessible at the class level only in which it is defined. Youcan use the private access specifier to declare members that should be available tothe class within which they are declared. The private keyword is used to declare amember as private.

The following syntax shows how to declare a data memberof a class asprivare:private ffoat <variabfeName>; / / private data member of ffoat tvpeprivate methodNane O; / / PrivaLe method

The Account class defines the show O method and the various data members, such asbalance and age. These members are to be accessed only by the objects of the sameclass. Therefore, these methods are declared private. You can use the following codesnippet that shows the Account class with private data variables, such as age andbafance i

ffi|W*&ry.Y ffi&& 6

In Java, you implement the concept of encapsulatio+,byusing the private keyword.

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

Page 109: Java Fundamentals - Part I

class Account{prlvate int accounL_no; // Data members converted to private to

encapsulate dataprivate 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) iSystem.out.println("Balance of this customer is: "+

bal-ance) ;)

]

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

The protected Access Specifier

The variables and methods that are declared protected are accessible only to thesubclasses of the class in which they are declared. The protecreo keyword is used todeclare 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 ofvarious data members, such oS flightNumber, date, tíme, 3fld destination, you canderive the confirmedricket subclass from the ricker class that consists of anadditional data member, searNumber. you can declare the data members of theTicket 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 protecteddata 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 datenróté.f é.'l (l- ri n¡ + i mar! v eev uvs

nrofF.fad Sfrinn doc1- in¡f in¡.protected void showData ot

/ / Code bodvl

]

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

Page 110: Java Fundamentals - Part I

In the preceding code snippet variousprotected.

data members and methods are declared

The friendly or package Access Specifier

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

The data members, such as pageNumbers 3ñd price, and the showData0 method ofthe eooks class are not given access specifiers. The following code snippet shows theBooks class that has friendly access specifier:

cfass Books{int pageNumbers; / / Tine defaul-t friendly access is provided to the data

membersfloat price;void showData o

{

// Code bodv]

I

In Java, friendly is not a keyword. It is a term that is usedfor the access level when no access specifier has beenspecified, You cannot declare a class, variable, or methodwith the friendly specifier.

Types of Permitted ModifiersModifiers determine or define how the data members and methods are used in otherclasses and objects. The main difference between access specifiers and modifiers isthat access specifiers define the accessibility of the data members in a class and themodifiers determine how these methods are used and modified by other classes. Thevarious modifiers permitted in Java are:

W static

final

abstract

native

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

ffi

*&

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

Page 111: Java Fundamentals - Part I

f# synchronized

stát¡c

The static keyword is used with methods, variables, and inner classes. The statickeyword is used to define chss variables and methods that belong to a class and notto any pafticular instance of the class.

A static method associates the data members with a class and not the objects of theclass, Therefore, all the objects of a class share the same static data members andmethods. Non-static methods are those, which are associated with objects, and as aresult the values of the data members differ for different objects. You cannot accessnon-static data members and methods from a static method.

For example, in an online shopping application, you can keep track of the number ofbooks sold by keeping static counter data member in the Books class that ¡ncrementeach time a book is sold.

final

fhe finat keyword is used with methods, variables, and classes. The final modifierindicates that the data member cannot be modified. For example, consider a variablethat has been assigned a value. If the variable has been declared fina1, you cannotmodify 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 asubclass and use them in a different manner. The f inar modifier has the followingcha 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 theclass to be subclassed.

4WW 3'*'* a* F z*'*z # m {T4 *ffit& * # AW"Lffi

Page 112: Java Fundamentals - Part I

abstract

The abstract keyword is used to declare classes that only define common propeftiesand behavior of other classes. An abstract class is used as a base class to derivespecific classes of the same type. For example, you can create an abstract Books classthat contains the common data members, such as title, page numbers, and type ofbinding for all the books.

native

Íhe native modifier is used only with methods. It is used to inform the compiler thatthe method has been coded in a programming language otherthan Java, such as C orC++. The natj-ve keyword with a method indicates thatthe method lies outside theJava 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 beavoided. They are used when you have an existing codein another language and do not want to rewrite the codein Java.

synchronized

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

In a multithreaded program, you need to synchronize various threads. As a result ofsynch.ronization, only one thread can access a shared resource when two or morethreads need access to the resource at the same time. For example, if multiplethreads need to print a document, only one thread can access the printer as the resultof synchronization.

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

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

Page 113: Java Fundamentals - Part I

-:n propertiesrEss to derive

Books class: and type of

tire :ompiler that.i,,i ..........re, such aS C or

rrs outside the

'er controlst. A thread

u mming and

ls a result ofIIVIE Or morert

'r- - tiple:s the result

CouprlrNc AN AppLrcATroN

After you create an application, you need to compile it before executing it. When youcompile the application, the compiler checks for the compile-time errors. Thesuccessful compilation of the application results in the Bytecode generation of theapplication, which is a .class file. The following application consists of the basicstructure of a Java application and should be written in a text editor appl¡cation, suchas Notepad:class Hello{

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:

1. Compile the application,

2. Execute the application,

Compiling an Application

To compile an application/ you need to save the code with a file name that is exactlythe same as that of the class name, with a .java extension. In this case the file nameshould be sello. j ava.

To compile the .java file, you need to perform the following steps:

1. Open the command window.

2. Set the PATH variable to the bin directory of the installation directory, asfollows:

C:\j2sdk1.4. r_O2\bin

3. Change to the directory where you have saved the .java file. You can also givethe complete path of the .java file while compiling it.

e*rsting codethe code

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

Page 114: Java Fundamentals - Part I

4. Compile the application by using the following command at the commandprompt.

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

Page 115: Java Fundamentals - Part I

wProblem StatementYou need to create an Account class that consists of various data members, such asaccount number, name, age, and balance. The application must initialize the datamembers to default values when an object of the Account class is created. In addition,the application must display the data stored in the object.

SolutionThe Java application is created using the system. out . printl-n ( ) method, To solve theabove 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 theobject. In addition, you need to define the rnain ( ) method that creates an object ofthe Account class and executes the showoata O method.

You can use the following code to create the Account class and save it asAccount. java file:cfass Account{private int account_no; / / Data members converted to private to

encapsulate dataprivate 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.*

Page 116: Java Fundamentals - Part I

publ-ic void showData O / / Vetnoa can be ca11ed from outside the cfass toaccess the data members

{System. out . printl-n ( "Account NumberSystem.out.príntIn ("Name : "+ name)q\rql- éñ ^rrl- ñri ñ1- l ñ lrlAdó : rr+ rñó\ .

vg9.r!+r¡94|gYv,'

System.out.printfn ("Balance of this

: rr+ :¡¡nrrnl- nn\'

customer is : "+balance) ;

]nrrhli¡ cl-¡f i¡ r¡nid

{Account ac :ac. sho!,¡Data (

]]

2. Compile and

The command to compile thejavac Account.java

The command to execute thejava Account

main (String args [ ] )

new Account O ;

Execute the Application

Account application is:

Hello application is:

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

Page 117: Java Fundamentals - Part I

:..4.:a

W A class includes data members and methods. Methods can include expressionsthat evaluate a value.

W Creating a class includes declaration of class members. Data members of sametype 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 gmemory 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. Theconstructor can be used to initialize data members of newly created object.

W There are two types of constructors the default constructor and the overloadedconstructor.

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

W There are private, public, and protected access specifiers. Private accessspecifier gives the most restricted access among all the access specifiers.

W Class members with public specifier can be accessed anywhere in the sameclass, same package, or a different package.

W A modifier determines the use of the data members and methods in otherclasses and objects.

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

'p^&";2n

Page 118: Java Fundamentals - Part I

ffi you must set the PATH variable of the operating system to the bin directory ofthe installation directory.

ffi You need to use the javac fileName.java command to compile the fileName.javafile.

ffi You need to use the java fileName to execute the fileName'class file'

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

Page 119: Java Fundamentals - Part I

Ce*-;-*ECIRATE

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

Page 120: Java Fundamentals - Part I

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

Page 121: Java Fundamentals - Part I

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 JavaInitially, Java was not developed forthe Internet programming. The Java designerslater added the functions such as distributed, security, and portability that makeInternet programming simpler to develop using Java. You can use Java to developnetwork-oriented programs because networking features are built-in in lava.

In 1991, a team of software developers at Sun Microsystems, USA, was designing alanguage for consumer electronic devices. The development team headed by JamesGosling wanted to design a portable language using which programs that could run oncomputers with different platforms. The team aimed at programming the devices fromdifferent manufacturers so that the devices could be controlled by a single remotecontrol. They also wanted the language to be simple so that anyone can learn it in lesstime. 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 softwareto manipulate electronic devices.

1991 A new language named Oak wasintroduced using the most popularobject-oriented language C++.

1993 The WWW appeared on the Internetthat transformed the text-basedInternet into graphical Internet.

r994 Sun Microsystems team developed aWeb browser called HoUava to locateand run applet programs on theInternet.

iQ:W6"Wtr 3 #. i,f & {: !,:t iZ 4:}, # f ",n,*.tt" ?,:* | * '"jt"' rá

Page 122: Java Fundamentals - Part I

Y:i€iÍt: : i1995 Oak was renamed as Java.

1996 Java was established as anObject-oriented program ming language.

Garbage Collection in JVMGarbage collection is a good way to free programmers from the burden of having toexplicitly free the allocated memory. On execution, a Java program creates and usesdifferent objects, Each object within a program uses some amount of systemresources, such as the system memory during the run time. Garbage collection is theprocess 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 bedeleted. The space that ¡s used by the object is released for use by another objects. Inthis way, garbage collection serves as a mode for memory recycling where the spaceoccupied by one object is recycled so that it is made available for subsequent newobjects.

The garbage collection feature implies that the new objects are created and all theunreferenced objects are deallocated from the memory. The different approaches usedfor 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 withina 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 byone. When a reference to an object goes out of scope or is assigned a new value, thereference count of the object is decremented.

An object that has a reference count of zero is not referenced in a program and is agarbage object. When the object is identified as garbage, the reference count of all theobjects that it refers to is decremented. Therefore, garbage collection of one objectcan lead to creation of more garbage objects.

The garbage collection method can be executed in small parts within a program andthe program need not be interrupted for a long time. An overhead occurs wheneverthe counters are incremented or decremented.

:;::ffi|ww"é"{..& 3 ;.2 "¿ ia F u¿ t' *A n tat * t zY ¡zÍ *

Page 123: Java Fundamentals - Part I

Tracing Collectors

In this technique, a set of roots is defined from the location where the objects aretraced. An object is reachable if there are objects that reference it, The objects thatare not reachable are considered garbage objects since they are not referenced andare not accessed within a program. The tracing collectors mark the objects that arereachable. 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 phasemarks all the referenced objects. The sweep phase garbage collects the unreferencedobjects.

Compacting Collectors

Compacting collectors reduce the fragmentation of memory by moving all the freespace to one side during garbage collection. The free memory is then available to beused by other objects. All references to the shifted objects are then updated to referto the new memory locations.

Setting the CLASSPATHThe CLASSPATH environment variable instructs the IVM class loader to find the classesthat are directly or indirectly invoked, including the system classes. CLASSPATH is theenvironment variable, which shows the Java compiler, javac.exe, the location wherethe 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 bysetting the CLASSPATH environment variable. The -classpath option is used whenthe SDK tools are called, such as java, javac, and javadoc. The following syntax showshow 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 environmentvariable:C: ) set CLASSPAfH=<classpathl>;<classpath2>. . .

In the preceding syntax, semi-colons separate the multiple entries in classpath. Theclasspath variable finds the path where the class files are stored while compiling theJava program using the javac compiler.

The class files or classes can be stored either in directories or in archive files. Thesyntax 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 bankclass, the JVM uses the classpath settings to determine the location of the packageand class.

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

Page 124: Java Fundamentals - Part I

If the class required is stored in a jar or zip archive file, you need to specify the nameof 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.baalThe 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 FileThe Java class file contains the Java Bytecode. The class files are platformindependent therefore you can run a Java program by loading the class file on anysystem with the Java Runtime Environment (JRE). The following command shows howto view the contents of a class file:javap -c (class_filenane)

The lavap command prints the instructions that consist of the Java bytecode, for eachof the methods in a class.

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

Page 125: Java Fundamentals - Part I

i

Fno¡¡ THE Expent's Drsx

Best Practices

Declaring Class Variables as private and Methods aspublic

You should declare all the class variables as private because data should alwaysremain hidden from the objects of other classes. Methods should be declared as publicbecause 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, suchas 45 to 90 but it is more efficient to begin arrays with an element 0 because it takesup 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 toelement 90, the compiler will still allocate the memory to the array starting fromelements 0 to array element 44.

Declaring Class Variables

You can follow Hungarian notation to declare variables in lava. The conventionsfollowed in the Hungarian notation are:

W The first letter of the variable should indicate the data type used. you can usethe letters, i, f, and b to indicate an integer, float, or a boolean variable. Forexample, iAge, fPrice, and bResult.

w The variable name should be meaningful. For example, iAge is an integervariable to store the age of a student.

W In case the variable name consists of multiple words, the first letter of eachword 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 theSystem.out.printlnO method in Java. The drawstrinSO method requires three

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

Page 126: Java Fundamentals - Part I

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

Setting CLASSPATH

cLAsspATH is an environment variable that enables the Java compiler javac.exe tolocate class files to be imported. You can use the sET cr,AssPArs= to set thecLAsspATH variable. The following syntax shows how to set crassPAr¡¡ in Java:

SET CLASSPATH= g ; \j2sdk1. 4. 1_02\bin

W

ffi

FAQs

"É.{:.'&".

Why is Java considered ideal for network communication?

Java is considered ideal for network communication because it is a platformindependent language. Java enables an application to be executed on anynetwork. The built-in classes of Java support TCP/IP and UDP protocols used fornetwork communication. Java suppotts the Client-Server model for networkcommunication,

What will happen if the data type of a variable and the value assigned to thevariable are different?

If the data type of a variable and the value assigned to the variable are differentthen compilation error occurs. If an integer variable is assigned a charactervalue, the ASCil value of the assigned character is displayed as an output. Thefollowing code shows assigning a character value to an integer variable.

^l:ca .lál- :f \/ñaf

n"l-.] i¡ ef af i^ rr¡id m¡in lQf rinc ¡ [l lyuvrru

{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 errormessage is displayed. The following code shows assigning a double value to a

character variable:class datatype{nrrl-'l i¡ cl- ¡l- i¡ r¡nid main lSr rino : ll lyqvrre

{

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

j A v m E, * rZ # m {:r:É q.Í r.24;.#l # #"jW{gE

Page 127: Java Fundamentals - Part I

w

w

I

!

t

i

Java is a strongly typed language and it allows the values of the spec¡fic datatypes, which are compatible with the type of variable.

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 usesome other data type, such as int, you need to convert the value to string.

can two variables have the same letters but different capitatization, as invariableName and VariableName?

No, Java is a case-sensitive language. It differentiates the two variables,variableName and VariableName.

L-

2.ü"',#

Page 128: Java Fundamentals - Part I

2. Match the following:

a. Variablesb. Literalsc. Keywords

i. Reseryed wordsii. Basic storage unitiii. Sequence of characters

3. Make words from the jumbled letters in the box given below and match themwith their description,

a. Class members that can be accessed by the subclasses of the class inwhich they are declared.

b. Class members that are accessible to all the classes of a package bydefault.

c. Class members that can be accessed only by the objects of the sameclass.

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

Page 129: Java Fundamentals - Part I

WLesseN 2trExpeRETcENT

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

Page 130: Java Fundamentals - Part I

.1-4".;í.nli#rr",:1.*{."t"4{,1;prtí*1,:i

Page 131: Java Fundamentals - Part I

WExercise 1ServeYourMoney bank offers sevices to its various customerc. The bank has variousbranches all over the country and therefore each of the branches has a unique id. Thebank 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óusdetails of its employegs, guch as employee name, employee id, address, phonenumber, and e-mail id. The bank offers its customers with a choice of aécbunts, suchas savings and current acount. Ask the students to identify the various classes andtheir attributes.

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

Exercise 3Write a program to display the name, address, and position of three applicants usingarrays. 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

Page 132: Java Fundamentals - Part I

2.

4.

5.

6.

1. Which of the following is correct extension of a lava file?

a. .javb. .javac. .IAVAd. .class

The lava compiler reads the Java source file and converts it to a file having an

extension:

a. . classb. .javac. .prgd. ,file

JVM stands for:

a. lava Virtual Machineb. Java Virtual Modelc. lava Virtual Mechanismd. Java Virtual MethodologY

JIT stands for:

a. Java In Timeb. lust In Timec. Java Is Testedd. Java Is Time saving

What is the maximum number of dimensions an array can accept:

a. 266b. 255c. 256d. 2s0

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

Page 133: Java Fundamentals - Part I

7.

C. CLASS Employee{

String employeeName;int employeelD;String employeeDes ignation ;

l

d-c1ass Employee details{

String employeeName,.int empfoyeelDtString employeeDesignation ;

iIdentify the correct code sn¡ppet to declare the main O method :

€|- public void static main(String[] args){// Code for maino nethodl

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 methodl

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.

Which of the following is the default access specif¡er in Java?a. publ¡cb. privatec. friendlyd. protected

8.

9.

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

Page 134: Java Fundamentals - Part I

10. Which of the following is a type of permitted modifier:

a. publicb. staticc. privated. protected

3 m"¿ w W ** rzúwr*wrs%mfr w

Page 135: Java Fundamentals - Part I

www.niitstudent.com