$ludent 0uide

ililT

Java Fundamentals

Student Guide

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

Information in this document is subject to change by NIIT without not¡ce. The names of companies, products, people, characters, and/or data mentioned herein are fictit¡ous and are in no way intended to represent any
real individual, company, entity, services, product or event, unless othenyise noted, All products are registered trademarks of their respective organ¡zaüons. All software is used for educational purposes only,

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

N
e..l

at

O é
q)

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

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

I

*:-=---_l .Counse Desreru From the Experts Desk Sotrtbns to Challenge Exerci*s) .

..............7 .......'....'.......... 1C...1c..........13 ..1C............ Methods Desk.3 . leq¡añ3qEs of Object-Oriented Programming.. l-gcslaLjon ¡us?c€fl :nrrúeftsrrae"...............'................. by ü"csÉon ü.Introduction to Object-Oriented Programming for Object-Oriented Prcgramming H--r-.Table of Contents Cycle 1 ..' 1A.18..... Cesses ancj Inheritence......15 -:rry iesson 18 ...1A.tÉd Analysis rruÉ?c { IC ..12 3nrcs arrd Objects l..18.....1A....F.'.'.. 1A'10 @mifr'.. 14.'........'.....'... '.3 ......' 18..... 1C'6 '...........lO .....5 ..'.....1A.......3 .'.'.... 1C'9 -rrc I I mf¡...12 .'...4 .... o?úilrirrrgr:rls¡n.....10 .........g the Applications of Object-Oriented Programming. 1C..ConcePt of OOPS F:¡h¡es d Object-Oriented Programming. F...rn tt= Erperfs qh.'. 18..18..........Fr<?€r.. 18..'... 1A.e..... 1C.7 OliEü (}bnted Programming.........3 ...3 ..... ..4 OOPS with Procedural Programming.'..Collaborate of .aror-s ..14 müpre....ng '...... . and Design -}.-esson 1A ..

.10 24...........17 28'19 ...........2A.24....13 ..13 ..24......'.. 28..".'28'IL ....'...3 ..18 .19 ".......'.............. Declaring Variables and Literals Using Various Data Types Defining Variables and Uterals.'28'7 ...'. Demonstration: Crcating a Java Application Problem Statement Solution...........3 .'.'.........'...28................2C..... Java....2C.... Architecture......'24'24 .. Manipulating Variables...' '.....'.28...8 ............""......... Soecifiers....."............'2C."'.....................5 '.'.2A.... Modifiers.......21 '..3 .......'......""""'.. Setting the CLASSPATII .Cycle 2 Lesson 2A Java Programming Need for Java Java Architecture Arrays...3 .... 2B'tL .......... .'......16 ". Arrays.......'.....19 ....9 Access Specifiers and Compifing an Application..Collaborate Byte.28....'...........................'.....'................3 ...24. ' 2A....28.......24. ..Classes and Objects Modifiers...3 .. Security.......2A..............28...14 Summary Lesson 2C Knowledge ....'.2A...............2C'4 "... - Introduction to Java .. Summary Using Arrays Accessing Language..2A..........2t .25 Structure of Java Application Creating Classes and Objects Adding Methods to a Class Defining Constructors Access Types of Permitted Lesson 28 .....'.28...'.. .28'21 Evolution and Need for Java Garbage Collection in JVM.......

I ! i i l .

AeeurTp*xs Cet*nse .

advantages of OOPs. Abstraction. ü Declare and work with variables.PnOUOGUE Description -1is course. Threads and exception handling. -'re course consists of three sub modules: 1.\i:. application of OOPs. Inheritance. Developing Object Based Applications in Java. 2. and modifiers. This sub module also deals with the basics of Java programm¡ng anguage such as variables. literals.lava. access specifiers. Imolement the d¡fferent conditional statements and looping statements' . ü Create classes and objects and add methods to a class' I I ldentify the various types of access specifiers. and polymorphism. literals.<ills: ft Fundamentals of Programming. . and concept of classes and objects' It cescribei the various features of OOPs: Encapsulation. Java Fundamentals. Applets. such as packages and streams. 3. focuses on the features of :-e Object-briented Prógramming (OOP). Objectives dfter completing this sub module. and arrays. Java Fundamentals Programming in Java Packages and Streams In this book. is covered' This sub module :rovides an introduction to the Object-Oriented Programming System (OOPs). This course begins with basic concepts of fOp añd then moves orito prográmming in Java language and advanced concepts of . students will be able to: I Describe the concept and features of object-oriented programming. The code reuiability feature oÍ :ava enables the software developers to upgrade the existing applications without re-rewriting the entire code of the application' Prerequisites -le students undergoing this sub module are recommended to have the following . the first sub module. Rationale java is an Object-oriented language that enables you to create real world applications.

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

which leads to new concrete co"c|Lrs'torT.IIT'.Methodologies. would learning architecture. provide the 'or the design of a new methodology' .Learner's personal involvement through concrete exPeriences Reflective observation.(RO) meaning - Learner reflects on experience and looks for logical Active exoerimentation. experiential learning involves four principal stages: ü concrete exoeriences.IAE) . expefinrents with similar exoerience Abstract conceotualization. the above interactions.havemainlyfocusedonthefirstmodeof of -te¡-action. almost all teaching-learning interactions/modes can be classified M .. The last two'or these possible modes. which can suitably integrate all of the above most challenging task sltuated cognition and collaborative constructivism. in situations.Learner experiments with similar a.oblems. :eideal. where the teaCher or external resource creates Or cOnstructS collaboration with the learners' learning.inthepast.s breakthrough LACC methodology builds in learning components that enable all :. to address the various stages of experiential learning and :atering to multiple learner types. where the teacher or external resource Creates the learning exDerience the Interactions. which leads to new concrete exper¡ence . which encompass the theory Stages in ExPeriential Learning l::crding to David A Kolb*.(AC't .(cE) .MernoDolocY Learning Architecture Based on collaborative Constructivism (LACC) Introduction :-e following: as one of 3-oadly. where the learners create their own learning experiences modes. x lry Interactions.Learner applies this meaning to form a problems.

W Converoers or the precision learners and W Accommodators or the dynamic learners' the NIIT's LACC methodology has Learning ComponenG. These two sessions are meant to through proviáe the required foundation for the student to be able to move to the w subsequent stages of learning.instructor who is a This component matter expert is required to lead the students subject intróduces the learner to new concepts and thereby constructing his/her learner knowledge base. learner coLLABoMTE: The next learning component makes it possible for the collaborative learning. Here to have contextual familiarity on the subject through *whzry . that are oriented towards all possible four stages of experieníiil tearning and hence is highly suitable to types/profiles of lea rners' Learning ComPonents NIIT's IACC methodology has the following learning components: An ffi CONSTRUCT: The learning begins with this component'here. The instructor brings in concrete experiences for the éxplanations and demonstrations. 'ffi Assimilators or the analytic learners.Learner TYPes styles are The cElAC and AEIRO dimensions are polar opposites as far as learning preference of an individual's learning styles/stages' concerned and depending on the four distinct types of leamers are possible' Divergers Accomodators Convergers Assim¡lators ffi Diveroers or the imaginative learners.

Adeouate Environment: To execute components like COLLABOMTE and APPLY ireference reading and ISAS) crIn . The tools used to provide such learning are project. scenario/problem statements and best practices to reflect on the concepts learnt in the previous sessions and apply his/her understanding in the larger context. Here the learner learns. The learner is provided with a rich choice of tools like case studies. the learner is exposed to active experimentation.I I the learner is provided with a mentor/direction/ and stimulus for reflective observation. EXPERIMENT: Here. refers. thinks and applies their entire knowledge spectrum and create solutions for a real life case study. The learner experiments his/her understanding of the concepts and observations to form a logical conclusion leading to better learning effectiveness and experience. information search and analysis skills (ISAS) and reference reading (RR). EXPERIMENT and APPLY (Projects) are executed in such a resource. APPLY: This learning component provides the environment for learners to develop conceptual clarity. compares. Required Resources -rs -ethodology requires the following resources for delivery: t I Online Classroom: Room having networked computer nodes for all students: Leaming Components like CONSTRUCT.

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

tt Beginning of a new concept -&p - - Additional information Tips and tricks ür _ -irrrtér Programming code -s¡: F Arial font Programming syntax . Construct. Demonstration k t: -.ConvrilTroHs 1 and k.

options present in dialog boxes. & i. r*e.9 . and keystrokes From the Expert's Desk W ''!l*!..'.Italicized text Introduction of a new term Bold faced text Menu options. : " ¡:. Th¡s "l¡^.t.

niitstudent.s t.lo O.3 . tr* rá r"¡t" v¿ E# 2"&".lt¿ .com to enhance your learning experience '-l 3nw a {l ryn 4 *. you will learn to: Apprec¡ate the need for object-oriented programming Compare OOPS with procedural programming identify the advantages of object-oriented programming identify the applications of object-oriented programming Identify classes and objects Visit the student website at www.: Lessoru 1A InrnoDucrloru T0 Oa¡ECTLrlrJ OnTENTET} PnOERAMMTNG Obiectlves s lesson.7"\ "J i.

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

