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

Java Unit 1

housing

Uploaded by

Mohammad O Ahmad
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)
28 views

Java Unit 1

housing

Uploaded by

Mohammad O Ahmad
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/ 26
Intredncing feel ‘A variable can be declared as final. Doing so prevents its contents from being modified. ‘This means that you must initialize a final variable when itis declared, For example: final nt FILE_NEW = 1; final int FILE_OPEN =2; final int FILE_SAVE=3; final int FILE_SAVEAS = 4; final int FILE_QUIT=5; Page 38 of 39 38/100 BE, II'SEM (AL& DS) B SECTION, MICET OOPS Using Java: PC 302 AD [Unit 1: Chapter 2] Subsequent parts of your program can now use FILE_OPEN, etc.,as ifthey were constants, without fear that a value has been changed. It is a common coding convention to choose all uppercase identifies for final variables. Variables declared 1s final do not occupy memory on a perinstance basis, Thus, a final variable is essentially a constant. The keyword final ‘can also be applied to methods, but its meaning is substantially different than when it is applied to variables. This second usage of final is described in the next chapter, when inheritance is described, final methods cannot be overridden, final classes cannot be inherited, (will be discussed later in Inheritance topic) © scanned with OKEN Scanner < OOPS-JAVA-Unit-1... B Qi ecmscaaieosynsicnon. Wier O01 ings Come AD Ui 1s Chapter 2] a a ae ns i iti th verre cn pt tine ict mete ‘Command Line Arguments ‘Shes CommndLie( 2/100 SEALE 20 8SFCTON. WT OPS ing eFC ADU I: Chapter 2] bli we esd man Sting oe) Tein eg nth) "sherpa © scanned with OKEN Scanner Operators: Arithmetic: The operands ofthe arithmetic operators must be of « numeric type. You cannot use them on boolean types but you can use them oa char types, since the char type in Java i, essentially, a subset of it. [Operator [Result I+ [Addition [Subtraction (also unary minus) Multiplication Division [Modulus Increment [Addition assignment |Subtraction assignment [Multiplication assignment Division assignment [Modulus assignment [Decrement ‘The following simple example program demonstrates the arithmetic operators. also illustrates the diference between floating-point division and integer division ‘4 Demonsrate the basic arithmetic operators clas BasioMath ( public static void main(String arg ( ‘aithetic sing integers ‘Systemout.pritin Integer Arithmetic"); ima in b= 03; © scanned with OKEN Scanner < OOPS-JAVA-Unit-1 BE, II SEM (AI & DS) B SECTION , MICET ‘Syatemout ral Systemoutprintne =" +.) ‘Sytemoutprintn'd ="+ 4) Systemoutprindae=" +2; ‘1 eitatc using doubles B ‘OOPS Using Java: PC ‘System out prin "aFloating Point Aritmetie™, double da =1 +1 ouble d= da *3: ouble de = 36/4; double dd=de double de = ‘System out prin ’da =" + ds ‘Sytem print db =" +d); ‘System out print’ de =" + 8, ‘Systemoutpraln'dl=" +d ‘Systemoutprntn'de =" + de, , ’ oureur: Integer Arithmetic © scanned with OKEN Scanner Floating Point Arithmetic aa=20 &=60 ens ai=-05 e=05 ‘The Modulus Operator ‘The modulus operatr,%,retums the reminder ofa division operation. Ican be applied to ‘oating- point types as well as integer types. The following example program demonstrates the 6: 1 Demonstrate the % operator. lass Modulus { public static void maintStsing args) ( System ovtprintin("x mod 10.<* +x % 10): System.ovtprintin("y mod 10 =" + y % 10); ’ , When you run this program, you will get the following output: x mod 10=2 y mod 10=225 Arithmetic Compound Assignment Operators: Java provides special operators that can be used to combine an arithmetic operation with an assignment. As you probably know, statements like the following are quite common in programming: 445 In Java, you can rewrite this statement as shown here: Page © scanned with OKEN Scanner < OOPS-JAVA-Unit-1.. @ Q BE, II SEM (AI & DS) BSECTION, MICET OOPS Using Java: PC:302 AD [Unit 1: Chapter 1] ‘Tis version ues the += compound asignnen operator. Boh tents fom the sme exon they inert the value fab 4 Heres ater example, arama: hich canbe expresed ss 39622 y In this cae, the %=obans the remainder of 2 and pts tht res bak it a. ‘Ther are compond assignment operas fr al fhe arthmet, iy operas. ‘Thus ay statement ofthe form a op expresso can be rerio “The compound assignment operators provide wo bones Fst hey ave you abit of typing Boca thy ae “donthand” fr thi euiaen lng forme Second, hey re implemented mor fie by th av run-ins system than are thei esivalen ong forms Forth rene, you wl fen the compound ssgnment pero usd i professisly writen avn rogams eres sample program tn shows several op assignments in tion ‘1 Demonstrate several asignment operators las Opal pi state oid aii aes) ( eb me 3: © scanned with OKEN Scanner m4) 0% “The output of his program i shown here as6 b= e=3 Increment and Decrement Operators “The increment operator increases its operand by one."The decrement operator decreases its operand by one. For example, this statement: xexth ‘ean be rewrite ik this by use ofthe increment operator: Hi OR +x; no differece_post increment and pre increment ‘Similarly, this surement is equivalentto 1 OR --x:/ no diference post decrement and pre-decrement For example: x24 yon: In this ease, ys set 043 as you would expect, because the increment occurs before xis assigned oy. “Thus, the ine y = +48 the equivalent ofthese two surements: xox you However, when written like this, Page 15 of 56 © scanned with OKEN Scanner PC 302 AD [Unit 1: Chapter 1] BE, SEM (AI& DS) BSECTION ,MICET OOPS Using Jay the vale of x obtined befor the incment operators executed, so the vale af y is 2. (OF cours, in bath eases is et 1048, ere the ine y = isthe equivalent ofthese two statements Biewise Operators: Sa defines several bitwise operators tht can be applied othe integer types lng in sort, char, and bye, These ‘operators st upon the individ its oftheir operands. They ae summarize nthe following abe [Operater [Result ei [Btwise nary NOT la [Bw AND a i | sit ight zero i [wise exclusive OR assignment [srt right assignment "Shit ght zero fil assignment [shift lot assignment ‘The Bitwise Logical Operators “The bitwise logical operators ate & (bitwise AND) | (bitwise OR "(bitwise XOR), and (bitwise NOT). The following table shows the oatcome ofeach operat. Inthe discussion that follows, keepin ind that the bit ‘opertors ae appli to cach indivi i within each oporand la E aie AaB ane Za lo 0 [6 ° e|ommeenen ea la 0 2 o a ° lo 1 1 ° 2 2 la a 1 1 ° ° ass Test [ ‘Output: NOT) © scanned with OKEN Scanner BE, IIISEM (AL & DS) BSECTION , MJCET OOPS Using Java: PC 302 AD [Unit 1: Chapter 1] Public atc vid mai Sting ep ID a C ia Explanation: System ot pinta); moro , becomes i ov0101 ater the NOT operator i api lass Testo [ ‘vipat: (AND) publi static vid maiSuing as) 0 i ima =42,0=15 Explanation: Systemou pring) ooo az , como 15 ’ eo0o1010 10 class Tes0 ( ‘vipat: OR) public ttc void mainSting arg) C Explanation: ima =42,b=15; ‘System ot paca, ooio1010 42 ) Lovoonnnt 15 ; ooo 47 ls Tet [ Output: (KOR 37 public atic void main Sting rg) c Explanation: ima =42,6=15; System out pina; on a i ongoti 15 , otro) 37 lus Tent [ Output: 256 Page 17 0F56 © scanned with OKEN Scanner BE, NISEM (AI & DS) BSECTION , MICET OOPS Using Java: PC 302 AD [Unit 1: Chapter 1] public ttc void main Sting args) t byea=t; System.ou printed) ‘The Left Shit ‘The et shit operator, >24), 1 lass Tel ( ‘Ourpurss ble state vod main Sting args) ‘The Right Shift ¢ Explanation: ina =35; ‘System out printa>>2); cotoon 35 >>2 1 ono1000 1 lass Test ‘Output: 256 ‘The Unsigned Right Shift / Shift Zero Fil Explanation: lass Opbinquals ( public static vod main(String age) ( ina=l, in ime-3 ‘Sysem.ou print System.outpinn"b =" Systemoutprintn’e =" ‘Bitwise Operator Compourid Assignments ‘The oupat ofthis program is shown hee: li of56 © scanned with OKEN Scanner < OOPS-JAVA-Unit-1 19/56 Ne MSEWALEDS ASEM AUCET OR Ug Joe: PCE ADU: Chapter 1 © scanned with OKEN Scanner [onmior Roa le een fi iogsion I ges xm eo ages wy tor oR asipme Sok asp ‘wal Nateaat hs may tne ‘heal Hn pert nd pc san i th se yh hy per on eninge ea pre nee cen ese ee nig ‘tc caf ge 20/56 DE ISEN(ALA DS) BSEETION,AUCET OOPS Ung Java: RC 32 AD [Unit 1: Chapter 1] Soret ea opt ‘lagen Aes omer i Sty. AND ae ia te bars vm hn pendent one expen cbs iu oni pn nn ordre tops a) ae nas of terial cenit ena a ete and 1 taco neq ex mn ivi hg ine rp © scanned with OKEN Scanner Te sae Opa ee ope imaged em: esp: Tim pmompe oe or ee we ee ti oil te cmin a|— Sthecet SoSits| See roars ‘eon geea roa ei om rpanaise 22/56 RINSE Ae DHRSSCTION NOCEF ORS ng Je C32 AD [Unit 1 Chapter 1} (est T lo { T lee = IE a I le las © scanned with OKEN Scanner ava deine ight primitive ypes of ata: ys bon gh. lat, due, done. Te priv pss tical mae fed a angle pes Fain point numbers This grupo faa del which epee umber wih ction rein, Cuaoces Ts olds ha wish pee sym in character tke ters dumb Boolean: This grep inclaes Honan, which’ pei pe or peeing ee vale Integers oa dfnes oriteyer peste, nog, AIL these sp penne amd neat vais, Name Width Range fone 6 -9,223,372,036854,775,608 10 9223,372,036, 858,775,807 ine 3 2,147,483 648 to 2,147 483,647 bre 8 “haat 137 aig pit types: lating pit hers, a ows ot al amber te ud when a Name Width in Bits Approximate Range double 64 490-324 to 186+308 float 32 41.de-045 to 3.4¢+038 ee 0 6 DE, HISEM (ALA DS)B SECTION, MICET OOPS ting daa: PC 302 AD [Unit Chapter 1] Doubles dae recs lsh 15016 Chari Tp din. seat, vn ue Unde reese character av hire a pe 4 Theragsof acai O 65316 Teas aonegane har. Name Width in Bits Approximate Range char 16 0t0 65,536 nso alent rg es ‘the onda expen ha govern col tents sah ant Name Wiath in Bits Approximate Range boolean 1 True or False © scanned with OKEN Scanner 4H, Control Statements 1. programming language uses conto statement o cause the flow of execution to advance ‘and branch based on changes to the stat of a program. 2. Java's program contra statements can be put into the following caegores: i, Conditional or Selection statements (nested ifs ele ele if swith) i, Loop orlteration statements or. while, do-wkile,fr-each) ii, Flow contol or Jump statements (retwn, brea, continue) 5. Conditional or Selection statements: These statements contol the low of program's execution ‘sed upon conditions known only uring runtime Control Statements: ifstatement vas conditional branch statement. I ean be used to route program execution though two diferent paths. General form ofthe if statement It ondtion) statement else statement2; ‘Bach statement may bea single statement or a compound statement enclosed in curly braces (that is, lock). Page 24 of 56 24/56 E,II'SEM (AI & DS) BSECTION MICET OOPS Using Java: PC 302 AD [Unit 1: Chapter 1] ‘The condition is any expression that returns a boolean vale, The ele clase is optional ‘The if works lke this: If the condition i tue, then sttement! i executed, Otherwise, sttement2 (if it exists) isexecuted. In na case will both statements be executed For example, consider the following: inca b; Mla cbya=0; else b= 05 © scanned with OKEN Scanner Only one statement can appear directly after the if or else, To ince more statement compound satement) under ior else, block (} must be erested, asin the below code fragment boolean data Available ime =1y=4: dataAvailable = toe if(dataaailabley ( Nesed is Anested itis statement that isthe target of another if or else, Nested ifs are very common in programming. ‘When you nest i, the msi thing to remembers that an else statement always teers to the nearest if saemeat that {is within the same block asthe else and that is ot already associated with an ele. Here isan example: ii = 1011 Mj < 20) a=; tis snot associated with any ee iftk > 100) €= Page 25 0f 6 EI SEM (AL & DS) B SECTION .MICET OOPS Using Juv : PC302 AD [Unit 1: Chapter 1] ‘else a=; // this else reer 1 if A> 100) , else a= dh this Final else efers to i 1 © scanned with OKEN Scanner else ae // this else refers toi (k> 100) ) else a= di this final else retest iti == 10) “The eof Ladder A common programming construct that s hase upon a sequence of nested if is he itakes itfcontiton) se itfcondition) else itfcondtion) The if statements are executed from the top down. As soon as one ofthe conditions controlling the ifs tue, the statement associated with hati is executed, and the rest of the ladder is bypassed. If none of the conditions is ue, then the Final ese statement wl be execute. “The final else acts 362 default condition thai, if al ther conditional tet fl, dhen the last else statement is performed. I dere is mo final else and ll ether conditions are alse then no ation wil take place Program that uses an if-else ladder to determine which season a particular months in Demonsrate if-else statements lass Ise ( Public tate void main Swing arg) it month = 5 / Apeit String season; 12) month ittmonth | month season = "Winter © scanned with OKEN Scanner ‘else iKmonth == 3 month = 4 month = 5) season = "Springs le imo season = "Summer"; se itfmonth == 9 j month == 10j month season = "Autumn eke season = "Bogus Monts System.out pri 1 ) Here isthe output produced by the program: 1 Apri is inthe "+ season +"); April isin the Spring nent within [No mater what value yu give for month one and only one assignment st the ladder willbe execute. “The switch statement is Java's multiway branch statement. Ht provides an easy way to dispatch execution to Aitfereat parts of your code based on the value of an expression. As such, it often provides a beter alternative than a large series of if-else ‘witch statement Statements, Here is the general fom of a switch statement site (expression) ( case value statement sequence ‘rea case value: statement sequence break case value © scanned with OKEN Scanner OVERLOAD two or more mths within the sane clas that share the same nae, with ica METHODS parameter declarations, the mthods are so he overload, and the process tefered to a method overloading. Meth oveoading ison ofthe ways that Java suppots polymogphism 7 When Jere eccunter call loan overloaded method t check the ype andl umber ofargumens a ts vie to dterine th version ofthe overload metho wo acally sal ‘Example: 7 Overhading Matos class OverondDemo f soit) Systemout peal"No parame" wid testi a System out print oid testi aia Sysemout penta and "+9 2"* +b): 1 double tetidouble) System out pene"duble a "+ 2 lass Overload Page 14 of 38 1DE,IISEM(AL& DS) BSECTION, MICET OOPS Using Java: PC-302 AD [Unit 1: Chapter 2] public Satis vond main Siring arg) T OverloadDem ob = new OverloadDeme() double rests obsess obsest 10): obtestt10, 20) result = ob test 123.25) Systemout pintn("Resul of obtest(12325)-" + result © scanned with OKEN Scanner Object oriented programming model: 1. OOP was introduced to manage increasing complexity 2. OOP Organizes a program around its data (that is objects) and a set of well defined interfaces to access that data. OOP is characterized by “data controlling access to code” By switching the control to “data” many benefits are achieved as mentioned below. Object-oriented concepts form the heart of Java just as they form the basis for human understanding. It is important to understand how these concepts translate into programs. 6. Object-oriented programming is a powerful and natural paradigm for creating programs that survive the inevitable changes accompanying the life cycle of any major software project, including conception, growth, and aging, 7. Once we have well-defined objects and clean, reliable interfaces to those objects, you can gracefully decommission or replace parts of an older system without fear © Abstraction: b. Essential element of OOP is “abstraction”. Humans manage complexity through abstraction. Eg. To drive a car, one needs to know the steering, accelerator, brakes, transmission(gears) shifting, driving basics and traffic rules. No need to know automobile engineering for driving a car and still use the entire car as an object. (This is an abstraction: Making available only the required information through proper interfaces and hiding the details and complexities). Hierarchical abstractions of complex systems can also be applied to computer programs. ‘The data from a traditional process-oriented program can be transformed by abstraction into its component objects. A sequence of process steps can become a collection of messages between these objects. Thus, each of these objects describes its own unique behavior. Objects are treated as concrete entities that respond \ges telling them to do something, This is the essence of object-oriented programming. Abstraction forms the basis to transform a process oriented program into an object oriented program. © scanned with OKEN Scanner BE, IIISEM (AL DS) BSECTION, MICET OOPS Using Java: -¢ 302 ab [Unit 1: Chapter 1] ‘a Encapsulation the mochuns that binds ogether code and the data manipulates. 1th dan pe ce re hep ne fen ute ference elses by encpaation. ©. Encapiltion ia protective wrapper tht preven the cove and da fom ing array accessed by othr coe defined outside the wrapper. 1d. Access tothe code and data inside the wrapper i tg cold hough a well-defined inerface. (@ Indava the basso encapelation is the lass 4. Clase 1h Aclas defines the ste and behavior (ata and ede, hat ae called members af cas) that willbe shared by a et of obec, ‘i Code imide the ln i referred oa member method or metho. (Noe functions in CXC are called ax methods avo), iv. Relais gia ems. ‘Object: Each obs of sven clas contains the srictre and bshavior define bythe las, TL Objctis an insta of als. 2. Ambject ns pyical rea i. Behavior and interface of lass is dined bythe methods tha operate on instance data 1. Scope/Accessbility Bach method or variable clans may be marked private oe publi The piecewise tte rf eco ‘© The private methods and data can only be acesed by code that sa meme of the cls 44 Thetfore, ny cher code thas not member ofthe cls cannot acces private eho visible & The pavate members of class may’ only be acesed hy oer parts of your program tno the able medods of els 1 Team be ensared tat no nieoper actos lake place. Hence the ple itertace should be cartlly designed nat 1o expose too much ofthe ier workings of + Inkeritance: ‘a Ineriance isthe process by which one objet aie the properties of ance objet, B._Suppons te concept of hierchical lsifration (hnowedge managed y top-down approach), © scanned with OKEN Scanner {Inheritance itera wh encapsation swell , {Ifa given clas (pret cl) encapslte some tributes then new sala (child cas) ines al the stbaies ofall of its ancesteevsuperaren claws pls any ait that it ads as pt of Hi speciabeaic, 1 Ineritanoe isa key concep that ets object-oriented programs grow in complex seonetilly Hinearty ether han ‘© Polymorphism: ‘2. Polymoepism (ra Grech ening “many forms") isa feature that allows one interface to be use fora _snerl clase actions. The specifi ston is dtermind hy the exact tire of the sition bb. The concept of polymorphism is expressed a “one interface, multiple metho This help educe complexity by allowing the same interface to be wsod to spe a gener lass of ston. Ie is the compiler’ job to soc the specific action (hati, method) a it applies to each situation Programmers do not need to mak this selection manually and need only remember and wiz the genera imertace 4. Two types of polymorphism: 4. Compiles polymorphism istic or carly binding): Achieved by metal vecoating which ‘ables the coexistence of many methods with the sme name hot dint parameter ists within & las, enables Java to accomplish compile-time polymorphism, i, Euample for compiles polumorphisan: Consider that two methods wth the sare na “add se wien within the Calculator clas, The fst method takes two integers a arguments and rears ‘hei sum as an eteger The second metho takes two doubles as rgircnts an eta thir im ssa double. Daring compilation, de eva compiler nalyes te argument types sed inthe rethod call and Steines the appropiate method to invoke. ‘i Runtime pubmorphism (or Dynamic Metal Dispash 1 a process in which a call to an foveridden maod is resolved at runtime rather than comple-tine. Acheved by laediass td ‘method overing. In this proces. an overridden med ie called dough the reference variable ‘of sperclas (hrvghupcasting: Reference variable of Parent clas eer t the obj of Chik ‘las The determination ofthe metbod tobe called is based onthe object being referred toby the teleence viable iv. Example fr run-time polymorphism: Consier a parent cass Shape, Shape as method called draw) tat has so specific implementation. Then consider wo cid clases tha are Rectangle and Circle that are inerited from class Shape an each child class metho called draw) So, when the pare clas refers to hid class Rectangle) object and the dea) metho scaled with this reference then, to rectangle is drawn. Ad when the paret cass ors toa cid class (Circle) ‘objet andthe ra) method ill with this ference thea the ec dea, Benefits of Polymexphis: Improves reaabliy esbliy and ede reusability Note: Association, Aggreyation and Composition describe the relationship between abjects Assocation: Ms ‘Ke dtines the diversiy between objets Di. Allobjets have their separate lieeyele, and theres wo owner. For example, many stdens ean associate with oae wachor wile ane sudeat can also associate with mulple teachers. ‘2 All objects have their separateifeycle 1. However. thesis ownership sich thatthe child abject ant bslong to another parca objet Page 3of 56 © scanned with OKEN Scanner €. For example, consider the class/objects department and teacher. Here, a single teacher can’t belong to multiple departments. If we delete the department, the teacher object will never be destroyed. © Composition: a. A composition is a specialized form of Aggregation bb. Itis also called a "death" relationship. ©. Child objects do not have a separate lifecycle. When the parent obj also be deleted automatically, d. Example of House and rooms: Any house ean have several rooms. One room can’t become part of two different houses. If the house object is deleted then the room object will also be deleted. i deleted then all child objects will © scanned with OKEN Scanner CONSTRUCTORS ¥ Java allows objects to initialize themselves when they are ereated. This automatic initialization is performed through the use of a constructor. ¥ Acconstructor initializes an object immediately upon ereation. It has the same name as the class in which it resides and is syntactically similar to a method, Y Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes. Y The parentheses are needed after the class name to call the constructor for that class ¥ When we do not explicitly define a constructor for a class, then Java creates a default constructor for the class. The default constructor automatically initializes all instance variables to zero, (Constructor demonstration, Example: class Box { double width; double height; double depth; This is the constructor for Box. Box { sm.out printin "Constructing Box"); compute and return volume double volume() { retum width * height * depth; class BoxDemo6 { public static void main(String args{]) { © scanned with OKEN Scanner // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out. printIn("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); © scanned with OKEN Scanner Command Line Argument Sometimes you will want to pass information into ® program when you run it This is acomplished by pessing ‘command-ne arguments to ma). +A commandline argument i the information that directly fllows the program's ae onthe comma ine whe its cexssitt class CommandLine { Page 21 0f 39 DE, SEM (AI DS)B SECTION. MICET OOPS Using Java: PC 302 AD [Unit 1: Chapter 2] public static void main(String args[]) { for(int =O; i jvae Commandl ine java PS E\O> java Commandhine 23 Oui © scanned with OKEN Scanner

You might also like