0% found this document useful (0 votes)
2 views102 pages

Java Unit 1 Part 1

The document introduces object-oriented programming (OOP) concepts, emphasizing the importance of classes and objects, as well as principles such as inheritance, encapsulation, and polymorphism. It explains how real-world scenarios can be modeled using agents and communities, and highlights the responsibilities of these agents in fulfilling user demands. Additionally, it outlines the features of Java as an object-oriented programming language, including its simplicity, portability, and security.

Uploaded by

kondapakab
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)
2 views102 pages

Java Unit 1 Part 1

The document introduces object-oriented programming (OOP) concepts, emphasizing the importance of classes and objects, as well as principles such as inheritance, encapsulation, and polymorphism. It explains how real-world scenarios can be modeled using agents and communities, and highlights the responsibilities of these agents in fulfilling user demands. Additionally, it outlines the features of Java as an object-oriented programming language, including its simplicity, portability, and security.

Uploaded by

kondapakab
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/ 102
Unit 1 Object oriented thinking (x olyect ove wled Thinking = { | | 1nd others ave Malten aveund “ulho Ws being otyuted” . | i | | aye. allnbuléy (€.9q.. Siro, Shape, cclov le like ‘ ld we can seo. obje > Evevyntheve, 1% tho. teal ule! evaed people. janimale, planh, cars, fui lings and com Le divide obyel inte Yoo Wpes, "hose OG > Soma limes, Animals. and Taaniwale + | tr 040. > Animale. ohgedi ave saliva in some. Sense They ~ around and do Things, Jnanimale, objet, on affey hand do viet move. on Mery own. — > Any Kipe af obyerte hove, Some Common Things, and weight) on alks 5 OY 3 behavioy Legs, o ball rolls, beuncos), a beby eves, Sleep and a ts evs accelevaley , brakes and tons; a towel absovhs We consist’ he Aw? elemoul teede tals. > All compalay progyams code (ov) >A prgram can be conceplisally orgawaed amund ik areund ibs dala - Willen arund “ulhele is happesieg Thal ic, Some progrannt ave > Tee oye the too. povadiqns Cov? medal thet govern has) & Program is consFucled. \ ! > The-fresk model 'ic ‘enlled as, process onenlid model . Te procest orevtecl model eon be thagh af as code adkug oncola ech. > The Second modol it called ag objet-diewltd model. Tho Objet Bioutad modal organizes a program ormad ike dato.ie dala. adkivg on code -£x: Jove. | A way of viewing world: 11 A Way of Viewing World To illustrate the major ideas in object-oriented programming, let us consider how we might go about handling a real-world situation and then ask how we could make the computer more closely model the techniques employed. Suppose I wish to send flowers to a friend who lives in a city many miles away. 2 5 ] Let me call my friend Sally. So I chooce a agent called Flora to carry flowers to my friend.1 tell Flora the variety and quantity of flowers. I wish to send and give Sally's address, and I can be assured the flowers will be delivered expediently and automatically Sally Delivery Person Gardeners Flower Arranger Grower — Bas a ale Sally's Florist Figure 1.1: The community of agents helping me Agent and community: Agent: Social Networking Application: whatsapp, facebook, twitter etc. Now we call all these i.e whatsapp is an agent, facebook is also an agent, twitter is also an agent. We are calling them as an agent because they are performing some particular task on behalf of the user. Agent means any application that perform some activ In java, everything is an object so agent is also an object in java. Communities: Group of agent is what a community is. Communities are group of agents which perform common applications. Ex: social networking application communities: whatsapp, facebook, twitter. Online cab booking application communities: ola, uber. Search engine application communities: google, yahoo, bing. Messages and methods: Messages: Message means some information. It means that messages are the information passed between the different agents to carry out the user demand task. Methods: Method means some function to perform some operation. And a program may consist of multiple methods and those methods will help in performing the task that the user is asking for. Responsibilitys: Responsibilities: ‘The agent is taking all the responsibility to fulfill the demand of the user. The user just need to give some information and the remaining things like searching the cabs, connecting with the cab driver, and showing us]the different available cabs etc are all performed by the agent only. btesenmen Clases and instances: 114 Classes and Instances i Although [ have only dealt with Flora a few times, I have a rough idea of the behavior I can expect when I go into her shop and present her with my request. 1 am able to make certain’ assumptions because I have information about forists in general, and I expect that Flora, being an instance of this category, will fit the general pattern. We can use the term Florist to represent the category (or class) of all forists. Let us incorporate these notions into our next principle of object-oriented programming: All objects are instances of a class:The method invoked by an object in response to a message is determined by the class of the receiver. All objects of a given class use the same method in response to similar messages. Material Object Shopkeeper \ Figure 1.2: The categary surrounding Flora Class Hierarches - Inheritance: 1.5 Class Hierarches - Inheritance T have more information about Flora not necessarily because she is a florist but because she is a shopkeeper, I know, for example, that T probably will be asked for money as part of the transaction, ‘and that in return for payment I will be given a receipt. These actions are true of grocers, stationers, and other shopkeepers. Since the category Florist is a more specialized form of the /category also trie of Florists and hence of Flora. Shopkeeper, any knowledge I have of Shopkeepers ‘One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy of categories (see Figure 1.2). Flora is a Florist, but Florist is a specialized form of Shopkeeper. Furthermore, a Shopkeeper is also a Human; so I know, for example, that Flora is probably bipedal. A Human is a Mammal (therefore they nurse their young and have hair), and a Mammal is an Animal (therefore it breathes oxygen), and an Animal isa Material Object (therefore it has mass and weight). ‘Thus, quite a lot of knowledge that I have that is applicable (o Flora is not directly associated with her, or even with her category Florist. Material Objects Aninval Plant Mammal Flower Soo an Dog Human Platypus Po — Carnation Shopkeeper Artist, Dentist Florist _ Flash Flora Elizabeth Kenneth Phyl Sally's flowers Figure 1.3: A classhirearchy for various meteral objects The principle that knowledge of a more general category is also applicable to a more specific category is called inheritance. We say that the class Florist will inherit attributes of the class (or category) Shopkeeper. ‘There is an alternative graphical technique often used to illustrate this relationship, particularly when there are many individuals.. This technique shows classes listed in a hierarchical tree-like structure, with more abstract classes (such as Material Object or Animal) listed near the top of the tee, and more specific classes, and finally individuals, are listed near the bottom. Figure 1.3 shows this class hierarchy for Flora, “Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will ink attributes from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for which there are no direct instances; it is used only to create subclasses.” Method Binding, Overriding and Exceptions: 11.6 Method Binding, Overriding and Exceptions I know that mammals give birth to live children, but Phyl is certainly a Mammal, but it lays eggs. To accommodate this, we need to find a technique to encode exceptions to a general rule. We do this by declearing that information contained in a subclass can override information inherited from a parent ¢lass, Most often, implementations of this approach takes the form of a method in a subelass having the same name as a method in the parent class, combined with 2 rule for how the search for a method to match a specific message is conducted: ‘The search for a method to invoke in response to a given message begins with the class of the receiver, If no appropriate method is found, the search is conducted in the parent class of this class, The search continues up the parent class chain undil either a method is found or the parent class chain is exhausted. In the former case the method és executed: in the latter case, an error message is issued. If methods with the same name can be Jerarchy, the method executed is said to override the inherited behavior. found higher in the class Even if the compiler cannot determine which method will be invoked at run time, in many object-oriented languages, such as Java, it can determine whether there will be an appropriate method and issue an error message 2s a compile-time error diagnostic rather than as a run-time message. If Elizabeth and my florist Flora will respond to my message by difierent methods is an example of onz form of polymorphism. We will discuss this important part of object-oriented programming in Chapter. As explained. that I do not, and need not, know exactly what method Flora will use to honor my message is an example of information hiding. Summary of Object - Oriented Concepts: kkk Javea 00%; Concepli:- > ops Stands far object Btiented ‘programming System, _Dobyel meant o Saab wild enkly suchas ‘pen, Chor, lavle ete. } > obsged ttenled progvamming is o metheddogy a pavodiym| te desqn a program using classes ond obs. > DE Sinnglzfos tee Lotfewave develop rant aud mos by pavideng Some fea tiwas 0 Concept + wlenance| > The programming language where averyttng ic represented os an obseth, is ennun at Wuly obsect cpiewtad pragvaramtng Language > Smalltalk and qava ava Cons duenlad programming language: devel os' td Frualy obsed-- j > The follening ove. the Concent dealers cB) pradpals os | obreik -Buewled progvamming. | + objet \ + class vy i . be ; | 2 Abstradon _ "." Encapsulation | fui ive 'e Gahavilance: + i , + poly wahphiimn ues i w | 1 meal pode endily Such os” pen jchos table , cor, dog ‘and chew > obgedks axe Kay te understanding obgeck ated ; Tits Baan’ texhnology » Scanned by CamScanner Fin qunevel, a maal whld cbyecti have tla ond behavior AD enample, a pen has stale Cedev, Company nome, model ) and behavior (Wtviting ,dvausing)+ f° molecbites, dey: Tn sdluoire, The obged-'s Shale is represented by Vowablet oud behaviay 1 raprasented by methods. De" “pa object it a Soffanve bundle. ey veodoblet ard rteted Mefheds! Lxamples-@ obgecks cat Slate: celor, mke Behavior: climb hill lao dash, Arce @® objet + Hote sale + covert location, calor RBehavny : Clesefopen main deor . elevate eke. + Clase :- fn class is @ collection ob Stealer obyedt. Jn the objets ch te Same vind] sual wild, you olen have many bicycle FA onomple, your bieyde iW quit one &t many The Wall. in levma oh obged Buen, We wk objet Knaon ob Soy Wal your bieyele object it am iilane of the Clots bicycles. pes SA class is o blueprint ne prtelype, tak dekwes thafariables and The metiods common 15 all obyedi or a Same kind Examples © objet: Byke t class + Byker Trat Some @ objet + Dogs Each dog have MME vartebles clay + pogs ond mMethody lire bavieceg 0 hungyt Scanned by CamScant + Pbelraction t= Abctmdlion is the concept cy hiding the intemal details oud dasenbing thug! We Simple Revs» Fev enample: phone call, we cowl Knno the inlémmol processing: pus “Uelng iwliwal dabils avd Sheoig cfanctowably is knan at absivaction® Leb ub fake tite example cha cav, We pest tetill ineveate. bul knno Teak if accelevaloy prested ,s don't Kneo the Wevned procelt hav spead will be incveol + Encapsulation s— Encaptublion is the Feehnigue Used (5 tmagament obs|yaudton in objet Bieulad Prigvanning + legethey nls a Sragle udabion” ith dafevenh madrcua. “Delts- “pinding code ond dali unit be Kmaon as ences por evample, captule, tt is csvapped A gave clot Ie Hye ercmple oo encoptutedion. 3 Sa Single Ltd, Enenpiulation is 0 process ok Wlvepping Code ond data inks Single unt. Leb ut take am enample ob communi cale lengh He vid directly ubblic tWtwlace heve+ a UR ho companys tele ith tke dapayfmenty. HR is aking of PI « Inhevilauce :- The process by which one chs acquive: Me properties and fundrvalitter of another class pet “When one objedk acquertt all Te peopertios aud behavors ob another Cpavent) clogeck is Knoon 4 is enasn a inher lance - thhew lance" 4 Gk prvides Code suusabilllF, Cb is used te achieve quandime polymBphicay, Rrennad tes Cees FA enample, A child iwheviti tie properher of ih pavent - Exam: Sy object ~Suientad termindogy , mMaudain bilces, eouing bites and tandem bikes ave all Jub clases cf the Bicyele Supay class > Each Gubclaat dnhewl? te prpertin and fandroveliies ch Super Cla "Bigele! (agi fpead, Cadence , braling de + poly maphieng :- pdymdphism is Ma concept Whave an obyece beloves differently Mm didfevant stheelen’+ eve exe hwo types + polyradphaim - compile. we and sunk, polymidphasen - DATE * then one laske 1s pecland by deffevent ways Knacn as plymdrphitm ” FAL ennraple, To dvaus Somathing 09. Shape A cuckiigle ef Examplts The Jame. menage ‘move’, Me Man uoalies, ish suxm ond birds dy, Java Buzzwords or Features of Java: kkk 118 Jaya Buzzwords or Features of Java ‘The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as java buzzwords. A list of most important features of Java language is given below. 1. Simple 2. Object-Oriented 3. Platform independent 4. Secured 5. Robust 6. Architecture neutral 7. Portable 8. Dynamic 9. Interpreted 10. High Performance 11, Multithreaded 12. istributed C2) eesaes} coathiren) >) am © Features Co (>) Java fcc) Ecc meee o.oo ™ Deen Prnicl) Figure 1.6: Features of Java & Simple: Java language is simple because: 1) Syntax is based on C+ (so easier for programmers to learn it after C++). 2) Removed many confusing and/or rarely-used features Ex.: explicit pointers, operator overloading etc. 3) No need to remove unreferenced objects to do this Automatic Garbage Collection in java. ob Object-oriented : ‘Object-Oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior. Object-oriented programming (OOPs) is a methodology that simplify software development and maintenance by providing some principles. They are : 13 1, Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation + Platform Independence : Java provides software-based platform. The Java platform differs from most other platforms in the sense that i's a software-based platform that runs on top of other hardware-based platforms. thas two components: 1. Runtime Environment 2. APICAPy Java code can be run on multiple platforms e.g.Windows,Linux,SunSolaris,Mac/OS ete. Java tion Programming Interface) code is compiled by the compiler and converted into bytecode. This bytecode is a platform independent code because it can be ran on multiple platforms ie. Write Once and Run Anywhere(WORA). Senet code java file bytecode .eluss file Machine code ‘Figure 1.7: platform independency Machinecode 4 + Secured: Java is secured because 1. There is no explicit pointers. 2. Programs run inside virtual machine sandbox. & Robust: Robust simply means strong. Java uses strong memory management. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java. All these points makes java robust. + Architecture-neutrat: ‘There are no implementation dependent features Ex.;size of primitive types is set + Portable ‘We may carry the java bytecode to any platform. + High-performance: Java is faster than traditional interpretation since byte code is “close” to native code still somewhat slower than a compiled language (e.g., C++) + Distributed = We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the methods from any machine on the internet. + Multi-threaded: A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi- 15 (or) 3% Fealsves de ova (ov) ova buzsworelt 2- mheve ave many jeabores de gave Ty ove atte kmaon as Tava buaz words: she -fealiives of gave given bela o Simple. » portable o obseck-oriented 2 Dynamic « platform inde pendewk 1 Gulzy preted © Secured 2 High performance « Robust 2 mull treated « Aychitedlave neutral . Dishibuted becouse} fo sun, Jove longuage is Simple > Syntax is bosed on © ® > temoved mony confusing ond 29, Explicit pointers , y overloading eke. > Noneed te Temoave uve feren cod obseds become Weve is oulomolic garbage colledion Ob eliminabes Ha complexities ob cond cat lrevebh Jove Was bean made Simple. in gava- o Obseth -Biewled > object ~guewled moons We dyanine OF Sottware a combmadon de diferent WGpes de obgedi Thak th dala ond behaviour: gram wa vg (ORs) 16 & mefhodoloy ond maintenance by as conloint be > obget- duented pr fy Soft davelopmenk Wak ginapli providing Some concepts Borudy. 5 Tu basic Concept A 00 oe? * obge” % Pbitraution | x closs x En copsuledion | a Snher tance » poly mevphiins Soames bey Conntioninme | * plaka independent? tabfdm is Te havdwave & Sa}fwore eniror! 3 A P' cme In which o progvam vuns+ > Theva, ove tivo types de plakfdmi siyhsconaanh and harduant bated Tava provides Soffeseve- based plakfon- > geva eode can be yun On multiple plob}auns eq. Windauss, Linux, Mac fos avd ete. saevo code is compiled by Conyertad inks byle code. This byle tod -pendent cate - > Tr is achieved by IvM CTeve vtylael Machine). The. philosophy dy gave. Us “paste once, Run Anywtheye (uora) © Seuveds 3 gore t poiwhevs and All qava program yuns inst | Matkine Sandbox + > gova uses b dg provickug souls - |e Robust: > Robust Sionply means Showy - We compiler anal le is a plakfdon wde- ¢ Sauved becouse gove dot nek use. enplick de the vidoe tke pablic Key encryption System gaya. is nobuste prgqramming language pecaute & Tove. uses Strong Memory Manogoment, a Treve, ave lack o& porwlens Weak avoids Seuanig poolern. x Theve. is antimadic garbage Colleton in gava. x eve ts exeaption hovdling aud [pe checking Mechanism (Mm qova- > alt thete potli makes qova Yobust. Scanned by CamScanner = Archilactinre - Newel! > Theve 's no imple mentation dependent teakiives eg: Site co primitive Hyper is eds > In 'c' programming, ink lata Wype oceupies 2 bytes de wemovy 81 32- bit avehitedine ond 4 byles ds memory an be bil ovchiladiouw + Buk ‘w! qova’, ik oceupi Ubylis oh Memory de both 22 ond 64 bik avclite es. ° portable: gave is porlable because We mony cory Mw gova bytecode te any plabfdm. is Witten in ANST © Ltith clear) > gava compiler porttabilily bauslary - > The gave progvame can 7M on ony herd -wore environment. ° Dynamics oe .d te be more dynamic adapt ty om evolving > Jove is considers C or Ctt Since it is designed to environment + 3 Javo. programs can Carry erctensive ampunt ob syun-ime iwkdadion Wak 6” be used be verity oud ame: netdve accesset ta dogeuts on YUN . Sukevprela At > gavo. byle code ts Komdaled on they nabive! mocune inshudctfons and ig nd Sted omywheve* code com be warped on any system = Java bylt vlial Mockine CIvM). tak provides a qove vi + High pevddimante > pith the use oh quit nTime Compilers, Tava: enables high pertrmonce+ { > gova is fesliv than Fradstonel inter predation . compiley Hransletes dove vue code fe VeNd > gusk-Tn—Time CT) bale cade. ively ihe nedive madd high Speed perddmance-+ + Multi threaded t SJova wos designed fo meet thy, Maol- wld grove. Supports mult - * seaguiva. ments « To accomplish tS, you te While progromt ‘Wraaded progvamming, Witch atlas Hak do mony things simultaneously + A thread ic ltke a Sepavale progvam, one Concurrently « he. main odvanlage fe walt cthveading & that TE doern'l occupy memory far tach threod, it Shaves Q common Memory aveas > gava is desiqned 42 Te dists baled environmen’ dy the thawed. We cam cveote Aisttbulaat opplicobion ™ Java + > We may accets files by calling Ihe methods from cuktuy ony Machine on Mh wav. > Teva's rvemote method imvocakion (RMT) Make dichbulad progvams pottible « An Overview of Java: % Adhal is Tove s- cpova. is a programming language oud a plalfdm. Bava is a high level, fobush, ceuuved ancl objeb-Buientad programing language + > gave. is a high Level modern program mins lang was inkoduad by “sun MicwoSyslams! 1" aa TE wat daueloped by a team under somes gosling”. > plakfam is nothing bul any a Sofvo ewvivonmenk in which a proven guns. Since fave Nas cake he TREL Tve Rankine envi wage, Anck ib howdworte its con vyuwkme environm -tonmenkS se Wheve cova is uses? (Uon Aavicet SUN Teves Theve according te sun, > bil ove many Hype de applications thak con be cranked using qova progvamming. Some dy them ave af —follavtt © slandalone Application : gt rg algo Known of dostetoe appication GI) ttindad pated application. Aa aniicalion Wak lle need te install on every mochine such aS media player, antivirus ond ee. D> AWT and suing ave uted tn gave. fil cvaading This Apply. « Web Appicabion t . fa applicaion Mak runt on the, sewer side ond is collad bleb applicakidy. Eft ivelz-coip creole, dynamic ‘page , AB cveathing! > Sevvell, Isp, Shrudi ish ledandlogies ave. used Uteb applications in Jove: + Enliemise Applicekions . pm appiicadion Wak is Gistabuled in naive, such as pomkevg oppleatiour eke. “eI@" is Usedqa this opplicctiog — Scanned by CamScanner » Mobile Apa codion 2 An oppiiestion frat u created 420 wobiles « > usrenty Andyoid ond cveabing Mobile appiicakious- qava ME ove usted 4d xe Histsy ole ove 2 > Teva team membert ovd patrick Naughton), inikaled te Tove language pe digi tal devices such aS set-top Mile Sheri proge boxes, Ctames. Gosling, in sume (941 felevisions ete - > The Small fam dy sun engineers called as “ Gyeon Team" > pivatly, ik wos called * eqreen tol extention was” al". as called soak". Why Oak? os o nakional qermany k’ by gomet Gosling ond File => aller that, ik he strength and choosen Gok is a Symbol whyies like U-S- A+ gvonce, Ieee de many COU ont eke+ ac, Ook was srenamed of gov.” becavte > Im 4 ib wos alveady a trademark by Oak Techndlagies + > The leam gatheved to choose o hew Name- words bleve dynamic" , Sevoluionay ™ “Site The Suggested “gett”, “pun” ete- > According te Tomes Gosling “ava was OMe ds The. top choices along bliT “afk, since gova Was $° Unique, of team member preferred TovOW+ -> gava. & om lend & Indonesia tdleve. rel coffee wat producd Ccalled gave coffee). > notice (Rat Tava is Test a nome > originally daveloped by James Gasliug of sum Mieosyslame ond r2leosed in inaS. most Rnanned hy Cam@rannar Data Types : AK* ‘1.1.10 Data Types Every variable has a type, every expression has a type and all types are strictly define .Every assignment should be checked by the compiler by the type compatibility hence java language is considered as| strongly typed language. In java, There are two types of Data Types: B Pri ive Data Types 4a Java Programming | 49 5 Non-Primitive Data Types 1. Primitive Data Types Data Types make a variable to store a single value at atime Data Type Primitive —_— oo String Boolean Numeric Array oN etc. Character Integral — Integer Floating-point JIN SS boolean char byte short int long float double Primitive Data Types : There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and named by a keyword. Primitive Data types Numeric Boolean Character Floating-point “The floating-point types: + float + double 49 Java Programming | 50 ‘Values of class type are references. Strings are references to an instance of class String. Type Sice(bytes) Range Default byte 1 -128 127 0 short 2 -32768 032767 0 Int 4 -2147483648 to 2147483647 0 long 8 -9223372036854775808 to 0 9223372036854775807 float 4 3.4038 t0 140-45 0.0 double 8 1.¢-308 to 4.9e-324 0.0 boolean | JVM Specific truc or false FALSE char 2 0.65535 \u0000 Derived | Data Types : Derived data types are those whose variables allow us to store — multiple values of same type. But ‘they never 2 allows to store multiple values of different — ‘types. T These are the ‘data type whose variable can hold more than One value of similar type. In general derived data type can be achieved using array. Categories of Deriv: iiveetnon a (ae ae Derived Data i € t Exampte : Tins se Gs es eh os 2 int al] = (10,20,30}: 1/ valid oe ee : ; __(or) = Data types specities th the size and type of values that can be stored. * Java langu has a variety of data types that can be shown below, Ee Date ini in Save oe | 4 fo 1 — User defined data types Numeric =< i Integer Floating Chara kk 1. Primitive Data Types (Built-in Data Types) : These are the fundarmentz| Onlalye. which are developed by sun micrasystem and supplied as part of their software whoy variables allows us to store single value. In java programming we have @ fundamental data types which ar categories. They are : assified into fou (i) Integer types. (ii) Floating point types. (iii) Character types. (iv) Boolean types. (i) Integer Types : The aim of integer type is to store integer data integer type can hol whole number such as 123, — 96, 5639 etc. Java supports 4 types of integers. They are : (i) Byte. (ii) Short. (iii) Int. (iv) Long. Size and Range of Integer Types : +127 =42 t byte tb | short 2 byte ~ 32768 = = 32767 = 215 - | int 7 4 bytes — 2147423648 = -23! + 2147483647 = 27! - | ong 4 bytes ~ 9223372036 + 9223872036 t 854775808 = - 2% 854775807 = +2 inrmooucrion or vava = Note : We can make integers long by appending a letter | or L. at the end of the number. Eg: 123 L (ii) Floating Point Types : The basic aim of floating point type is to store real values ne ce a omic ol epee which @ are containing fractional parts. ae nnn EL There are two kinds of floating points in java i.e., float, double (i) The float type values are single precession numbers which takes 7 decimal places after the end the value must be followed by a letter f. otherwise we will get the compile time error. Eg: + 3.4F = 11.0110011 (ii) Double types represents double precession numbers which takes 15 decimal places after the .(dot) and it may or may not be followed by a letter D or d Eg: 3.4d or. 3.4 — 11.011001100110011 vais 4 bytes 3.4e - 0.38 1.7e+0.38 Float Double 15 8 bytes 3.4e — 038 1.7e + 308 = (iii) Character Types : A character is used to store character constants which is enclosed ‘with in single quotes Eg: ‘A, ‘9’, '$' etc Java character size is 2 bytes, it holds only single character A collection of characters enclosed with in Getble quotes is known as string. Eg : “GPT Masabtank” Character datatype in C & C++ takes 1byte because C,C++ follow ASCII character set. In java programming character data type take 2 bytes. because java follows UNICODE character set and java programming is available in 18 international language (English, Latin, Greek etc). (iv) Boolean Type : Boolean type is used when we want to test particular condition during the execution of program. There are only 2 values. on. Sf ae + we 3 ~ Se eee eee (i) True (ii) False In java programming logical values are stored by using boolean. It stores only one jy of memory space (1-true, 0-false). Note : Each and every keyword in java written in small letters. The-default values of integer data type is 0, floating is 0.0, character is null, boolea is false. Variables: aAK* % Vorriables s- . Voriable is a Name ds memory locaton, in Mak ple can able to Store The value fo the partiwlay progam. Thee, ave three eet A vestiables + Local varable > Trslance Vortable > gladie vervieble ext 5 & ink as lof they «& Tc Vestiable Neme~ Types of Variable _ ‘There are three types of variables in java «Local Variable + Instance Variable © Static Variable Types of Variable Dlocal 2)instance 3)static Local Variable A variable that is declared inside the method is called Local variable. Instance Variable A variable that is declared inside the class but outside the method is called instance variable. It is not declared as static. Static variable ared as static is called static variable. It cannot be local. A Variable that is Example to understand the types of variables class A { int data=50;//instance variable static int m=100;//static variable void method() { int n=90; /Mlocal variable } } Hend of class. Scope and life time of a variable: ne The. scope and Lifetime de Variables > Each Vohable in modes progvamming lauguoge. hes: + a name * an oddest «a Wipe 3 Tq addition te obove properties, each voriable alto WS: © a Scope «a Lifeline « scopes Scores The Scape Oy Vowable is the locaHons/places/ range) in a pagram Where The Vomioble is accessible /visible- 5 Wle can dadaye vorobles puithin ony Block > Block i begun wth om opening curly brace ond ended by a clotiny curly brace > one block aval te one yew Scope in Jovo+ > e scope dalntnes hha voriebles ot visiable. fs other pote dr you™ pryram ond also dalévmanes tia Lgebioe ce be bel. ne Liyetime dra vosnable 15 tH localion (ee place) Ltheve tke vavioble enislr. > The Lfelime sufert ts tee amount ob me o Vorjolle ens. > Vertables ame created when their Scope is enlewed, and dethayad when Maiy Stope is lef}. thes Meant (Hat a vortable dotlamd uit in a wollied Vlill at hdld Vii Values culecda th. mothad « > variables ave cvealad ancl dettaysd labile The Prgram is -yumning. | { Scanned by CamScanner kkk ¥* constant: vol values th The maak world which > There ove Sev called os conan. witl never Change, hase ot 0 day will alusouys have 24 hrs eg pica) volves is 2.1g2 amd -> A conslawk in gava % used te Map or aikign at a. Vosiable « | enatk ond uncharging voluu fe | conslanli, Hesever, | | | 5 eva doetnd devel) support o Stakic fiuel variable 1S effeckvely a conslank. gxompla: public stadte fmol im MAx_NALUE =25; | Scanned by CamScanner Type conversion and casting: > pBgplly converting from one ‘Datakype sy Another » widening / Aubowake] promotion, Detoty pe 2) Neyrorsing / parual ees ye envied pew foun oF bo Hib OF oe int Os 10, a ¢ int — aby = lan Be a ie (omy —- & boy whoo aie m 4tHalin DT fp Lowen DT yore contebel pom eee Long Le 503 double d= 59-965 int @ > Cint 4; St ee Boolean - | bit [ Tru |talce J chan - 2 byles byte - byte ghe" > bytes int — & bytes Log — & byte? flor - A bytes double — @ byes % Type. conversion, ond casting s- « Type conversion :- Tk converte the One dola. Foe nls another. Us both ane compokiable , (Wen gove- compiler coil paring | the Gee conversion aulomakically + AR cnomple converting ant wha fleck, converting a look into doutle- aa ink [= 100; we «value 109 long A= u ~ A velue 100 Pool += Ll: Uf vole 109-0 is done by Java Compiler, bul- 2m data. Kjpe hs Te they. > Ype Convey Smo" ember we can Sloe & larga ¢ Type casting :- When a use Igpe ints lower dale (Gp then ik is called at tie lYpe 7 CoM convert the one high ey dolj casting. Th both ave Incompet able IGpes, Wie musie Wpe casting: Scanned by CamScanr Example /- dAguble d= 10-045 5 ae lp d volue [0.04 long L= Clong)d; yale 10 int f= Cobyls i value 10. Note: Type converSston is done by compiler ond Type costivg is done by were Example +- Class Type Conversion L public static votd main (shivgl] vgs) { ink x= loys Hol y: yeu Sysltiq souk. prinlly Cy velas. 1s “yy; t py valu is 124.0 class “Type Costing Vaid woin CSMvg ld avged public stobic f duble d= lo.o4 Long L= Clowg tk t= Cin Syslim-ouk- prinkly C'd volus syste souks panda CO" U vale iat ! cytlam. ok paint Cf value ital) j t aps di value is 10.04 * CL value ig lo tively 10 is “tay Arrays: KKK L112 Arrays Introduction Definition of Array Normally, array is a collection of Java array is an object the contains elements of similar data type. It isa data structure where we store similar elements. Wecan store only fixed set of elements in a java array. Array in java is index based, first element of the array is stored at 0 index. SARS An array is an indexed collection of fixed number of homogeneous data elements. Types of Array in java ‘There are two types of array. 1. Single Dimensional Array 2. Multidimensional Array. ‘Single Dimensional Array: Single dimensional array declaration: Sytax: Datatype arrayname{ J} Or Datatype[ ] arrayname; Example : Single dimensional array is a collection of similar type of data element witch has int af only one variable and one subscript is called Single D A x: int al.) [. Idenotes subscript lar type of elements that have contiguous memory location. 61 Java Programming | 62 int{ ]a; recommended to use because name is clearly separated from the type int Las At the time of declaration we can’t specify the size otherwise we will get compile time error. Example : int{ ] ay/valid int[5] ayfinvalid Creation of Array constructio Every array in java is an object hence we can create by using new operator. Syntax fur Creating: arrayname=new datatypelsize]; a= new int[3]; we can also combine declaration and creation into one step Syntax Datatype[ ] arrayname=new datatype[size]; Example: int{] a=new int[3]; 2 of program: = LE ATAg rnpert gene Gry so} «Lt xf) xf Class one £ fiol z!30! Gol sy 3 , Oo | + 3 & Pp: S- Vv: m CSHY asys0i) 2 2p ioe i inf XO J = he mt (53; XloJ=lo' XC = O/p xX GJ = 30; X(B7 = bo; (0 *Cey = y Ro So. ping Ip array element 27 : & x for (int f20; Peet Per) to ) SOPRCaCH); + Mall dimensional aways » Multi dimensional array ot mow dimensions Bt indarics. Te ie on ovroy with cuod Ub can be Visualized as a Mabin de rons ond cduuwas. tds take a -tun- dimensional away, Sy this costs dota i Covad Wa eno ond column bated inclen Colto Kanon ot mohix Seplie_ dd array declevabny, C-tw0) lls Dalaljpe vatable (]L] = new dabitipe Ld] Le Con) (oy dotalipe yoriable (11 = Delatgpe vowiableCI() ; [Ley ener} LeutunJ-- Variable = new datalipe [aod teal : Def: similar to 1dimension but 2 subscripts BE ink mares tie = new ik C8 Ce; Cor) lev) pk marke] 0 = iWe mowkt (703 5 Sburere Tle Hide 5 mores = new Int Ca felt : LD Array vy O Declare Syntan: ve birndy pe Army -hamel JC Jo ex: mt xC 10 J: Construciion a an are, Santas ed _ array nance = hed ba ty pe Coeosiae] (colurmnsige J ex, X = hew mt CQ IC) cols @) tritaligakor : — * — oe = lo Sones: TO inc Array rane[voe pos ICL pa t= Valug” | & xCerfed='e: AD Array Sone: | } yeboemtype omagrane( 3 J={ Usk Values 4; | am int =x If j= { tte, 20, 8, {¥e, 2, cot \ x > |O all in one ° <[o}f, * ce a SE Program: AD Array } rnpet java any: x 5 _ é | . - offe | > lec Ce / | P-S. Ve mV CShing avysc ) 2 ilye/ « fee | Int Or C; . tnt x CILJ = £ Lt0, Dw, 304, | ae {4o, o. 60} YS = 3 S-0- pls Cc" Two Dim Array Clencwde’” )- o/p (8205 ¥e8); F44) [[roK5 lO 2030 - >to Soto for (esd; cea2, C++) f[lcols = rn So.pCxCIeI) | $ 2 Operators: Operal-ag Sab Mu operead | @pewiet) opuwd > |. Arithmake operaldu:. +- Addition a “ — _ Sublracken —_ e_ Multiphicalion oa Division Silke : Hodulo Division =m ~ — Relakorel. voy: : Z ignale —_ Zz luatan Bewalt = eb y qrale thon arb >: qyveato Hen 8 eiwh grb Se ed te areb alet seh yo teh opere+ou Logica NID ical es eer & Lest & | NoT icol oc _ | x operators t- An operalor So Symbol Mak is used to pevefiier cpevalions, There ave many [ypes ch opevalovs in gave Such as «= rithmelic opevalors +, kL tt + Relational opevalors == re 22 + Logical opevalars £ Te b [asp | aib arb + Gifwise opevalors | 9 Lo } o o B= Bihwise AND o\! ° t ! 1 _ gitwise oR LLLP} © ! t 1 — Biasise Tit 3 A= Bikstse Cndanve bee hate. A a2 0901008 » BFR aceb 0100000 >> - Righk shift. eas ooavat0 . Assign mek opevalors =,+= + conditvonal opevalor emp valet 2 volute > % opevaley procastence, B Iievarchy :- Opevelors precadence | [[bifuane erdbiweet] 0 eth wagner | fedou oe tT} pose ret np» — Oey logical AnD | 42 wulliplicabive. | ag, 77 tae _ok [il oddihve + - enditonek shalt SS. =? avgamenk srlational le, > <=, >= eel bihue AND |Z 1.1.13 Operators Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups — + Arithmetic Operators Relational Operators Bitwise Operators + * + Logi + + I Operators Assignment Operators ‘Misc Operators ‘The Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators — 1s Java Program 76 Assume integer variable A holds 10 and variable B holds 20, then ~ Show Examples Operator Description Example + (Addition) Adds values on either side of the operator. A+B will give 30 =(Subtraction) _—_Subtracts right-hand operand from left-hand operand, . A - Bwill give -10 * (Multiplication) — Multiplies values on either side of the operator. A* B will give 200 / Division) Divides left-hand operand by right-hand operand. B/A will give2 i *8 left-har ight-| ‘a % (Modulus) Divides left-hand operand by right-hand operand and B% A will giveo returns remainder. ++ (Increment) Increases the value of operand by 1 B+ gives 21 == (Decrement) Decreases the value of opcrand by 1. B-- gives 19 ‘The Relational Operators ‘There are following relational operators supported by Java language. Assume variable A holds 10 and variable B holds 20, then -Show Examples Operator Description Example _ Checks if the values of two operands are equal or not, if'yes js = (equal) ‘ten condition becomes true. (AB) isnot trug. 76 Java Programming | 77 Checks if the values of two operands are equal or not, if ls . becomes true. les) Stue {= (not equal to) values are not equal then condi Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. A> B)is pot tne. > (greater than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A= (greater than Checks if the value of left operand is greater than or equal to ‘A >=B) is not t orequal to) the value of right operand, if yes then condition becomes trie. © ) is not true. <= (less than or Checks if the value of left operand is less than or equal to the (A <=B) ist ‘equal to) value of right operand, if yes then condition becomes true. ( ) is tre. The Bitwise Operators Java defines several bitwise operators, which cin:be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows = a=0011 1100 b=0000 1101 a&b = 0000 1100. OOLL 1101 ab = 0011 0001 ~a = 11000011 The following table lists the bitwise operators ~ le A holds 60 and variable B holds 13 then - Assume integer vari Show Examples 7 nt Operator & (bitwise and) | (bitwise or) A (bitwise XOR) ~ (bitwise compliment) << (left shift) >> (right shift) >>> (zero fill right shift) Description Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary Ones Complement Operator is unary and has the effect of ‘flipping’ bits. Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. Example (A & B) will give 12 which is 0000 1100 (A| B) will give 61 which is 0011 1101 (A‘B) will give 49 which is 0011 0001 (~A) will give -61 which is 1100 0011 in 2's Complement form due to a signed binary number. A << 2 will give 240 which is 1111 0000 A>> 2 will give 15 which is 1111 A>>>2 will give 15 which is 0000 1111 78 Java Programming | 79 ‘The Logical Operators The following table lists the logical operators — Assume Boolean variables A holds true and variable B holds false, then — Show Examples Operator Description Example | Called Logical AND operator. If both the &E& (le 1 we operands are non-zero, then the condition (A&& B) is false becomes true. Called Logical OR Operator. If any of the two [I Cogical or) operands are non-zero, then the condition (A||B) is true becomes true. Called Logical NOT Operator. Use to reverses the logical state of its operand. Ifa condition is 'Cogical not) ye then Logical NOT operator will make \A && B) is true false. ‘The Assignment Operators Following are the assignment operators supported by Java language — Show Examples Operator Description Example Simple assignment operator. Assigns values from C= A +B will assign value of right side operands to left side operand. A+B intoC Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C+4=A is equivalent to C=C +A 79 LL Subtract AND assignment operator, It subtracts = right operand from the left operand and assign the result to left operand, C-= Ais equivalent to C C-A Multiply AND assignment operator. It multiplies = right operand with the left operand and assign the result to left operand. C*=Ais equivalent to C=C *A Divide AND assignment operator. It divides left Ie operand with the right operand and assign the result to left operand. C/s Ais equivalent to C = C/ A Modulus AND assignment operator. It takes %= modulus using two operands and assign the result © %®= Ais equivalent to C=C to left operand. BA | <<= Left shift AND assignment operator. C <<=2 is same as C=C<< >>= Right shift AND assignment operator. C>>= is same as C=C>>2 &= —__Bitwise AND assignment operator. C&=2 is same as C=C &2 = bitwise exclusive OR and assignment operator. C= 2 is same as C=CA2 bitwise inclusive OR and assignment operator. C2 is same as C=C |2 Miscellaneous Operators Miscellaneous operators includes Java Programming | 81 > Conditional Operator (? : ) > instanceof Operator ‘There are few other operators supported by Java Language. Conditional Operator ( Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the variable. The operator is written as ~ variable x = (expression) ? value if true : value if false Following is an example — Example publicelassTest ( publicstaticvoid main(String args{]){ int a, bs a=10; b=(a=1)720:30; System out printin("Value of bis :"+ b); b=(a=10)720:30; System.out, printin(’Value of bis : "+b ); 1 } This will produce the following result — Output Value of b is : 30 Value of b is : 20 aL ‘The Unary Operators “The unary operators require only one operand; they perform various operations such as incrementing / decrementing a value by one, negating an expression, or inverting the value of a boolean. (Operator Description F__[Unury plus operator, indicates positive value (numbers are positive without this, however) - [Unary minus operator; negates an expression + [increment operator: increments a value by 1 [Decrement operator; decrements a value by 1 [Logical complement operator; inverts the value of a boolzan Expressions: > Expyession t+ fin enpression is a contrat Opevaldys and method jnvocalfong Wie ave. conducted made up ch variables , that evalule: tea according te the Sywlax de the languoge, Single value - Erampless ink marks =26+ fn Extmaek6= FS2 i+ otal =O) ola = marles + Exlmavks ) % Type convevsion ond Cattug s— + Type conversion 1 Th convert the one dala Woe Lp both axe compakiable, tem gave compl the [Gpe conversibn aulemakically « 4& example converting a ink th leat, converting a Float ide devtle- = ink ji ztoo; . ° li € Value 100 long ke bs A wdua 100 Hoal t= L; fe vole 100-0 ‘nhs another. Noy will perdny > pe conversion is done by qava. Compiley,bu- Fem ember we cam igre o Large dala type ils the otha. * Type _cashyg:— When a user ean convert the one higher dott WGpe tute tower dal Kjge then ih is called at the Wipe casting Db both ave. castiug. WMoompatiable [Gpet, wa muse Woe oe ‘L114 Expressions Expressions, Statements, and Blocks Definition: An expression is a series of variables, operators, and method calls (constructed according to} the syntax of the language) that evaluates to a single value. As discussed in the previous section, operators} return a value, so the use of an operator is an expression, This partial listing of| the MaxVariablesDemo program shows some of the program's expressions in boldface: other primitive types char aChar = 'S'; boolean aBoolean = true; / display them all ‘System.out printIn(""The largest byte value is " + largestByte); if (Character.isUpperCase(aChar)) { } Each expression performs an operation and retums a value, as shown in the following table. ‘Expression ‘Action Value Returned ce ‘Assign the character S*to the character | The value of aChar after pan = variable aChar the assignment (‘S') ‘Concatenate the string "The largest byte - "The largest byte value ‘The resulting string: The value is " and the value is" + largestByte largest byte value is 127 of largestByte converted to a string Character.isUpperCase( | The return value of the Call the method isUpperCase aChar) method: true Java Programming | 95 ‘The data type of the value returned by an expression depends on the elements used in the expression, The expression aChar ="S' returns a character because the assignment operator returns a value of the same data {ype as its operands and aChar and ‘S* are characters. As you see from the other expressions, an expression can return a boolean value, a string, and so on. The Java programming language allows you to construct compound expressions and statements from various smaller expressions as long as the data type required by one part of the expression muitches the éata type of the other. Here's an example of a compound expression: xt ya . For example, the following expression gives different results, depending on whether you perform the addition or the division operation firs: x+y/100 fuunbiguous You can specify exactly how you want an expression tobe evaluated, using balanced parentheses— (and ), For example, to make the previous expression unambiguous, you could write: (x+y) 100 //unambiguous, recommended If you don't explicitly indicate the order in Which you want the operations in a compound expression to be rerformed, the order is determined by the precedence assigned to the operators in use within the expression. Operators with a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Thus, the two following statements are equivalent: x+y 100 x+(y/ 100) unambiguous, recommended When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first. This pratice will make your code easier to read and to maintain. 95 Control Statements : Mug TAvA Control Statements. > Set of InstrutHos 18 colled progran. =) To handle Gone Statens woe Lew a poo of controls ane Called Conve! Some Cardrole, Statement a Conmire! = Styuctow c:s CI ig B Leapitd Jurp if stole Lk I— break, Suoitdh do Cork nue — +s we expres in, Operators with a higher precedence get evaluated first. For example, the division operator has higher precedence than does the addition operator. Thus, the two following statements are equivalent: x y/ 100 x~(y/ 100) “unambiguous, recommended When writing compound expressions, you should be explicit and indicate with parentheses which operators should be evaluated first. This pratice will make your code easier to read and to maintain, 95, Java Programming | 96 ALLIS. Control Statements A control statement works as a determiner for deciding the next task of the other statements whether to execute ar not, An ‘IP statement decides whether to execute. statement or which statement has to execute| first between the two. In Java, the control statements are divided into three categories which are selection’ statements, iteration statements, and jump statements. A program can execute from top to bottom but if we use a control statement, We can set or for executing a program based on values and logic, see below fable. %» Decision Making in Java Simple if Statement if_.else Statement Nested if statement if...clse if...else statement vyrvyy Switch statement » — Looping Statements in Java > While » — Do...while > For For-Each Loop » Branching Statements in Java Decision Making in Java 96] Java Programming | 97 Decision making statements are statements which decides what to execute and when. They are similar to decision making in real time, Control flow statements control the flow of a program’s execution. Here ow of execution will be based on state of a program, We have 4 decision making statements available in Java. |Simple if Statement = |Simple if statement is the basic of decision-making statements in Java, It decides if certain amount of code |should be executed based on the condition. Syntax: if (condition) + = break > Continue > — Return Decision Making in Java 96) ES Java Programming | 97 Decision making statements are statements which decides what to execute and when. They are similar to decision making in real time. Control flow statements control the flow of a program's execution. Here flow of execution will be based on state of a program. We have 4 decision making statements available in Java. Simple if Statement : Simple if statement is the basic of decision-making statements in Java. It decides if certain amotint of code should be exeented based on the conditi Syntax: if (condition) Statemen 1; //if condition becomes true then this will be executed } Statement 2; //this will be executed irrespective of condition becomes true or false Example: class ifTest { public static void main(String args{]){ intx = 5; if(x > 10) System.out.printin(” side If"); ‘System.out.printin("After if statement"); Output: After if statement 97 Ea Java Programming | 98 if...else Statement : Init false then else block will be executed. Syntax; if (condition) { Statemen 1; //if condition becomes true then this will be executed } Example: .else statement, if condition is true then statements in if block will be executed but if it comes out as, Output: After if statement 97 Java Programming | 98 Ise Statement : In if...else statement, if condition is true then statements in if block will be executed but if it comes out as false then else block will be executed. Syntax: if (condition) ( Statemen 1; /if condition becomes true then this will be executed } Example: class ifelseTest { public static void main(String args[]) { int x=9; if (x> 10) ‘System.out.printIn("i is greater than 10"); else’ ‘System.out.printin("i is less than 10"); System.out.printin(" After if else statement"); Output: oa So Java Programming | 99 iis less than 10 After if else statement Nested if statement : Nested if statement is if inside an if block. It is same as normal if...else statement but they are written inside another if,..clse statement, ‘Syntax: if (condition1) { ‘Statemen 1; //executed when condition! is true if (condition2) { intent 92> executed when condition? ts trac Java Programming | 99 iis less than 10 After if else statement Nested if statement : Nested if statement is if inside an if block. It is same as normal if inside another if...else statement. f...else statement but they are written if (condition) { Statemen 1; //executed when condition1 is true if (condition2) { Statement 2; //executed when condition? is true } Syntax: else { Statement 3; //executed when condition2 is false ) } Example: class nestedifTest ( public static void main(String args{]) { im x=25; if(x>10) if (x%2==0) 99 else ‘System.out.printh } else { ‘System.out.printIn("i is less than 10"); } Java Programming | 100 ‘System.out.printIn("i is greater than 10 and even number" greater than 10 and odd number"); ‘System.out.printin(" After nested if statement’ "5 Java Programming | 100 ‘System.out.printIn("i is greater than 10 and even number"); else System.out.printin("i is greater than 10 and odd number"); } else { System.out.printin( "i is less than 10"); ) ‘System.out.printIn("“After nested if statement"); Output: iis greater than 10 and odd number After nested if statement if...else statement : if...else if statements will be used when we need to compare the value with more than 2 conditions. They are executed from top to bottom approach. As soon as the code finds the matching condition, that block will be executed. But if no condition is matching then the last else statement will be executed. tax: if (conditiont) ( Statemen 1; /f condition! becomes true then this will be executed } dse if (condition2) { Statement 2; // if condition2 becomes true then this will be executed } sie ( ‘Statement 3; //executed when no matching condition found 0 } are executed from top to bottom approach. As soon as the code finds the matching condition, that block will be executed. But if no condition is matching then the last else statement will be executed. mtax: if (conditionl) { Statemen 1; /if condition] becomes true then this will be executed ) else if (condition?) ( Statement 2; //if condition? becomes true then this will be executed ) else { ‘Statement 3; //executed when no matching condition found bol } Java Programming | 101 Example: class ifelseifTest { public static void main(String args{]){ if(x> 10) { ‘System.out.printin("i is greater than 10"); else if (x<10) ‘System.out.printin(" is tess than 10"); alse { ‘System.otit printin(" is 10"); ‘System-out.printin(" After if else if ladder statement"); Output: iis less than 10 101 Java Programming | 102 After if else if ladder statement Switch statement : Jaya switch statement compares the value and executes one of the case blocks based on the condition. It is same as if,..else if ladder. Below are some points to consider while working with switch statements: » case value must be of the same type as expression used in switch statement » case value must be a constant or literal. It doesn’t allow variables » case values should be unique. If itis duplicate, then program will give compile time error Let us understand it through one example. System.out.printin("After if else if ladder statement"); Output: iis tess than 10 101 Java Programming | 102 After iffelse if ladder statement Switch statement : Java switch statement compares the value and executes one of the case blocks based on the condition. It is same as if...clse if ladder. Below are some points to consider while working with switch statements: » case value must be of the same type as expression used! in switch statement » case value must be a constant or literal, It doesn’t allow variables » case values should be unique. If it is duplicate, then program will give compile time error Let us understand it through one example. class switchDemo{ public static void main(String argsf}) { int i=2; switch(i) { case 0: System.out.printin("i is 0"); break: case 1: System.out.printIn("i is 1"); break; case 2: System.out.printin("% is 2"); break; case 3: 102 Java Programming | 103 System.out.printin( break; case 4: System.out.printin("i is 4"): break; default: System.out printIn("i is not in the list"); break; case I: ‘System.out.printIn(“i is 1"); brea case 2: System out printin("i is 2"); 102| So Java Programming | 103 System.out.printIn(" is 3°); break; case 4: System.out.println("i is 4 break; default ‘System.out printin("% is not in the list"); break; } [Looping Statements in Java : Looping statements are the statements which'éxecutes a block of code repeatedly until some condition meet to the criteria. Loops can be"considered as repeating if statements. There are 3 types of loops available in Java. While : While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes the body of loop, Thi repeated until the condition becomes false. Condition in while loop must be given as a Boolean expression. If int or string is used instead, compile will give the error. Syntax: Initialization; while (condition) { statement; increment/decrement; ) 103 Java Programming | 104 Example: class whileLoopTest_{ public static void main(String args{}) { intj while (j<= 10) { System out.printin(); ee ae Be) . Oe s used instead, compile will give the error. given‘as a Boolean expression. If int or string Syntax: Initialization; while (condition) { statementl; increment/decrement; } 103 i Java Programming | 104 Example: class whileLoopTest { public static void main(String args{]) { inj while (j<=10) { System.out printin(), J=j125 ) ' y Output: 13.579 Do...while : Do....while works same as while loop. It has only one difference that in do...while, condition is checked afier the exedution of the loop body. That is why this loop is considered as exit control loop. In do...while loop; body of loop will be executed at least once before checking the condition Syntax: = { statement; Jwhile(condition); 104 Java Programming | 105 Example: class dowhileLoopTest { Public static void main(String args[]) { int j= 10; do { Systemout.printin(j); je; ) while (j<= 10) eee gg OS ES OOP. BAe OGY One CUICTENCe MIA! In GO...WHEe, CONCIION 18 Checked afler the execution of the loop body. That is why this loop is considered as exit control loop. In do...while Joop, body of loop will be executed at least once betore checking the condition Syntax: a { statement; }while(condition); 104 Java Programming | 105 Output: Example: class dowhileLoopTest | public static void vain(String args{]) { im j= 10; do { System.out printing) } while (j<= 10) 10 For Statement : Itis the most common and widely used Joop in Java. It is the easiest way to construct a code as initialization of a variable, a condition and incremenVdecrement are declared only in a single line of code. It is easy to debug structure in Java, loop structure in Syntax: for (initialization; condition; increment/decrement) { ‘statement; ) 105 Java Programming | 106 Example: class forLoopTest { public static void main(String args{) for int j= 1; j<= 5: j++) System.out.printin(j); Output: statement; 105 Output: Java Programming | 106 Example: class forLoopTest { public static void main(String args{]) ( in) System.out.println()); b ) Output 1 3 4 5 For-Each Loop : For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to increment the value. It returns the elements from the array or collection one by one. Example: class foreachDemo { public static void main(String args{)) { int al] = {10,15.20.25,30}; for (int i: a) ( 106 Java Programming | 107 ‘System out printin(i): Example: class foreachDemo { public static void main(String argsf)) ( int af] = (10,15,20,25,30}; for (inti: a) { 106 Java Programming | 107 Systemout.printin(i): Output: 10 15 20 25 30 Branching Statements in Java : Branching statements jump from one statement to another and transfer the execution flow. There are 3 iching, statements in Java, Break : Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the innermost loop. Example: class breakTest{ public static void main(String args[)—{ for (int j=0:j<5:j+4) ( / come out of loop when iis 4. 107 Java Programming 108 itj==4) break: System out printin(j); } System.out.printin(”After loop"); Output: 0 terminate the innermost loop. Example: public static void main(String args{])—{ for (int O:j< Sj) [ #7 come out of loop when iis 4 107 Java Programming | 108 ifj==4) break: System.out.printin(j): 1 ‘System.out.printin(" After loop”); Output: Alier loop Continue : Continue statement works same as break but the difference is it only comes out of loop for that iteration and continue to execute the code for next iterations. So it only bypasses the current iteration. Example: class continueTest | public static void main(String args())— { 108 Java Programming | 109 O:j< Mj) E for Gint j #/ Wthe number is odd then bypass and continue with next value if (92 !=0) continue; only even numbers will be printed System.out.print(j +" —_—_—_—— for (int j I

You might also like