The program has a function. .*-.. comprex software systems. EmployeeDetails.:--a< ngin procedural programmingdata from and accessible throughout the ¡t easy to manipulate the ' anywhere in the pro{ram.i.:::=_ This made program development a complex task.::i ..¡J z¿.. there are ways to ensure that this ::: ^ct become a stumbring brock to the smooth functioninq of the .as too simple and proved insufficient for programming comprex ..:-. such as Railway Reservation by using the .-:. procedurar programmrng =:: l'ientedr¡.i¡ il. the need of the hour is to develop simple and speedy l:..F *: :"" N==o FoR 0e:=cr-OnreruTED Pnoe RAMMING : -::: : . arthough :' :': software system is a reality.trascal and BASIC (Beginner's All purpose symbolic Instruction code). printDetails.-..'q * r z g. difficult to :'?-i :-: 'rom another. * -' :-' 3 result.rams written h. If you want to print the details -a: : ' ==s cf a different organization. coded in procedural language :-::: :-e details of employees of a bank.. A :-Jgram contains the instructional steps that are performed to carrv out ll|r r :] '.^i^^ l--^r:mc by using !L^ procedurar programming approaéh consist the -.:e instantly svp.. therefore. e world. entire function has - : -.-r. These interdependent functions cannot n" reusáJ ¡n oif. This function can be called : -=' "3m different parts of the same program. This nas resulted In tr '!'r applied Lv vqr rcu ELlurr errenLS. Programming (oop) came into effect. even for a similar task across programs.. All --v -^guages lack support for OOp. This 'ying this complexity is to split the software system into its is váry simirar tne way :-: oyees of an organization can be grouped according to thetofunctions --J then arranged In a hierarchy.r*. : 'ou nave a program.rifla^ :-:. n.¿ &'¡¡ í¿ 3i a ¿ r ¡.-^--r -:: ons. These functions can be executed anywhere within the program. the . ' : -: es of procedural languages are coBol (common Business oriented . '::: :ata is visible *:-:.r q..-:s and arrange the parts in a hierarchy.. -"'l: : : :-at prlnts the details of each bank employée. then you have to recode it in another program. However. :::: . r nrs has in the -:-:^: and sometimes.. : : -= coBoL was used primarily for documentation and data handlinq.1 -.":: :-! :f a procedural program are interdependent and.rsu to varied Irequirements.

subroutines. o. These modules can defined or can be taken from are also A module can cons¡st of single or multiple procedures. programmer to Thus.¿r on tr'" ¿er¡nit¡án. also have functions to employees of any orgañization.app|icatio.ct. Eacn prográr*ing meihodology coñsists of its own features that various ap-plications. In OOP. OOP also offers some bu¡it-¡n libraries' These can be used by all programs' A major á rEt-oioO¡"cts and pre-defined functions and effort required to advantage of OOP is the reusability of code because it saves the defined in libraries' rewrite the same code for every program using the functions Compaiing OOPS with Procedural Programming YoucanuseVar¡ousprogrammingmethodo|ogiestocreatean.oP combines into a single entity called an obje. Any program can reuse this Employee object. These.procedures or methods in various programming known as functions.4 3 mw a zxruúm{**r2t. of For example.. defined independently or within another procedure. objects can defined data and instructions libraries consist of be placed in libraries.nora can be program.r is divided ¡nto óne orlibraries' or modules. objects can be reused across various programs. routinei.erffi W . in ooPS you can have an Employee object that Employee object_can.r: WTl . languages. Tñe commonly used programming used for creating methodologies include : ffi W Procedural Programm¡ng Object-oriented programming (OOP) Procedural Programm¡ng program ¡nto a se The procedural programming methodology involves dividing a large perform specific tasks' In this methodology' i of subprocedures or subprograms that be usermore units órog. The same printiñ"ru emptóyeá details.op"r.of the objectThe limitations of the procedural programming led to the evolution the prográm is broken into independent chunks known as oriented approach. This enables a deveiop án application in a relatively shorter durat¡on' userooP enables you to consider a real-world entity as an object. The procédure data within the procedure that has lower or inner scope' . of a higher or outer scope cannot access thr various levels or r. !"k. In OOP objects.Aprocedurecanbe the procedure . . Aprocedura|programcanconsistofmu|tip|e|eve|sorScopes. Similarly. The level of the data available in the procedure also exhibit ¡ó. w'nicn can be integrated to create a complete program' keeps the details.

a =:'example.'de the program into subprograms. in a program that needs to accept. In a program following procedural methodology./t. Display Data. to read program code 3 É. -- s enables you to reuse the program code as and when required in a program. :-:.: srocedure or a subprogram is a set of commands that can be executed -¡ependently. respectively.:edural programming is used for developing simple applications. and print data.¿ qr T i. you can use a subprogram at multiple locations within a :-:gram to perform a specific task. You can create three subprograms that accept :=:a.*|ttw p nt *:.+B Frir¡t Valus trf A Print Value {rf g trrccedure 3 {Print Data) Print ValÍ3 nf Proced u ra I P rog ra m m i C ng *-e preceding figure displays a program that consists of three procedures/ Accept )=:a."'*. display data. -::-':: cí rhe benefits of the procedural programming methodology are: Easy . Data is accepted in the Accept Data procedure.. display. as shown in the following figure: Variable A Variable B Variable C Procedure 1 (Accept Data) Accept Valre nf A Accept value of g Frccedure 2 (Display Data) aisplay value of A Oisplay vól$e of g C=4.{. Each subprogram performs a defined '--ction while the combined action of subprograms makes a complete program. The languages :-:: *se the procedural programming methodology include Pascal and C languages. you can : . . and print data.¿ !:r. ¡':hout rewriting the entire code. and printed in the Print Data procedure. and Print Data. : s: ayed in the Display Data procedure. -- procedural programming. each step of -i-rcrogram is linked to the previous step.

The salary is calculated on the basis of the base salary of an employee..::: h&"ffi Saww W*xsn&m*r*effiqffi&% {#tW . and dearness and housing allowance.éiéia:. Smith. number of leaves taken by the employee in excess to the leaves allowed in a month. In the procedural programming approach. SelveYourMoney bank needs to calculate the salaries of its employees.é. a change in the application results in rewriting a large poftion of the code.. This was one of the reasons that led tothe evolution of the object-oriented approach' Object-oriented Prog ram m¡ ng A large application consists of component objects. such as regular.ii:i:?1":i. This results in decreased productivity and increased maintenance cost of the application. When you need to reuse the procedural program in another application. This code is reused for employees at all levels.li¡. For example. develops a code to calculate the employees'salaries by using an object-oriented programming language.'ffi W Easy maintainable program code as various procedures can be debugged in isolation Code is more flexible as you can change a specific procedure that gets implemented across the program The features of procedural programming methodology are: W W Large programs are divided into smaller programs. These components can be used to develop various applications. a programmer.i.ij'. For example. You need to create a separate module to calculate the salary of the employees in an educational institute. contract. The organization consists of various types of employees. i.. the module used to calculate the salary of the employees in a bank management system cannot be used to calculate the salary of the employees in an educational institute. This is referred to as the object-oriented approach to develop an appl¡cat¡on. and waged.. portions of the code are so interdependent that the code in one application cannot be reused in another.. Reusability of code enables Smith to use the same code for employees at all levels. which interact with each other.-!á. Most of the data is shared as global that can be accessed from anywhere within the program.

The concept can be explained by using the following analogy' processes.As discussed earlier. Some of the advantages of objectcriented programming include: objects COp emulates the real world in a software system.7 '¡ I I T . you create a basic structure of a program and the functionality of the program as per the requirements.wruz*qztw\w 3"p. The automated sales system is the first process to be a axlw Tnwm ffiumd.extend the entire keep establishment. which can be used by several applicatiois. object-oriented programming enables you to reuse various time. you build classes. Similarly in OOP. Reqsability of code not only saves ¡t¡t also the effoft of the programming team' i Advantages of Object-Oriented Programming ürat can be categorized in different classes. The real world consists of I I I f I Real-world programming Reusability of code Modularity of code Resilience to change Information hiding Real World Programming structure' Over a Consider the scenario to setup a business establishment w¡th a basic period of time. connponents of a program across programs. procedural aPProach' ReusabilitY of Code In the object-oriented approach. the As a strategic intervention of revamping their existing products and *unag"ru-nt of BeautylnFitness has det¡ded to automate their existing systems using staggered approach. The objectextending oriented ápproach models the reai world more accurately than the conventional.. you keep acoing the various objects required to.

including the payroll division of the Personnel department. In addition to the regular employees. salaries.implemented. the automated system needs to keep track of employees. You can make modifications in the required object without affecting the functionality of other objects. one of the most common entities is the employee of the organization. The employee component of the sales automation system can be used to track the details of the employees across depaftments. to store the details of the contract employees. the programmer can extend the functionality of the existing employee component and make the desired changes in the existing component. In this scenario. After integrating all the modules. Modularity of Code Another advantage of object-oriented programming is its modularity. In addition. the programmer can reuse the existing components. In the existing automated system. the system again requires the employee component. and wages of the employees. the programmer need not recreate the entire component again. 3"&"& Smwn Tuaszúwrn*mtaTw r#Jw&w . The system enables the management to analyze the sales data and build strategies for the products. All these objects are independent of each other and are maintained separately. However. Over a period of time. the programmer has already created a component that stores the details of an employee. which in turn results in cost effectiveness. the Personnel department needs to keep track of the contract employees who join the organization temporarily for a specific period. The benefit of reusability translates to savings in time and effort. the various modules to be added for the system must take care of the finance and Personnel depaftments. a consolidated system can be created that has various components reused across the modules. Therefore. The finance department needs to make payments against various payouts. In this module too. In addition. the management decides to extend the functionality of the automated system to the purchase department. the automated system also tracks salesperson-wise data to provide incentives to the high performers. but also reduces the chances of introduction of errors in various modules. The reuse of the components once created not only reduces the effott of recreating the components. To store the employee details. employee and contract employees. such as. In the Personnel department. It means that an object can be maintained independently of other objects.

GUI can be programmed using object-oriented programming methodology. GUI is a method of interacting with a computer by directly manipulating graphical images in addition to text. such as business management. These applications can be Character User Interface (CUI) or Graphical User Interface (GUI) Character User Interface (CUI) based Applications CUI is an interface used to interact with a computer. Identifying the Applications of Object-Oriented Programming Object-oriented programming has applications in several domains. which uses various objects. C++ for GUI Applications C++ is an OOP language that enables you to create GUI applications. In a GUl-based program. The hardware simulations for Personal Digital Assistant (PDA) tools are also peformed by using C++. such as size and position. home computing. and accounts management. such as Microsoft Windows and Linux. which inform the system that an event has occurred. Object-oriented programming hides the data and processing methods. For example. inventory control. An object represents each element of the GUL IT determines the attributes and the behavior of each element of GUI. C++ is used to develop banking software. or pulling down a menu. h#". A user working on CUI needs to type commands on the command-line to interact with the computer Input commands can be long and complex. A window of GUI has various attributes. various events take place by clicking a button on the screen/ moving the mouse.site| %l il.#"{3 3 ry"w'e W w {z *e YYz ry. CUI is not user-friendly because a user needs to remember all the commands and the syntax of the commands. Various applications are written to run in graphical user environments.application authenticates your login ID and provides the access is completely hidden from you. Graphical User Interface (GUI) based Applications Errors induced due to typing long commands often discourage the user and affect the productivity and efficiency of the user.1' Ltt . and payroll systems. The objects communicate with each other by sending messages to each other. The most common examples of CUl-based applications are DOS and UNIX. An object receiving a message responds to the message sent by another object by executing one of its pre-defined functions.

For example, if a user closes a window, object-oriented programming system sends a

message to the window that executes an algorithm to remove the image on the
screen.

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

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

environment.

In a hypothetical adventure game, the player controls a character around a fantasy world and fights creatures, collects treasure, and so on'
Position Class

Main Class

It*m

Clasx

Treasure Class

Key Class

Class Hierarchy for a Hypothet¡cal Adventure Game

a

xtzv

3 r¡qr

n

ffi z*vz

úm nz

q.

vckmtw

h&^.3.3.

3

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

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

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

W

State: The state of an object is indicated by a set of attributes and the values of these attributes. For example, when you design an online shopping site for books, each book, which is an object in the program, has its size, number of pages/ type of binding, and its shipping details.
Behavior: The behavior of an object refers to a change of its state over a period of time. For example, in the online shopping site, when you place an order for a book, the status of the book might change from available to sold out. The changed state of a book is its behavior. has a unique identity. For example, multiple books consist of the same size, number of pages, type of binding, and shipping details. However, each book has its distinct identity, for example the book number. The book number identifies a book among other books.

W

W ldentity: Each object has a unique identity, iust as each person

An object is an instance of a class. A class in object-oriented methodology is a collection of various attributes, such as data and methods. You can access the data of a class by using its methods. Consider a pay phone where you put in a coin and then dial the number that you want to call. The pay phone exhibits a certain kind of behavior, that is, when you drop a coin and dial a number, it connects you to the person you want to talk to at the other end of the line. The order in which the operations are carried out is important, The pay phone behaves in this manner because of the existence of a state. One state of the

:::

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

¿:r¡;ii:

;::

¡:

:,,

i, ¿ ;;

;

¿::; ¿ L

r::

:::i::::: ,:::::::::.: :

:

aaa

a:a,a,

a,

a;.;t.;t ,:.',:..

:::::..:,:t.a:a:

ft"&"3"X

kwwm W*urz&nrm*mtm&u

.

it;:Wi"tV 1 A4& 4

flme b üat a cailer ¡nserts a coin but the number is not diared and in the other ! ¡ a¡frr b inserted as welt as the numbei i, ¿iul"¿.
stab af.d behavior together, comprise.the properties of object. For exampre, pPqgtt_y of the object pay phone could be ihe amount or-an monáy or the number of s b be lnserted.
Boodr, the famous author who has written many books on oops has defined a ty as:
úrg an object uniquely that object."

iilrercnt or distinct characteristic, trait, quatity or feature that contributes to
do not exist in isoration. They interact with other objects and react to these ons. These interactions take place through messages. Grady Booch has behavior as:

r

is how an object acts and reacts, in terms

of

its state changes and message

ilentity of an object distinguishes it from ail other objects. In the case of the pay rc' 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 but have the same identity, The identity-of ou¡e.f n"u"i .nunges in its H..

"n

al people have described techniques for identifying crasses. According to one of -of . rh e n, yo u [ijl?, : :"^:t :.1,: _q" T s rl, h d e,scri ptío.n iñ the nou

ns. The "r""il'::nou ns rep reselicu nái¿-ái"'.lurr"r.

;;d ñ

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

r r
I

I I

Counter
Salesperson

Product Customer Payment

F The following figure shows the Customer class and its objects: Classes and Objeds .

object-oriented approach. Modularity. The areas of gngtic_atjon of the object-oriented programming include Games. classes are designed such that they can be reused. Various programming methodologies that can be used are: o o Procedural programming Object-oriented programming The procedural programming methodology involves dividing a large program into a set of subprocedures or subprograms that perform specific tasks.In this lesson. 9Ujgct oriented programming offers features such as Reusability. you learned: r I r r I r r f An object is a software package consisting of variables and methods. An object is defined as an instance of a class. cul. and CAD/CAM-based programs. and Information hiding. In the. Java Frmdam€Htals .The-procedural programming methodology allows code reusability in large applications. Resilence. GUI.

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

you will |earn to: d Identify the features of object-oriented programming t t t E Encapsulation Abstraction Inheritance Polymorphism Sava Fumdam*ntx|'* .t'.'t t xhesselu SB CEPT oF OOPS üús lesson.

ni.i!+.qE ffiÑFÉlt::..1:#WÉpéi¿ñ..a:++#z#:w#ffiñ)F.¿.ffiw!)e-xffiffiffi LW"2 Sawa Ywnúamentals &tWffi .

& 4n 3-{A." object are hidden from the =-:apsulation implies that the non-essential details of an -s:: and an access is provided to its essential details. when you plug in the cord of a vacuum cleaner :-: switch it on. a famous authorwho has written many books on OOPS has defined the :apsulation feature as: =- 'l^. age.t^+i^^ = . ..ll .vorking principle of a vacuum cleaner to convert electricity into suction power. -. The user only needs to know -:¡.t :: Enca osu lation Abstraction Inheritance Polymorphism Encapsulation !':cy f ¿vr. An end-user need not know :-: ...+-'-:-. to play the game.ob¡ect-oriented methodology. ".v 1. The complexity of an object is hidden as a result of . Objects are the basic : -=. human beings have state. dancing. For example. I I pS consists of the followinq features: ': c.p. and height and behaviorsuch as walking.dPSuloLlUll.. .. The real world objects '-:l .1{ I. However.. Forexample..e two characteristics: state and behavior.r. --: switch of the vacuum cleaner encapsulates the complex process of conversion of =::tricity into suction power. encapsulation is also :: ed information hiding. s3r.. l:rr puter games also use the feature of encapsulation. Therefore. - cing block of Object-Oriented Programming System (OOPS). the vacuum cleaner starts functioning..capsulation is the process of hiding all of the details of an obiect that do not :: ^:ribute to its essential characteristics. need of encapsulation arises because the emphasis :^ designing classes in such a manner that the classes share data and methods is 3 n'¿ a V s¿ rz qJ ffi rv:¿ r* nf. the complex working of game is hidden from the . color.. as name.i"i'') Booch.::ctng. and All the objects in OOPS are based on real world having a specific state and : =-avior.+ í i.^^^^.:} .-' ¡J \ 1 i FeRruREs oF Oe:ecr-OnrrNTED PnocnnMMING -:_ect-Oriented Programming (OOP) is used to build OOPS.t o{/ '.

and cassettes. +. The backend transaction process is encapsulated. you use objects of various items. such as books. access is denied.&&& ^6 . while developing an online shopping site for books. Accessing an ATM Machine Abstraction (eUs\recr." it Abstraction refers to the attributes of an object that clearly demarcates it from other objects. compact disks (CDs). Encapsulation is the feature that provides security to the data and the methods of a class. An Anytime money(ATM) that you use to withdraw money also has an encapsulated function. and subject. a book has page numbers. All these objects have a well-defined set of attributes that distinguish these objects from each other.:.:. However.. If the pin code is correct. You inseft an ATM card in the machine and provide the pin code' The only access that you have to the ATM is to provide the pin code for your account and not to the process of validating the password. if you try to access another account. d ¡ ró aá ^ 3"W"& 3m qá x W a* {e * mr. . type of binding. as you are not authorized to access any account other than your account.::.. For example.:a*) Grady Booch defined the abstraction feature as: "An Abstraction denotes the essential characteristics of an object that distinguishes from all other kinds of objects and thus provides crisply defined conceptual boundaries.r among themselves. For example.^ n d¡n-¡é ü9 t9:ee!!::r:i n. In addition. relative to the perspective of the viewer.\z * {*te& # #tW*WW 'w ffi. ::::7. you can make the desired transaction..

"J 1'.r .. such as audio or visual. acuum cleaner. which have memory allocated as soon as it is created..:r ¡'r. You do not read. the program provides a restricted access to the user's account.1:i I 1^. This is implemented by ::s:raction. and gender. ignoring the non-essential details -::. like switching on and off the washing --:1¡ne are the only details relevant for the user to know.!ork. abstraction enables you to :-rr. You create a class that inherits the attributes and behavior of class. larly. For example. For example.l üf"i:. i":. -:.-:ther existing class. the operation of a washing machine is hidden or =-:apsulated from the user. =:: example. when you want to send e-mail messages/ you should know the processes of ng e-mail messages and sending it to the receiver. To store data. date of birth.object-oriented methodology. :. inheritance enables you to extend the functionality of :- . Rest of the working of the washing machine is encapsulated from the -s:-. You will not concentrate on the advertisements of other products. such :s .I : _:D has type of media. -. '" ' '' . understand. and air conditioner. Classes form the :=-rplates for creating objects. duration. :-: respond to all of these because these are not of your interest. washing machine. I n heritance l tr*. attributes -:'3r to the data and behavior refers to the methods. However.ide a restricted access to data. and storage capacity of the --e concept of abstraction is implemented in object-oriented programming by creating : isses.ever/ you cannot store any data in a class because creating a class does not : :cate any memory space to the class.'¿¡ t'í'4 "¿i t"r"/. -. abstraction means :':'r object and concentrating on its essential details. Encapsulation hides :-: irrelevant details of an object and abstraction makes only the relevant details of :. who in addition to characteristics of . you need to create objects of :-: class.rbject visible. You can extend :-e functions of the student class to a day scholar. Instead. All the attributes of the objects of the classes are defined in the class. you will concentrate on the advertisements featuring -:'igerators. trt tr ti I lr.. you also use the encapsulation feature.gr¡''il. In terms of classes and objects. it is not necessary :-'/ou to know the entire process of sending the e-mail messages across the -: - -: nplement abstraction.. you ::-centrate only on messages that are of your specific interest. The details.L'¿t rJ. In addition.:cject-oriented programming. if you .:ddition to the well-defined characteristics of an object.i'ir'.'. :-: user is not required to know the entire process of a transaction and how the data s:cred. you might have the Student class that consists of the basic :-aracteristics of students. As discussed earlier.. the new class can consist of a few new attributes and ::-aviors that are specific to the class. You come across hundreds of advertising --sssages every day through magazines or newspapers.. ) -.7 a v a¡ ? e. However.a-t to buy a refrigerator.:7r. in an ATM. such as name.

Confirmed and Requested. such as locker number and residential address. time. Both types of air tickets inherit these common attributes. The Confirmed ticket will however have a seat number while a Requested ticket will have a status attribute. such as flight number. date. an Air ticket can be of two types. and destination. Superclass and Subclass In inheritanc e.r"- the Student class contains its own features. Inheritance also enables you to share data and methods among multiple classes. Asubclass or child class is a class that inherits attributes and behavior from a superclass. For example. . a superclass or parentclass is the one from which another class inherits attributes and behavior. The following figure shows the concept of superclass and subclass: FligkNualer Date Attribtáes: Tihe Dectin*ion ctass: Requested T¡cket lnherhed áttrlbstes: Slightl{umber Date Inherited AttributBE: FligbtNumber Date Time Destination Tim* Destinaúisx Superclass and Subclass 9W"ffi Swzaw ffiatm&mrrt*mYe\s ffi:W. It also has various attributes. Inheritance enables you to add new features and functionality to an existing class without modifying the existing class.

implement inheritance in object-oriented programming. various relationships exist the various classes of the program.has the following characteristics : I I - A subclass is a specialized form of the superclass. objects peform actions in response to messages from other objects the receiving object's behavior. . In object-oriented ng. A subclass may have some additional and unique features in addition to the features inherited from its superclass. a subclass is a type of suPerclass. This approach specifies the relationships classes based on the behavior of individual class. A subclass can inherit the attributes of a superclass. ips Between Classes and objects are related to and ¡nteract with each other. various relationships that can exist between the various classes of a program are: r I I I 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. 3E!f Sava Fundarnentals Ls'v . A subclass can inherit the propefties and methods of its parent or superclass.

.. the subclasses.:. which in tum is a kind of ticket. and organization.49'61¿686én hw"& Ta.. in the tickeüng system.:. country..!:. it depicts the paft-of relationship. you might real¡ze that you need to store address of various entities. state. For example. You can use this class as an element of the classes where you need to store address... such as address line 1.:i:2:a.¿:::at:t .F@- In the ticketing example discussed earlier.:t7. while developing a program. You might further realize that the address consists of various sub-attributes. a ticket class is a superclass and confirmed ticket is a subclass. To reuse the entire set of these attributes. you can create a class that consists of the required attributes. such as confirmed ticket and requested tickets are the kind of tickets.t::::.:¿..::t ):!: |:!. For example. customérs.|!!| y|p9 !. address line 2. The relationship between these three reads as the ticket for New York is a confirmed ticket...a|. The following figure depicts the Is-a relationship between the three classes: Gonfirmed Ticket Ticket frr l\ley¡ York Is-A Relat¡onsh¡D Part-Of Relationship When a class is an element of another class. such as students.aw #a3{aúmm*mtals #ttW&W a*?w@& .::t:.::¿:2?)t:aitj. lt!taltl:41¿.:. A confirmed ticket for New York is an object of the confirmed ticket class. and zip code. The following figure depicts the kind-of relationship between the confirmed ticket and ticket classes: Crnfirmsd Ticket Tick*t Kind-Of Relationship Is-A Relationship The relationship between objects of superclass and subclass is referred to as an is-a relationship.:::. The address class exhibits the paft-of relationship with respect to the class in which it is included. city.

als inherit these as "eatures and have their own specialized attributes. it depicts the has-a relationship.A. 3 aq n F z*n rJ. the relationship between the student :nd address class reads as the student class has an address. The tyPe of relationships among classes result in different types of inheritance. -ld55e>. You create various classes that exhibit various relationships among :nem. such inherit the attribute of birds and land animals' Similarly' :ats and archaeopteryx. Consider the example of the animal kingdom.Fr !' 1* ¡ ':' ' . Aves. such as salámanders and frogs. and aquatic anim.Y. Address Part-Of Relat¡onsh¡P Student I l-las-A Relationship -he has-a relationship is reverse of the part-of relationship.ddress classes: Address Has-A Relat¡onsh¡P :'r a program.% i e. when you nclude the address class in the student class. When a class consists of another class as its eiement. YLtr. The has-a relationship is also known as aggregation or composition. inherit the attributes of land animals and aquatic animals. ámphib¡ans. -he following figure shows the has-a relationship between the Student Detail and . One of the basic attributes of all members of the animal kingdom is :rat they cln move. For example.".r I I M -he foltowing figure shows the part-of relationship between the Address and Student I -l^-^^-. flying animals. m rn * {rkí21 ffi 3"W. In addition. Types of Inheritance -he animal kingdom has many exampres of inheritance. terrestrial animais.

W6. but also to extend the functionality of the existing program.N&u tA^ e-.4 *rÍír# 'v. This hierarchy not only enables programmers to reuse the existing code.$ ¡l $r\tg ¡. in object-oriented programming.l f^-.( -a'( el"^f *.\1áb ."Q. {tt tf¡ .. you can create a hierarchy of inheritance among various classes. y xt "."-.***l JJ háve wings áfld teéth have hngs and gillá Animal Hierarchy Similarly. ¡"1[ ¡irr].The following figure illustrates the hierarchy of inheritance among the various classes in the animal kingdom.n. have w¡ñgs E + hav€ te€th añd lungs hav* grll* lr"*"*"ñ.^la UJ'1¿13 **.

you can inherit the attributes of the existing employee dass to the contract employee class and add the attributes for the contract employees. The subclass or the child class inherits the attributes of the parent class or super class.ffig #. and Fish are example of single inheritance because these classes have inherited the characteristics from one superclass.Ff'¡r'¿""g{a {*.For example.lh 6r¡c¡^ -> \ c\.a e*. Similar to the animal kingdom hierarchy.rfi*"r. For example. ñuen Numbers S¡ngle Inheritance rWWffi 3 ww w Y a*ra& w {ffi e {zg. such as Birds. subclass is derived from only one superclass. such as contract employees. classes called Even numbers. and Prime numbers is derived from the class Numerals. if you need to include a new category of employees. The foHowing figure displays the single inheritance: $ub ülass {child} The Single Inheritance In the Animal Hierarchy figure. in an organization.. Animal. classes in a program can have following types of inheritance: I I Single inheritance Multiple inheritance Single Inheritance In single inheritance.- ... Land Animals. Odd numbers. a aw.trtu yr*rr"*q{ p.stl \t I cr.i é -> qvjr t a^:. Nww+¿ao {-A f dA q¡-.r+t f. the animal category classes.

3"& 3 azs a F w rzrS mrYz* mtat 6 r. a subclass is derived from more than one super class. Consider an example of an organization with the name. The following figure shows multíple inheritance: Insurance Compar¡y Global Courier Multiole Inheritance 2w. The type of inheritance involved in this scenario is multiple inheritance. the Global Courier Company class inherits the characteristics of the Courier Company and Insurance Company classes. Land Animals and Fish. The subclass or the child class inherits various attributes from its suoerclasses. Birds and Land Animals.Multiple Inheritance In multiple inheritance. in the parent-child relationship. Global Courier Company. Therefore. The Amphibian class has inherited properties from two parent classes. The Flying Animal class has inherited characteristics from two parent classes. the animal category classes. For example. The Global Courier Company is a subclass and Courier Company and Insurance Company are superclass. The following figure displays multiple inheritance: Super clóss (Pa rent 1 ) Super Class {Pa rent2 ) Sub Class (chird) Multiple Inheritance In the Animal Hierarchy figure. wEzT . such as Flying Animals and Amphibians are examples of multiple inheritance. The organization is a Courier Company as well as Insurance Company. a child inherits characteristics of mother and father.

r-* e*'"}oÁshca !e. object-oriented methodology. For example.^LJJ q"k\ -? Qta{ . The entity can a variable.Polymorphism is derived from two Latin words-Poly. and husband his wife. Polymorphism enables an entity to have more rn one form depending upon the context in which it is used. polymorphism is the feature that enables you to ilgn a different meaning or usage to an entity in different contexts. child to his parents.\narh-s . a person assumes various roles when he interacts with the of his family. means forms. Any thing that exists in more than one form is known as a You might have noticed that a person assumes different roles in different . He is a fatherto his children. or an object. Although. Polymorphism enables entity to be used as a general category for different types of actions. the person is same. and morph. *) eampr-la . he behaves differently with the family as per his relation with the member.€. which means many. method.

L4 3 aw m Y xayzú a rvt e YÉee. Multiple inheritance.Hides the implementation details of an object and therefore hides its complexity. you learned: W W Encapsulation. Inheritance.In this lesson.A class inherits attributes from only one superclass.Assigns a different meaning or usage to an entity in different contexts. Abstraction. 6 üwffi . A subclass inherits its attributes and behavior from parent classes. Polymorphism.A class inherits attributes from two or more superclasses. hw.Creates a hierarchy of ciasses and helps in reuse of attributes and methods of a class.Focuses on the essential features of an object. The relationship among the classes can be classified as: W W o o o o W W Kind-of Is-a Part-of Has-a A superclass shares its attributes and behavior with its child classes. There are two types of inheritance: m o o W Single inheritance.

" . Snqn '#mn4.ril-l -i&"'LessoN tC CoLLABORATE 3...mmz*mt¿nt* L1*" i.

.

:. and . such as: g Collecting information about the software that needs to be developed * Documenting the retrieved information Creating design documents consists of well-defined activities and methods needed to perform lmplementing and coding the software Testing the software i:.-=ments of the new system. In m_e::-oriented analysis. f '".e various attributes. For example. you will learn about: I I 3:ject-Oriented Analysis and Design " arious Types of Inheritance Jbstract Classes and Methods Object-Oriented Analysis and Design rn-t. in a:: : l:l to the development and planning of the software.Kn¡owr-EDGE Bvre "f: s section. :r. the 5*--.. Scftware Development Life Cycle (SDLC) is a set of phases that divides the entire r := je of the SDLC :*:-s tasks. In object-oriented analysis the emphasis is on the 'riü':s:gation of a problem based on the requirements.". such as Customer_ID and Customer_Name and methods. T- -:::ss of building a large program or application into smaller and more manageable -.= Each phase has defined inputs.3s get_CustlDQ and set_CustlD0 to enable a customer to perform automated -.r.í:. the end users and the developers of the system analyze the reg. the Customer class needs r: -=. Inc.e:-oriented analysis and design (OOAD) consists of object-oriented analysis and "rr:-= rbject-oriented design. ..ru i3 collaborate these objects to fulfill the requirements of the new system to be r¿. in the bank management system. involves application of tools and techniques.:'r'curMoney.:-:-ates a specific output.i:. bank requires a new automated bank management system.::-criented design.= :3ed.. :8. -g transaction.'"")a '':...r:. Each stage of the SDLC requires documentation. For example. 3 . the emphasis is on defining the software objects and 1.

the the following four phases: software intensive system includes W Inception -1 (rr^^*) W Elaboration ffi W Construction Transition Inception (rr.W Deploying the software sDLC of any According to Grady Booch. and Ivar Jacobson..u. .J. / r. ihe requiremenis of stage are: documented in this stage.**'!=l-"dt S co?e/ arttbr t<r ' -? at <pr¡<r. The various activities involved stage are: ffi understanding the problem and the methods for solving it. W Specifying the scope.explained and defined at this stage. The various activities involved in Elaboration W W phase Elaborating the system specification obtained from the inception Analyzing the Problem Describing the system's requirements by creating a model of the system Analyzing the requirements for the project Developing the Project Plan ffi W W kü"& 3 mv¿ m F a* númuvt * {zt"m$ * #¡W'#ffi 1a¿**$':'*. 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 system is This is the second phase of the sDLC process. objectives. James Rumbaugh.lo\ in Incept¡on This is the first phase of the sDLC process.e. The architecture of the the system are also.

and outline various modules to monitor the progress of üre project. land. and water connection. h the elaboration phase. Defects identified are then documented and corrected. I I I I Delivering the integrated modules. get a blueprint of the house to be prepared. As the construction progresses. landscaping. start arranging fu finance. you build a vision of why you want a house and what kind of hse it should be. You discuss the same with-your family members. This stage involves the following Elaborating the solution specification obtained from the elaboration phase . lr the inception phase.. You need to follow the similar stages as that of software development for the g¡struction process. and finally give acceptance to the architect to staft construction. verify it. you keep checking the functionality of various ftahrres. contractors lrd other skilled perconnel get busy in the process of translating the blueprint into 3E? Saxra fwczá*r*ent"afs Lü"5 Dli/n-.: I 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 "l -t sition er Th is the last phase of the SDLC process. you complete a detailed analysis of each and every aspect of üre house.is the third phase of the SDLC process. The software is handed over to the endand is tested for defects. personnel. Deploying the integrated modules. Correcting problems in the deployed modules. such as the electrical wiring. In case you h the construction phase. You call an architect. Engineers. realrty.1o -Jre5a {d"1}!^r-+ **ffifr*& . Yq¡ can compare the various stages of software development with the construction of ¡ house. d for modifications. the construction team takes over. transition stage of a software system involves the following activities: Integ rating different modules.

such as a problem with the drainage system. and SavingsAccount classes are known as the subclasses or the derived classes. You have already learned about single and multiple inheritance. . CurrentAccount. FixedAccount. b In the transition phase. In case you find an unexpected probiem. #)wtt. you move into your newly built house. A period of maintenance now stafts where repairs and modifications are carried out as and when problems are detected. CurrentAccount. which are inherited by the FixedAccount' CurrentAccount.t/ &g I . you immediately call a plumber and get the problem rectified. The other types of inheritance are: ffi W 'ffi Multilevel Hybrid ffi Hierarchical Multipath 3"ü"ffi 3 mw m W as'nrT mtvi w ffiteTffi. The Account class has the actount number and balance attributes. Various Types of Inher¡tance Inheritance is the propefty that enables a class or an object to acquire the attributes and methods of another class.P* find something not satisfying your requirements. For example. you immediately ask for changes prevent inconveniences later. The Account class is known as the superclass or base class and the FixedAccount. and SavingsAccount are the three subclasses of the Account class. and SavingsAccount subclasses.

'!t multile.Iultilevel fnheritance '. the Gived class inherits features from other derived classes. As a result. The Children class inherits the attributes and rnethods of the parents ctáss rrd the Grandparents class. Class A Parent Class for Class B M u ltilevel In herita nce Sava Fux***rnen*alg. Grandparents 'büte base class' The Parents class is a derived class that inherits features from the ke class.vel inheritance. . ror example. a class is derived from an inherited class.

Class A Parent Class for Classes B. which is multiple inheritance. For example. C.o Sava Fundamentals ffixtrlt . Hierarch ical Inher¡tance More than one subclass can be derived from a single base class in hierarchical inheritance. a derived class exhibits two or more than two types of inheritance. One of the base classes is derived from a single parent class. which is single inheritance. and D Hierarchica I In herita nce ¿fr.Hybrid Inheritance In hybrid inheritance. a derived class inherits attributes and methods of two or more base classes.

such as mango.nj í: *.l{ D ultipath Inheritance l0 I I tiple inheritance.'. The methods having no implementation in the abstract class are =¿lled :f abstract methods. rhe food represents the abstract concept of the things that we eat.:" f$i¡ . you are not able to see the instance of the food you eat.' I . m rzt mTn 3-{:"ry . Abstract Classes and Methods \n abstract c/ass is a class that cannot be instantiated. An abstract class is always inherited by 3ther classes. B. and D. An abstract method is implemented in the subclass instead being implemented in the abstract class. ?437"f: 3 n w ¿n. v-:ipath inheritance is a combination of multiple and hierarchical inheritance. The :-: ihe following figure. In -:- -:thods of two or more base classes. the two paths of inheritance for the D class are: A. r-: . i I : . apple. It contains methods that have -c implementation. A. and chocolates.'ú utz &m r:*. and D. You are only :ble to see the instances of various food items. =or example. C. a child class is a derived class that inherits attributes and base classes are derived from a single :?-ent class in hierarchical inheritance.

C++. HOOD. class A. CLOS. Smalltalk. and Java. Simula was the first objectoriented programming language. and UML. Simula 1 was a simulation language and Simula 67 was referred to as Simula.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. such as classes. classes. CIass Hierarchy hü"3-w C". inheritance. ffi Class B inherits features from its base class. IBM. W What are the primary object-oriented methodologies used currentlyT The primary object-oriented methodologies are: BON. and graphical user environment. Smalltalk was another language having various features. and inheritance. W How did object-orientation evolve? The object-orientation evolved with the evolution of Simula that provided features. Python. B. FUSION. Class C is a sub class of class B and inherits features from class B.' "a .V 3m u¿ m T T u* a4 mzzz * r*t m4 s ''rywLTtr B\r¡e- **¡ arlCl'¡ { u '' . and C. How many times will the features of class A appear in class C? The following figure shows the class heirarchy for classes A. such as objects.

Class B' The features inherited by Class C include the features that Class B inherited from Class A.efor€. Thér. Class A.****" . the features of Class A appear only once in Class C' eww thrrcQ"ra Sana Fean&a*tentar* LT"IL -" Pen. These features occur only once in Class B. Class C inherits features from its base class.Class B inherits features from its base class.

Functional Programming Language Make words from the jumbled letters in the box given below and match them with their description : a. Object-oriented Programming d. . (a) Tdaa bmreem ?nc^rP*itar'ra' rde+ií+1 Srctaabt Entiitvd Noitalusoacne qd\ abs\ra*. The attribgte of a class is represented by ___. Procedural Programming Language c. Canniest informationhiding. Java i.-. 3 av n F a¿ rs$awnxrzLtnts ti. FORTRAN v.* óq) #"*. ¿¡¿ge!¿JiüÉeature of objectioriented programming i-also called 2.-1.. i r . b.i¡*rtrof a class.C iii. LISP iv. An objec! of class has a unique l&. d.¡dñp3 . An object is an .f E *ca. c.*-f rrv R¡bs{r¡ottass is not instantiated. Imperative Programming Language e.7F :::i 1.k2. e.tWíT \v r*bleJ-yre¡r. Match the followino: a. 1^". Structured Programming Language ".-*ii.

Solve the following crossword: Across: i. ( 10) e.wEY{ 7nnrm ffiwra{A'em4ntffit# 3"ü.3. lv.3"m . Type of Inheritance in which there is one base class and one sub class (6) The characteristic of an object that refers to a change of the state of the object over a period of time (8) 69 Down: an example of procedural programmins (5) program that can be divided into small user-defined units(6) 2 A--is 5 The type of inheritance in which there is more than one level of inheritance.

mt"ele wwr .Sawa F*ndanr*.

Lessem 3B FHRTMENT Swwm Wa¿m&mwremtffig# .

.

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

Exercise 3 ldentify the types of inheÉtance in the following figures: Andrewsons Institub of Medical Sciences F¡gurc 7 Savw f*znúame*tals .

Car C0rrputer .lachine b.e r identify the relationships between the various classes depicted in the following f ig u res: a.Motcr Bike Fsure 2 Motor Sike Truck rxéicisi.t. ?t'ql'T . l'.

number common aitributes. time. í¡ "j :X Lt ": ?: .-'.".ut for ttre three classes depicting the inherited attributes of the sub classes and their individual attributes. . FmplsyeelS Exercise 5 A passenger of FlyHigh Airlines can travel by two types of ticket reservations. h" É " i. | "^""{.} r. A ! Y. Draw the class hierarchy Jiug. .d.'. and destination. attributes. The Airline reservation has various Both types of classes ¡nherit these such as flight number.r. T'he Confirmed ticket class would however have a seat *fr¡1" u Requested ticket would have a status attribute. ". dáte. Confirmeá ticket and Requested ticket.

'!
a

HOUT ASSIGNMENT
Which language is an Object Oriented Programming language?

b. coBoL c. FORTRAN @ Java
z. Which option is correct about the procedural programming approach? @ In the procedural programming approach, portions of the code are so interdependent that the code in one application cannot be reused in another. b. In the procedural programming approach, portions of the code can be

a.

BASIC

c. d.
3.

reused.

The procedural programming language provides the advantage of information hiding. The procedural programming language provides the advantage of real world programming.

Which feature of Object Oriented Programming language ensures data security

in a program?

O b. c. d.
4.

Information Hiding
Resuability of code
Resilience to change

Modularity of code Ob¡ects are the basic building blocks of OOP. Objects are the basic building blocks of procedural programing methodology. class is an instance of an object. The objects can exist in isolation.

Which option is correct about the classes and objects in OOPS?

$ b. c. d.
5.

Which option is correct about the objects in object oriented programming language? Two objects may have the same behavior, may or may not have the same state but will never have the same identity.
b.

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

T:WZTtr

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

"r:!li,

d.

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

6.

Which option is correct about the objects in Object Oriented Programming language?

@ fne identity of an object can be changed in its lifetime. b. The identity of an object never changes in its lifetime. c. The behavior of an object distinguishes it from all other objects. d. The behavior of an object refers to a change of its behavior over a
period of time.

7.

In single inheritance, a subclass is derived from

@ onty one superclass.
b. Two superclasses. c. Three superclasses.
I I

1l
I

d. Four superclasses.
8.

Inmu|tip|einheritance,asubc|assisderivedfrom-_'
a. Only one superclass.
b. Two superclasses. c. Three superclasses,
@,i More than one super class.
14

9.

A computer has a monitor then what is the kind of relationship depicted between the Computer and Monitor class,

a. Kind-of
b. Is-a

c. Part-of

(l)

Has-a

10. Which option is correct about inheritance?

a. Inheritance does not allow you to share data and methods among multiple classes. Inheritance enables you to,add new features and functionality to an existing class without modifying the existing class. c. In inheritance, a subclass is also called a parent class,
d. In inheritance, a superclass is also called a child class.

kffi"ffi

Tmw* Wq**&mmwrz4*4s

w
Éil Éil

hess*F* Re.
TC)

IwrnepucTuelu

#*v*

In this lesson, you will learn about: Éil Concepts of Java programming language
Vat'iables ArraYs

Sava Fundarxentals

rztals i&jWú .W Sawm Funúarsz*.v &4^ a .w- 2.&.

These piograms require a Java-enabled browser.::'wffi1r J mv *. A few types of Java applications are: W Applications that use Character User Interface (CUI): Applications are executable programs that are controlled by the operating system' These applications haúe an access to the system resources. from the smallest devices. Java is used to create applications that can run on a single computer as well as a distributed network. you can use Java to wr¡te a variety of applications. telephone. television. F a¿n úa {ffi w q21 t}. such as . such as file systems and can read and write to files on local computers' Applications that use Graphical User Interface (GUI): These applications are used in the W¡ndows environment.9 4á ?.k. Applets have limited access to system resources' Servlets: Servlets are the programs that are used to extend the functionality of Web servers. Java software works everywhere. you interact with the application in W graphical mode. . The lava programs work on any type of compatible device that supports Java. You can use Java to bevelop network-orieñted programs because networking features are built-in features in Java. Java has become a widely used programming anguage. which is a service of the Internet to retrieve information in the form of Web pages. or the operating system these devices run on. ffi W Applets: Applets are small executable programs that run on a Web page. Need for Java The Java language contains built-in support for the World Wide Web (WWW). In GUI.3 . With the increasing use of the Internet.IÁv* Pi¡ lava is an object-oriented programming language that was designed to meet the need 'or a platform independent language. Java is both a language and a rechnology used to develop stand-alone and Internet-based applications.nicrowave ovens and remote controls to Supercomputers' Java programs are ndependent of the type of computer. such as Internet Explorer or Netscape Navigator. The primary motive behind developing Java language was the need for a portable and platform-independenl language that could be used to produce code that would run on a variety of Control Processing Unit(CPU) under different environments.

This saves your effort to write and compile the same application for different platforms. The applications running on these computers can be Web-based or Internet-based. Any program downloaded through the Internet can perform some malicious task on the local computer if the local computer does not implement security checks. Most programming languages are platform dependent. Java provides a solution to all these problems. Characteristics of Java Simple Solutions Systems Inc. Java is a platform independent language that enables you to compile an application on one platform and execute it on any platform. when downloaded from the Internet on a computer cannot access the file system on the local computer. which implements various security checks on Java applets and does not allow them to peform any malicious task. to the language that the computer can understand. which is a program embedded within a Web page. or Solaris. The organization needs to develop an automated application within a short duration. Compilation of an application refers to conversion of the program instructions. In addition. Computers connected to the Internet run on different operating systems and hardware platforms. Applications developed by using such programming languages can run only on those types of hardware and software platforms on which the applications are compiled.4 ?as¿w #**ndar**cata\g {. such as viruses.run time environment. You use Java programming language to develop an Internet-based application that can be accessed by programmers working on various types of computers. you can download a file or an executable program on a computer connected to the Internet.6}WAW . The system should be reliable enough to handle error-causing conditions. which means two or more applications running on different computers communicate with each other by exchanging messages and data. 2"&. Linux. is a software development organization. Java applet. Internet applications are distributed. Java provides a. written in a programming language. which has branches across the globe. The applicants across the globe might use any type of operating system. The organization also wants a Web-based application for the recruitment system that enables an individual from any country to apply for a job.. such as Windows.W Packages: Packages are collections of classes that can be reused by applications and applets. The application must enable the employees to obtain information about the benefits and opportunities offered by the organization.

Programme¡s need to explicitly handle memory in the program for its opt¡mum utilization. such as abstraction.18W Smwm Famümffie. Java does not support pointers and consists of the built-in functionality to manage Object-Oriented Java supports the object-oriented approach to develop programs. ¡s to handle memory allocation.7zW'?.The choice for having a programming language that fulfills all these requirements is Java because it exhibits the following characteristics: X & & ffi ffi ffi Simple object-or¡ented Compiled and interpreted Portable Distributed Secure Simple A lava programmer does not need to know the internal details of Java as to how memory is allocated to data because in Java. the entire code of the program must be written within a class. One of the major problem areas in most of the object-oriented languages. such as C++. the programmer does not need to handle memory manipulation.nte. Java is a simple language that can be learned easily even if you have just stafted programming.&. To implement the object-oriented language. inheritance.% . Even the most basic program in Java must be within a class. However. It was designed to be easy for the programmer to learn and use effectively. and polymorphism. they use pointers that enable a program to refer to memory location of the computer. To handle memory allocation.&# 7. encapsulation. The lava language does not suppoft stand-alone statements. The syntax for various Java statements is easy to understand. It supports various features of an object-oriented language. ..

Afteryou have made the program error-free and have recompiled it. The compiler generates a class file for each class in the source. The IVM is the interpreter of the Bytecode. cross-platform programs by compiling the programs into an intermediate representation called Java Bytecode. Converting a Java program into Bytecode makes a Java program portable because any computer installed with the JVM for the platform on which it is running can interpret the Bytecode.f Compiled and Interpreted The Java programs are first compiled and then interpreted.java) files.class extension. While compiling. the compiler software checks for the errors in the program and lists all the errors on the screen. translates them into Java Bytecode.java). Wher you compile a Java source code file (. ye". Bytecode is the result of compiling a Java program. which reads the Bytecode line by line and executes it. While interpreting the interpreter software reads and executes the code line by line. The programs developed on one computercan run or another computer.class) files. Therefore. The Java compiler compiles the code to a Bytecode that is understood by Java. the Java compiler generates the Bytecode which is a compiled Java program with a . other people can use the programs that you write in Java even if they have different computers with different operating systems.ffi 7mvm Tan*mq. The Java compiler reads lava language source (. Java enables the creation o. If the operating system of the computer changes/ you only need to install the IVM for the new operating system without requiring any changes ¡n the source code of the Java program. the compiler converts the program into computer language.n*s2Yn. The lava compiler is written in Java and the interpreter is C written in programming language Poftable Portability refers to the ability of a program to run on any platform without changing the source code of the program. You can execute this code on any platform.s ttii¡W717 . The Java Virtual Machine (JVM) then interprets this Bytecode into the computer code and runs it. The Java interpreter can execute Java code directly on any computer on which a JVM has been installed. and saves the Bytecode into class (. which might have a different platform.

.uows . eytecodente) { (.:' .. The following figure shows how the Java Bytecode and the IVM together make Java programs portable on different platforms: rylJava $ource Code fr 4___g::__J { \ \-Try-/ I --. or Macintosh.class . u**. Distributed Java is used to develop applications that can be distributed among various computers on the network. UNIX. The Java compiles and converts the source code of a Java application available in a .f-Éffi Jéva I \j:_/ \.=]\ I i *-T-*lf.ffi\ f. such as Windows.e\%: ?"e.java file to a Bytecode file (.7 . & Máchine uNrx lfi tuacrntostr I $ UNIX | [ Macintosh | fl uacirine I f M€chine q___jga_J t__eg!Lj il $ tt/indows | I I t_:gsj Java portability with Mult¡ple Platforms The preceding figure displays how a Java application is portable across platforms. fite f.. Java is designed for the distributed environment of tne Internet ryiwÉrr 3 av n W *zm* myrz e rkV./'l\ " *. The same . Each platform iee7s to ttave its own JVM to run a Java application.IVM is not platform independent.wi.class file can'be interpreted by the :úV of a specific platform.:. The Bytecode supports connection to multiple databases.class file).

d blbe p@e 4 !! t!!t ¿!4e Yyj\ |'1' e ee!6. All references to the memory are symbolic references. Host computer is the remote computer where the application is stored. This ensures the security of the lava program over the Internet.because it supports the various Internet protocols. they perform operations.. _Java applications can open and' access remote objects on the Internet in the same manner as they can open and access objects in a local network.tnda{w*. Java contains a package. the compiled Bytecode is strongly type checked. which is termed as the local computer.. it is susceptible to attacks from the virus programs. Applets cannot access the resources on the local computer. Any change made in the Bytecode are flagged as errors and the program does not execute. In Java. iñ. which means that the programs cannot access memory locations w¡thout proper authorization.t . Java does not allor the use of explicit pointers. When you access a program over the Internet. Remote Method Invocation (java.rmi). You run the application from the host computer over a network by using a computer.r.::: ::.. such as Transmission Control Protocols and Internet Protocol (TCP/IP). It cannot make connection with other remote computers. which is used to build distributed and client-server based applications. from the host computer from where you run the applet.óñiié¿iiñ Various components of the Java architecture are: W W Java programming language Java class file Java Viftual Machine (JVM) Java {1¡plication Programming Interface (API) ffi W ee 4 ee:ebq4¿ éqip.ntals wfrtr.: ::x 2e"& 3*wa f*. An applet can only communicate with the remote server from which you download the applet. such as accessing the files on a remote system. Secure lava has built-in security features that verify that the programs do not perform any destructive task. such as accessing files and read/write function. In addition. which áre used to referto the memory locátions in a C++ program. if Java applets are downloaded from the Internet.

Applets cannot access the resources on the local computer. which is termed as the local computer. In Java. which are used to referto the memory locations in a C++ program. In addition. An applet can only communicate with the remote server from which you download the applet. they peform operations. which is used to build distributed and client-server based applications. All references to the memory are symbolic references. JaVa does not allow the use of explicit pointers. from the host computer from where you run the applet.because it supports the various Internet protocols. such as accessing files and read/write function. it is susceptible to attacks from the virus programs. Any changes made in the Bytecode are flagged as errors and the program does not execute. Host computer is the remote computer where the application is stored. You run the application from the host computer over a network by using a computer. It cannot make connection with other remote computers. which means that the programs cannot access memory locations without proper authorization. such as Transmission Control Protocols and Internet Protocol (TCP/IP). the compiled Bytecode is strongly type checked. Java contains a package. if Java applets are downloaded from the Internet. This ensures the security of the Java program over the Internet.rmi). Remote Method Invocation (java. such as access¡ng the files on a remote system. Secure Java has built-in security features that verify that the programs do not perform any destructive task. Java Architecture Various components of the Java architecture are: W Java programming language Java class file Java Viftual Machine (JVM) Java Application?rognamming Interface (API) ffi ffi W . -Java applications can open and access remote objects on the Internet in the same manner as they can open and access objects in a local network. When you access a program over the Internet.

A .java. which contains the Bytecode. A JVM can have following types of class loaders: W W Primordial Class Loader: Loads the Java API classes required by the running Java program.Java Programming Language and class File Java programs are saved with an extension.class file to machine object code. ütne Java application program' An application can create class loaders at runtime for loading the classes of the application. Components of the JVM IVM for different platforms uses different techniques to execute the Bytecode. Class Loader Objects: Loads the classes *:"ffi&TK 3 mzx m W *q nú mwm *rz:t mTw ZP". The major components of JVM are: ffi W Class loader Execution engine ffi lust In Time (JIT) compiler Class Loader The c/ass loader loads the class files. which are required by a program running in the memory. The classes are loaded dynamically when required by the running program. The JVM convefts the Bytecode contained in the . .java file is compiled to generate the . The JVM needs to be implemented for each platform running on a different operating system.class file.W . The following figure shows the relationship among various components of the lava prog ram ming environment: lav¡ File Syter0de The Java programming env¡ronment Java Virtual Machine (JVM) The JVM forms the base for the Java platform and is convenient to use on various hardware-based platforms.

6. P?A 4l. The related classes and interfaces of the lava ApI are grouped into packages. The JVM runs the JIT compiled code without interpreting because the JlT-compiled code is in the machine code format. The Java execution engine converts the Bytecode to the machine object code and runs it. The architecture consists of the following security features: W Compiler level security .compiled code is faster than running the interpreted code because it is compiled and does not require to be run. line after line.:ava) I L*_eL_l ffi I Hardware ffiFI t_____=______l | l. lí:¡ 1y: lWtt¿A ffi*** . The following figure shows how the Java API and the JVM forms the platform for the Java programs on top of the hardware: | | :aua crogram (. such as GUI.li::V::te:\rt4. R:*9 .: 1 !. JIT Compiler The JIT compiler is used for compiling the Bytecode into executable code. Java Application Programm¡ng Intedace (ApI) The Java API is a collection of software components that provide capabilities.a!6\é|.i Z:! rr?!1!.!p.Fr_ Execution Engine The Java execution engine is the component of the IVM that runs the Bytecode one line after another. Running the JIT. The execution engines implemented by different vendors use different techniques to run the Bytecode.------------ -*Java\.-\ L__J i Components of Java platform Java Architecture Security Java architecture also consists of a few security features that make lava a secure programming language.Ét:.

which might result in improper usage of memory. e6w 2. The problem of memory usage is resolved in Java. Pointers enable a program to access memory directly.&*23 {.iww t 3 m'sr m W axffi qáa frw *rzq.w w Bytecode verifier Class loader W Sandbox model The following figure shows the various levels of security implemented on Java programs: &ut*rq*t¡ L*1rs* 2r Svtecsde vprifi*r *ewrlfY U*u*.. Java prevents errors that I:::::::: i': . such as c++.:. "t't: tí:. wasthe availability of pointers.. *\ Cl¿ss lnader *erarr*rÍ L*v** 4: Sandbrx M*del Security Levels ín Java Arch¡tedure Compiler Level Security one of the problem areas in earlierobject-oriented languages. as it does not support pointers at the program level.¿r-J* "'Ye/*& .

such as read/write operat¡ons' and verifies that the Bytecode does not forge pointers. reducing the compile-time errors. 7. Conversion of data from one type to another is Bytecode Verifier The Bytecode verifier checks the Bytecode before it runs on a computer. Class Loader The c/ass loader determines how and when an applet will use classes in a running Java environment. such as text to number or number to text. such as a text and a number.Java employs typecasting between data types that implies that when one type of data is assigned to another type of variable. you might need to compare incompatible data. W The second phase occurs when the Bytecode is run. At times. The class loader loads all the applets and their references. In addition. arise due to improper memory usage. Sandbox Model lhe sandbox model is implemented in the Java applets container. Native APIs are the application programming interfaces of the operating system on which the Java application is executed. there can be many class loaders and each class loader can create its own run-time environment. an automatic type conversion takes place. the verifier checks for the structure of the . Typecasting in Java ensures that there is no data loss in the result or output of a Java code. you need to convert data of one type to another. The Bytecode verifier checks the validity of classes. and methods used in a program. The sandbox model determines the limitations of Java applets that they can only access the resources of the host computer and cannot access the files on the local computer.&"ñ"4 Zmr¿m Wzxrz&amav2te*& 'f"1W . Java applications do not employ this security model and are allowed to read from and write to files on the local computers. variables.class file. To compare such data. such as Web browsers. It ensures that the Bytecode does not violate access restrictions. In a Java environment. The Bytecode is verified in two phases: W In the first phase.

Data types are used to define the operations possible on variables and the storage method. a person's age is stored as a numeric value and an address is stored as alphanumeric characters. which cannot be used as names forvariables. There are eight primitive data types in Java.?i""3 . or string. char. For example. Keywords are the reserved words for Java programming language. Java is a strictly typed language.:aa:). or method. which means that lava gives impoftance to type checking. and variables. aaa. 2.^. such as data types. The various data types in Java are: ffi ffi Primitive or the simple data types 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.& ffi É . literals. which are fufther grouped in the following categories: W Integer type: Can store whole number values. r¿ rr? {& r'tt. Wi LITERALSI '.á. o o byte shoÉ int lono ':azm' 3 ms¿ n W z* ru ú. Expressions and variables in Java can be of different types.Dec¡-aRING VnnrnBLEs AND Java supports some basic programming elements. class. The four integer data types are: o . such as int. The data stored in the memory of a computercan be of differenttypes. keywords.!aa Using Various Data Types The data stored in memory of the computer can be of many types. Type checking is one of the impoftant steps in compilation of a program. The size of the values of the variables depends upon the chosen integer data type.

Boolean type: Can store only the true and false values. there is one data type.r llr:. grouped in four categories: GróiuB Integer Data Type byte SÍZe One byte -27 Pe. ''."lt4 3 xt¿ * W z* rzú m r"n * rztmZn i. 7.4e-038 0. such as letters and numbers. Boolean data type is reouired when a condition has to be checked.: .4u*038 0 byte Floating float Four 3. The true orfalse value of the Charactertype: Can store symbols. i : .&.0 point byte double Eight 1. char. In character type. unlike C/C++ does not support the concept of unsigned integers. . Integerand Floating point can store negative values. Java. The two types of floating point type are: o o ffi W float double expression or the condition determines further execution of the Java program.'Y4tue 0 '1 short int long Two byte Four _2ts ¡o 2rs _1 0 -237 to 23r_! 0 byte Eight -263 to 263-r tO 3.0 0..t'?{i{t .7e-308 tO 1. .7"*308 byte Boolean Cha boolean One bit Two true or false a single character false null racter char byte The groups. The following table lists the primitive data types with their size and range.F-_-_-- W Floating point type: Can store fractional numbers.nge' to 27-! (signed) üátáattt .

The keywords with all or some letters in uppercase can be treated as variable name but that should be avoided. and extracting a part of a string. String provides methods for concatenating two strings. and other characters.:. Keywords cannot be used for naming purpose of variables. digits.Abstract data types The abstract data types include the data types derived from the primitive data types and have more functions than primitive data types.Ét. You cannot perform calculations on a variable of the String data type even if the data stored in it has digits. For example.b% . However.MÉA'tr 3 mw m ffi ¿zvzúarzz*q"eYwIs ?. Java is a case sensitive language and the keywords should be written in lowercase only. searching for one string within another. :. or classes. O. and #. Keywords ava¡lable in Java The keywords are the reserved words for a language. The following table lists the Java keywords: Abstract case Const Double Finally boolean catch break cnar byte CIASS continue etse default extends oo final goto instanceof native protected float implements interface pacKage for If Int New Public Impott long private short switch return super static synchron ized tra nsient Strictfp This Try throw void throws volatile while . which express the language features. such as /. $.:. String is an abstract data type that can store letters. constants.

number. &. '$'. must be declared and it should be of the type int. A program does not compile if you have not followed the rules of the language. such as ?. These rules are enforced by a programming language. i. fl. and /. Conventions help to improve the readability of the program. o o A variable name should not contain embedded white spaces. 3 *'q r^z #a¡ n rJ a rt* e *?.+ . or the dollar symbol ($). Java allocates memory to each variable that you use in your program. but following them is not mandatory. The class variables are declared inside the class before their use. For example. is to be used for storing an integer value. o/o. and without any embedded space or symbol. r& The name of a variable needs to be meaningfui. Ceftain rules and conventions govern the naming of variables. You can use an underscore for spacing purpose. an underscore (-). A variable name in Java is case sensitive. . A variable name should not consist of a keyword.Defining Variables and Literals A variable is used to store and manipulate data or values in programs. if the variable. number. ". i. age is not same as Age' Types of Variables The area or the region of a program where a variable can be accessed is known as variable scope. short. A variable name should not start with a digit. :.l. or '_'. {}.3_ *. A variable name must be unique. #. If the name. W. number is a variable. number. al n i: ffi2T3' . You can assign different values to a variable during program execution. The naming conventions for a variable in Java are. which can be followed by a sequence of letters or digits (0 to 9). There is a difference between uppercase and lowercase names. @. the variable. Each variable that is used in a program must be declared. W 'ffi A variable name must begin with a letter. Naming Conventions for Variables A program refers to a variable by using its name. is used to refer to an area in memory in which a value is stored. For example. The various types of variables on the basis of the variable scope in Java are: ffi Class variables: Are accessible within a class and its objects. Avariable is the name that refers to a memory location where some data value is stored.

: : . is W Local variables: Are declared inside a method. W Static variables: Are allocated memory only once but are globally accessible to all instances of a class. and num2 to calculate the sum of two numbers: int num1.. numl. The Java compiler initializes the class data variables to default values when an object is created. You can also assign the same value to more than one variable in a single statement.: | . and the scope of a variable. you need to initialize variables before you use them. The following syntax shows how to declare a variable: <type> <variablename>.& .. num2:10. i&1 €gy. In the preceding syntax.variable2name. // Single varj-abfe of gÍven type. the static variable is not destroyed and is available to other instances of that class. ntm2. Theirscope is within the block of code in which they are defined. . when an instance of a class is destroyed. They are local to the block of code and are not accessible outside the method. For example.'l I w Instance variables: Are declared inside a class and are created when the class instantiated. The following syntax shows how to assign values to a variable: <type> <variablename>=<vafue>. and num2 to calculate the sum of two numbers: int num1. The automatic variables are created when a function is called and are destroyed when you exit the function. Objects give different values to instance variables as per the specific requirements of the object of that class type. iij .:a' &a& @ 3*wm Yeanúmrrq*ffita&s 2fi^"27 . you can use the following statement to assign values to the variables.. '! :: .variable variables of given type. . data type.. n name> // ltultiple <type><variablelname. num2. For example. A variable has to be declared before you access it. :. You can assign values to a variable during declaration or after declaration of the variable before first use of the variable. w Automatic variables: Are accessible within the function in which they are declared. Declaring Variables The declaration of a variable informs the compiler about the variable name. / / During declaration. ::: : ' . The following statement shows the assignment of the same value to more than one variable: ^ _L_^_ ? . // Assigning values to the variables. ! '.. // Declaration of variables' numl : 5. 1 : ::: | . num1. <variablename):(value) // After decl-aration. Therefore. !: . ' :' : : ' . you can use the following statement to declare the variables.

Boolean literals: Are the literals having value. which accept one or more operands or arguments and produce an output. alphabets. you use operators.&""zffi Yat¿w ?an*aryt*ntw\s l.: op2. or any other symbol that represents the value to be stored.WLí. Literals in Java Literals are the values to be stored in variables and constants. n=0x456 is integer literal in hexadecimal notation. A literal contains a sequence of characters. For example. the assignment operator assigns the value of right operand. The data type of the variable is compatible with data type of the value assigned to the variable. The operators used to manipulate variables are assignment and arithmetic operators.f . The various types of literals in Java are: ffi Integer literals: Are numeric type values. then to b and finally to a. n=0123 is integer literal in octal notation. For example. integer value 3 is first assigned to variable c. is ffi ffi ffi W Character literals: Are represented in single quotation marks.9 is a floating point literal. The octal notation of a number prefixed by zero and hexadecimal numbers are prefixed by 0x. op2 to the left operand. x='k' is a character literal. such as digits. Assignment Operator You use the assignment operator (=) to assign a value to a variable. op1. The numerical values can be reoresented in octal and hexadecimal notation. true or false.In the preceding command. 7. x=7 . Floating point literals: Are numeric values with fractional paft. For example. Manipulati ng Variables To manipulate data and variables in Java. For example. x= false is a Boolean literal. String literals: Are enclosed in double quotation marks. x="James" is a string literal. and n=2 is decimal notation for an integer literal. For example. The following syntax is used for the assignment operator: op1. In the preceding syntax.

4 and 5. and / operators. you perform the basic mathematical operations..Ls" the following statement: The addition operator 4+5 In the preceding statement. and division using +. you have two numbers.I Arithmetic Operators Arithmetic operators are used to compute mathematical expressions. -. The following table lists the various arithmetic operators. yo. you can use the + operator to concatenate two str¡ng values' For example.{'W&$V ?awm Fayndaryiernte\# a&. In addition to the numbers. multiplication. (+) is used to add two ¡ntegers and concatenate two string values' For example. To add these numberr. +. you use the. such as addition. Operatoi + Adds two operands Subtracts one operand from another.9# . operator to concatenate the two values to produce a result 9. . x. produces the result. subtraction. the expression. Multiplies two operands Divides two operands o/o Calculates the modulus ++ Increments a variable Decrements a variable Basic Arith metic Operators In Java. ab + cd. abcd.

2 < 4.2. . you add 3 to -10) -7+3=-4 -4+3=-! l-11 < 3.2: 9.4 5. the result of the modulus operator is -1.ava fundamentals ffirg## .20 f. s -!00/o-6: -10-(-6)=-4 l-41 < l-61. You can apply the modulus operator on both integer and floating-point values. Therefore. I 9. Therefore.2=5. the result of the modulus operator is 1. 24.2. Therefore. Therefore. the result of the modult¡s operator is -4. J -10 Vo 3: -10 + 3 = -7 (To reduce the magnitude of -10 by 3.4-4.2 L.6 o/o 4.6-4. The following examples show the results of modulus operator on two operands: * L5 o/o 6: 15-6=9 9-6=3 3 < 6. the result of the modulus operator is 3.2=L.Modulus Operator The modulus operator (9o) returns the remainder of a divisjon as a result of a division operation.

might need an array of integers to hold the IDs of the employees. An array is a group of variables of the same data type and referred to Dy a common name. In addition. Arrays make it easy to do calculations in a loop. such as determining the total number of values stored in an array. you can declare an array. to store the marks of 5000 students. The advantage of using array lies in the fact that you can refer to a large number of elements by just specifying the subscript preceded by the array name. of size 5000 and can store the marks of as many students.'?áXÁry 3 aaa a W e3 ffi {3 m rvi * ffitffiE%. The complete set of values is known as an array and the individual entities are called as elements of the array. you can use arrays. An array consists of a name and the number of elements of the array.You might come across a situation where you need to store similar Wpe of values for a large number of data items. each variable name needs to be unique. you need to declare thousands of variables. For example. which is known as the index number. the automated employee management system of SimpleSystemsSolutions Inc. marks. Creating Arrays The length of an array is fixed at the time of its creation. to store the marks of all the students of a university. The following command shows an array named employee: employee l5l . The related data items form a group and are referred to by the same name. You can refer to a specific array element by the array name and the element number. The index is also known as subscript and the array may be called as a collection of subscripted elements of the same data type. To avoid such situations. An array represents related entities having the same data type in contiguous or adjacent memory locations. as perthe variable naming rules. x&"3"9 . i. An array is a contiguous block of memory locations referred by a common name. For example. For example. It is practically impossible for a person to ¡'emember the name of each variable. A specific value in an array is indicated by writing the array name and placing the index of the desired element in square brackets.

The following syntax shows how to declare a one-dimensional string array: af ri nn ¡laci n¡¡+i nn f r¡naa .' In the preceding syntax/ type is the data type of the array.t a i.' rtt i. for its employees.. You can use the following statement to allocate memory to an array having 3 elements: Emp_ID : b3y/ string [3].. [10]. . you have an array that contains the names of the various designations offered by SimpleSystemsSolutions Inc..F--- The various types of arrays in Java are: W W One-dimensional arrays Multi-dimensional arrays One-dimens¡onal Arrays One-dimensional array is a list of variables of the same data type. the designation_types array is declared that can store 10 designation types in it. All the elements of the array contain variables of the same data type as the array. The following syntax shows how to declare a one-dimensional array: type arr [] . :. The following syntax shows how to allocate memory to a one-dimensional array: arr = ner^7 type Isize] .:1:). For example.. Allocating Memory to Arrays You use the new operator to allocate memory to an array._types l1ñ l . In the preceding syntax.::ti::i:t:::!::::1 ke"?"x Sawa Frs*&azw*r*Eals wlw&..

The SimpleSolutionsSystem Inc. The following code snippet manually allocates memory to the second dimension: muftiDim[0] : new int[4]t multiDim[1] = new ínt[4]. emp*ID l2l Memory Allocation to Arrays M ulti-dimens¡onal Arrays In addition to one-dimensional arrays. The following figure shows how memory locations are allocated to the emp_ID[] array.1finimrlr mul-LiDim[2] = new int[4]. you need not allocate the same number to each dimension.. To declare multi-dimensional arrays/ you need to specify multiple square brackets after the array name. :u'MYYW Smww Wanúmcw*.tttwfrs m&"ffiffi . as shown in the preceding syntax. multiDim[0] = new ínt [1].r-rñr-'1 tLL L I - -=w Itr intt3l [].' Ll _ rrr intt3] tI. you can create multi-dimensional arrays. ñ. In a multi-dimensional array. you need to allocate memory for only the first dimension.z in which the sizes of the second dimension are not eoual: i-r *_. You can use the following code snippet to create a multi-dimensional arra. emp-ID[].. - ñóil int[2]. You can allocate the remaining dimensions separately. For example. the following syntax displays the declaration of a two dimensional array: r-+ ¿rr L Iluf Lf yf -.r+rñr*.-eh. In addition. needs to store the employee IDs in an array. when you allocate memory to the second dimension of a multi-dimensional array. multiDim[2] : new int[4]. LrvrrLf .

"Assistant Manager". _ . For example. The following syntax shows how to declare an array and allocate the array in a single statement: tYPe arrLl = new:YPelsizel. you need to specify the name of the array and the index number of the element. you can access values from elements the array by referring to the element by its index number. retrieve.:wztT . The following statement used to access and display an element stored at a specific index position: nacinn:f i¡n r¡'naciñl-^aci¡n:f i^n '" f \. You can use the following code snippet to assign values to different elements of the given array: String designation_types.*úwm*. des i gnat i or_:vpes i j : designation types l0l -"Genera: Mar. the following statement assigns the value "ceneraf Manager" to the first element of the array.' : r" Generaf Manager".nteAfi tr.ñeS[2]"JF in is In the preceding statement.' designation typesl2l= "Managing Di. The index position of the first element in the array is 0.ager". You can use the following code snippet to declare and initialize arrays in the same statement: "Managing Director" ] . the value of the third element of the array is assigned to the first element of the array. You can declare and allocate memory to a user-defined array in a-single statement.Accessing Arrays You need to access various elements of an array to assign. designation types: new Scringl3l. String Designation_typesil Accessing values from var¡ous elements of an array Similar to assigning values to array elements. designation typesl0l: "General Manager". designation types l1l: "Assistant Manager". 3&"24 3atra ft¿. and manipulate the values stored in the array Assigning Values to the Elements of an Array To access a specific array.rector".

The JVM converts the Bytecode contained in the . a #:Wb{'{ Tmww Wzxn#ar{e*{2tffi&# ¿. w The abstract data types include the data types derived from the primitive data types.. w A variable is the basic storage unit in Java.é4.. ffi Simple Object-oriented Compiled and interpreted Portable Distributed Robust Secure Various components of the Java architecture are: Java Java Java Java programming language class file Virtual Machine Application Programming Interface (API). Characters: Include char. int. short. Boolean: Include boolean.In this lesson. w The built-in or the intrinsic data types in Java are known as the primitive or the simple data types. ¿.3 . you learned: W W Java is both a language and a technology used to develop desktop and Internet-based applications known as Java applications and applets. It is the name that refers to memory location where some data value is stored. which express the language features. ffi ¡ . data type. w The various data types defined in Java are: o o o o Integers: Include byte. o . The various characteristics of Java programming language are: ¡ ¡ o o o ¡ . data type. and long data types Floating-point numbers: Include double and float data types. ffi The keywords are the reserved words for a language.class file to machine object code.

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

W . int. ffi The keywords are the reserved words for a language. Java Java Java Java programming language class t¡te The various data types defined in Java are: Integers: Include bvte. w r . o .w Java is both a language and a technology used to develoo desktop and Internet-based applications known as Java applications and applets. ffi A variable is the basic storage uh¡t ¡n Java. w The built-in or the intrinsic data types in Java are known as the primitive or the simple data types. r r . which express the language features. and long data types Floating-point numbers: Include double and float data types. a ?. The abstract data types ínclude the data types derived from the primitive data types.class file to machine object code. It is the name that refers to memory location where some data value is stored. Characters: Include char. short.A. o o o o ¡ t W S¡mple Object-oriented Compiled and interpreted Portable Distributed Robust Secure Var¡ous components of the Java architecture are: Viftual Machine Application Programming Interface (ApI) w The JVM converts the Bytecode contained in the . w The various characterístics of Java programming language are: . Boolean: Include boolean. data type.27 . data type.

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

rt.:l:iii...W hessom kB Cmsses AF*n On¡EcTs ectives In this lesson.:..Á.....: '3 * q "* Y ¿¿'* rÁ * t"rz r.:a::.t..i:::.::t.g v¿"6..i::.t. "..:t!.i:. . you will learn about: d Structure of a Java program F Access specifiers and mbd¡f¡ers 5 Creating a Java application Have you reg¡ster at.:at.::t.:n::t.:.!t..:. s ¿ lq "!: '.:::.:i:!..::i..!i.

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

The state of each book is independent of the state of another book. A networked application uses the resources available over a network. {}. which indicate the start and end of the class. In addition. An object is an instance of a class. the books have various common methods. Classes and objects form the basis of the structure of a Java application. Methods of a class contain a set of executable statements that gives a desired output. Creating Classes and Objects A class defines user-defined objects and their characteristics. and it encapsulates the methods and data members of a class. and title. A stand-alone application uses resources of a local computer. The class block orthe class body is included within a set of braces. in which you declare the data members and methods. such as the number of pages. when you create an online shopping site for books. you can either create a stand-alone application or a networked application.a-l At-t r ¡ o SrnucruRE or Jnva AppucATroN In Java. each book is an instance of the Books class. such as being selected. The main components of a class are: I S Data members (attributes) Methods Classes contain statements that include the declaration of data members. For example. All books have attributes. A class defines the attributes and methods of objects of the same type sharing common characteristics. For example. Any concept that you need to implement in a Java program is encapsulated within a class. ti'#lNY . and being sold. Objects can be reused across programs. being bought. which specify the type of data to be stored. a networked application is allowed to read from or write to files on remote computers. Methods define the action to be carried out on the data members of the class. A lava application cons¡sts of a class.-l -l f. type of binding.

This name is required to create objects of the class. You can also declare an empty class that does not contain any data members and methods. The following syntax shows how to declare a class: class CfassName / /DecIaraLion of data members / /DecLaraLion of methods l l In the preceding syntax. Organization. These sta[ements are considered as comment entries by the compiler. It best practice to include comment entries to describe the code. which does not have data members and methods.:"""' . without any data members and methods: class Organizatron { // No data members and methods l :. 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. float price. int pages. consider a class. Organization. The preceding syntax consists of a few statements that are prefixed with double slash. void getQ.The following figure shows the members of the Book class: String title. .. //. For example. the word class is a keyword in lava used to declare a class and className is the name given to the class. The statements written in a Java class must end with a semicolon. The is the Compiler ignores these statements and these are not executed at run time. Y. The following syntax shows the declaration of an empty class.

.u.' String employeeDesignation.ir""'-J'l I )!'(v a¡. a class is an abstraction of the common properties of various objects.' ) Creating Objects of Classes An object is an instance of a class and has a unique identity. a V: as'¡: # t* rz' v r* *. The new operator allocates memory to an object and returns a reference to that memory location in the object variable. .WlY 3 .' :. 2. The following syntax shows how to create an object: obj ect_name= new cfass_name ( ) .v""rl fttttlo"¡ '= c'<¿C) ) I 'i-'r. and em ployeeDesignation. To allocate memory to the object. you cannot store data in the data members of the object.' 'rr 'l - ! . While an object has a unique identity.n 54¿vt.' \. you need to use the new operator. memory is not allocated to it.' j-nt emp]oyeeID.. The following syntax shows how to declare an object of the class: cf ass_name obj ect_name.. When you declare an object. employeelD.!...You can use the following code snippet to declare the Employee class that defines various data members. you need to perform the following steps: 1.c. such as employeeName.. i:rr'e ütc*:r*:5 ga+t¡ l r'l '.-r. To create an object.'4re¿ {rrr t' 'i . '4. Classes and objects are closely linked to each other. Declaration: Declares a variable that holds the reference to the object.' Instantiation or creation: Creates an object of the specified class.' . cJ-ass Employee I String empf oyeeName. Therefore.|'tr1"7'oVC)'. The identity of an object distinguishes it from other objects. E rqu\) .t.t x a+ r¿ .

The following syntax shovrs how to access the data members of a class outside the class: obj ect_name .€ wt fi oecra'e Yt Ernproye* a I el --.' Accessing Data Members of a Class You need to assign values to data members of the object before using them. You c¿access the data members of a class outside the class by specifying the object name followed by the dot operator and the data member name. e1. . Employee e3 :new Employee O. ob¡ ect_name refers to the name of the object and dara_member_name refers to the name of the data variable inside the object that yowant to access. Employee e2 =new Employee O .The following figure shows how an object is created and reference is assigned to memory allocated for the object: t. You can use the following code snippet to create objects for four employees of an organization: Employee el :new lmployee O . ---+ I 4_________J " Cre¿te el E rn = new plnyee{) Creating an Object You can use the following statement to declare and instantiate an object. data_member_name In the preceding syntax.l l{lIT .& J:. Empf oyee e4 :new Employee O .:."J:?. of the Employee class in a single statement: Employee e1= new Employee O.

e1 and e2: e1 . use many"' at various The following figure shows the reusability of code by calling a method places in a Program: MEth0d lt il tl I tl methods.membersofac|asscanbeatedioustask. The practice of reusing a method is also called "write once.referringtomu|tipledata."it" a methbd that can be used to access the data members' Using methods a Java program provides the following advantages: W or a Reusability: Enables you to reuse the whole code or a paft of it.. method at rd add two ñumbers defined in a class. employeeName:" John" . emp-Lovee LD=¿ i el. . When you call the addg . e2 . For eiample. you have a method.- wtr\T ."n c..céssing ¿aía mem¡ers directly overrules the concept of encapsulation' in . and employeeDesignation and them through objects.. employeelD:1. The programmercan addo that is class by executing methods. task ¡s encapsulated in a method that can be accessed from anywhere program.empfoyeeDesignation : "Manaqer" e2. You can use the following code snippet to access data members of the assign values to such as employeeName]employeeiD. '¡.whichareimp|ementedas ffi Data Hiding: Hides the implementation details of an object' When you call a how that method from another location in the code.¡ you call the method by its name' You need not a different location in the code.InYou á¿J¡tioni". Adding Methods to a Class Inaprogram. Fraqram 2 | 1_____*________J Access¡ng Methods ffi Reduce complexity: Reduces complexity in a code having hundreds of lines' A |argeandcomplexcodeisdividedintoprocedures. A function in the . you do not need. emmployeeName="AndY" i e1 . eZ .ernployeeDesignation : "Director" .to know access the data members of the method is being executed.Employee class.

static. You need not create an obiect of the class to call the main ( ) methOd.just calling it. define the functionality of the addO method again. The following syntax shows how to define a method: void methodName // Mo1 hnri ( ) l¡ndr¡ In the preceding syntax. Declaring the main g Method O method that calls the methods defined in a class. The main O method can be declared in any class. such as adding. the void keyword specifies that the function does not return any value.1i¡ { efrf i¡ ¡¡niA A Java program consists of the main main(String[] () args) / / Code for main ] method In the preceding syntax. The automated solution of the organization consists of various methods for performing these functions. The file must ¡"'mtlr . deleting. You can create a number of classes in a Java program. the method header contains three words public. You can reuse the method by Adding Methods to Classes The management of SimplesystemsSolutions Inc. you need to include a mainO method in the program. performs various functions. and void. static: The static keyword is used with the main O method that associates the method with its class. but the name of the file and the class name in which the main O method is declared should be the same. The Java compiler compiles all the classes in an application but to execute a program. The implications of these three words are: W W 'ffi public: The public keyword indicatesthatthe method can be accessed from any object in a Java program. and modifying the details of its employees. void: The void keyword signifies that the maín O method returns no value. The methodName SpeCifies the name of the method. The following syntax shows how to declare the main O method: nrrl-.

t} ?a í:. if the main O method is declared in class Employee. Defining Constructors You might have observed that to initialize the data members of a class. r.: | 1:.::':::- aar 1:l :. the method header shows one argument in parentheses. / / Data members of the cfass int interesrRa:e.. ar:. the name of the file should be Employee. you need to assign values to each data member. However. An argument is a variable that you need to pass to a method for providing an input value to the method.:. / / initiafization ínteresLRace : 5. Constructors do not have a return type. Accc:inr O of the class to initialize the values of the data members of the Account class. cfass Accou:r-int prlnclpai...java extension. AccountO // Ccost-ructor method principal : 10000. :. .2 {: A.:'1 4.is the array containing the string values.4 &iWiáHW ' ¡'. Strings are a sequence of characters. int time. it might turn out to be a tedious task if you need to initialize a large number of data members..n q . For example. :::::: ::. A constructor of a class is automatically invoked every time an instance of a class is created.13 . 7: "t+i !* r'fi. void interest O // method decfaration { { { of data members ] . For example. time= 2. ai:. an array of strings is sent to the program that helps in program initialization. you can create constructors of the classes that automatically initialize the data members of the class when you create an object..:.a':: (S--:'ng arr [ ] ) In the preceding statement. You can use the following code snippet to add a constructor. The main g method accepts a single argument in the form of an array of elements of type String as shown in the following command: public static vc' j ::. to calculate the interest on the balance amount in the account of a customer you can create an Account class.a:.:!':l::. A constructor is a method with the same name as the class name.have the ..1:t-. j ava. The argument implies that when the class Employee is executed. In Java.

There is no retum type for a constructor. each time an object of the Account class is created. Constructors have the following characteristics: I t I A constructor has the same name as the class itself. A constructor is used to assign values to the data members of each object created from a class.1ü Java Fundarnentals sttrtr? . 28. A constructor returns the instance of the class instead of a value.float amou¡¡: (principal*interestRate*tine) /100.' // method accessing the data members of the class ] l In the preceding code snippet. the constructor is invoked and the object data members are initialized to the default values as specified in the constructor.

in a banking appfication you might need to hide information. A pckage is a collection of classes' The pui-:: keytrrord is used to declare a member as public. . such as customer balance.'3" 1t. or a package other than the one in which the class is dedared. package in whkh the dass is created.=l:--: ::a::e>. but outside the class you need to resüict access to üis information' Java provides access specrñers and modifiers to decide which part of the class. Yot¡ can use a public class. For example.' &:I*lT 3. such as data members ar¡d rnetilods will be accessible to other classes or objects and how the data members are r¡sed in oüter classes and objects. data member. The varbr"¡s tyoes of access specifiers in Java are: W W W public private protected t friendly or pactage The public Access SPecifier Class members witfr publE specifiercan be accessed anywhere in the same class. from unauthorized access by other classes of the application' Within the Account dass. Access Specifiers An access specifrer aontrols tñe access of class members and variables by other objects. the meürods access the information. The following statement shows how to dedare a data member of a class as public: nrhl'e <i=-= -. or a methOd from any object in a Java progñrn.::> <.í¡* .3 hr- Accrss SPecrrrERs HoorrrERs AND Classes enable an object to access data variables or methods of another class.

/ / PrivaLe method ffoat The Account class defines the show O method and the various data members. You can use the following code snippet to define a class. such as name and account number. / / private data member of ffoat methodNane O. such as age and bafance i kw"kx 3 wza -m Y a.Y ffi&& 6 . In Java. A data member of a class declared private is accessible at the class level only in which it is defined. You can use the private access specifier to declare members that should be available to the class within which they are declared.F I "I 'a f The class Account defines the show O method and various data members. these data members and the method are declared public. Accounr that contains public data variables and method: public class Account public int account_no.a ra# m nz * w.println("Account number of this customer is: "+ In the example of a library. All the classes in the program can access the various details of a customer.t m& w ffi|W*&ry . Therefore. The showl¡ method is used to display the account number and customer name of a customer.out. such as name and account number. public void showO //¡tethod declaration { System. a The following syntax shows how to declare a data memberof a class asprivare: tvpe private private <variabfeName>. these methods are declared private. You can use the following code snippet that shows the Account class with private data variables. The private Access Specifier The private access specifier provides most restricted level access. The private keyword is used to declare member as private. you implement the concept of encapsulatio+. the books that are access¡ble by general public are declared public. / / Data members are accessibfe outside the class public String name.out.. ] ) System. such as balance and age. These members are to be accessed only by the objects of the same class.println("Name :"+ name) .//Statement of the method { account_no) .by using the private keyword. Therefore.

out. the objects of Account class can call the show o method. privat.. private int age. ffiW Sazaw YÍtm*mm*rz%mTw x&"93 .println("Balance of this customer is: "+ ] In the preceding code sn¡ppet. tíme.f é.:E:::4i6i6&Ett¿e. you can create the Ticket class that cons¡sts of various data members.out.in¡f cr-asses in¡.i. but objects of other classes cannot access or invoke the private members of Account class.e ffoat balance.E{tt.'+ age) i System.'l (l.println ("Age :. such oS flightNumber.). You can.!tF.fad Sfrinn r! v eev uvs protected String date + i ma doc1.use the following code snippet to define the ricret class that has protected data variables: public class Tícket { ñr^ró^+^A i nr f I i nhr\r. searNumber.iii. protected void t showData o / l ] / Code bodv t.#í)#.tti. The protecreo keyword is used to declare a member as protected. you can derive the confirmedricket subclass from the ricker class that consists of an additional data member.íf. 3fld destination. In an airline reservat¡on application. date. System. The following statement shows how to declare a member as protected: protected <data type> <name of the variable). which can be accessed by the confirmedTicker subclass.ri n¡ nrofF. The protected Access Specifier The variables and methods that are declared protected are accessible only to the subclasses of the class in which they are declared..'1i.. // Data members converted to private to encapsulate data private String name.¿ nróté.rm]¡ar' / /protected data members accessib_Le to 'áJrr-r. you can declare the data members of the Ticket class as protected.class Account int accounL_no. public void showO // Method can be cafled from outside the class to access the data members { prlvate { bal-ance) ) .. ::Eltii:dÉi!..tiifa: .a&::! :.

variable. such as pageNumbers 3ñd price. / / float price. It is a term that is used for the access level when no access specifier has been specified.}3!:!.#: HW. The data members.É&!:^+*:+*üj2.Z& Smwm Wwv. The following code snippet shows the Books class that has friendly access specifier: cfass { Books Tine int pageNumbers. Types of Permitted Modifiers Modifiers determine or define how the data members and methods are used in other classes and objects.ry::.ffike4% ffiffiv .1*::i. which are organized into groups in a package. the scope of data members and methods is friendly.Á6aá86ffiñ@t@*:n:zi::i.4Y.In the preceding code snippet various data members and methods are declared protected. You cannot declare a class. The friendly or package Access Specifier If you do not specify any access specifier. A class.1#KáiÉ:#trp-gseE@e4|e:e.*w*iaááM)táidñw9@F. or method that has friendly access is accessible only to the classes of a package.z&m#e*.4. The main difference between access specifiers and modifiers is that access specifiers define the accessibility of the data members in a class and the modifiers determine how these methods are used and modified by other classes. or method with the friendly specifier. The various modifiers permitted in Java are: W static ffi final * abstract & native á6áúfu¿. friendly is not a keyword. and the showData0 method of the eooks class are not given access specifiers. void showData o { defaul-t friendly access is provided to the data members // Code bodv ] I In Java. Java provides a large number of classes. variable.

class are implicitly final. and you do not want anybody to modify the methods in a subclass and use them in a different manner. and inner classes. it will cause run-time errors' A variable declared final is initialized at the time it is declared. A class can be declared as final if you do not want the 4WW 3'*'* a* F z*'*z # m {T4 *ffit& # * AW"Lffi . If the variable has been declared fina1. consider a variable that has been assigned a value.modifier does not allow. The f ínal. and classes. you can keep track of the number of books sold by keeping static counter data member in the Books class that ¡ncrement each time a book is sold. The static keyword is used to define chss variables and methods that belong to a class and not to any pafticular instance of the class. You cannot access non-static data members and methods from a static method. The f inar modifier has the following cha racteristics: fhe finat keyword is used with methods. For example. final indicates that the data member cannot be modified. It is used to create classes that serve as a standard. The final modifier W A finaf method cannot be modified in the subclass. which are associated with objects. For example. you cannot modify the value of the variable and if you try to do so. all the objects of a class share the same static data members and methods. the class to be inherited. Therefore. variables. Non-static methods are those. variables. ffi A final class cannot be inherited' W All the methods and data members in a f inal class to be subclassed. A static method associates the data members with a class and not the objects of the class. and as a result the values of the data members differ for different objects.f# synchronized stát¡c The static keyword is used with methods. in an online shopping application.

i. kffi. The natj-ve keyword with a method indicates thatthe method lies outside the Java Runtime Environment (JRE).) . only one thread can access a shared resource when two or more threads need access to the resource at the same time. In addition. native Íhe native modifier is used only with methods. A thread is a unit of execution within a process. For example. For example. An abstract class is used as a base class to derive specific classes of the same type.zü 3 p. synchronized The synchronized modifier is used for methods. It is used to inform the compiler that the method has been coded in a programming language otherthan Java. The native method makes a program platform- dependent. u¡ * W sa ** m r* * rz{*fr '* ffiwyt . only one thread can access the printer as the result of synchronization. such as C or C++.|ái. In a multithreaded program. and type of binding for all the books. you can create an abstract Books class that contains the common data members. page numbers. such as title. :!: :! ei: F9 d a a i d. The synchronized modifier controls the access to a block of code in a multithreaded programming environment. They are used when you have an existing code in another language and do not want to rewrite the code in Java..abstract The abstract keyword is used to declare classes that only define common propefties and behavior of other classes.ronization.t. . The following syntax shows how to declare a native modifier: public native void nativeMethod(varI. you need to synchronize various threads. . writing native methods must be avoided. As a result of synch. Java supports multithreaded programming and each thread defines a separate path of execution. var2. if multiple threads need to print a document.

..ff'{ :. A thread u mming and a result of IIVIE Or more rt . as Notepad: { such aS C or class Hello public static { rrs outside the void main(String args[]) /* Output of the String */ Syst.class file. To compile the .' Hl1'{" .. You can also give the complete path of the ....println("Welcome to the Exciting World of Java").CouprlrNc rEss to derive Books class : and type of AN AppLrcATroN -:n properties After you create an application.java file while compiling it. Open the command window. Change to the directory where you have saved the .re. Compile the application. When you compile the application. Execute the application. The successful compilation of the application results in the Bytecode generation of the application.. with a .. the compiler checks for the compile-time errors. Compiling an Application 'er controls t. The following application consists of the basic structure of a Java application and should be written in a text editor appl¡cation. such tire :ompiler that . In this case the file name should be sello. 2.. r_O2\bin 3.java file. as follows: C:\j2sdk1.. . you need to compile it before executing it. 2.$$.:l.tiple 'r- To compile an application/ you need to save the code with a file name that is exactly the same as that of the class name.4..i.java extension.i . you need to perform the following steps: e*rsting code the code 1. ] ] To complete and execute the application. which is a . you need to perform the following steps: ls :s the result 1. Set the PATH variable to the bin directory of the installation directory.out.em. j ava..java file.

.4. Compile the application by using the following command at the command prompt. ffiW . 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.

such as account number. publíc Account o { { encapsulate data duuOUnE_nO age : 35. w 1. private int age. printl-n ( ) method. Code the Application You need to write the code to create an application that consists of the Account class. Compile and execute the application. out . To solve the above problem. java file: cfass Account private int account_no. and balance. the application must display the data stored in the object. you need to define the rnain ( ) method that creates an object of the Account class and executes the showoata O method. 1. Solution The Java application is created using the system. In addition. The class must conta¡n a constructor that initializes the data members of the class. ) name : I. = "Susan Ward". name.' private float balance. ffiW Twwm W**n&mnzwr'*Km&* p. / / Data members converted to private to private Strj-ng name.Problem Statement You need to create an Account class that consists of various data members. You can use the following code to create the Account class and save it as Account. 2. perform the following tasks: Code the application.* . The application must initialize the data members to default values when an object of the Account class is created.U"3. In addition. You also need to define the shownata ( ) method that displays the data stored in the object. bafance = 500. age.

91r!::::!!.¡Data ] ] 2.out.+^Rj:+wg/9!.pq9!e@p@vá.49.java The command to execute the Hello application is: java Account i*:Yiil:Y.::)li:i#*1::!.' ñri ñ1. Compile and Execute the Application The command to compile the Account application is: javac Account. sho!.príntIn ("Name : "+ name) System.4lpi€.l ñ lrlAdó : rr+ rñó\ . out q\rql.éñ ^rrl- : rr+ :¡¡nrrnl- nn\' balance) ] nrrhli¡ { System.Frg)g94iasgtílnñ:@:F/fsdddddtí$ .ffiff .xffi"n& 3 mza w W q* ra & * {ve *{EE ffiá # #.r!+r¡94|gYv.printfn ("Balance of this customer is : "+ ..publ-ic void showData O / / Vetnoa can be ca11ed from outside the cfass to access the data members { . i¡ r¡nid vg9. cl-¡f main ( (String args [ ] ) Account ac : new Account O .P99g.9t:9.dÁná. printl-n ( "Account Number System. ac.out.r!9!!!enAi94p.r¡.

Class members with public specifier can be accessed anywhere in the same class. same package. Creating a class includes declaration of class members. public.:a W A class includes data members and methods. A class with only data members is of no practical use. final.4. You can access data members outside the class through class objects. 'p^&". A constructor returns no value and has the same name as the class itself. and synchronized. There are private. There are two types of constructors the default constructor and the overloaded constructor.2n . Data members of same type can be declared in a single line. A Java application requires a mainO method to start execution. Object creation includes declaration of class object variable and assignin g memory to object variable. and protected access specifiers. W W W W W W W W W W W W W The Java interpreter first of all looks for the maino method. You can declare a class without data variables and methods. Methods can include expressions that evaluate a value. W W W A modifier determines the use of the data members and methods in other classes and objects..:. The constructor can be used to initialize data members of newly created object. or a different package. Private access specifier gives the most restricted access among all the access specifiers. You can use access specifiers to restrict the access to class members by other classes. The various modifiers available in Java are static. native. The class name and the file name in which the mainO method is declared are same. You can interact directly with data members inside the class only. abstract. A constructor is invoked on every creation of an object of a class type.

You need to use the java fileName to execute the fileName'class file' &&.&w.java file.java command to compile the fileName.ffi ffi ffi you must set the PATH variable of the operating system to the bin directory of the installation directory. You need to use the javac fileName. 3m vm W a*rs**sz:s *.ffiHm*w .

Ce*-.-*ECIRATE 3 mw n Y q* rs &w r¿z *ratm E s .

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

tt" ?. was designing a language for consumer electronic devices. The team considered C++ as the model language for designing Java language. They also wanted the language to be simple so that anyone can learn it in less time. security. you will learn about: ffi Evolution and Need for Java W Garbage Collection ín Java Virtual W Setting the CLASSPATH W Significance of the Java class file Machine (JVM) Evolution and Need for Java Initially. iQ:W6"Wtr 3 #.n. USA. The Java designers later added the functions such as distributed. Sun Microsystems developed software A new language named Oak was introduced using the most popular object-oriented language C++. You can use Java to develop network-oriented programs because networking features are built-in in lava. this developed language was called Oak.il!" 'ii. The WWW appeared on the Internet 1993 that transformed the text-based Internet into graphical Internet. In 1991. The team deprecated various ambiguous features from this new language.:t iZ 4:}. Java was not developed forthe Internet programming.*. and portability that make Internet programming simpler to develop using Java. r994 Sun Microsystems team developed a Web browser called HoUava to locate and run applet programs on the Internet. a team of software developers at Sun Microsystems. i. # f ". KnOwIEDGE Bwe In this section.:* | * '"jt"' rá . but was later renamed to Java. Initially. The team aimed at programming the devices from different manufacturers so that the devices could be controlled by a single remote control.f & {: !. The development team headed by James Gosling wanted to design a portable language using which programs that could run on computers with different platforms. Yeár 1990 1991 Development to manipulate electronic devices.

the reference count of the object is set to one. a Java program creates and uses different objects. The space that ¡s used by the object is released for use by another objects. such as the system memory during the run time. Garbage collection is the process that is used to free the memory of the objects that are no longer in use. 1996 Garbage Collection in JVM Garbage collection is a good way to free programmers from the burden of having to explicitly free the allocated memory. On execution. An object that has a reference count of zero is not referenced in a program and is a garbage object. An overhead occurs whenever the counters are incremented or decremented. Each object within a program uses some amount of system resources.. The different approaches used for detecting garbage objects are: W Reference-Counting Collectors W Tracing Collectors W Compacting Collectors Reference-Co u nti ng Col lectors Reference-counting garbage collectors store the references of the objects used within a program. When the object is identified as garbage.:: "é"{. Java was established as an Object-oriented program ming language.& 3 . the reference count of all the objects that it refers to is decremented.Y:i€iÍt: 1995 : i Oak was renamed as Java. it is not required any more and can be deleted. :. In this way. Therefore. The garbage collection feature implies that the new objects are created and all the unreferenced objects are deallocated from the memory. When you reference the object. The garbage collection method can be executed in small parts within a program and the program need not be interrupted for a long time. the reference count of the object is decremented.2 "¿ ia F u¿ t' *A n tat * t zY ¡zÍ * ffi|ww . When a program stops referencing an object. garbage collection serves as a mode for memory recycling where the space occupied by one object is recycled so that it is made available for subsequent new objects. the reference count of the object is incremented by one. When a reference to an object goes out of scope or is assigned a new value. When an object is created.. garbage collection of one object can lead to creation of more garbage objects.

javac.exe. An object is reachable if there are objects that reference it. . either using the -classpath option with Software Development Kit (SDK) tool or by setting the CLASSPATH environment variable. The -classpath option is used when the SDK tools are called.bankrnfo package is: C:) java -classpath C:\Mlprogs\Utility app. The syntax to import a class. The tracing collectors mark the objects that are reachable. all unmarked objects are identified as garbage. Tracing Collector is also known as the mark-and-sweep algorithm.<classpath2>. The following syntax shows how to set the CLASSPATH with an SDK tool: C:) sdktool -classpath (classpathl). The sweep phase garbage collects the unreferenced objects. javac. The class files or classes can be stored either in directories or in archive files. the JVM uses the classpath settings to determine the location of the package and class. t:ffi. semi-colons separate the multiple entries in classpath. 'rwx-tr 3. You can set the CLASSPATH variable using two methods. . At the end of the trace. The mark phase marks all the referenced objects. and javadoc. bank. when you execute the Java program impofting the bank class. Setting the CLASSPATH The CLASSPATH environment variable instructs the IVM class loader to find the classes that are directly or indirectly invoked. variable: C: .:'¡¡ :¡:¡ "{ t:.bankrnfo.bank In the preceding syntax. The following syntax shows how to set the classpath using the classpath environment ) set CLASSPAfH=<classpathl>. r*. All references to the shifted objects are then updated to refer to the new memory locations. CLASSPATH is the environment variable. including the system classes. .r.t :¿Ét:. such as java. The free memory is then available to be used by other objects. a set of roots is defined from the location where the objects are traced. which shows the Java compiler. Compacting Collectors Compacting collectors reduce the fragmentation of memory by moving all the free space to one side during garbage collection. The objects that are not reachable are considered garbage objects since they are not referenced and are not accessed within a program. . . of the app.42 t3'*.Tracing Collectors In this technique.(classpath2). The classpath variable finds the path where the class files are stored while compiling the Java program using the javac compiler. In the preceding syntax. the location where the class files are stored.

if the class.banklnfo.{'app .If the class required is stored in a jar or zip archive file. The following command shows how to view the contents of a class file: javap -c (class_filenane) The of the methods in a class. is contained in a jar file.jar app. you need to specify the name of the archive file as well. then the following syntax shows how to set the classpath variable: C:) java -classpath C:\Mlprogs\Utility\bankdetails. The class files are platform independent therefore you can run a Java program by loading the class file on any system with the Java Runtime Environment (JRE).progs\!. for each ?_ü.baal The following syntax shows how to specify multiple entries in classpath: _C : ) j ava -classpath C : \Mtprogs\Utility . C : \My. lavap command prints the instructions that consist of the Java bytecode.q Smww #s*ffi*mrzu*vaknfrx ffiwf . bank. Significance of the Java Class File The Java class file contains the Java Bytecode. For example.

For example. The variable name should be meaningful.Fno¡¡ THE Expent's Drsx Best Practices Declaring Class Variables as private and Methods as public You should declare all the class variables as private because data should always remain hidden from the objects of other classes. w W In case the variable name consists of multiple words. Tips and Tricks Displaying Text in a Java Program You can also use the drawSrrins O method to display text in addition to the System. The drawstrinSO method requires three tV\W$gW 3 ww m'{. For example. * w rim r* *r*t *á n É. float. you can use the letters. or a boolean variable.v . Methods should be declared as public because the methods provide an interface to the objects of the other classes.{:. i Declaring Class Variables You can follow Hungarian notation to declare variables in lava. fPrice.printlnO method in Java. f.. iAge. If you write a Java program having the for loop that starts from array element 45 to element 90. iAge is an integer variable to store the age of a student. Declaring Arrays Arrays can range from a higher minimum numberto a higher maximum number. The conventions followed in the Hungarian notation are: W The first letter of the variable should indicate the data type used. such as 45 to 90 but it is more efficient to begin arrays with an element 0 because it takes up less memory in the computer to store arrays that begin with 0. the compiler will still allocate the memory to the array starting from elements 0 to array element 44.out. and b to indicate an integer. for example iTotalMarks and fPriceOfCommodity. the first letter of each word should be capitalized. and bResult. i.

The following syntax shows how to set crassPAr¡¡ in Java: SET CLASSPATH= g . The first argument represents the string to be displayed on an applet.. The following code shows assigning a double value to a character variable: class datatype{ nrrl-'l i¡ yqvrre cl.lál- :f \/ñaf i^ rr¡id m¡in lQf rinc ¡ [l l ef af System.print (x) ] ] { . You can use the sET cr. If an integer variable is assigned a character value. \j2sdk1. System.] yuvrru i¡ { i-! . j Av m E. 4.. Similarly. ^l:ca n"l-. out.¡l. In the preceding code. Java suppotts the Client-Server model for network communication. the ASCII value of the character b is displayed as 98.AssPArs= to set the cLAsspATH variable. ffi What will happen if the data type of a variable and the value assigned to the variable are different? If the data type of a variable and the value assigned to the variable are different then compilation error occurs. an error message is displayed.'&".print (x) . "É. The built-in classes of Java support TCP/IP and UDP protocols used for network communication.5. .24. The second and third arguments represent the x and y coordinates of the string to be displayed.arguments.Í r. Setting CLASSPATH cLAsspATH is an environment variable that enables the Java compiler javac.lLl.i¡ r¡nid main lSr rino : ll l char x: 5.#l # #"jW{gE . 1_02\bin FAQs W Why is Java considered ideal for network communication? Java is considered ideal for network communication because it is a platform independent language. Java enables an application to be executed on any network.exe to locate class files to be imported. the ASCil value of the assigned character is displayed as an output. ] ] out. if you assign a float or a double value to a character variable.{:. * rZ # m {:r:É q. The following code shows assigning a character value to an integer variable.

such as int. can two variables have the same letters but different capitatization.# L- .Java is a strongly typed language and it allows the values of the spec¡fic data types.ü"'. which are compatible with the type of variable. w Do all arguments sent to a Java applicat¡on have to be strings? Yes. It differentiates the two variables. variableName and VariableName. you need to convert the value to string. I ! t i 2. all the arguments sent to a Java application have to be string. If you use some other data type. Java is a case-sensitive language. as in variableName and VariableName? w No.

2.

Match the following:

a. b. c.

Variables Literals Keywords

i. Reseryed words ii. Basic storage unit iii. Sequence of characters

3.

Make words from the jumbled letters in the box given below and match them

with their description,

a. b. c.

Class members that can be accessed by the subclasses of the class in

which they are declared.
Class members that are accessible to all the classes of a package by

default.
Class members that can be accessed only by the objects of the same class.

d. Class members that can be accessed anywhere in the same class. e. This method of the String class is used to find the length of a string. f . Collection of classes that can be reused.
S. Are the reserved
words for a language.

h.

A method with the same name as the class name.
IULBPC DFINRE ORETCDPET ELHTGN VPTIARE CKESPAAGS KRDYOESW CNTCSUOORRT

x.ü"L#

"iÉ

mv

w

W

z*

rz&mfsy & {ÉE&A#

ffijwt

W LesseN 2tr
ExpeRETcENT

WW

3 mzs

w

W a*sz rS m

rm

*

szYnfr x

x.w"z

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

such as savings and current acount. The bank offers its customers with a choice of aécbunts. The bank has various branches all over the country and therefore each of the branches has a unique id. phone number. the bank stores the varióus details of its employegs. and display the values stored in the array. address.W Exercise 1 ServeYourMoney bank offers sevices to its various customerc. phone number. account number. and e-mail id. In addition.ú*ret**ka4s #. WW Éi.3 . employee id..ffijÁeÁ.i. such as customer name.iii***ea") Tav* Yxlr. guch as employee name. address. Exercise 2 Write a program to perform arithmetic addition.i. and e-mail address. 12 and 5. multiplication and division on two numbers.*ii. The bank stores üre detaits of its customers. subtraction.w. Ask the students to identify the various classes and their attributes. Exercise 3 Write a program to display the name. address. Create and initialize the arrays. and position of three applicants using arrays.

b. 2. String emPloYeeDes ignation . d. String emPloYeeDesignation. lust In Time c. d.class The lava compiler reads the Java source file and converts it to a file having an extension: a. c. d.IAVA . c. b. b.file JVM stands for: lava Virtual Java Virtual lava Virtual Java Virtual Machine Model Mechanism MethodologY JIT stands for: a. Java In Time b. Identify the correct code snippet to declare a class a.prg . c. 255 256 2s0 : 6. Cl-ass EmploYee { String emPloYeeName. What is the maximum number of dimensions an array can accept: a.jav . ffijWf . d. Employee b.1. int empfoyeelD. 7. . 4. Java Is Time saving 5. a. Which of the following is correct extension of a lava file? a. 266 b. Java Is Tested d. c.W^4 3 *zc m Y L4 rzú mm *. class { ] String emPloYeeName" int employeelD.java . class .java . . rat :a*&r.

int empfoyeelDt String employeeDesignation .C. a. public main(String[] args) // ) { Coae for rnain0 method C. CLASS Employee { l { String employeeName. A constructor does not retum the instane of the dass instead of a value. A constructor has a return type. A constructor ¡s not used to ass¡gn values to the data members of each object created from a class. public static void main(String[] args) { / ) / Code for main O method d. A constructor has the same name as the class itself.. String employeeDes ignation . friendly d. : Identify the correct code sn¡ppet to declare the main O method €|. 9. which of the following characteristic is supported by consFtrctors in Java: a. protected Which of the following is the default access specif¡er in Java? EW Java T*snáarrzemte*e kw"% . b. public static void main(StringO args) / / Code for main O method { l 8.public void static main(String[] args) // l { Code for maino nethod b. d. publ¡c b. private c. c. String employeeName. d-c1ass Employee details i 7. int employeelD.

c. d. Which of the following is a type of permitted modifier: a.10. b. public static private protected 3 m"¿ w W ** rzúwr*wrs%mfr w .

com .niitstudent.www.

Sign up to vote on this title
UsefulNot useful