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

Computer Sc_ UT_1

The document introduces Object-Oriented Programming (OOP) as a solution to the complexities and errors associated with traditional programming languages. It discusses key concepts of OOP such as data abstraction, encapsulation, inheritance, and polymorphism, emphasizing their importance in creating reliable and maintainable software. The chapter aims to provide a foundational understanding of OOP principles before delving into practical applications using Java.

Uploaded by

patraanita322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
4 views

Computer Sc_ UT_1

The document introduces Object-Oriented Programming (OOP) as a solution to the complexities and errors associated with traditional programming languages. It discusses key concepts of OOP such as data abstraction, encapsulation, inheritance, and polymorphism, emphasizing their importance in creating reliable and maintainable software. The chapter aims to provide a foundational understanding of OOP principles before delving into practical applications using Java.

Uploaded by

patraanita322
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 31
31 Ae pe Gener General OOP cone aot Introduction With the rapidly changing worlg epts competitive and versaty and the highly Programs, because of this complexity, prone to errors, in traditional langua, ges. Large are more and software errors can be expensive and even life-threatening. The most adopted and popular programming approach, structured programming approach, failed to show the desired results in terms of bug-free, easy-to- maintain, and reusable programs. The programming approach, Object-Oriented Programming (OOP), offers a new and powerful way to cope with this complexity. Its goal is clearer, more reliable, more easily maintained programs. This chapter introduces general OOP concepts that the traditional languages like C, Pascal, COBOL and BASIC lack in and the new generation Object-Oriented support. Languages In This Chapter — 3.2. Introduction 3.2 Evolution of Software 3.3 Basic Concepts of OOP: ae 6 or 3,2 Evolution of Sohnwore ye ie ; sun serves te OP TF cocneawide but star A prem en only co as a a prema rene rhe tne Ma OP A PRIN, har, language or hangers Mie Aeesert featenes A propramn languanes “e Ws, Lanw Level Langan” U ge oh cemmepriter "ade (using, 1 ands 0), 8 te OB WAGERGE He Cn, ‘ np, birwary @ ly , i which pratrnactacms BO wwentien Using syn” READ, ADD, STORE ee) gb, TRIB, Wis, pk fecduense tans mac hire CRE prop ammarnng, Homevet, 200) PHO a0, iu machine language O%, assembler strate. Nae, . High Level Lanqvoges High Level Languages (HLL) the other aed, Ble ExagiMiec keey wong, erence, election (decison) and erase Ooping) 206 we > ses sng Sita wevery easy to progam with such languages compared 40 How level 1 olen tHe we commer as mace BERGE PE i aoa computer can work with machine language oby “™, {A programming, language should serve tive related porprees 0 it should provide a vehicle for the programenes to specty actions to be (i) it should provide a set of concepts for the programmes t0 use when at na what can be done. The first aspect ideally requires a language that is “close to the mackene”, so that al , simply 2nd efcicaty ia 2 ay that is east The low level languages serve only the first aspect ic. they are close to r, they ‘the machine, high lee! languages serve only the second aspect iz. they are close tote pp However, the languages’C’ and ‘C+ « serve both the aspects, hence can be called na evel languages’. 3.2.1 Programming Paradigms By paradigm, one means 2 way of thinking or doing things. Since the invention of the computer, many programening approaches have been tt = email achenipobomsvonponisiectraiorang seep Gat nod eluchds aad saaiiaieaB increasing complexity of m= Lat ue diecoms (bee Aidiomat hs 4 Paradign means 0 erring ff r dural Programming pron program in a Procedural omputer to do some, MNBuap. © Fg “ thing, The pate the desired c Mputation, 99 i isis A lit of ‘this paradigm is "the instruc m cong shee ich stat , algorithm, eat ™MDt tells the Decide which Procedures Reeded to perform You want ey Languages support this Paradi the be Algorith (subprograms) and returning wn by 5 YOu can fing ¥ pre Hes from viding i facilitie In procedural paradigm, the empha Functions (sg Passing argument all the reason f0F a propranr doing resem) Mts 0 functions function that displays or Checye ees ’ at happens t status while programming Portant part of poe the data? Data is, after HOY daa Yq oD PORE r vas Proaroning data is given second-clace With the increase in Program size, . program is broken down inna” * Single d Into sm, breaking a Program into funcioy can fa . grouping a number of functions to er be extended by called a module, but the Pring thet into a larger entity JA set of related eal ‘ites related. procedure components that carry out Specific Task ner * Brouping of | With the data they Sond 's called’a module is ecomes unwiel "i sth’ functions ‘ieldy. Thus a lar Where there is no grouping of Procedu, > Te5 With rel style suffices. The techniques for designing “good ote the procedural programming procedure of a module. Procedures The Object Oriented Programming To understand this most recent concept among programming paradigms, let us take an example. We have to prepare lot of dishes that involve baking ; for instance, cake, biscuits pe, Pastries, buns etc. We have to write programs for it. Using procedural programming paradigm, we'll have to write separate programs for every recipe and each program will be containing instructions for operating oven. Ovens are used to make a lot of different dishes, ‘We don’t want to create a new oven every time we encounter a new recipe. Having solved a $ sblem once, it would toe new fo beable 10 e108 the satiny fon % rcedural programing, paradigin RATERS HH Tig dry irigyy hi is theoretically poroible, hut It Vt woken) very well in between conventional Mane Hone and its ouirrenmrudinyyy thy interaction b However, if the same pany" ved wing Ojo OMented approach, i fl not only cCompler but alse hake | OMe ar Pivane reuse (easile and POOSDle The ohyctayenied | vim % ’ behaving “hn approach views a problem in terms of objects involved rathwr havnt hy than procedure for doing, it take For instance, we can say ‘Orange’ iy an hj. ty characteristics ate si, colour is orange ete, Its behaviour iy : iN in juicy citrus atid iF tyoy, programming using OOP approach, the characteristics of an opel are, and its behaviour is represented by ity functions aswclated. Theretiy to PH Me, in yy, object represents an entity that can store data and has ito interface throwyh ” fhe tuy The above mentioned problem of baking dishes, in OOP approach, will be vi objects involved (i, OVEN) and ity interlace (ie, the funtion represen This not only results in simpler program design but alws reduces vetting, To understand this concept more traffic flow at a red light crossing, clearly, Jet us consider another exam 1, As you know, procedural programming, paradiga focuses un the: procedures action. te, Using procedural programming paradigm, the above said probletn will be viewey working happening in the traffic-flow i,, moving, halting, turning, etc. The op. however, aims at the objects and their interface. Thus in OOP approach te Problem will be viewed in terms of the objects involved. The objects involved are: cn buses, scooters, auto-rickshaws, taxis ete. : With this elaboration, the concept must be clear enough to {/A M¥ i + 109 o proceed for the OOP paradigm definition. But before that let | pa eee us understand another very important term class. In the above example, cars have been identified as objects. They have characteristis i steering wheel, seats, a motor, brakes etc. and their behaviour is their mobility. Car, bow, is not an object, it is a class (compare with the definition). Opel Astra having reg. no. 52s) object that belongs to the class ‘car’. ‘Car’ is a subclass of another class ‘automobile vs again is a subclass of ‘vehicles’. ‘Object is an instance of ‘class’. For example, we can sy! a class but ‘parrot named Mithu’ is an object. Now, after understanding the basic terminology, we can define object-oriented progr (OOP) paradigm as : Decide which classes and objects are needed ; provide a full set of operations for each cas. ‘This entire chapter focuses on OOP paradigm and in the coming chapters, 7’ implementing some! of these concepts using programming language Java. ‘Some concepts such as Inheritance shall be covered in class XIL. 33 Basic Concepts «4 Oop 33.) The object-oriented pr, draw backs 0A Converting) concepts that help conventional preys These KenIeral comeeps of Cy 5, @ Data Abstraction @ Modularity © Polymorphism Now we'll discuss these COmCepAy in, Witte Data Abstraction Abstraction is the COMET of “ into its al snPhityin, 4 ah wins | Moshe eetion thers 4 the wt a To understand abstraction, let verted 3 US take Athens arin You ny i eee te ea pa : al features to deve tana don pe ae eA handling tse of cer ng arving do you pet ermal details of car like wiring, mony ny ange - Ply the brakes etc. Whis ie kine? Yon jue ch hieution f » ineide in hidden 4s roe only know the exsential things to drive a car withean ioctu bap background details or explanations. Take anuthor cxample of ‘wide beat nee press certain switches accordin, sense ipo eae ieee . 7 _ happening ‘tc. You needn't know. Again this is abstraction you know | oe < cseential things to operate on switch board without knowing the tors so comet ing, ground details of The wrapping up of data and Encapsulation is the most fundamental concept of OOP. it | S0etons (that operate on the is the way of combining both data and the funcions that | Sn) im? 2 ble wnt (called operate on that data under a single unit. ee details te MAI then enon, The only way to access the data is provided by the functions (that are combined along with the data). These functions are called member functions or methods in Java. The data cannot be accessed directly. If you want to read a data item in an object (an instance of the class), you call a member function in the object. It will read the item and retumn the value to you. You can’t access the data directly. The data is hidden, so it is safe from accidental alteration. Data and its functions are said to be encapsulated into a single entity. Let us now consider an analogy to encapsulation. In a big company, there are so many departments, Sales, Accounts, Payroll, Purchase, Production etc. Each department has its own Personnel that maintain its data. Suppose an employee in the production dept. wants to know how much raw material has been purchased for the next month. The production dept employee would not be allowed to himself go through the purchase dept. data files. Rather ee o 334 oriented Languages, sn fect » ase ace them In modules to prog e aad bh applications. in which we may hace hie rm hany 103 hap manage complexity, Varin, oor 1 apie, modula: ¥ in Java is impren munity a.com . Pac sn packaBer’ OMLEDLS Can Use them eM Packs kages, ou ot through; i wy when you start writing Jaya Programs POM commane fae — that depend ate Pecallay packayess ‘ome more clear understanding inheritance is iti, al te sanding "0 understand the whole poi wy nce, we are hum, fori ae ae inherit from the class “Hy, Inherit : to spe. T iyo = ap Fate : reat breathe, at, drink etc. | €babilty of one clase at ‘Human’ inherits these properties from the rae rr, | ie mop inherits some of its Properties from another ‘Mammal’ Capabilities or properties facets (Which | from another clsss, We take our same old exam, nimat behind obj ‘oriented loser to the real world. The principle behind this « rn eeitloped by lan common characteristics with the class from whic @ ‘Automobiles’ and “Pulled Vehicles’ are subclasses of | de guages is much Sort of division is that each subclass shares h it is derived (Fig. 32) ‘Vehicles’. ‘Vehicles’ is Vehicles base class or super class of ‘Automobiles’ and ‘Pulled | Vehicles’. ‘Automobiles Pulled ® ‘Car’ and ‘Bus’ are sub- eee veer classes or derived classes | ro of ‘Automobiles’. © ‘Automobiles’ is the base- red | «CSR bee ir class or super class of ‘Car’ and “Bay Figure 3.2. Property Inheritance. Why Inheritance 2 There are several reasons why inheritance was introduced into OO languages. We are discussing here some major reasons behind introduction of inheritance. majo ind this i i inherit ionship which 1. One major reason behind this is the capability to express the inheritance relationship makes it ensure the closeness with the real-world models (remember the real world stuff mentioned above). "Why ") j rounalsl lt Inheritance allows the addi, . idea 0 | srive ; my jw the wet aul nywdlify ings | Cine can derive 0 HOW Clagy tou ing clone suppome ‘ we have a clase etideny h a joatiren (0 J new feat “We derive the 1 and wow clans Gradiatesigy Many I, yo aril a vsituitert hoot “Coraduate sti . ae add the © a tall? vial the all we teally need 4 ite he erty ry ating tes te tierce tweet students anid prada yy ‘| MI ello 7 ‘cnuduale sie ‘inant oy and efforts ia new clans “Graduate Stinteyy h yo. Hor example ant’ which itself is a nuby-clane of Person’ Wen Grady, jtance in transitive, Ifa claun A inherits propertion Henge pherit the propertics of B hy, eduction the ree nati s0ne reason io the tranitive ied a a wub-clas stl deca be afer it ner Bh asses of A will automatically 1 Bn, then all sul this property | called transitive nature of Inheritance This carries a benefit with it, Suppose we Inherit class B from exiating, a6 A, The clog ¢ D inherit from class B. Later we find that class A (bave claw of B) haw a bug that," corrected. ‘After correcting the bug in A, it ‘automatically will be reflec ted AC1O¥9 All clay,” inherit from A, if the class A has been inherited without changes. See the reduction in gy,” of efforts that one would have done if each class inherited from A was to be ‘mods, separately, a gifted benefit of being transitive, 7 Some Facts and Terms. When we say that the class ‘Student’ inher then’ Person’ is a base class of Student’ and ‘Student’ is a subclass (or derived class) of ‘Pera Although ‘Student’ is a ‘Person’ yet the reverse is not true. A ‘Person’ need. not be ‘student, All members of ‘Student’ are not Note members of class ‘Person’. The class ‘Student’ has properties it does not share with class ‘Person’. For instance, ‘Student’ has a ‘marks-percentage’, but ‘Person’ does not have. its from the CaP A subclass defing only those features thy are unique t0 it. Polymorphism Polymorphism is a key to the power of object-oriented programming, It is so important ha languages that don’t support polymorphism cannot advertise themselves as OO languages Languages that support classes but not polymorphism are called object-based languages. Ada is such language. Polymorphism is the concept that supports the capabili Polyairphisn of object of a class to behave differently in response =i en Se esis hee action. For instance, ‘Human’ isa subclass of ‘Mammal’. Similar a tees t ‘Dog’, ‘Cat’, are also subclasses of ‘Mammal’. Mammals can ee oan: through day-light. So if a message ‘see through daylight’ is d ill behave alike, Now if a message ‘ h passed to all mammals, they al logs will not be able to view 7 night wn Ee oan tee aa erea: ts wil i . A cats (mammals) can behave differently ihn pris ee ee i ae action. This is polymorphism. mammals in response to a message Take another example. If you gi : - If you give 5 +7, it results i ‘A+ BC. it results into‘ it results into 12, the su i ye to distinguish between ae Concatenated strings, The seme o : ie fo ve i ea ‘0 operations (summatior PERE ES AY lata type it is working on, m and concatenation) depending uP “serat OOP CONCEPTS call 105 re we can define He Polymorphism in context of OO programming also as follows: Polymorphism is a pro, fa essence! al " a ey the same message can be sent to objects of several fferent classes, in respond in a different way depending on its class. Adjacent Fig. 3.3 illustrates that a single function name can be used Shape to handle different number and oreo() different types of arguments. This is something similar to a A I Sy rticular word having several pal IB Several Circle Triangle Rectangle different meanings depending on the context. Figure 3.3 Polymorphism, Low Level Languages (LLLs) ie, machine language and assembly language are more clase to the machine as these are machine oriented and require extensive knowledge of computer circuitry. High Level Languages (HLLs) are more close to the programmer as these offer English like keywords and programming constructs (sequence, selection, iteration). + Procedural Programming aims more at procedures. The emphasis is on doing things. Data takes the back seat here. > Modular Programming combines related procedures in a module and hides data under modules. The data are dependent on the functions. The arrangement of data can’t be changed without modifying all the functions that access it. Object oriented prograr inheritance, and polymorp! Object represents data and its associated functions under single unit Class represents a group of similar objects. Abstraction is the way of representing essential Encapsulation is the way of combining data and its associated implements abstraction. Modularity is the property of decomposing a syst Inheritance is the capability of a class to inherit prope’ class is subclass or derived class and the other class is base class % Inheritance supports reusability and is transitive in nature. A subclass defines only those features that are unique to it, rest it inherits from its base class. + Polymorphism is the ability for a message or data to be processed in more than one form. The same operation is performed differently depending upon the data type it is working upon. + mming is based on the principles of data hiding, abstraction, encapsulation, modularity, ism. It implements programs using the objects in an object-oriented language. + I features with background details. functions under single unit. Encapsulation eo oe tem into a set of cohesive and loosely coupled modules. rties from another class. That class that inherits from other oo - CHAP TED Introducing Jayq 41 Introduction Java is a popular third-generati In Thi . nguige which ok be used to een eunecuele thousands of things that a computer sottyare pee do. With the features it offers, Java has become ure fee language of choice for Intemet and Intaws Tiara ee ero applications. Java plays an important role for the oe JAVA Program Java offers, has contributed a lot towards the popularity of Java. This chapter is going to talk about a brief history of Java, its important features, functionality etc, In this chapter, you shall also learn about how to execute java programs. 42 About Java Java is both a programming language and a platform. Like any other programming language, you can use Java to write or create various types of computer applications. Thus, Java fits the definition of a programming language. Java is also a platform for application development. The word platform generally is used to refer to some combination of hardware and system software e.g., operating system Windows Vista on Intel Pentium V or Windows NT on DEC Alphas or System 8.5 on PowerMacs etc. oe pistes datrerent from many ther oe eructive, dynamuc and secur aon . Ppl poe, wo fart deta jog 0% sonar sooner. Wie we nn Pa, * wo smund the World Wide w, 2) iar A deveinped beeping 1 b> aa cutie names Green) to find a way of allowing Bay Pv ap ones ant controllers t0 use 2 common ay. cca ses was originals named Oo bat ine ids ‘by james Gosling along with two other penn Lage was wr : eran wit Fer faueginve while they were working at Sun Microsystems, Ever 8 race ae me Sng mam Changes ty sane tumor ane close f source cole of ave virtual machine (7) 5 the terms ofthe GNU General Putlic License (GPL, —- i ro Zim entry, we mesa f Sats acronyms by Oracle Corporation by ten, se forse hows comes we wera PiattoeEs © fons Cond bor srnerrczets o fons Pisthonm, Miso Edition (joe ME) — targeting environments with limited reson. 6 Soon Pisthorm, Standaxt Edition (jae SE) — targeting workstation environmens © Sone Fiathorss, Extexptine Edition (jae £5) — targeting large distributed enters, , emestet ecroeruremets. 22 Gye Cote De yrs have that compuier programs ase very closely tied to the specific hardware ag oprxitey, eyes toey ran om. For example, 2 Windows program will not be able to run on; computes that onity rams DOS ; A Wisc application can't run on a Unix workstation, and soon, ‘Ts tackle wits Goversity of platiorms, major commercial applications like MS-Word « Nescape Siasopster have to be written almost independently for all different platforms tx om Bat for the applications developed with Java, this is not the case. For, these applications zx Pathormndepentest it. they ase not aftected with changing platforms. Java solves te probhess of ghatform-smbepenience by wsing byte cede. In order to understand the byte code row mmuet be cheer doout compilation process first, which is being discussed below. ntieary Comgiaton Process fa yor seo that 2 program is a set of instructions given to a computer. The program or «st wren by » progzamane say called the Source Cade. This source ce neds © omc to machine lanpuoge cade, wich 2 computer can easily understand. The procs“ emma, + nce cute who machine code, is called compilation. The machine RTRODUICING FAVA carte dependls a tot on the: ui alifteront machine code eaveutable ole Dlattorn it ioe 1 product MH pO, That ae (A100, This resultont men tae ere at whine ovate is called nator Mactune cout ov Macintosh a Figure 4.4 (a) A DOS Prompt. The prompt shows your current directory. When you bring up the prompt for Windows 95/98, your current directory is usually WINDOWS on your C drive (as shown above) or WINNT for Ry “Cy, : ampite your source code file, change your Ne i . re the directory where your file is located. For : : wer 9 wre directory is java on the C drive, you ‘cy example, Hyer rowing command (cd" command) at the | ive, ya" Midd type the following ies prop! and press Enter : : aie . = \WINDOWS> cp D: Now the prompt should change to C:\java>, Io ay ‘Aw shown here, to change to the java directory oe on the D drive, you must reenter the drive, d: It you type dir? at the prompt, you should see all the files under current directory including your file, HelloWorldApp.Java Figure 4.4 (6) Changing Direct CO command * y sana rDin Uolune in drive C has no label. Volume Serial Number is 98R4-P2D2 Directory of C:\JAUA 17 He LoWor ld. java 1% <8 > 17,863.704,576 hytes Free Figure 4.4 (c) Viewing list of files through DIR command. Now you can compile. At the prompt, type the following command and press Enter: Javac Helloworld. java If your prompt reappears without error messages, congratulations. You have success compiled your program. However, if you see any type of error messages then careful the following lines. Error Explanation Dir is a DOS command that lists names of Bad command or file name If you receive above shown error, this means Windows could not find the Java comple javac. Here's one way to tell Windows where to find javac. Suppose you installed the Java Sot" Development Kit in C:\jdk9.0.4. At the prompt you would type the following comm: press Enter ; DOS command, used for ‘current working directory files under one directory. oe AAEUAHT CORN ater 8 WHat, (hy nedterworlel@es ALINE Prony, ign ANNDIY Wytecode tite Web 0 tw 1 Ravn (f) The class, (4 The class tHe comes after Successful compilation, Now that you have a class file, You can run your NM Your program as explained in the following, step. 4. Run the Program In the same directory, now type the following command at the Prompt and press Enter. java HelloWorldApp It will now show you the result of your program. 107 Het oorid. Java 2 Piece» Ges bytes 2 Dircad 17,715,200,224 bytes free s\aauad, ir a RESULT Figure 4.4 (e) Running Java Program Congratulations! Your program works. 2 Creating and Running Java Program Using JCreator LE You can also create and run Java programs in man} \y softwares. Out of these JCreator is my personal favourite because of these reasons : its light weight version (JCreator LE) is a freeware (which can be downloaded from www. jereator.com/download.htm?), @ itis an IDE (Integrated Development Environment) ic,, editor, compiler, executor etc are all available together, and its look and feel is like professional software. Serres ewe ge Make sure to download Creator LE, which is a freeware. Do not download [Creator Pro, it has to be purchased. aseuee COMPUTE, Ses eer i 11 pevoutr, make sure that fava (IDK IN) is insta ay Creator, na Ug yoate and run Java programs i [Creator LE as ’Xplaineg me is “oy, ‘ Before you iris thers you or tt 1. Sat JCreo' — , woator's shortcut on the desktop, It will open [Creat Double click on [Creator's shortey ; P Hor IDE, nce in Creator, click on Pile -» New > File (see below) or press ¢ _ Once th, » . | Figure 4.5 (a) (0) 2. Specify file name and location Te will bring up File Wizard wherein type the filename and directory Where it is t0 8 go We specified HelloWorld,java (see Fig. 4.5(b)). And then click Finish i 3. Type the Code Now it will create works; space for you. Start typing your Program code Fig. 4.5(c)] in the right pane|se % Oh eo De bot BM Ie Gere tem pe JWI Dw sae re 2 teat | Progam Halen java ss velawone eb state veld mat (String ars) ‘ Syston out print Hts Wor) (On First run it may associated vA MN ggooucins 1A 119 LN t pile ond Execute co ing the program, firstly i Mo Afee Neer the crore Ty compile it by ‘licking at Build -+ Compile File command. in \ case 0 : (pa [tock _ coven 15) comet Figure 45 (a types of Program Errors Before you run your program, you need to compile. The compiler is capable of finding some types errors and once your pro d Gram is reported error-free by the compiler, you can execute it. “No compile time error” does not guarantee the cw From the point of view of when errors are detected, errors 1. Compile time errors syntax errors and static sem, 2. Runtime errors dynamic semantic errors, by the compiler (debugging). can be these types antic errors indicated by the compiler. and logical errors, that cannot be detected In order to understand these types of errors, itis important that you understand them with some code examples. Thus we shall get back to this discussion of errors and related of Exception in a later chapter ~ Program Error Types and Basic Exception Handling in Java after you have leat about some basic code of Java. Well, here we are throu; this chapter. igh with the chapter. Let us quickly brush up what we have leamt in Jovy ac, Popular third generation programming language. : J0va was originally named as Oak J0v0 byte code is a machine instruction for a Java processor chip called Java virtual machined. Comp UrtR Sem, + The Jew bye code is independent ofthe computer system it has 10 Tn Pt “tThe byte codes are always exactly the same irrespective of the Ce aaputer system they are to eye. & Java programs are compiled into Java bytecode. : "ty Jave virmal machine is an abstract machine which is implemented om the £0 of N59 proces, + de Jove program there can be many classes but ony ne intl Css ° Trae we no nes of va aplications-interet applet and standalone application. Am Internet applet nuns within a web browser. 4 A seandalone application can run on any plarform. 2 CATT, age, the compiler converts the hy LL. When you compile a program written in the Java programming langua ? source file into platform independent code that a JVM can Me erstand ? What i this plaform inet called ? ‘ Solution. Byte code 2 lr co you sy tht Je Doth programming language and «efor 7 Solution. Like any other programming language, we can use Java fo write or create various n la refer to some combination of hardvay,. computer applications. The word platform generally is used f0 : system software. The Java platform is a new software platform designed to deliver and run highly ine. “k. How is ordinary compilation process diferent from Jaoa compilation ? toa machine code, which i depnig Solution. In ordinary compilation, the source code is converted upon the machine or the platform. ‘This resultant machine code is called native executable code, Contrary to ordinary compilers the Java compiler does not produce native executable code for a parte machine. Instead it produces a special format called byte code. The Java byte code looks a lot like mate language tot unlike machine language Jac byte code is exactly the same on every platform: 4 What do you understand by JVM ? Solution. The Jace Virtual Machine isan abstract machine designed to be implemented on the mpd existing processors. It hides the underlying operating system from Java applications. Programs written in seed into Jace Byte code, which i then interpreted by a special Java Interpreter for a specific ue ‘Actually this Jave interpreter is known as the Java Virtual Machine (JVM). 5. What is Write Omce Run Anywhere characteristic of Java ? Solution. The Java programs need to be written just once, which can be run on different plows without making changes in te Java program. Only the Java interpreter is changed depending upon he pato™ ‘This characteristic is known as Write Once Run Anywhere. 6 Whet wall be the result produced by following Java program ? class MyClass { public static void main (String [ ] a ngs) System. out.println ("Printed from anaes 5 ‘System.out.printIn ("MyClass*) ; - ; 3 , Solution. Printed from inside of pyClass 6.2 A P cu Teta. Flow of Contro| ction Introduction rally a program executes ji ening toend. But not many fee inn from their statements in strict order in &xecute all Most programs decide what to do my mnBtOend. changing circumstances. These progray shone 19 store data but they also Manipulate data fics aus consolidating, rearranging, ‘modiying dont perform their manipulative mirades, propa y tools for performing repetitive actions ang for making decisions. Java of course provides such tools by providing statements to attain so. Such statements are called program flow control statements. This chapter is going to discuss various program flow control statements viz. selection statements, iteration statements and jump statements, Every programming language provides some constructs which are necessary for it to be called as a programming language. Let us talk about these programming constructs briefly, before talking about selection statements. Programming Constructs In a program, statements may be executed sequentially, selectively or _ iteratively. Every Programming language provides constructs to support sequence, selection or iteration. Let us discuss what is meant by sequence, selection or iteration constructs, In This Chopter — 6.1 Introduction 52 Programming Constructs 83 Selection Statements 64 eration Statements 65 Elements that Control a Loop (Pans of a Loop) 8.6 The for Loop — Fixed Nu of erations 67 The while Loop 68 The do-while Loop 6.9 Nested Loops 6.10 Comparison of Loops. 6.11 Jump Statements Sequence. The sequence construct means the statements are being executed sequentially. This represents the default flow of statement (see Fig 6.1). a Every Java function execution begins with its firs i statement, Each statement in turn is executed (sequene me construct). When the final statement of the function is executed, the function is done. This construct specifies the normal flow of control in a program and is the simplest oe Fore ei, Selection. The selection construct means the execution of statemens, condition-test. If a condition evaluates to true, a Course-of-action followed otherwise another course-of-action (a different set of (2 see Figure 6.2 The Selection construct. Iteration. The iteration construct means repetition of a setof-statements depening ioe ion is true (or false depending upon te inn, set-of-statements are repeated again and again. As soon as the condition becomes false (or true depending upon the Statement), the repetition stops. The iteration construct is also called looping construct. Following figure (Fig. 63) illustrates an iteration construct. The set-of-statements that are repeated again and again is called the body of the loop. The condition on which the execution or exit of the loop depends is called the exit condition or test-condition. - 187 Stet Comarness get eration . Seepression’s truth 0 choose the o value Java provides tit gasnnon. in certain Grcumstance Os fon erect a 20 tyP eS of sehectig ion depending upon "Pet ator can be on, sified ee ae * are Maternent ‘so called conditional dae. 2 an alternative to if statement. The yl The # Statement of Java HS OF decision statements where a statement may consist of a single statement, tae of empty statement). The expression must be endosed wr pcan ifn eane in ; parentheses. If the expression exabastes to true ie, a nonzero value, the statement is executed, otherwise F jqstance, the following code fragment ome Fo if (ch =="") spaces ++ 5 checks whether the character variable ch stores 2 space or not if t does, the number of spaces ze incremented by 1. Consider another example illustrating the use of if statement : if(h=="") System.out.printla (“It is 2 space character”) 5 Sf ( ch >= (0 BE hee 9”) System.out.println ("It is 2 digit”) 5 reads flashes a message character. Ifthe character input is 2 space if noe age TY Tae am ae Stowing example also makes use of an if statement if (A> 888815) 4 c=a- Hts 9; oe Syrteuauk pret (The rest 18 +05 y of if. Oe cenpot cme ir you have ween 1 far allerw yons fo execute 4 jon evaluates ter frie What if there is another... evaluates to filer There is anther torr og i < 4 i the examples 0 et 1 exprens condition or exprenat followed I eronaition by prceiding. an ele clause The eyntne of 4 ; kind of Ine” the following tement 2) n evaluates to true ie, a nonzero value, the statement 1 i6 eso ited he expres Samad is executed. ‘The statement-1 and statement 2 can be» singie ., compound statement, or a null statement note Remember, in an ifelse statement, only the cone associated with If (ie, statement 1) op y, associated with else (i.e. statement-2) executes, never both Following figure (Pig, 6.4) illustrates if and if-else constructs of fava 1 4 <> max) max =y ; Af (2 > max) max =z; System.out.printin(*Largest number 1s "+ max ) ; cONTROL rd ! : public static Void nain(stn,, | we a new eedac 5, weg, ||| eee Te objt.Test (4, 5,6); 17 op : 11 2OHCK crest : sethon Yom ae “uy | nen ) Sens Yor tea snare gon opt ABOVE PORN lb 7 ‘aber 136 , mn 6.2 si reo PrO9rOM thot gives the use ‘ee petond depending upon user's choice caries ont Og Falverhg uy FON ending 1 for °C 10°F converso arn ems User con chooks to xecste denned °C, © Conversion ino rash neenady et) public class ex11_2 { public void FahToCelsius( Fo, float tempc = (tempr-32) System. out. printin( at tempr) 11.8 “Equivalent temper: “F An Celst { ature of *s teage } US AS + temp) public void CelToFahrenhest( Float enc) float tempF = (tempc *1.8F) 432, ‘ System.out printin( “Equivalent temperature of * “Cin Fahrenhest is + tem) } + tempr) 5 public void Choice(int 4) ( ex11_2 obj2 = new exi1_2() ; af (iee1) { : 0bj2.CelToFahrenheit (37.0F) ; // converting 37 © inte tanrenhett else { obj2.FahToCelsius (98.4F) ; // converting 98.4 F into celcsivs 7 } public static void main(String[ ] args) { x11_2 obj = new ex11_2( ) ; System.out.println( "Converting a temperature fron Celsius to Fahrenheit. obj1.Choice(1) 5 ‘system.out.print1n("\nConverting a temperature from Fahrenheit to Celsius: obj1.choice(2) ; } The output of above program will be as : Converting a temperature from Celsius to Fahrenheit... Equivalent temperature of 37.0c in Fahrenheit is 98.6 Converting a temperature from Fahrenheit to Celsius... Equivalent temperature of 98.4F in Celsius is 36.8868

You might also like