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

Sma391 Object Oriented Programming

The document outlines a course on Object Oriented Programming (OOP) offered by Kenyatta University, detailing its structure, topics, and learning outcomes. It covers fundamental concepts such as classes, objects, methods, and Java technologies over a 14-week period, with assessments including online activities and a final examination. The course aims to provide students with practical skills in Java programming and OOP principles through blended learning methods.

Uploaded by

rigiiih10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Sma391 Object Oriented Programming

The document outlines a course on Object Oriented Programming (OOP) offered by Kenyatta University, detailing its structure, topics, and learning outcomes. It covers fundamental concepts such as classes, objects, methods, and Java technologies over a 14-week period, with assessments including online activities and a final examination. The course aims to provide students with practical skills in Java programming and OOP principles through blended learning methods.

Uploaded by

rigiiih10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

lOMoARcPSD|40753519

SMA391 - Object Oriented Programming

Object Oriented Programming (Kenyatta University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Reeves Faraja ([email protected])
lOMoARcPSD|40753519

KENYATTA UNIVERSITY
DIGITAL SCHOOL OF VIRTUAL AND OPEN LEARNING
IN COLLABORATION WITH
SCHOOL OF PURE AND APPLIED SCIENCES
DEPARTMENT OF MATHEMATICS,
STRATEGIC PARTNERSHIPS FOR HIGHER EDUCATION
INNOVATION AND REFORM (SPHEIR),
THE ASSOCIATION OF COMMONWEALTH UNIVERSITIES (ACU) &
PARTNERSHIP FOR ENHANCED AND BLENDED LEARNING (PEBL)

OBJECT ORIENTED PROGRAMMING


WRITTEN BY: MR. BENARD OMOI ONDARA

VETTED BY: PEBL Quality Assurance Team Members

Licensed under a Creative Commons Attribution-Non Commercial-Share Alike 4.0 International


License

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

INTRODUCTION
Welcome ito ithis imodule. iYou imay ihave iheard iabout iObject iOriented iProgramming, ior iat ileast,
i the iterm iprogramming. iBut iagain, iyou iare ifamiliar iwith iobjects. iIn ithis imodule, iwe iwill iintroduce
i you ito ithe ibasic iconcepts iin iobject ioriented iprogramming iand iwhy iyou ishould istudy iit. i iThis iis ian
i interactive iinstructional imodule ithat iuses iboth iactive iand icollaborative ilearning istyles ithat
i provide iyou iwith idiverse ionline ilearning iexperiences iand ieffective ilearning iprocesses. iThe ikey
i purpose iof ithis imodule iis ito iexpose iyou ialbeit itheoretically iand ialso ipractically ito ithe ivarious
i fundamentals iof iObject iOriented iProgramming, iits ibenefits, iJava itechnologies, iObject
i Programming, iapplication idevelopment, ithe iuse iof iobjects iand itheir ilife icycle iservices, iOOP
i Design ias iwell ias ithe iOOP iarchitectures iand iframeworks

OBJECT ORIENTED PROGRAMMING


FLOWCHART
WEEK TOPIC
WEEK 0: Introduction
WEEK 1: Introduction to Object Oriented Programming, its brief history, and benefits
WEEK 2: Classes and Objects
WEEK 3: Methods
WEEK 4: Data Types
WEEK 5: Operators
WEEK 6: Control Statements
WEEK 7: Arrays
WEEK 8: Strings
WEEK 9: Looping
WEEK 10: Defining Your Own Classes in Java
WEEK 11 Inheritance and Polymorphism
WEEK 12 Practice Writing Your Own Programs
WEEK Exams
13&14

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

OVERVIEW OF THE COURSE


Week 0: Introduction (Your Context, Your Goals)
This ilesson iis iintended ito ihelp iyou iacclimatize ito iblended ilearning iand ito icreate ia icommunity iof
i learners iwho iwill imotivate ieach iother iduring ithe icourse. i iYou iwill ibe irequired ito iintroduce
i yourself ito iyour ilecturer iand icolleagues ieither iphysically iduring ia iface ito iface isession ior ieven
i online ibefore iother iacademic iinteractions istart. iThis iwill ibe iat ithe idiscretion iof iindividual
i universities iand ilecturers. iIt iwill ibe iimportant ito ialso istate iyour icontext iand igoals ias iwell ias iwhat
i you ithink iabout icomponent iprogramming. iYou ican ialso ishare iany iexperience ithat iyou imay ihave
i regarding iObject iOriented iProgramming.

Week 1: Introduction to Object Oriented Programming, Benefits and History of OOP


In ithis ifirst ilesson, iwe ilay ithe ifoundation iof ithe ientire icourse iby idefining ithe iconcepts iin iObject
i Oriented iProgramming ias iwell ias iother ivarious iterms. i iThe ipurpose iof ithis ilesson iis ito ienable iyou
i to iunderstand ithe ifundamental iconcepts iof iObject iOriented iProgramming iand ithe ibenefits iof
i Object iOriented iSoftware iDevelopment.

Week: 2 Classes and Objects


In ithis ilesson, iwe iexplore ithe iprinciples iof iObject iOriented iProgramming; iget ian iunderstanding iof
i its itechnologies iand iits iinfrastructures. iThe ipurpose iof ithis ilesson iis ito ienable ito iyou ito icarefully
i analyze ithe icomponents iof iOOP, ithe iinfrastructure iand ialso ibe iable ito iexplain ithe iunderlying
i principle iof ithe iOOP.

Week 3: Methods
In this lesson, we introduce Java method declaration, method body, return types and method
calls.

Week 4: Data Types


This lesson focuses on the Java Data Types, declaration of variables, and their scope.

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Week 5: Operators
Here we study Operators and how they are used to perform operations on variables and values.
We study, arithmetic, assignment, comparison and logical operators.
Week 6: Control Statements
This lesson explores control statements in Java and how they are used on decision making. We
focus on categories which include; selection statements, iteration statements and jump
statements.

Week 7: Arrays
This ilesson ideals iwith ithe istudy iof iarrays. iArrays; ia idata istructure iin iwhich ithe iitems iare iarranged
i as ia inumbered isequence, iso ias ieach iitem iis ireferred ito iby iits iposition inumber. iIn iJava ithe iitems
i must iof ithe isame itype iand inumbering istarts iat izero. iWe ialso iintroduce itypes iof iarrays iin ijava.

Week 8: String in java


In ithis ilesson, iwe iintroduce ithe iconcepts iof iStrings. iStrings iin iJava iare iObjects ithat iare ibacked
i internally iby ia ichar iarray. iSince iarrays iare iimmutable i(cannot igrow), iStrings iare iimmutable ias
i well. iWhenever ia ichange ito ia iString iis imade, ian ientirely inew iString iis icreated.

Week 9: Looping in Java


In ithis ilesson, iyou iwill ilearn iloops iin iJava. iIn iprogramming ilanguages, iloops iare iused ito iexecute ia
i set iof iinstructions/functions irepeatedly iwhen isome iconditions ibecome itrue. iThere iare ithree itypes
i of iloops iin iJava; ifor iloop, iwhile iloop iand ido-while iloop. iWe ialso ilearn iwhy iloops iare iimportant.

Week 10: Defining Your Own Classes in Java


In ithis ilesson, ithe istudent ilearns iabout icreating itheir iown iclasses, ideclare iproperties iand imethods
i for itheir iclasses, iuse iof ithis ireference ito iaccess iinstance idata, icreate iand icall ioverloaded imethods,
i and iuse iaccess imodifiers ito icontrol iaccess ito iclass imembers.

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Week 11: Inheritance and Polymorphism


This lesson explores two important principals of OOP. We start by looking at inheritance and
later polymorphism. Inheritance allows us to reuse code. Polymorphism allows us to perform a
single action in different ways.

Week 12: Examination


These itwo iweeks ibring itogether ithe iwork iyou ihave ibeen idoing ito ian iend. i iThis icourse iunit iwill ibe
i examined iand iwill ipartially icontribute ito ithe iaward iof ithe idegree iin ithe iprogramme ithat iyou iare
i undertaking. iWe iacknowledge ithat idifferent iuniversities iacross iEast iAfrica imay ihave idifferent
i Semester idates. iIt iis ihowever ianticipated ithat imost iUniversities iwill ihave ia iminimum iof i13
i weeks’ isemester. iWe ihave itherefore iplaced iexaminations iin ithe ilast itwo iweeks ibut iUniversities
i are iallowed ito igo iwith itheir ischedules. iYour iuniversity iexaminations iregulations iwill iapply. i

MODULE LEARNING OUTCOMES


By the end of this module, you will be able to:
1. Explain programming concepts such as data types, variables, java key words and
modifies in java.
2. Describe the fundamentals principals of OOP
3. Apply classes, objects, methods and strings in Java Programming
4. Demonstrate the application of arrays, file handling, exception handling in java
5. Utilize the JAVA SDK platform to design and develop a simple program
6. Connect Java programs to databases via JDBC
.
COURSE DESCRIPTION
Fundamentals: Definition & nature OOP, Data types and variables, arrays, methods, and strings;
Control statements in Java (if, if else, for loop, while, do while, switch), Java database
connectivity, Exception handling: Inheritance; Polymorphism; File Handling

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

COURSE REQUIREMENTS
This iis ia iblended ilearning icourse ithat iwill iutilize ithe iflex imodel. iThis imeans ithat ilearning
i materials iand iinstructions iwill ibe igiven ionline iand ithe ilessons iwill ibe iself-guided iwith ithe
i lecturer ibeing iavailable ibriefly ifor iface ito iface isessions iand isupport iand ialso ion-site i(online) imost
i of ithe itime. iYour ilecturer iwill ibe imeeting iyou iface ito iface ito iintroduce ia ilesson iand iput iit iinto
i perspective iand iyou iwill iactively iparticipate iin iyour isearch ifor iknowledge iby iundertaking iseveral
i online iactivities. iThis imeans ithat isome iof ithe i39 iinstructional ihours iof ithe icourse iwill ibe
i delivered iface ito iface iwhile iother ilessons iwill ibe itaught ionline ithrough ivarious ilearner iand
i lecturer iactivities. iYou ineed ito inote ithat ione iinstructional ihour iis iequivalent ito itwo ionline ihours.
i Three iinstructional ihours iwill ibe ineeded iper iweek. iOut iof ithese, ione iwill ibe iused ifor iface ito iface
i contact iwith iyour ilecturer i(also ireferred ito ias ie-moderator iin ithe ionline iactivities) iwhile ithe iother
i two iinstructional ihours i(translating ito ifour ionline ihours) iwill ibe iused ifor ionline iactivities
i otherwise ireferred ito ias ie-tivities iin ithe ilessons. iThis iwill iadd iup ito ithe i5 ihours’ irequirement iper
i lesson iearlier imentioned. iThere iare i36 ionline iactivities ieach itaking iat ileast itwo ihours iand itotaling
i to i72 ionline ihours. iYou iare iadvised ito ifollow ithe itopic iflow-chart igiven iso ithat iyou icover iat ileast
i a ilesson ievery iweek.

You iwill ibe irequired ito iparticipate iand iinteract ionline iwith iyour ipeers iand ithe ie-moderator iwho iin
i this icase iis iyour ilecturer. iGuidelines ifor ithe ionline iactivities i(which iwe ishall ikeep ireferring ito ias
i e-tivities) iwill ibe iprovided iwhenever ithere iis ian ie-tivity. iPlease inote ithat isince ithe ionline ie-tivities
i are ipart iof ithe ilearning iprocess, ithey imay ibe igraded iat ithe idiscretion iof iyour ie-moderator. iSuch
i grading iwill ihowever ibe icommunicated iin ithe ie-tivity iguidelines iand ifeedback igiven ias isoon ias
i possible iafter ithe ie-tivity. iThe ie-tivities iwill iinclude ibut iwill inot ibe ilimited ito ionline iassessment
i quizzes, iassignments, iand idiscussions. iThere iare ialso iassessment iquestions ithat iyou ican iattempt
i at ithe iend iof ievery ilesson ito itest iyour iunderstanding iof ithe ilesson. iThe ianswers ito iall ithe
i assessment iquestions iare iat ithe iend iof ithe imodule iafter ilesson i10. iAll ithe iresources ithat ihave ibeen
i used iin ithis imodule iin ithe iform iof ibooks iare iavailable iunder ithe iresources isection iafter ithe
i answers ito ithe iquestions.

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

ASSESSMENT
It iis iimportant ito inote ithat ithe imodule ihas iembedded icertain ilearner iformative iassessment
i feedback itools ithat iwill ienable iyou ito igauge iyour iown ilearning iprogress. iThe itools iinclude ionline
i collaborative idiscussions iforums ithat ifocus ion iteam ilearning iand ipersonal imastery iand iwill,
i therefore, iprovide iyou iwith ipeer ifeedback, ilecturer iassessment, iand iself- ireflection. i iYou iwill ialso
i be irequired ito ido ione imajor iassignment/project ithat iis imeant ito iassess ithe iapplication iof ithe iskills
i and iknowledge igained iduring ithe icourse. iThe iproject iscore iin icombination iwith iscores ifor ie-
tivities i(where igraded) iwill iaccount ifor i30% iof iyour ifinal iexamination iscore iwith ithe iremaining
i 70% icoming ifrom ia iface ito iface isit-in ifinal iwritten iexamination ithat iwill ibe iguided iby iyour
i university iexamination ipolicy iand iprocedures. iWe iwish iyou ithe ivery ibest iof iexperiences iin ithis
i course. i i

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

TABLE OF CONTENTS
LESSON 1 ............................................................................................................................................ 11
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING .......................................................... 11
1.1 History of Object-Oriented Programming (OOP) ........................................................................... 11
1.2 Introduction to Java Programming ............................................................................................... 11
1.3 Feature of Java............................................................................................................................. 12
1.4 iHistory iof iJava ........................................................................................................................... 13
1.5 Tools You Will Need ..................................................................................................................... 13
1.6. Local Environment Setup ............................................................................................................ 13
1.7 Popular Java Editors .................................................................................................................... 14
1.8 First Java Program ....................................................................................................................... 15
1.9 Basic Syntax ................................................................................................................................ 16
1.10 Java Identifiers ........................................................................................................................... 16
1.11 Java Modifiers ........................................................................................................................... 17
1.12 Java Variables ............................................................................................................................ 17
E-tivity 1 ........................................................................................................................................... 17
Assessment Questions ....................................................................................................................... 18
References ......................................................................................................................................... 19
LESSON 2 ............................................................................................................................................ 20
CLASSES AND OBJECTS ................................................................................................................... 20
2.1 Introduction to classes and objects ............................................................................................... 20
2.2 Objects in Java ............................................................................................................................. 20
2.3 Classes in Java ............................................................................................................................. 20
2.4 Constructors ................................................................................................................................ 21
2.5 Creating an Object ....................................................................................................................... 22
2.6 Accessing Instance Variables and Methods .................................................................................. 23
E-tivity 2 ........................................................................................................................................... 25
Assessment Questions ....................................................................................................................... 26
LESSON 3 ............................................................................................................................................ 30
METHODS ........................................................................................................................................... 30
3.1 Introduction to Methods ............................................................................................................... 30
3.2 Creating Method .......................................................................................................................... 30
3.3 Method Calling ............................................................................................................................ 31
3.4 The void Keyword ....................................................................................................................... 32
3.5 Passing Parameters by Value........................................................................................................ 33
3.6 More illustrations using Java ........................................................................................................ 34
E-tivity 3 ........................................................................................................................................... 37
Assessment Questions ....................................................................................................................... 38
References ......................................................................................................................................... 39
LESSON 4 ............................................................................................................................................ 41
DATA TYPES ...................................................................................................................................... 41
4.1 iPrimitive iData iTypes ................................................................................................................ 41
4.2 iReference iDatatypes .................................................................................................................. 43
4.3 Java Literals................................................................................................................................. 43
4.4 Variables in Java .......................................................................................................................... 44
4.5 Instance Variables ........................................................................................................................ 47
4.6 Class/Static Variables .................................................................................................................. 49

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

E-tivity 4-1 ........................................................................................................................................ 50


Assessment Questions ....................................................................................................................... 52
4.7 Java - Files and I/O ...................................................................................................................... 53
4.8 Standard Streams ......................................................................................................................... 56
E-tivity 4-2 ........................................................................................................................................ 57
Assessment Questions ....................................................................................................................... 58
4.9 Java - Date and Time ................................................................................................................... 58
4.10 Getting Current Date and Time .................................................................................................. 59
4.11 Date Formatting Using SimpleDateFormat ................................................................................. 59
Assessment Questions ....................................................................................................................... 61
References ......................................................................................................................................... 61
LESSON 5 ............................................................................................................................................ 62
OPERATORS ....................................................................................................................................... 62
5.1 The Arithmetic Operators............................................................................................................. 62
5.2 The Relational Operators ............................................................................................................. 62
5.3 The Logical Operators ................................................................................................................. 63
5.4 The Assignment Operators ........................................................................................................... 65
E-tivity 5 ........................................................................................................................................... 66
Assessment Questions ....................................................................................................................... 67
References ......................................................................................................................................... 68
LESSON 6 ............................................................................................................................................ 69
CONTROL STATEMENTS .................................................................................................................. 69
6.1 Introduction to control Statements ................................................................................................ 69
6.2 Java – If Then Else Statement ...................................................................................................... 69
6.3 If Else-If statement....................................................................................................................... 70
6.4 Java – Switch statement ............................................................................................................... 71
E-tivity 6 ........................................................................................................................................... 72
Assessment Questions ....................................................................................................................... 73
References ......................................................................................................................................... 74
LESSON 7 ............................................................................................................................................ 75
ARRAYS .............................................................................................................................................. 75
7.1 Arrays in Java .............................................................................................................................. 75
7.2 One Dimensional Array ............................................................................................................... 75
7.3 iCreating iArrays ......................................................................................................................... 75
7.4 Processing Arrays ........................................................................................................................ 76
7.5 Passing Arrays to Methods ........................................................................................................... 78
7.6 Returning an Array from a Method .............................................................................................. 79
7.7 The Arrays Class ......................................................................................................................... 79
7.8 Two-Dimensional Array .............................................................................................................. 80
E-tivity 7 ........................................................................................................................................... 82
Assessment Questions ....................................................................................................................... 83
References ......................................................................................................................................... 84
LESSON 8 ............................................................................................................................................ 85
STRINGS.............................................................................................................................................. 85
8.1 Creating Strings ........................................................................................................................... 85
8.2 String Length ............................................................................................................................... 85
8.3 Concatenating Strings .................................................................................................................. 86
8.4 Creating Format Strings ............................................................................................................... 87

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

8.5 String Methods ............................................................................................................................ 87


E-tivity 8 ........................................................................................................................................... 89
Assessment Questions ....................................................................................................................... 90
References ......................................................................................................................................... 91
LESSON 9 ............................................................................................................................................ 92
LOOPING IN JAVA ............................................................................................................................. 92
9.1 Loops in Java ............................................................................................................................... 92
9.2 while loop: ................................................................................................................................... 92
9.3 for loop ........................................................................................................................................ 93
9.4 Enhanced For loop ....................................................................................................................... 94
9.5 do while ....................................................................................................................................... 96
E-tivity 9 ........................................................................................................................................... 97
Assessment Questions on Loops ........................................................................................................ 98
Assessment Questions ....................................................................................................................... 98
References ......................................................................................................................................... 98
LESSON 10 .......................................................................................................................................... 99
DEFINING YOUR OWN CLASSES IN JAVA ..................................................................................... 99
10.1. Creating your own classes. Abstraction ..................................................................................... 99
10.2 Constructors............................................................................................................................... 99
References ....................................................................................................................................... 108
LESSON 11 ........................................................................................................................................ 110
INHERITANCE AND POLYMORPHISM ......................................................................................... 110
11.1 Inheritance ............................................................................................................................... 110
11.2 iextends iKeyword ................................................................................................................... 110
11.3 iThe isuper ikeyword ............................................................................................................... 112
11.4 iDifferentiating ithe iMembers ................................................................................................. 112
Sample iCode ............................................................................................................................... 112
11.5 Invoking Superclass Constructor .............................................................................................. 114
11.6 Polymorphism.......................................................................................................................... 115
11.7 iVirtual iMethods ..................................................................................................................... 117
E-tivity 11 ....................................................................................................................................... 119
References ....................................................................................................................................... 120
LESSON 12 ........................................................................................................................................ 121
PRACTICE WRITING JAVA PROGRAMS ....................................................................................... 121
12.1 Exception Handling ................................................................................................................. 121
12.2 Java Database Connectivity with MySQL ................................................................................ 122
References ....................................................................................................................................... 123

10

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 1
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
1.1 History of Object-Oriented Programming (OOP)
Many ipeople ibelieve ithat iOOP iis ia iproduct iof ithe i1980s iand ithe iwork idone iby iBjarne iStroustrup
i in imoving ithe iC ilanguage iinto ithe iobject-oriented iworld iby icreating ithe iC++ ilanguage. iActually,
i SIMULA i1 i(1962) iand iSimula i67 i(1967) iare ithe itwo iearliest iobject-oriented ilanguages. iThe iwork
i on ithe iSimula ilanguages iwas idone iby iOle-John iDahl iand iKristen iNygaard iat ithe iNorwegian
i Computing iCenter iin iOslo, iNorway. iWhile imost iof ithe iadvantages iof iOOP iwere iavailable iin ithe
i earlier iSimula ilanguages, iit iwasn't iuntil iC++ ibecame ientrenched iin ithe i1990s ithat iOOP ibegan ito
i flourish.

C iwas ithe iparent ilanguage iof iC++ iand iit iwas ioften isaid ithat iC iwas ipowerful ienough ito ishoot
i yourself iin ithe ifoot imultiple itimes. iC++, ion ithe iother ihand, inot ionly iwas ipowerful ienough ito
i shoot iyourself iin ithe ifoot, ibut iyou icould iblow iyour ientire ileg ioff iwithout itoo imuch idifficulty.
i Most iprogrammers iadmit ithat iC++ iis ia ivery ipowerful ilanguage iand iit iis istill iin iwidespread iuse
i today. iHowever, iwith ithat ipower icomes ia ilot iof icomplexity. iLanguage idevelopers iwanted ia
i simpler iand iperhaps iless icomplex ilanguage ifor iOOP idevelopment.
The inext istep iin ithe idevelopment iof iOOP istarted iin iJanuary iof i1991 iwhen iJames iGosling, iBill
i Joy, iPatrick iNaughton, iMike iSheradin, iand iseveral iothers imet iin iAspen, iColorado, ito idiscuss
i ideas ifor ithe iStealth iProject. iThe igroup iwanted ito idevelop iintelligent ielectronic idevices icapable
i of ibeing icentrally icontrolled iand iprogrammed ifrom ia ihandheld idevice.

1.2 Introduction to Java Programming


Java programming language was originally developed by Sun Microsystems which was initiated
by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform
(Java 1.0 [J2SE]).
The ilatest irelease iof ithe iJava iStandard iEdition iis iJava iSE i8. iWith ithe iadvancement iof iJava iand iits
i widespread ipopularity, imultiple iconfigurations iwere ibuilt ito isuit ivarious itypes iof iplatforms. iFor
i example: iJ2EE ifor iEnterprise iApplications, iJ2ME ifor iMobile iApplications.
The inew iJ2 iversions iwere irenamed ias iJava iSE, iJava iEE, iand iJava iME irespectively. iJava iis
i guaranteed ito ibe iWrite iOnce, iRun iAnywhere.

11

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

1.3 Feature of Java


 Object iOriented i− iIn iJava, ieverything iis ian iObject. iJava ican ibe ieasily iextended isince iit iis
i based ion ithe iObject imodel.
 Platform iIndependent i− iUnlike imany iother iprogramming ilanguages iincluding iC iand
i C++, iwhen iJava iis icompiled, iit iis inot icompiled iinto iplatform ispecific imachine, irather
i into iplatform iindependent ibyte icode. iThis ibyte icode iis idistributed iover ithe iweb iand
i interpreted iby ithe iVirtual iMachine i(JVM) ion iwhichever iplatform iit iis ibeing irun ion.
 Simple i− iJava iis idesigned ito ibe ieasy ito ilearn. iIf iyou iunderstand ithe ibasic iconcept iof iOOP
i Java, iit iwould ibe ieasy ito imaster.
 Secure i− iWith iJava's isecure ifeature iit ienables ito idevelop ivirus-free, itamper-free isystems.
i Authentication itechniques iare ibased ion ipublic-key iencryption.
 Architecture-neutral i− iJava icompiler igenerates ian iarchitecture-neutral iobject ifile
i format, iwhich imakes ithe icompiled icode iexecutable ion imany iprocessors, iwith ithe
i presence iof iJava iruntime isystem.
 Portable i− iBeing iarchitecture-neutral iand ihaving ino iimplementation idependent iaspects
i of ithe ispecification imakes iJava iportable. iCompiler iin iJava iis iwritten iin iANSI iC iwith ia
i clean iportability iboundary, iwhich iis ia iPOSIX isubset.
 Robust i− iJava imakes ian ieffort ito ieliminate ierror iprone isituations iby iemphasizing imainly
i on icompile itime ierror ichecking iand iruntime ichecking.
 Multithreaded i− iWith iJava's imultithreaded ifeature iit iis ipossible ito iwrite iprograms ithat
i can iperform imany itasks isimultaneously. iThis idesign ifeature iallows ithe idevelopers ito
i construct iinteractive iapplications ithat ican irun ismoothly.
 Interpreted i− iJava ibyte icode iis itranslated ion ithe ifly ito inative imachine iinstructions iand iis
i not istored ianywhere. iThe idevelopment iprocess iis imore irapid iand ianalytical isince ithe
i linking iis ian iincremental iand ilight-weight iprocess.
 High iPerformance i− iwith ithe iuse iof iJust-In-Time icompilers, iJava ienables ihigh
i performance.
 Distributed i− iJava iis idesigned ifor ithe idistributed ienvironment iof ithe iinternet.
 Dynamic i− iJava iis iconsidered ito ibe imore idynamic ithan iC ior iC++ isince iit iis idesigned ito
i adapt ito ian ievolving ienvironment. iJava iprograms ican icarry iextensive iamount iof irun-time
i information ithat ican ibe iused ito iverify iand iresolve iaccesses ito iobjects ion irun-time.

12

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

1.4 iHistory iof iJava


James iGosling iinitiated iJava ilanguage iproject iin iJune i1991 ifor iuse iin ione iof ihis imany iset-top ibox
i projects. iThe ilanguage, iinitially icalled i‘Oak’ iafter ian ioak itree ithat istood ioutside iGosling's ioffice,
i also iwent iby ithe iname i‘Green’ iand iended iup ilater ibeing irenamed ias iJava, ifrom ia ilist iof irandom
i words.
Sun ireleased ithe ifirst ipublic iimplementation ias iJava i1.0 iin i1995. iIt ipromised iWrite iOnce, iRun
Anywhere i(WORA), iproviding ino-cost irun-times ion ipopular iplatforms.
i

On i13 iNovember, i2006, iSun ireleased imuch iof iJava ias ifree iand iopen isource isoftware iunder ithe
i terms iof ithe iGNU iGeneral iPublic iLicense i(GPL).
On i8 iMay, i2007, iSun ifinished ithe iprocess, imaking iall iof iJava's icore icode ifree iand iopen-source,
i aside ifrom ia ismall iportion iof icode ito iwhich iSun idid inot ihold ithe icopyright.

1.5 Tools You Will Need


For iperforming ithe iexamples idiscussed iin ithis itutorial, iyou iwill ineed ia iPentium i200-MHz
i computer iwith ia iminimum iof i64 iMB iof iRAM i(128 iMB iof iRAM irecommended).
You iwill ialso ineed ithe ifollowing isoftware i
 Linux 7.1 or Windows xp/7/8/10 operating system
 Java JDK 8
 Microsoft Notepad or any other text editor

In this chapter, we will discuss on the different aspects of setting up a congenial environment
for Java.

1.6. Local Environment Setup


This isection iguides iyou ion ihow ito idownload iand iset iup iJava ion iyour imachine. iFollowing iare ithe
i steps ito iset iup ithe ienvironment.
Java iSE iis ifreely iavailable ifrom ithe ilink iDownload iJava. iYou ican idownload ia iversion ibased ion
i your ioperating isystem.

13

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Follow the instructions to download Java and run the .exe to install Java on your machine. Once
you installed Java on your machine, you will need to set environment variables to point to
correct installation directories −
Setting Up the Path for Windows
Assuming iyou ihave iinstalled iJava iin ic:\Program iFiles\java\jdk idirectory i−
 Right-click ion i'My iComputer' iand iselect i'Properties'.
 Click ithe i'Environment ivariables' ibutton iunder ithe i'Advanced' itab.
 Now, ialter ithe i'Path' ivariable iso ithat iit ialso icontains ithe ipath ito ithe iJava iexecutable.
Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your
path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment ivariable iPATH ishould ibe iset ito ipoint ito iwhere ithe iJava ibinaries ihave ibeen
i installed. iRefer ito iyour ishell idocumentation, iif iyou ihave itrouble idoing ithis.
Example, iif iyou iuse ibash ias iyour ishell, ithen iyou iwould iadd ithe ifollowing iline ito ithe iend iof iyour
i '.bashrc: iexport iPATH i= i/path/to/java:$PATH'

1.7 Popular Java Editors


To write your Java programs, you will need a text editor. There are even more sophisticated
IDEs available in the market. But for now, you can consider one of the following −
 Notepad i− iOn iWindows imachine, iyou ican iuse iany isimple itext ieditor ilike iNotepad
i (Recommended ifor ithis itutorial), iTextPad.
 Netbeans i− iA iJava iIDE ithat iis iopen-source iand ifree iwhich ican ibe idownloaded ifrom
i https://www.netbeans.org/index.html.
 Eclipse i− iA iJava iIDE ideveloped iby ithe ieclipse iopen-source icommunity iand ican ibe
i downloaded ifrom ihttps://www.eclipse.org/

When we consider a Java program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods,
and instance variables mean.

14

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 Object i− iObjects ihave istates iand ibehaviors. iExample: iA idog ihas istates i- icolor, iname,
i breed ias iwell ias ibehavior isuch ias iwagging itheir itail, ibarking, ieating. iAn iobject iis ian
i instance iof ia iclass.
 Class i− iA iclass ican ibe idefined ias ia itemplate/blueprint ithat idescribes ithe ibehavior/state
i that ithe iobject iof iits itype isupports.
 Methods i− iA imethod iis ibasically ia ibehavior. iA iclass ican icontain imany imethods. iIt iis iin
i methods iwhere ithe ilogics iare iwritten, idata iis imanipulated iand iall ithe iactions iare
i executed.
 Instance iVariables i− iEach iobject ihas iits iunique iset iof iinstance ivariables. iAn iobject's
i state iis icreated iby ithe ivalues iassigned ito ithese iinstance ivariables.
1.8 First Java Program
Let us look at a simple code that will print the words Hello World.
Example
public iclass iMyFirstJavaProgram i{
iii /* iThis iis imy ifirst ijava iprogram.
iiii * iThis iwill iprint i'Hello iWorld' ias ithe ioutput
iiii */
iii public istatic ivoid imain(String i[]args) i{
iiiiii System.out.println("Hello iWorld"); i// iprints iHello iWorld
iii }
}
Let's look at how to save the file, compile, and run the program. Please follow the subsequent
steps −
 Open inotepad iand iadd ithe icode ias iabove.
 Save ithe ifile ias: iMyFirstJavaProgram.java.
 Open ia icommand iprompt iwindow iand igo ito ithe idirectory iwhere iyou isaved ithe iclass.
i Assume iit's iC:\.
 Type i'javac iMyFirstJavaProgram.java' iand ipress ienter ito icompile iyour icode. iIf ithere iare
i no ierrors iin iyour icode, ithe icommand iprompt iwill itake iyou ito ithe inext iline i(Assumption:
i The ipath ivariable iis iset).
 Now, itype i' ijava iMyFirstJavaProgram i' ito irun iyour iprogram.

15

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 You iwill ibe iable ito isee i' iHello iWorld i' iprinted ion ithe iwindow.

1.9 Basic Syntax


About iJava iprograms, iit iis ivery iimportant ito ikeep iin imind ithe ifollowing ipoints.
 Case iSensitivity i− iJava iis icase isensitive, iwhich imeans iidentifier iHello iand ihello iwould
i have idifferent imeaning iin iJava.
 Class iNames i− iFor iall iclass inames ithe ifirst iletter ishould ibe iin iUpper iCase. iIf iseveral
i words iare iused ito iform ia iname iof ithe iclass, ieach iinner iword's ifirst iletter ishould ibe iin
i Upper iCase.
Example: iclass iMyFirstJavaClass
 Method iNames i− iAll imethod inames ishould istart iwith ia iLower iCase iletter. iIf iseveral
i words iare iused ito iform ithe iname iof ithe imethod, ithen ieach iinner iword's ifirst iletter ishould
i be iin iUpper iCase.
Example: ipublic ivoid imyMethodName()
 Program iFile iName i− iName iof ithe iprogram ifile ishould iexactly imatch ithe iclass iname.
When isaving ithe ifile, iyou ishould isave iit iusing ithe iclass iname i(Remember iJava iis icase
i sensitive) iand iappend i'.java' ito ithe iend iof ithe iname i(if ithe ifile iname iand ithe iclass iname
i do inot imatch, iyour iprogram iwill inot icompile).
But iplease imake ia inote ithat iin icase iyou ido inot ihave ia ipublic iclass ipresent iin ithe ifile ithen
i file iname ican ibe idifferent ithan iclass iname. iIt iis ialso inot imandatory ito ihave ia ipublic iclass
i in ithe ifile.
Example: iAssume i'MyFirstJavaProgram' iis ithe iclass iname. iThen ithe ifile ishould ibe isaved
i as i'MyFirstJavaProgram.java'
 public istatic ivoid imain(String iargs[]) i− iJava iprogram iprocessing istarts ifrom ithe imain()
i method iwhich iis ia imandatory ipart iof ievery iJava iprogram.

1.10 Java Identifiers


All iJava icomponents irequire inames. iNames iused ifor iclasses, ivariables, iand imethods iare icalled
i identifiers.
In iJava, ithere iare iseveral ipoints ito iremember iabout iidentifiers. iThey iare ias ifollows i−

16

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 All iidentifiers ishould ibegin iwith ia iletter i(A ito iZ ior ia ito iz), icurrency icharacter i($) ior ian
i underscore i(_).
 After ithe ifirst icharacter, iidentifiers ican ihave iany icombination iof icharacters.
 A ikey iword icannot ibe iused ias ian iidentifier.
 Most iimportantly, iidentifiers iare icase isensitive.
 Examples iof ilegal iidentifiers: iage, i$salary, i_value, i__1_value.
 Examples iof iillegal iidentifiers: i123abc, i-salary.

1.11 Java Modifiers


Like iother ilanguages, iit iis ipossible ito imodify iclasses, imethods, ietc., iby iusing imodifiers. iThere
i are itwo icategories iof imodifiers i−
 Access iModifiers i− idefault, ipublic, iprotected, iprivate
 Non-access iModifiers i− ifinal, iabstract, istrictfp
We iwill ibe ilooking iinto imore idetails iabout imodifiers iin ithe inext isection.

1.12 Java Variables


Following iare ithe itypes iof ivariables iin iJava i−
 Local iVariables
 Class iVariables i(Static iVariables)
 Instance iVariables i(Non-static iVariables)
E-tivity 1
Numbering, 1
pacing and
sequencing
Title Classes and Objects
Purpose The ipurpose iof ithis ie-tivity iis ito iintroduce iyou ito iobjects iand iclasses iwhich
iare icore iconcepts i in iOOP.

Brief summary Watch videos on these links


of overall task 1 https://www.youtube.com/watch?v=4xKihjI6HJ0 by Telusko
2 https://www.youtube.com/watch?v=3sMxJxeUOLg byTelusko
3 https://www.youtube.com/watch?v=ZHLdVRXIuC8 by programming

17

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

knowledge
Spark

Individual task (a) Describe a brief history of OOP


(b)Give a brief history of java programming language
c)Explain Features of Java programming language
d) Write your first Java program printing the message “Welcome to
the World of Java”
Interaction a) Post itwo ithemes icommon iin iHistory iof iOOP
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners i‘views
i and iideas. iDo ithis ion ithe idiscussion iforum i2.2.1
E-moderator 1Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
2 Stimulate ifurther ilearning iand igeneration iof inew iideas. i
3 Provide ifeedback ion ithe ilearning iprogress.
4 Round-up ithe ie-tivity
Schedule and This itask ishould itake i3 i ihours
time
Next Classes and Objects

Assessment Questions
1.Who is Father of Java?
A. James Bong
B. James Gosling
C. Gosling Trump
D. Non of the Above

2.Initially Java is called as?


A. Green

18

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Outside
C. Oak
D. All of the above
3.When Java first version was realized?
A.1994
B.1995
C.1996
D.1990
4.Java Latest version and its name?
A. Java 8
Java 15
C. Java 11
Java 13.
E. Java 14

5.Which one of the following belongs to the part of the Java system that is responsible for
executing Java programs?
a. RTS
b. JDC
c. JNDI
d. JDK
e. JVM

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6.https://www.o’reilly.com

19

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 2
CLASSES AND OBJECTS
2.1 Introduction to classes and objects
Java iis ian iObject-Oriented iLanguage. iAs ia ilanguage ithat ihas ithe iObject-Oriented ifeature
 Classes
 Objects
 Instance
 Method
In this chapter, we will look into the concepts - Classes and Objects.
 Object i− iObjects ihave istates iand ibehaviors. iExample: iA idog ihas istates i- icolor, iname,
i breed ias iwell ias ibehaviors i– iwagging ithe itail, ibarking, ieating. iAn iobject iis ian iinstance iof
i a iclass.
 Class i− iA iclass ican ibe idefined ias ia itemplate/blueprint ithat idescribes ithe ibehavior/state
i that ithe iobject iof iits itype isupport.
2.2 Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If iwe iconsider ia idog, ithen iits istate iis i- iname, ibreed, icolor, iand ithe ibehavior iis i- ibarking, iwagging
i the itail, irunning.
If iyou icompare ithe isoftware iobject iwith ia ireal-world iobject, ithey ihave ivery isimilar
i characteristics.
Software iobjects ialso ihave ia istate iand ia ibehavior. iA isoftware iobject's istate iis istored iin ifields iand
i behavior iis ishown ivia imethods.
So iin isoftware idevelopment, imethods operate on the internal state of an object and the object-
to-object communication is done via methods.
2.3 Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public iclass iDog i{
iii String ibreed;

20

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii int iage;


iii String icolor;

iii void ibarking() i{


iii }

iii void ihungry() i{


iii }

iii void isleeping() i{


iii }
}

A class can contain any of the following variable types.


 Local variables − Variables idefined iinside imethods, iconstructors ior iblocks iare
icalled ilocal ivariables. iThe ivariable iwill ibe ideclared iand iinitialized iwithin ithe
imethod iand ithe ivariable iwill ibe idestroyed iwhen ithe imethod ihas icompleted.
 Instance ivariables i− iInstance ivariables iare ivariables iwithin ia iclass ibut ioutside iany
i method. iThese ivariables iare iinitialized iwhen ithe iclass iis iinstantiated. iInstance ivariables
i can ibe iaccessed ifrom iinside iany imethod, iconstructor ior iblocks iof ithat iparticular iclass.
 Class ivariables i− iClass ivariables iare ivariables ideclared iwithin ia iclass, ioutside iany
i method, iwith ithe istatic ikeyword.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into classes
of the Java Language.
2.4 Constructors
When idiscussing iabout iclasses, ione iof ithe imost iimportant isub itopic iwould ibe iconstructors. iEvery
i class ihas ia iconstructor. iIf iwe ido inot iexplicitly iwrite ia iconstructor ifor ia iclass, ithe iJava icompiler
i builds ia idefault iconstructor ifor ithat iclass.

21

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Each itime ia inew iobject iis icreated, iat ileast ione iconstructor iwill ibe iinvoked. iThe imain irule iof
i constructors iis ithat ithey ishould ihave ithe isame iname ias ithe iclass. iA iclass ican ihave imore ithan ione
i constructor.
Following is an example of a constructor −
Example
public class Puppy {
public Puppy() {
}

public Puppy(String name) {


// This constructor has one parameter, name.
}
}
Java also supports Singleton Classes where you would be able to create only one instance of a
class.
Note − We ihave itwo idifferent itypes iof iconstructors. iWe iare igoing ito idiscuss iconstructors iin
i detail iin ithe isubsequent ichapters.
2.5 Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In iJava, ithe inew ikeyword iis iused ito icreate inew iobjects.
There iare ithree isteps iwhen icreating ian iobject ifrom ia iclass i−
 Declaration i− iA ivariable ideclaration iwith ia ivariable iname iwith ian iobject itype.
 Instantiation i− iThe i'new' ikeyword iis iused ito icreate ithe iobject.
 Initialization i− iThe i'new' ikeyword iis ifollowed iby ia icall ito ia iconstructor. iThis icall
i initializes ithe inew iobject.

Following is an example of creating an object −


Example
public iclass iPuppy i{
iii public iPuppy(String iname) i{
iiiiii // iThis iconstructor ihas ione iparameter, iname.

22

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiii System.out.println("Passed iName iis i:" i+ iname i);


iii }

iii public istatic ivoid imain(String i[]args) i{


iiiiii // iFollowing istatement iwould icreate ian iobject imyPuppy
iiiiii Puppy imyPuppy i= inew iPuppy( i"tommy" i);
iii }
}

If we compile and run the above program, then it will produce the following result −
Output
Passed Name is :tommy
2.6 Accessing Instance Variables and Methods
Instance ivariables iand imethods iare iaccessed ivia icreated iobjects. iTo iaccess ian iinstance ivariable,
i following iis ithe ifully iqualified ipath i−
/* iFirst icreate ian iobject i*/
ObjectReference i= inew iConstructor();

/* iNow icall ia ivariable ias ifollows i*/


ObjectReference.variableName;

/* iNow iyou ican icall ia iclass imethod ias ifollows i*/


ObjectReference.MethodName();

Example
This example explains how to access instance variables and methods of a class.
public iclass iPuppy i{
iii int ipuppyAge;

iii public iPuppy(String iname) i{


iiiiii // iThis iconstructor ihas ione iparameter, iname.
23

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiii System.out.println("Name ichosen iis i:" i+ iname i);


iii }

iii public ivoid isetAge( iint iage i) i{


iiiiii puppyAge i= iage;
iii }

iii public iint igetAge( i) i{


iiiiii System.out.println("Puppy's iage iis i:" i+ ipuppyAge i);
iiiiii return ipuppyAge;
iii }

iii public istatic ivoid imain(String i[]args) i{


iiiiii /* iObject icreation i*/
iiiiii Puppy imyPuppy i= inew iPuppy( i"tommy" i);

iiiiii /* iCall iclass imethod ito iset ipuppy's iage i*/


iiiiii myPuppy.setAge( i2 i);

iiiiii /* iCall ianother iclass imethod ito iget ipuppy's iage i*/
iiiiii myPuppy.getAge( i);

iiiiii /* iYou ican iaccess iinstance ivariable ias ifollows ias iwell i*/
iiiiii System.out.println("Variable iValue i:" i+ imyPuppy.puppyAge i);
iii }
}

If we compile and run the above program, then it will produce the following result −
Output
Name chosen is :tommy
Puppy's age is :2

24

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Variable Value :2

E-tivity 2
Numbering, 9
pacing and
sequencing
Title Classes and Objects
Purpose The purpose of this e-tivity is to introduce you to objects and classes
which are core concepts in OOP.
Brief summary Watch videos on these links
of overall task 4 https://www.youtube.com/watch?v=4xKihjI6HJ0 by Telusko
5 https://www.youtube.com/watch?v=3sMxJxeUOLg byTelusko
6 https://www.youtube.com/watch?v=ZHLdVRXIuC8by programming
knowledge
Spark

Individual task (a) Define a class and an object as used in Java OOP
(b)Write a program with a class Car creating an object called Benz to
access the class in the main method
c)State and explain two types of constructors in java
d) Explain five key principles of OOP.
Interaction c) Post two themes common in Classes and Objects
begins d) Provide positive and constructive feedback on the team learners
‘views and ideas. Do this on the discussion forum 2.2.1

25

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

E-moderator 1 Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
2 Stimulate ifurther ilearning iand igeneration iof inew iideas. i
3 Provide ifeedback ion ithe ilearning iprogress.
4 Round-up ithe ie-tivity
Schedule and This itask ishould itake i2 i ihours
time
Next Methods

Assessment Questions
1.Predict ithe ioutput iof ifollowing iJava iprogram?
class iTest i{
ii int ii;
}i
class iMain i{
iii public istatic ivoid imain(String iargs[]) i{ i
iiiii Test it; i
iiiii System.out.println(t.i); i
}ii

A 0
B garbage ivalue
C compiler ierror
D runtime ierror
2. iWhat iis ithe ioutput iof ithe ifollowing iprogram
class idemo
{
iiii int ia, ib;
iiiii

iiii demo()
iiii {

26

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiiiii a i= i10;
iiiiiiii b i= i20;
iiii }
iiiii

iiii public ivoid iprint()


iiii {
iiiiiiii System.out.println i("a i= i" i+ ia i+ i" ib i= i" i+ ib i+ i"n");
iiii }
}
i

class iTest
{
i

iiii public istatic ivoid imain(String[] iargs)


iiii {
iiiiiiii demo iobj1 i= inew idemo();
iiiiiiii demo iobj2 i= iobj1;
i

iiiiiiii obj1.a i+= i1;


iiiiiiii obj1.b i+= i1;
i

iiiiiiii System.out.println i("values iof iobj1 i: i");


iiiiiiii obj1.print();
iiiiiiii System.out.println i("values iof iobj2 i: i");
iiiiiiii obj2.print();
i

iiii }
}

A Compile ierror
values iof iobj1: i
a i= i11 ib i= i21
B
values iof iobj2: i
a i= i11 ib i= i21

27

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

values iof iobj1: i


a i= i11 ib i= i21
C values iof iobj2: i
a i= i10 ib i= i20

values iof iobj1: i


a i= i11 ib i= i20
D values iof iobj2: i
a i= i10 ib i= i21

E Run itime ierror

3.Predict ithe ioutput iof ifollowing iJava iprogram.


class idemoClass
{
iiii int ia i= i1;
i

iiii void ifunc()


iiii {
iiiiiiii demo iobj i= inew idemo();
iiiiiiii obj.display();
iiii }
i
i

iiii class idemo


iiii {
iiiiiiii int ib i= i2;
i

iiiiiiii void idisplay()


iiiiiiii {
iiiiiiiiiiii System.out.println("na i= i" i+ ia);
iiiiiiii }

28

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiii }
i

iiii void iget()


iiii {
iiiiiiii System.out.println("nb i= i" i+ ib);
iiii }
}
i
i

class iTest
{
iiii public istatic ivoid imain(String[] iargs)
iiii {
iiiiiiii demoClass iobj i= inew idemoClass();
iiiiiiii obj.func();
iiiiiiii obj.get();
i

iiii }
}

a i= i1
A
b i= i2
B Compilation ierror
b i= i2
C
a i= i1

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6. O’reilly.com

29

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 3
METHODS
3.1 Introduction to Methods
A iJava imethod iis ia icollection iof istatements ithat iare igrouped itogether ito iperform ian
ioperation. iWhen iyou icall ithe iSystem.out.println() imethod, ifor iexample, ithe isystem
iactually iexecutes iseveral istatements iin iorder ito idisplay ia imessage ion ithe iconsole.
Now iyou iwill ilearn ihow ito icreate iyour iown imethods iwith ior iwithout ireturn ivalues,
iinvoke ia imethod iwith ior iwithout iparameters, iand iapply imethod iabstraction iin ithe
iprogram idesign.

3.2 Creating Method


Considering ithe ifollowing iexample ito iexplain ithe isyntax iof ia imethod i−
Syntax
public istatic iint imethodName(int ia, iint ib) i{
iii // ibody
}
Here,
 public istatic i− imodifier
 int i− ireturn itype
 methodName i− iname iof ithe imethod
 a, ib i− iformal iparameters
 int ia, iint ib i− ilist iof iparameters
Method idefinition iconsists iof ia imethod iheader iand ia imethod ibody. iThe isame iis ishown iin ithe
i following isyntax i−
Syntax
modifier ireturnType inameOfMethod i(Parameter iList) i{
iii // imethod ibody
}
The isyntax ishown iabove iincludes i−
 modifier i− iIt idefines ithe iaccess itype iof ithe imethod iand iit iis ioptional ito iuse.
 returnType i− iMethod imay ireturn ia ivalue.

30

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 nameOfMethod i− iThis iis ithe imethod iname. iThe imethod isignature iconsists iof ithe imethod
i name iand ithe iparameter ilist.
 Parameter iList i− iThe ilist iof iparameters, iit iis ithe itype, iorder, iand inumber iof iparameters
i of ia imethod. iThese iare ioptional, imethod imay icontain izero iparameters.
 method ibody i− iThe imethod ibody idefines iwhat ithe imethod idoes iwith ithe istatements.
Example
Here iis ithe isource icode iof ithe iabove idefined imethod icalled imin(). iThis imethod itakes itwo
i parameters inum1 iand inum2 iand ireturns ithe imaximum ibetween ithe itwo i−
/** ithe isnippet ireturns ithe iminimum ibetween itwo inumbers i*/

public istatic iint iminFunction(int in1, iint in2) i{


iii int imin;
iii if i(n1 i> in2)
iiiiii min i= in2;
iii else
iiiiii min i= in1;

iii return imin; i


}

3.3 Method Calling


For iusing ia imethod, iit ishould ibe icalled. iThere iare itwo iways iin iwhich ia imethod iis icalled ii.e.,
i method ireturns ia ivalue ior ireturning inothing i(no ireturn ivalue).
The iprocess iof imethod icalling iis isimple. iWhen ia iprogram iinvokes ia imethod, ithe iprogram icontrol
i gets itransferred ito ithe icalled imethod. iThis icalled imethod ithen ireturns icontrol ito ithe icaller iin itwo
i conditions, iwhen i−
 the ireturn istatement iis iexecuted.
 it ireaches ithe imethod iending iclosing ibrace.
The imethods ireturning ivoid iis iconsidered ias icall ito ia istatement. iLets iconsider ian iexample i−
System.out.println("This iis itutorialspoint.com!");
The imethod ireturning ivalue ican ibe iunderstood iby ithe ifollowing iexample i−
31

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

int iresult i= isum(6, i9);


Following iis ithe iexample ito idemonstrate ihow ito idefine ia imethod iand ihow ito icall iit i−
Example
public iclass iExampleMinNumber i{
iii

iii public istatic ivoid imain(String[] iargs) i{


iiiiii int ia i= i11;
iiiiii int ib i= i6;
iiiiii int ic i= iminFunction(a, ib);
iiiiii System.out.println("Minimum iValue i= i" i+ ic);
iii }

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}
This will produce the following result −
Output
Minimum value = 6
3.4 The void Keyword
The ivoid ikeyword iallows ius ito icreate imethods iwhich ido inot ireturn ia ivalue. iHere, iin ithe
i following iexample iwe're iconsidering ia ivoid imethod imethodRankPoints. iThis imethod iis ia ivoid
i method, iwhich idoes inot ireturn iany ivalue. iCall ito ia ivoid imethod imust ibe ia istatement ii.e.

32

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

i methodRankPoints(255.7);. iIt iis ia iJava istatement iwhich iends iwith ia isemicolon ias ishown iin ithe
i following iexample.

Example
public iclass iExampleVoid i{

iii public istatic ivoid imain(String[] iargs) i{


iiiiii methodRankPoints(255.7);
iii }

iii public istatic ivoid imethodRankPoints(double ipoints) i{


iiiiii if i(points i>= i202.5) i{
iiiiiiiii System.out.println("Rank:A1");
iiiiii }else iif i(points i>= i122.4) i{
iiiiiiiii System.out.println("Rank:A2");
iiiiii }else i{
iiiiiiiii System.out.println("Rank:A3");
iiiiii }
iii }
}

3.5 Passing Parameters by Value


While iworking iunder icalling iprocess, iarguments iis ito ibe ipassed. iThese ishould ibe iin ithe isame
i order ias itheir irespective iparameters iin ithe imethod ispecification. iParameters ican ibe ipassed iby
i value ior iby ireference
Passing Parameters by Value means calling a method with a parameter. Through this, the
argument value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The values of the
arguments remains the same even after the method invocation.
public class swappingExample {
33

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

public static void main(String[] args) {


int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}

public static void swapFunction(int a, int b) {


System.out.println("Before swapping(Inside), a = " + a + " b = " + b);

// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}

3.6 More illustrations using Java


Program: Check whether String is palindrome using recursion
package ibeginnersbook.com;
import ijava.util.Scanner;
class iPalindromeCheck
{
iiii //My iMethod ito icheck
iiii public istatic iboolean iisPal(String is)

34

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiii { i i i// iif ilength iis i0 ior i1 ithen iString iis ipalindrome
iiiiiiii if(s.length() i== i0 i|| is.length() i== i1)
iiiiiiiiiiii return itrue; i
iiiiiiii if(s.charAt(0) i== is.charAt(s.length()-1))
iiiiiiii /* icheck ifor ifirst iand ilast ichar iof iString:
iiiiiiiii * iif ithey iare isame ithen ido ithe isame ithing ifor ia isubstring
iiiiiiiii * iwith ifirst iand ilast ichar iremoved. iand icarry ion ithis
iiiiiiiii * iuntil iyou istring icompletes ior icondition ifails
iiiiiiiii * iFunction icalling iitself: iRecursion
iiiiiiiii */
iiiiiiii return iisPal(s.substring(1, is.length()-1));

iiiiiiii /* iIf iprogram icontrol ireaches ito ithis istatement iit imeans
iiiiiiiii * ithe iString iis inot ipalindrome ihence ireturn ifalse.
iiiiiiiii */
iiiiiiii return ifalse;
iiii }

iiii public istatic ivoid imain(String[]args)


iiii {
iiii //For icapturing iuser iinput
iiiiiiii Scanner iscanner i= inew iScanner(System.in);
iiiiiiii System.out.println("Enter ithe iString ifor icheck:");
iiiiiiii String istring i= iscanner.nextLine();
iiiiiiii /* iIf ifunction ireturns itrue ithen ithe istring iis
iiiiiiiii * ipalindrome ielse inot
iiiiiiiii */
iiiiiiii if(isPal(string))
iiiiiiiiiiii System.out.println(string i+ i" iis ia ipalindrome");
iiiiiiii else
iiiiiiiiiiii System.out.println(string i+ i" iis inot ia ipalindrome");

35

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

}
}

Write a Java program to calculate the sum of two integers and return true if the sum is equal to a
third integer.
Sample Solution:
Java Code:
import java.util.*;
public class Exercise52 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.print("The result is: "+sumoftwo(x, y, z));
System.out.print("\n");
}

public static boolean sumoftwo(int p, int q, int r)


{
return ((p + q) == r || (q + r) == p || (r + p) == q);
}
}

Write ia iJava iprogram ithat iaccepts ithree iintegers ifrom ithe iuser iand ireturn itrue iif ithe isecond
i number iis igreater ithan ifirst inumber iand ithird inumber iis igreater ithan isecond inumber. iIf ianother
i variable i"abc" iis itrue isecond inumber idoes inot ineed ito ibe igreater ithan ifirst inumber.

36

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Sample Solution:
Java Code:
import java.util.*;
public class Exercise53 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the first number : ");
int x = in.nextInt();
System.out.print("Input the second number: ");
int y = in.nextInt();
System.out.print("Input the third number : ");
int z = in.nextInt();
System.out.print("The result is: "+test(x, y, z,true));
System.out.print("\n");
}

public static boolean test(int p, int q, int r, boolean xyz)


{
if(xyz)
return (r > q);
return (q > p && r > q);
}
}
E-tivity 3
Numbering, 3
pacing and
sequencing
Title Methods

37

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Purpose The purpose of this e-tivity is to enable you to define methods, create
methods and pass data known as parameters in java.
Brief summary Watch videos on these links
of overall task 1.https://www.youtube.com/watch?v=cCgOESMQe44 by Alex Lee
2. https://www.youtube.com/watch?v=0kDMKHAZdQk By Sriyank
3. https://www.youtube.com/watch?v=1cWAcMdEXiQ By Tutorials
Point
Spark

Individual task (a) Explain what is a method in programming


(b)Declare a method in Java
c)Write a method in java for finding total of two integers entered
through the keyboard
Interaction a) Post itwo ithemes ithat iare icommon iin imethods
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This itask ishould itake i4 i ihours
time
Next Data Types

Assessment Questions

38

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

1. What is the return type of a method that does not return any value?
a) int
b) float
c) void
d) double
2. What is the process of defining more than one method in a class differentiated by method
signature?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of the mentioned
3. Which method can be defined only once in a program?
a) main method
b) finalize method
c) static method
d) private method
4. Which of the following is a method having same name as that of it’s class?
a) finalize
b) delete
c) class
d) constructor
5. iWhich iof ithis istatement iis iincorrect?
a) iAll iobject iof ia iclass iare iallotted imemory ifor ithe iall ithe ivariables idefined iin ithe iclass
b) iIf ia ifunction iis idefined ipublic iit ican ibe iaccessed iby iobject iof iother iclass iby iinheritation
c) imain() imethod imust ibe imade ipublic
d) iAll iobject iof ia iclass iare iallotted imemory ifor ithe imethods idefined iin ithe iclass

References
1.https://www.geeksforgeeks.org/

39

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6. O’reilly.com

40

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 4
DATA TYPES
There iare itwo idata itypes iavailable iin iJava i−
 Primitive iData iTypes
 Reference/Object iData iTypes
4.1 iPrimitive iData iTypes
There iare ieight iprimitive idatatypes isupported iby iJava. iPrimitive idatatypes iare ipredefined iby ithe
i language iand inamed iby ia ikeyword. iLet ius inow ilook iinto ithe ieight iprimitive idata itypes iin idetail.
byte
 Byte idata itype iis ian i8-bit isigned itwo's icomplement iinteger
 Minimum ivalue iis i-128 i(-2^7)
 Maximum ivalue iis i127 i(inclusive)(2^7 i-1)
 Default ivalue iis i0
 Byte idata itype iis iused ito isave ispace iin ilarge iarrays, imainly iin iplace iof iintegers, isince ia
i byte iis ifour itimes ismaller ithan ian iinteger.
 Example: ibyte ia i= i100, ibyte ib i= i-50
short
 Short idata itype iis ia i16-bit isigned itwo's icomplement iinteger
 Minimum ivalue iis i-32,768 i(-2^15)
 Maximum ivalue iis i32,767 i(inclusive) i(2^15 i-1)
 Short idata itype ican ialso ibe iused ito isave imemory ias ibyte idata itype. iA ishort iis i2 itimes
i smaller ithan ian iinteger
 Default ivalue iis i0.
 Example: ishort is i= i10000, ishort ir i= i-20000
int
 Int idata itype iis ia i32-bit isigned itwo's icomplement iinteger.
 Minimum ivalue iis i- i2,147,483,648 i(-2^31)
 Maximum ivalue iis i2,147,483,647(inclusive) i(2^31 i-1)
 Integer iis igenerally iused ias ithe idefault idata itype ifor iintegral ivalues iunless ithere iis ia
i concern iabout imemory.
 The idefault ivalue iis i0

41

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 Example: iint ia i= i100000, iint ib i= i-200000


long
 Long idata itype iis ia i64-bit isigned itwo's icomplement iinteger
 Minimum ivalue iis i-9,223,372,036,854,775,808(-2^63)
 Maximum ivalue iis i9,223,372,036,854,775,807 i(inclusive)(2^63 i-1)
 This itype iis iused iwhen ia iwider irange ithan iint iis ineeded
 Default ivalue iis i0L
 Example: ilong ia i= i100000L, ilong ib i= i-200000L
float
 Float idata itype iis ia isingle-precision i32-bit iIEEE i754 ifloating ipoint
 Float iis imainly iused ito isave imemory iin ilarge iarrays iof ifloating ipoint inumbers
 Default ivalue iis i0.0f
 Float idata itype iis inever iused ifor iprecise ivalues isuch ias icurrency
 Example: ifloat if1 i= i234.5f
double
 double idata itype iis ia idouble-precision i64-bit iIEEE i754 ifloating ipoint
 This idata itype iis igenerally iused ias ithe idefault idata itype ifor idecimal ivalues, igenerally ithe
i default ichoice
 Double idata itype ishould inever ibe iused ifor iprecise ivalues isuch ias icurrency
 Default ivalue iis i0.0d
 Example: idouble id1 i= i123.4
boolean
 boolean idata itype irepresents ione ibit iof iinformation
 There iare ionly itwo ipossible ivalues: itrue iand ifalse
 This idata itype iis iused ifor isimple iflags ithat itrack itrue/false iconditions
 Default ivalue iis ifalse
 Example: iboolean ione i= itrue
char
 char idata itype iis ia isingle i16-bit iUnicode icharacter
 Minimum ivalue iis i'\u0000' i(or i0)
 Maximum ivalue iis i'\uffff' i(or i65,535 iinclusive)

42

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 Char idata itype iis iused ito istore iany icharacter


 Example: ichar iletterA i= i'A'
4.2 iReference iDatatypes
 Reference ivariables iare icreated iusing idefined iconstructors iof ithe iclasses. iThey iare iused ito
i access iobjects. iThese ivariables iare ideclared ito ibe iof ia ispecific itype ithat icannot ibe
i changed. iFor iexample, iEmployee, iPuppy, ietc.
 Class iobjects iand ivarious itype iof iarray ivariables icome iunder ireference idatatype.
 Default ivalue iof iany ireference ivariable iis inull.
 A ireference ivariable ican ibe iused ito irefer iany iobject iof ithe ideclared itype ior iany icompatible
i type.
 Example: iAnimal ianimal i= inew iAnimal("giraffe");

4.3 Java Literals


A iliteral iis ia isource icode irepresentation iof ia ifixed ivalue. iThey iare irepresented idirectly
iin ithe icode iwithout iany icomputation.
Literals ican ibe iassigned ito iany iprimitive itype ivariable. For example −

byte a = 68;
char a = 'A';
byte, iint, ilong, iand ishort ican ibe iexpressed iin idecimal(base i10), ihexadecimal(base i16) ior
i octal(base i8) inumber isystems ias iwell.
Prefix i0 iis iused ito iindicate ioctal, iand iprefix i0x iindicates ihexadecimal iwhen iusing ithese inumber isystems
ifor iliterals.For example −

int decimal = 100;


int octal = 0144;
int hexa = 0x64;
String iliterals iin iJava iare ispecified ilike ithey iare iin imost iother ilanguages iby ienclosing ia isequence
i of icharacters ibetween ia ipair iof idouble iquotes. iExamples iof istring iliterals iare i−
Example
"Hello World"
"two\nlines"

43

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001';
String a = "\u0001";
Java language supports few special escape sequences for String and char literals as well. They
are −

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t tab

\" Double quote

\' Single quote

\\ backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

4.4 Variables in Java


A ivariable iprovides ius iwith inamed istorage ithat iour iprograms ican imanipulate. iEach ivariable iin
i Java ihas ia ispecific itype, iwhich idetermines ithe isize iand ilayout iof ithe ivariable's imemory; ithe

44

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

i range iof ivalues ithat ican ibe istored iwithin ithat imemory; iand ithe iset iof ioperations ithat ican ibe
i applied ito ithe ivariable.

You must declare all variables before they can be used. Following is the basic form of a variable
declaration −
data type variable [ = value][, variable [ = value] ...] ;

Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example

int ia, ib, ic; i i i i i i i i i// iDeclares ithree iints, ia, ib, iand ic.
int ia i= i10, ib i= i10; i i// iExample iof iinitialization
byte iB i= i22; i i i i i i i i i// iinitializes ia ibyte itype ivariable iB.
double ipi i= i3.14159; i// ideclares iand iassigns ia ivalue iof iPI.
char ia i= i'a'; i i i i i i i i// ithe ichar ivariable ia iis iinitialized iwith ivalue i'a'

This chapter will explain various variable types available in Java Language. There are three
kinds of variables in Java −
 Local variables
 Instance variables
Class/Static variables
Local Variables
 Local ivariables iare ideclared iin imethods, iconstructors, ior iblocks.
 Local ivariables iare icreated iwhen ithe imethod, iconstructor ior iblock iis ientered iand ithe
i variable iwill ibe idestroyed ionce iit iexits ithe imethod, iconstructor, ior iblock.
 Access imodifiers icannot ibe iused ifor ilocal ivariables.
 Local ivariables iare ivisible ionly iwithin ithe ideclared imethod, iconstructor, ior iblock.
 Local ivariables iare iimplemented iat istack ilevel iinternally.

45

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 There iis ino idefault ivalue ifor ilocal ivariables, iso ilocal ivariables ishould ibe ideclared iand ian
i initial ivalue ishould ibe iassigned ibefore ithe ifirst iuse.
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to
only this method.
public iclass iTest i{
iii public ivoid ipupAge() i{
iiiiii int iage i= i0;
iiiiii age i= iage i+ i7;
iiiiii System.out.println("Puppy iage iis i: i" i+ iage);
iii }

iii public istatic ivoid imain(String iargs[]) i{


iiiiii Test itest i= inew iTest();
iiiiii test.pupAge();
iii }
}

This will produce the following result −


Output
Puppy age is: 7
Example
Following example uses age without initializing it, so it would give an error at the time of
compilation.
public iclass iTest i{
iii public ivoid ipupAge() i{
iiiiii int iage;
iiiiii age i= iage i+ i7;
iiiiii System.out.println("Puppy iage iis i: i" i+ iage);
iii }

46

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii public istatic ivoid imain(String iargs[]) i{


iiiiii Test itest i= inew iTest();
iiiiii test.pupAge();
iii }
}

This will produce the following error while compiling it −


Output
Test.java:4:variable number might not have been initialized
age = age + 7;
4.5 Instance Variables
 Instance ivariables iare ideclared iin ia iclass, ibut ioutside ia imethod, iconstructor ior iany iblock.
 When ia ispace iis iallocated ifor ian iobject iin ithe iheap, ia islot ifor ieach iinstance ivariable ivalue
i is icreated.
 Instance ivariables iare icreated iwhen ian iobject iis icreated iwith ithe iuse iof ithe ikeyword i'new'
i and idestroyed iwhen ithe iobject iis idestroyed.
 Instance ivariables ihold ivalues ithat imust ibe ireferenced iby imore ithan ione imethod,
i constructor ior iblock, ior iessential iparts iof ian iobject's istate ithat imust ibe ipresent ithroughout
i the iclass.
 Instance ivariables ican ibe ideclared iin iclass ilevel ibefore ior iafter iuse.
 Access imodifiers ican ibe igiven ifor iinstance ivariables.
 The iinstance ivariables iare ivisible ifor iall imethods, iconstructors iand iblock iin ithe iclass.
i Normally, iit iis irecommended ito imake ithese ivariables iprivate i(access ilevel). iHowever,
i visibility ifor isubclasses ican ibe igiven ifor ithese ivariables iwith ithe iuse iof iaccess imodifiers.
 Instance ivariables ihave idefault ivalues. iFor inumbers, ithe idefault ivalue iis i0, ifor iBooleans iit
i is ifalse, iand ifor iobject ireferences iit iis inull. iValues ican ibe iassigned iduring ithe ideclaration
i or iwithin ithe iconstructor.
 Instance ivariables ican ibe iaccessed idirectly iby icalling ithe ivariable iname iinside ithe iclass.
i However, iwithin istatic imethods i(when iinstance ivariables iare igiven iaccessibility), ithey
i should ibe icalled iusing ithe ifully iqualified iname. ObjectReference.VariableName.
Example

47

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

import ijava.io.*;
public iclass iEmployee i{

iii // ithis iinstance ivariable iis ivisible ifor iany ichild iclass.
iii public iString iname;

iii // isalary ivariable iis ivisible iin iEmployee iclass ionly.


iii private idouble isalary;

iii // iThe iname ivariable iis iassigned iin ithe iconstructor.


iii public iEmployee i(String iempName) i{
iiiiii name i= iempName;
iii }

iii // iThe isalary ivariable iis iassigned ia ivalue.


iii public ivoid isetSalary(double iempSal) i{
iiiiii salary i= iempSal;
iii }

iii // iThis imethod iprints ithe iemployee idetails.


iii public ivoid iprintEmp() i{
iiiiii System.out.println("name i i: i" i+ iname i);
iiiiii System.out.println("salary i:" i+ isalary);
iii }

iii public istatic ivoid imain(String iargs[]) i{


iiiiii Employee iempOne i= inew iEmployee("Ransika");
iiiiii empOne.setSalary(1000);
iiiiii empOne.printEmp();
iii }
}

48

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

This will produce the following result −


Output
name : Ransika
salary :1000.0
4.6 Class/Static Variables
 Class ivariables ialso iknown ias istatic ivariables iare ideclared iwith ithe istatic ikeyword iin ia
i class, ibut ioutside ia imethod, iconstructor ior ia iblock.
 There iwould ionly ibe ione icopy iof ieach iclass ivariable iper iclass, iregardless iof ihow imany
i objects iare icreated ifrom iit.
 Static ivariables iare irarely iused iother ithan ibeing ideclared ias iconstants. iConstants iare
i variables ithat iare ideclared ias ipublic/private, ifinal, iand istatic. iConstant ivariables inever
i change ifrom itheir iinitial ivalue.
 Static ivariables iare istored iin ithe istatic imemory. iIt iis irare ito iuse istatic ivariables iother ithan
i declared ifinal iand iused ias ieither ipublic ior iprivate iconstants.
 Static ivariables iare icreated iwhen ithe iprogram istarts iand idestroyed iwhen ithe iprogram
i stops.
 Visibility iis isimilar ito iinstance ivariables. iHowever, imost istatic ivariables iare ideclared
i public isince ithey imust ibe iavailable ifor iusers iof ithe iclass.
 Default ivalues iare isame ias iinstance ivariables. iFor inumbers, ithe idefault ivalue iis i0; ifor
i Booleans, iit iis ifalse; iand ifor iobject ireferences, iit iis inull. iValues ican ibe iassigned iduring
i the ideclaration ior iwithin ithe iconstructor. iAdditionally, ivalues ican ibe iassigned iin ispecial
i static iinitializer iblocks.
 Static i variables i can i be i accessed i by i calling i with i the i class i name
i ClassName.VariableName.
 When ideclaring iclass ivariables ias ipublic istatic ifinal, ithen ivariable inames i(constants) iare
i all iin iupper icase. iIf ithe istatic ivariables iare inot ipublic iand ifinal, ithe inaming isyntax iis ithe
i same ias iinstance iand ilocal ivariables.

Example
import java.io.*;

49

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}

E-tivity 4-1
Numbering, 9
pacing and
sequencing
Title Variables And Data types
Purpose The purpose of this e-tivity is to enable you to define a variable, state
types of variables in java, and introduce you to data types in java.
Brief summary Watch videos on these links
of overall task 7 https://www.youtube.com/watch?v=iFzA43xR04s by sriyank
8 https://www.youtube.com/watch?v=RnD6NJs5xoIhttps://www.youtu
be.com/watch?v=odrntJn2o98 by web mentors
9 https://www.youtube.com/watch?v=yy3yLGkuXPkby WebMoTLeY
10 https://www.youtube.com/watch?v=0MFC_Vw9NxYby Tutorials
point ltd.

50

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Spark

Individual task (a) Explain different types of data types in java giving examples in
each
(b)Define a variable
c)Using code snippets declare and initialize different variables in java
d)Differentiate between local and global variables in java

Interaction a) Post itwo ithemes ithat iare icommon iin ivariables i


begins b) Post itwo ithemes ithat iare icommon iin idata itypes
c) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 4 hours

51

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

time
Next Files and I/O

Assessment Questions
1. iComment ion ithe ioutput iof ithis iC icode?

int imain()
{
int ia[5] i= i{1, i2, i3, i4, i5};
int ii;
for i(i i= i0; ii i< i5; ii++)
if i((char)a[i] i== i'5')
printf("%d\n", ia[i]);
else
printf("FAIL\n");
}
A. iThe icompiler iwill iflag ian ierror
B. iProgram iwill icompile iand iprint ithe ioutput i5
C. iProgram iwill icompile iand iprint ithe iASCII ivalue iof i5
D. iProgram iwill icompile iand iprint iFAIL ifor i5 itimes
2. iThe iformat iidentifier i‘%i’ iis ialso iused ifor i_____ idata itype?
A. ichar
B. iint
C. ifloat
D. idouble
3. iWhich idata itype iis imost isuitable ifor istoring ia inumber i65000 iin ia i32-bit isystem?
A. ishort
B. iint
C. ilong
D. idouble

52

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

4.What iis ithe isize iof ian iint idata itype?


A. i4 iBytes
 B. i8 iBytes
 C. iDepends ion ithe isystem/compiler
 D. iCannot ibe idetermined.

4.7 Java - Files and I/O


The ijava.io ipackage icontains inearly ievery iclass iyou imight iever ineed ito iperform iinput
iand ioutput i(I/O) iin iJava. iAll ithese istreams irepresent ian iinput isource iand ian ioutput
idestination. iThe istream iin ithe ijava.io ipackage isupports imany idata isuch ias primitives,
object, localized characters, etc.
Stream
A istream ican ibe idefined ias ia isequence iof idata. iThere iare itwo ikinds iof iStreams i−
 InPutStream i− iThe iInputStream iis iused ito iread idata ifrom ia isource.
 OutPutStream i− iThe iOutputStream iis iused ifor iwriting idata ito ia idestination.

Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly used
examples one by one −
Byte Streams
Java ibyte istreams iare iused ito iperform iinput iand ioutput iof i8-bit ibytes. iThough ithere iare imany
i classes irelated ito ibyte istreams ibut ithe imost ifrequently iused iclasses iare, iFileInputStream iand
i FileOutputStream. iFollowing iis ian iexample iwhich imakes iuse iof ithese itwo iclasses ito icopy ian
i input ifile iinto ian ioutput ifile i−

Example
import ijava.io.*;
public iclass iCopyFile i{

53

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii public istatic ivoid imain(String iargs[]) ithrows iIOException i{ i i


iiiiii FileInputStream iin i= inull;
iiiiii FileOutputStream iout i= inull;

iiiiii try i{
iiiiiiiii in i= inew iFileInputStream("input.txt");
iiiiiiiii out i= inew iFileOutputStream("output.txt");
iiiiiiiii

iiiiiiiii int ic;


iiiiiiiii while i((c i= iin.read()) i!= i-1) i{
iiiiiiiiiiii out.write(c);
iiiiiiiii }
iiiiii }finally i{
iiiiiiiii if i(in i!= inull) i{
iiiiiiiiiiii in.close();
iiiiiiiii }
iiiiiiiii if i(out i!= inull) i{
iiiiiiiiiiii out.close();
iiiiiiiii }
iiiiii }
iii }
}

Now let's have a file input.txt with the following content −


This is test for copy file.
As a next step, compile ithe iabove iprogram iand iexecute iit, iwhich iwill iresult iin icreating ioutput.txt
i file iwith ithe isame icontent ias iwe ihave iin iinput.txt. iSo ilet's iput ithe iabove icode iin iCopyFile.java
i file iand ido ithe ifollowing i−
$javac iCopyFile.java
$java iCopyFile

54

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Character iStreams
Java iByte istreams iare iused ito iperform iinput iand ioutput iof i8-bit ibytes, iwhereas iJava iCharacter
i streams iare iused ito iperform iinput iand ioutput ifor i16-bit iunicode. iThough ithere iare imany iclasses
i related ito icharacter istreams ibut ithe imost ifrequently iused iclasses iare, iFileReader iand
i FileWriter. iThough iinternally iFileReader iuses iFileInputStream iand iFileWriter iuses
i FileOutputStream ibut ihere ithe imajor idifference iis ithat iFileReader ireads itwo ibytes iat ia itime iand
i FileWriter iwrites itwo ibytes iat ia itime.
We ican ire-write ithe iabove iexample, iwhich imakes ithe iuse iof ithese itwo iclasses ito icopy ian iinput
i file i(having iunicode icharacters) iinto ian ioutput ifile i−
Example
import ijava.io.*;
public iclass iCopyFile i{

iii public istatic ivoid imain(String iargs[]) ithrows iIOException i{


iiiiii FileReader iin i= inull;
iiiiii FileWriter iout i= inull;

iiiiii try i{
iiiiiiiii in i= inew iFileReader("input.txt");
iiiiiiiii out i= inew iFileWriter("output.txt");
iiiiiiiii

iiiiiiiii int ic;


iiiiiiiii while i((c i= iin.read()) i!= i-1) i{
iiiiiiiiiiii out.write(c);
iiiiiiiii }
iiiiii }finally i{
iiiiiiiii if i(in i!= inull) i{
iiiiiiiiiiii in.close();
iiiiiiiii }
iiiiiiiii if i(out i!= inull) i{
iiiiiiiiiiii out.close();
iiiiiiiii }

55

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiii }
iii }
}

Now let's have a file input.txt with the following content −


This is test for copy file.
As a next step, compile the above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put the above code in
CopyFile.java file and do the following −
$javac CopyFile.java
$java CopyFile
4.8 Standard Streams
All ithe iprogramming ilanguages iprovide isupport ifor istandard iI/O iwhere ithe iuser's iprogram ican
i take iinput ifrom ia ikeyboard iand ithen iproduce ian ioutput ion ithe icomputer iscreen. iIf iyou iare iaware
i of iC ior iC++ iprogramming ilanguages, ithen iyou imust ibe iaware iof ithree istandard idevices iSTDIN,
i STDOUT iand iSTDERR. iSimilarly, iJava iprovides ithe ifollowing ithree istandard istreams i−
 Standard iInput i− iThis iis iused ito ifeed ithe idata ito iuser's iprogram iand iusually ia ikeyboard
i is iused ias istandard iinput istream iand irepresented ias iSystem.in.
 Standard iOutput i− iThis iis iused ito ioutput ithe idata iproduced iby ithe iuser's iprogram iand
i usually ia icomputer iscreen iis iused ifor istandard ioutput istream iand irepresented ias
i System.out.
 Standard iError i− iThis iis iused ito ioutput ithe ierror idata iproduced iby ithe iuser's iprogram
i and iusually ia icomputer iscreen iis iused ifor istandard ierror istream iand irepresented ias
i System.err.
Following iis ia isimple iprogram, iwhich icreates iInputStreamReader ito iread istandard iinput
i stream iuntil ithe iuser itypes ia i"q" i−
Example

import ijava.io.*;
public iclass iReadConsole i{44

56

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii public istatic ivoid imain(String iargs[]) ithrows iIOException i{


iiiiii InputStreamReader icin i= inull;

iiiiii try i{
iiiiiiiii cin i= inew iInputStreamReader(System.in);
iiiiiiiii System.out.println("Enter icharacters, i'q' ito iquit.");
iiiiiiiii char ic;
iiiiiiiii do i{
iiiiiiiiiiii c i= i(char) icin.read();
iiiiiiiiiiii System.out.print(c);
iiiiiiiii } iwhile(c i!= i'q');
iiiiii }finally i{
iiiiiiiii if i(cin i!= inull) i{
iiiiiiiiiiii cin.close();
iiiiiiiii }
iiiiii }
iii }
}

E-tivity 4-2
Numbering, 9
pacing and
sequencing
Title Files and I/O
Purpose The purpose of this e-tivity is to enable you to implement java
programs that can read and create files in hard disk Also it will enable
you to perform input and output..
Brief summary Watch videos on these links
of overall task 1. https://www.youtube.com/watch?v=3YRahx2ltSg by Margret
Posch

57

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

2. https://www.youtube.com/watch?v=SslMi6ptwH8 By Edureka

Spark

Individual task (a) Explain the File and I/O classes


(b)Create a program that reads a file stored on the desk top

Interaction a) Post itwo ithemes ithat iare icommon iin iFiles iand iI/O
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 1 hours
time
Next Date

Assessment Questions
Q: What is Java I/O ?
Q: What is difference between Scanner and BufferedReader?
Q: How to process java.io.InputStream object and produce a String?
Q: How to create a Java String from the contents of a file??
Q: What are the uses of FileInputStream and FileOutputStream in java?

4.9 Java - Date and Time

58

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Java iprovides ithe iDate iclass iavailable iin ijava.util ipackage, ithis iclass iencapsulates ithe icurrent
i date iand itime.The Date class supports two constructors as shown in the following table.

Sr.No. Constructor & Description

1 Date( )
This constructor initializes the object with the current date and time.

2 Date(long millisec)
This constructor accepts an argument that equals the number of milliseconds that have
elapsed since midnight, January 1, 1970.

4.10 Getting Current Date and Time


This iis ia ivery ieasy imethod ito iget icurrent idate iand itime iin iJava. iYou ican iuse ia isimple iDate iobject
i with itoString() imethod ito iprint ithe icurrent idate iand itime ias ifollows−

Example
import ijava.util.Date;
public iclass iDateDemo i{

iii public istatic ivoid imain(String iargs[]) i{


iiiiii // iInstantiate ia iDate iobject
iiiiii Date idate i= inew iDate();

iiiiii // idisplay itime iand idate iusing itoString()


iiiiii System.out.println(date.toString());

4.11 Date Formatting Using SimpleDateFormat


SimpleDateFormat iis ia iconcrete iclass ifor iformatting iand iparsing idates iin ia ilocale-sensitive
i manner. iSimpleDateFormat iallows iyou ito istart iby ichoosing iany iuser-defined ipatterns ifor idate-
time iformatting.
Example

59

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

import java.util.*;
import java.text.*;

public class DateDemo {

public static void main(String args[]) {


Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

System.out.println("Current Date: " + ft.format(dNow));


}
}

Numbering, 9
pacing and
sequencing
Title Date and Time
Purpose The purpose of this e-tivity is to enable you to handle both date and
time ina java using the Date-Time API
Brief summary Watch videos on these links
of overall task 1https://www.youtube.com/watch?v=JtAplwiTOXcby programming
knowledge
2https://www.youtube.com/watch?v=nvluJ9yf4ho By Telusko
Spark

60

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Individual task (a) Write a java program to display the current date and time

Interaction a) Post itwo ithemes ithat iare icommon iin ijava idate iand itime
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 1 hours
time
Next Operators

Assessment Questions
1. How do you format a date in Java? like in the ddMMyyyy format?
2. Does SimpleDateFormat be safe to use in the multithreaded program?
3. Can you tell some differences between old and new Date Time API of Java 8?
4. What is the relationship between java.sql.Date and java.util.Date?
5.Can you format Calendar in Java?

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010), Head First Java
6. O’reilly.com

61

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 5
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
 Logical Operators
 Assignment Operators
5.1 The Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra.
Assume integer variable A holds 10 and variable B holds 20, then –
Operator Description Example
+ i(Addition) Adds ivalues ion ieither iside iof ithe ioperator A i+ iB iwill igive i30
-(Subtraction) Subtracts iright-hand ioperand ifrom ileft-hand A i- iB iwill igive i-10
i operand
* i(Multiplication): Multiplies ivalues ion ieither iside iof ithe ioperator A i* iB iwill igive i200
/ i(Division) Divides ileft-hand ioperand iby iright-hand ioperand B i/ iA iwill igive i2
% i(Modulus Divides ileft-hand ioperand iby iright-hand ioperand B i% iA iwill igive i0
i and ireturns iremainder
++ i(Increment) Increases ithe ivalue iof ioperand iby i1 B++ igives i21
-- i(Decrement) i i Decreases ithe ivalue iof ioperand iby i1. B-- igives i19

5.2 The Relational Operators


There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then –

Operator Description Example


== i(equal ito) Checks iif ithe ivalues iof itwo ioperands iare iequal ior (A i== iB) iis inot itrue
i not, iif iyes ithen icondition ibecomes itrueis inot itrue.

62

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

!= i(not iequal ito) Checks iif ithe ivalues iof itwo ioperands iare iequal ior (A i!= iB) iis itrue.
i not, iif ivalues iare inot iequal ithen icondition ibecomes
i true.
>(greater ithan) Checks iif ithe ivalue iof ileft ioperand iis igreater ithan (A i> iB) iis inot itrue.
i the ivalue iof iright ioperand, iif iyes ithen icondition
i becomes itrue.
< i(less ithan) Checks iif ithe ivalue iof ileft ioperand iis iless ithan ithe (A i< iB) iis itrue.
i value iof iright ioperand, iif iyes ithen icondition
i becomes itrue.
>= i(greater ithan Checks iif ithe ivalue iof ileft ioperand iis igreater ithan (A i>= iB) iis inot
i or iequal ito) i or iequal ito ithe ivalue iof iright ioperand, iif iyes ithen i true.
i condition ibecomes itrue.
<= i(less ithan ior Checks iif ithe ivalue iof ileft ioperand iis iless ithan ior (A i<= iB) iis itrue.
i equal ito) i equal ito ithe ivalue iof iright ioperand, iif iyes ithen
i condition ibecomes itrue.
Operator Description Example
+ ii(Addition) Adds iivalues iion iieither iiside iiof iithe iioperator A ii+ iiB iiwill iigive
ii 30
-(Subtraction) Subtracts iiright-hand iioperand iifrom iileft-hand A ii- iiB iiwill iigive ii-
ii operand 10
* ii(Multiplication): Multiplies iivalues iion iieither iiside iiof iithe iioperator A ii* iiB iiwill iigive
ii 200
/ ii(Division) Divides ii left-hand ii operand ii by ii right-hand B ii/ iiA iiwill iigive ii2
ii operand
% ii(Modulus Divides ii left-hand ii operand ii by ii right-hand B ii% iiA iiwill iigive ii0
ii operand iiand iireturns iiremainder
++ ii(Increment) Increases iithe iivalue iiof iioperand iiby ii1 B++ iigives ii21
-- ii(Decrement) ii ii Decreases iithe iivalue iiof iioperand iiby ii1. B-- iigives ii19

5.3 The Logical Operators


The following table lists the logical operators −

63

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Assume Boolean variables A holds true and variable B holds false, then –
Operator i Description Example
&& i(logical iand) Called iLogical iAND ioperator. iIf iboth ithe A i&& iB) iis ifalse
i operands iare inon-zero, ithen ithe icondition
i becomes itrue.
|| i(logical ior) Called iLogical iOR iOperator. iIf iany iof ithe itwo (A i|| iB) iis itrue
i operands iare inon-zero, ithen ithe icondition
i becomes itrue.
! i(logical inot) Called iLogical iNOT iOperator. iUse ito ireverses ithe !(A i&& iB) iis itrue
i logical istate iof iits ioperand. iIf ia icondition iis itrue
i then iLogical iNOT ioperator iwill imake ifalse.

64

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

5.4 The Assignment Operators


Following are the assignment operators supported by Java language −
Operator Description Example
= Simple iassignment ioperator. iAssigns ivalues ifrom C i= iA i+ iB iwill
i right iside ioperands ito ileft iside ioperand i assign ivalue iof iA
i + iB iinto iC
+= Add iAND iassignment ioperator. iIt iadds iright ioperand C i+= iA iis
i to ithe ileft ioperand iand iassign ithe iresult ito ileft i equivalent ito iC i=
i operand. i C i+ iA
-= Subtract iAND iassignment ioperator. iIt isubtracts iright C i-= iA iis
i operand ifrom ithe ileft ioperand iand iassign ithe iresult ito i equivalent ito iC i=
i left ioperand. i C i– iA
*= Multiply iAND iassignment ioperator. iIt imultiplies iright C i*= iA iis
i operand iwith ithe ileft ioperand iand iassign ithe iresult ito i equivalent ito iC i=
i left ioperand. i C i* iA
/= Divide iAND iassignment ioperator. iIt idivides ileft C i/= iA iis
i operand iwith ithe iright ioperand iand iassign ithe iresult ito i equivalent ito iC i=
i left ioperand. i C i/ iA
%= Modulus iAND iassignment ioperator. iIt itakes imodulus C i%= iA iis
i using itwo ioperands iand iassign ithe iresult ito ileft i equivalent ito iC i=
i operand. i C i%
<<= Left ishift iAND iassignment ioperator. C i<<= i2 iis isame
i as iC i= iC i<< i2
>>= Right ishift iAND iassignment ioperator. C i>>= i2 iis isame
i as iC i= iC i>> i2
&= Bitwise iAND iassignment ioperator. C i&= i2 iis isame ias
i C i= iC i & i 2
^= bitwise iexclusive iOR iand iassignment ioperator. C i^= i2 iis isame ias
i C i= iC i^ i2
|= bitwise iinclusive iOR iand iassignment ioperator. C i|= i2 iis isame ias

65

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

i C i= iC i| i2

E-tivity 5
Numbering, 9
pacing and
sequencing
Title Operators in Java
Purpose The purpose of this e-tivity is to enable you operators in Java, and
their applications in writing java programs.
Brief summary Watch videos on these links
of overall task 11 https://www.youtube.com/watch?v=8CX4Tdttbqk by Tutorials point
ltd
12 https://www.youtube.com/watch?v=Pa0lUMWmmm0
13 https://www.youtube.com/watch?v=PAaqgTr7Cx4
14 https://www.youtube.com/watch?v=MZ_0lm1ur_I by Tutorials point
LTD
Spark

66

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Individual task (a) Write code snippets showing use of arithmetic operators in
Java
(b)State and explain 4 types of operators in java giving an example in
each case
c.)Demonstrate operator precedence in java

Interaction a) Post itwo ithemes ithat iare icommon iin ioperators


begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 3 hours
time
Next Control Statements

Assessment Questions
1. Which of these is returned by greater than, <, and equal to, ==, operator?
A. Integers
B. Floating - point numbers
C. Boolean
D. None of the mentioned

2.Which of the following operators can operate on a boolean variable?


1. &&
2. ==
3. ?:
4. +=
A. 3 & 2

67

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

B. 1 & 4
C. 1, 2 & 4
D. 1, 2 & 3
3.Which of these operators can skip evaluating right hand operand?
A. !
B. |
C. &
D. &&
4.Which of these have highest precedence?
A. ()
B. ++
C. *
D. >>
References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6.O’reilly.com

68

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 6
CONTROL STATEMENTS
6.1 Introduction to control Statements
A icontrol istatement iin ijava iis ia istatement ithat idetermines iwhether ithe iother istatements iwill ibe
iexecuted ior inot. iIt icontrols ithe i flow iof ia iprogram. An 'if' statement in java determines the

sequence of execution between a set of two statements.


6.2 Java – If Then Else Statement
Java If then Else statement provides two paths. The if block is executed when the condition holds
true. When the condition evaluates to false, the statements inside the else block are executed.
SYNTAX FOR JAVA IF THEN ELSE :

if(condition)
{ //statements, when condition is true
}
else
{
//statements, when condition is false
}
Class Great{

Public static void main(String args[]){

int a = 3, b = 5;

if(a>b)

System.out.println(“a is greater than b”);

69

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

else

System.out.println(“b is greater than a”);

6.3 If Else-If statement


If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If
block. Again, if the condition is not met, then it will move to the else block.
if(condition){
// statements (if Block)
}
else if{
// statements (Else-If block)
}
else{
//statements(Else Block)
}//other statements

Program to understand If statements


class WriteExample{
public static void main(String []args){
int a=2; int b=3; int c=4;
if(a>b){
System.out.print(“Institute1”);
}
else if(a>c){

70

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

System.out.print(“Institute2”);
}
else{
System.out.print(“Intellipaat”);
}
}
}

6.4 Java – Switch statement


Java Switch Statement can have multiple execution paths. It is similar to that of ‘if else-if’
statement except that switch can handle expressions which results to any primitive data type and
if statements handle only boolean expressions.

SYNTAX FOR JAVA SWITCH STATEMENT:

switch (expression)
{
case ‘value1’:
//statements
break;
case ‘value2’:
//statements
break;
case ‘value3’:
//statements
break;

default:
//statements

71

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 The value of the expression is matched with the case values. Only the statements inside the
matched case are executed.
 The ‘break’ keyword is added after each case in order to exit from the switch case. If the
‘break’ keyword is not specified, all the cases would be checked and the matching cases
would be executed.
 The default case is considered when no case value is matched.
class WriteExample{
public static void main(String []args){
int choice=2; int a=1;
switch(choice){
case a:
System.out.print(“For Right Study”); break;
case choice:
System.out.print(“Intellipaat Trainings”); break;
default:
System.out.print(“No choice found”); break;
}
}
}
E-tivity 6
6
Methods
The purpose of this e-tivity is to enable you to define methods, create methods and pass data
known as parameters in java.
Watch videos on these links
1. https://www.youtube.com/watch?v=ScPauMuDKWk by Satish C
2. https://www.youtube.com/watch?v=44VPxJYgtkw By Neso Academy
3. https://www.youtube.com/watch?v=WiT0yakVp3A By Java Tutorial TV

72

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

(a) Demonstrate the use use if, if else, switch statements using code snippets
(b)Make decisions in java programming

a) Post itwo ithemes ithat iare icommon iin iDecision imaking iin ijava
b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners i‘views iand iideas. iDo ithis
ion ithe idiscussion i forum i2.2.1

a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof idiscussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
This task should take 4 hours
Arrays

Assessment Questions
1.For iinitialization ia i= i2, ic i= i1 ithe ivalue iof ia iand ic iafter ithis icode iwill ibe ic i= i(c) i? ia i= i0 i: i2;
 A. ia i= i0, ic i= i0;
 B. ia i= i2, ic i= i2;
 C. ia i= i2, ic i= i2;
 D. ia i= i1, ic i= i2;
2.What iwill ibe ithe idata itype iof ithe iexpression i(a i< i50) i? ivar1 i: ivar2; iprovided ia i= iint, ivar1 i=
i double, ivar2 i= ifloat
2. A. ifloat
3. B. iint
4. C. idouble
5. D. iCannot ibe idetermined
3.Which iexpression ihas ito ibe ipresent iin ithe ifollowing? iexp1 i? iexp2 i: iexp3;
 A. iexp1
 B. iexp2

73

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

 C. iexp3
 D. iAll iof ithe imentioned

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6.O’reilly.com

74

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 7
ARRAYS
7.1 Arrays in Java
An Array is a data structure which stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
7.2 One Dimensional Array
Declaring Array Variables
To iuse ian iarray iin ia iprogram, iyou imust ideclare ia ivariable ito ireference ithe iarray, iand iyou imust
i specify ithe itype iof iarray ithe ivariable ican ireference. iHere iis ithe isyntax ifor ideclaring ian iarray
i variable i−
Syntax
dataType[] iarrayRefVar; i i i// ipreferred iway.
or
dataType iarrayRefVar[]; i i// iworks ibut inot ipreferred iway.
Example
The ifollowing icode isnippets iare iexamples iof ithis isyntax i−
double[] imyList; i i i// ipreferred iway.
or
double imyList[]; i i i
7.3 iCreating iArrays
You ican icreate ian iarray iby iusing ithe inew ioperator iwith ithe ifollowing isyntax i−
Syntax
arrayRefVar i= inew idataType[arraySize];
The iabove istatement idoes itwo ithings i−
 It icreates ian iarray iusing inew idataType[arraySize].
 It iassigns ithe ireference iof ithe inewly icreated iarray ito ithe ivariable iarrayRefVar.
Declaring ian iarray ivariable, icreating ian iarray, iand iassigning ithe ireference iof ithe iarray ito ithe
i variable ican ibe icombined iin ione istatement, ias ishown ibelow i−
dataType[] iarrayRefVar i= inew idataType[arraySize];
Alternatively iyou ican icreate iarrays ias ifollows i−

75

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

dataType[] iarrayRefVar i= i{value0, ivalue1, i..., ivaluek};


The iarray ielements iare iaccessed ithrough ithe iindex. iArray iindices iare i0-based; ithat iis, ithey istart
i from i0 ito iarrayRefVar.length-1.
Example
Following istatement ideclares ian iarray ivariable, imyList, icreates ian iarray iof i10 ielements iof idouble
i type iand iassigns iits ireference ito imyList i−
double[] imyList i= inew idouble[10];
Following ipicture irepresents iarray imyList. Here, myList holds ten double values and the
indices are from 0 to 9.

7.4 Processing Arrays


When iprocessing iarray ielements, iwe ioften iuse ieither ifor iloop ior iforeach iloop ibecause iall iof ithe
i elements iin ian iarray iare iof ithe isame itype iand ithe isize iof ithe iarray iis iknown.
Example
Here is a complete example showing how to create, initialize, and process arrays −
public iclass iTestArray i{

iii public istatic ivoid imain(String[] iargs) i{


iiiiii double[] imyList i= i{1.9, i2.9, i3.4, i3.5};

iiiiii // iPrint iall ithe iarray ielements


iiiiii for i(int ii i= i0; ii i< imyList.length; ii++) i{
iiiiiiiii System.out.println(myList[i] i+ i" i");

76

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiii }
iiiii

iiiiii // iSumming iall ielements


iiiiii double itotal i= i0;
iiiiii for i(int ii i= i0; ii i< imyList.length; ii++) i{
iiiiiiiii total i+= imyList[i];
iiiiii }
iiiiii System.out.println("Total iis i" i+ itotal);
iiiiii

iiiiii // iFinding ithe ilargest ielement


iiiiii double imax i= imyList[0];
iiiiii for i(int ii i= i1; ii i< imyList.length; ii++) i{
iiiiiiiii if i(myList[i] i> imax) imax i= imyList[i];
iiiiii }
iiiiii System.out.println("Max iis i" i+ imax); i i
iii }
}

This will produce the following result −


Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
The foreach Loops
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.
Example
The following code displays all the elements in the array myList −
public iclass iTestArray i{

77

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii public istatic ivoid imain(String[] iargs) i{


iiiiii double[] imyList i= i{1.9, i2.9, i3.4, i3.5};

iiiiii // iPrint iall ithe iarray ielements


iiiiii for i(double ielement: imyList) i{
iiiiiiiii System.out.println(element);
iiiiii }
iii }
}

This will produce the following result −


Output
1.9
2.9
3.4
3.5
7.5 Passing Arrays to Methods
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array −
Example
public istatic ivoid iprintArray(int[] iarray) i{
iii for i(int ii i= i0; ii i< iarray.length; ii++) i{
iiiiii System.out.print(array[i] i+ i" i");
iii }
}

You ican iinvoke iit iby ipassing ian iarray. iFor iexample, ithe ifollowing istatement iinvokes
ithe printArray method to display 3, 1, 2, 6, 4, and 2 −
Example

78

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

printArray(new int[]{3, 1, 2, 6, 4, 2});


7.6 Returning an Array from a Method
A imethod imay ialso ireturn ian iarray. iFor iexample, ithe ifollowing imethod ireturns ian iarray ithat iis
i the ireversal iof ianother iarray i−
Example
public istatic iint[] ireverse(int[] ilist) i{
iii int[] iresult i= inew iint[list.length];

iii for i(int ii i= i0, ij i= iresult.length i- i1; ii i< ilist.length; ii++, ij--) i{
iiiiii result[j] i= ilist[i];
iii }
iii return iresult;
}

7.7 The Arrays Class


The ijava.util.Arrays iclass icontains ivarious istatic imethods ifor isorting iand isearching iarrays,
i comparing iarrays, iand ifilling iarray ielements. iThese imethods iare ioverloaded ifor iall iprimitive
i types.

Sr.No. Method i& iDescription

1 public istatic iint ibinarySearch(Object[] ia, iObject ikey)


Searches ithe ispecified iarray iof iObject i( iByte, iInt i, idouble, ietc.) ifor ithe ispecified ivalue
i using ithe ibinary isearch ialgorithm. iThe iarray imust ibe isorted iprior ito imaking ithis icall. iThis
i returns iindex iof ithe isearch ikey, iif iit iis icontained iin ithe ilist; iotherwise, iit ireturns i( i–
i (insertion ipoint i+ i1)).

2 public istatic iboolean iequals(long[] ia, ilong[] ia2)


Returns itrue iif ithe itwo ispecified iarrays iof ilongs iare iequal ito ione ianother. iTwo iarrays iare
i considered iequal iif iboth iarrays icontain ithe isame inumber iof ielements, iand iall
i corresponding ipairs iof ielements iin ithe itwo iarrays iare iequal. iThis ireturns itrue iif ithe itwo

79

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

i arrays iare iequal. iSame imethod icould ibe iused iby iall iother iprimitive idata itypes i(Byte, ishort,
i Int, ietc.)

3 public istatic ivoid ifill(int[] ia, iint ival)


Assigns ithe ispecified iint ivalue ito ieach ielement iof ithe ispecified iarray iof iints. iThe isame
i method icould ibe iused iby iall iother iprimitive idata itypes i(Byte, ishort, iInt, ietc.)

4 public istatic ivoid isort(Object[] ia)


Sorts ithe ispecified iarray iof iobjects iinto ian iascending iorder, iaccording ito ithe inatural
i ordering iof iits ielements. iThe isame imethod icould ibe iused iby iall iother iprimitive idata itypes i(
i Byte, ishort, iInt, ietc.)

7.8 Two-Dimensional Array


The isimplest iof ithe imulti-dimensional iarray iis ia itwo-dimensional iarray. iA isimple idefinition iof i2D
i arrays iis: iA i2D iarray iis ian iarray iof ione-dimensional iarrays.
In iJava, ia itwo-dimensional iarray iis istored iin ithe iform iof irows iand icolumns iand iis irepresented iin
i the iform iof ia imatrix.
The general declaration of a two-dimensional array is,
data_type [] [] array_name;
Here,
data_type = data type of elements that will be stored in an array.
array_name = name of the two-dimensional array.
You can create a 2D array using new as follows:
data_type [] [] array_name = new data_type[row_size][column_size];
Here,
row_size = number of rows an array will contain.
column_size = number of columns array will contain.
Initialize 2d Array
There iare ivarious iways iof iinitializing ithe i2d iarray iwith ivalues. iThe ifirst imethod iis ithe itraditional
i method iof iassigning ivalues ito ieach ielement.

80

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

The igeneral isyntax ifor iinitialization iis:


array_name[row_index][column_index] i= ivalue;
Example:
int[][] imyarray i= inew iint[2][2];
iiii myarray[0][0] i= i1;
iiii myarray[0][1] i= i imyarray[1][0] i= i i0;
iiii myarray[1][1] i= i1;
The iabove istatements iinitialize iall ithe ielements iof ithe igiven i2d iarray.
Let's iput iit iin ia iprogram iand icheck ithe ioutput.
public iclass iMain
{
iiii public istatic ivoid imain(String[] iargs) i{
iiiiiiii int[][] imyarray i= inew iint[2][2];
iiiiiiii myarray[0][0] i= i1;
iiiiiiii myarray[0][1] i= i imyarray[1][0] i= i i0;
iiiiiiii myarray[1][1] i= i1;
iiiiiiii System.out.println("Array ielements iare:");
iiiiiiii System.out.println(myarray[0][0] i+ i" i" i+myarray[0][1]);
iiiiiiii System.out.println(myarray[1][0] i+ i" i" i+myarray[1][1]);
iiii }
}

This imethod imay ibe iuseful iwhen ithe idimensions iinvolved iare ismaller. iAs ithe iarray idimension
i grows, iit iis idifficult ito iuse ithis imethod iof iindividually iinitializing ithe ielements.
The inext imethod iof iinitializing ithe i2d iarray iin iJava iis iby iinitializing ithe iarray iat ithe itime iof
i declaration ionly.
The general syntax for this initialization method is as given below:
data_type[][] array_name = {{val_r1c1,val_r1c2,...val_r1cn},
{val_r2c1, val_r2c2,...val_r2cn}, …
{val_rnc1, val_rnc2,…val_rncn}};

81

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

For Example, if you have a 2×3 array of type int, then you can initialize it with the
declaration as:
int [][] intArray = {{1, 2, 3},
{4, 5, 6}};
The following example shows the 2d array declaration with initialization.
public class Main
{
public static void main(String[] args) {
//2-d array initialised with values
int[][] intArray = { { 1, 2 }, { 3, 4 },{5,6}};
//print the array
System.out.println("Initialized Two dimensional array:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(intArray [i][j] + " ");
}

System.out.println();
}
}
}
E-tivity 7
9
Arrays
The purpose of this e-tivity introduces how to declare array variables, create arrays, and
process arrays using indexed variables.
Watch videos on these links
1. https://www.youtube.com/watch?v=2eKjuhzI87g by Math and Science
2. https://www.youtube.com/watch?v=TmM9XAIKa-Y By edureka
3https://www.youtube.com/watch?v=Wm84BWMLQvw By edureka
4. https://www.youtube.com/watch?v=L06uGnF4IpY by the newboston

82

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

(a) Write a Java program to sort a numeric array and a string array
(b) Write a Java program to calculate the average value of array elements

a) Post itwo ithemes ithat iare icommon iin iArrays iin ijava
b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners i‘views iand iideas. iDo ithis
ion ithe idiscussion i forum i2.2.1

a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof idiscussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
This task should take 2 hours
Strings

Assessment Questions
1.Which iof ithese ioperators iis iused ito iallocate imemory ito iarray ivariable iin iJava?
A. imalloc
B. ialloc
C. inew
D. inew imalloc
2.Which iof ithese iis ian iincorrect iarray ideclaration?
A. iint iarr[] i= inew iint[5]
B. iint i[] iarr i= inew iint[5]
C. iint iarr[]
arr i= inew iint[5]
D. iint iarr[] i= iint i[5] inew

83

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

3.What iwill ithis icode iprint?


i int iarr[] i= inew iint i[5];
i System.out.print(arr);
A. i0
B. ivalue istored iin iarr[0].
C. i00000
D. iGarbage ivalue
4. iWhich iof ithese iis ian iincorrect iStatement?
A. iIt iis inecessary ito iuse inew ioperator ito iinitialize ian iarray.
B. iArray ican ibe iinitialized iusing icomma iseparated iexpressions isurrounded iby icurly ibraces.
C. iArray ican ibe iinitialized iwhen ithey iare ideclared.
D. iNone iof ithe imentioned
5.Which iof ithese iis inecessary ito ispecify iat itime iof iarray iinitialization?
A. iRow
B. iColumn
C. iBoth iRow iand iColumn
D. iNone iof ithe imentioned

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java

84

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 8
STRINGS
Strings, iwhich iare iwidely iused iin iJava iprogramming, iare ia isequence iof icharacters. iIn iJava
i programming ilanguage, istrings iare itreated ias iobjects.
The iJava iplatform iprovides ithe iString iclass ito icreate iand imanipulate istrings.

8.1 Creating Strings


The imost idirect iway ito icreate ia istring iis ito iwrite i−
String igreeting i= i"Hello iworld!";
Whenever iit iencounters ia istring iliteral iin iyour icode, ithe icompiler icreates ia iString iobject iwith iits
i value iin ithis icase, i"Hello iworld!'.
As iwith iany iother iobject, iyou ican icreate iString iobjects iby iusing ithe inew ikeyword iand ia
i constructor. iThe iString iclass ihas i11 iconstructors ithat iallow iyou ito iprovide ithe iinitial ivalue iof ithe
i string iusing idifferent isources, isuch ias ian iarray iof icharacters.
Example
public iclass iStringDemo i{

iii public istatic ivoid imain(String iargs[]) i{


iiiiii char[] ihelloArray i= i{ i'h', i'e', i'l', i'l', i'o', i'.' i};
iiiiii String ihelloString i= inew iString(helloArray); i i
iiiiii System.out.println( ihelloString i);
iii }
}

8.2 String Length


Methods iused ito iobtain iinformation iabout ian iobject iare iknown ias iaccessor imethods. iOne
i accessor imethod ithat iyou ican iuse iwith istrings iis ithe ilength() imethod, iwhich ireturns ithe inumber
i of icharacters icontained iin ithe istring iobject.
The ifollowing iprogram iis ian iexample iof ilength(), imethod iString iclass.
Example
public iclass iStringDemo i{
85

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii public istatic ivoid imain(String iargs[]) i{


iiiiii String ipalindrome i= i"Dot isaw iI iwas iTod";
iiiiii int ilen i= ipalindrome.length();
iiiiii System.out.println( i"String iLength iis i: i" i+ ilen i);
iii }
}

This will produce the following result −


Output
String Length is : 17
8.3 Concatenating Strings
The iString iclass iincludes ia imethod ifor iconcatenating itwo istrings i−
string1.concat(string2);
This ireturns ia inew istring ithat iis istring1 iwith istring2 iadded ito iit iat ithe iend. iYou ican ialso iuse ithe
i concat() imethod iwith istring iliterals, ias iin i−
"My iname iis i".concat("Zara");
Strings iare imore icommonly iconcatenated iwith ithe i+ ioperator, ias iin i−
"Hello," i+ i" iworld" i+ i"!"
which iresults iin i−
"Hello, world!"
Let us look at the following example −
Example
public iclass iStringDemo i{

iii public istatic ivoid imain(String iargs[]) i{


iiiiii String istring1 i= i"saw iI iwas i";
iiiiii System.out.println("Dot i" i+ istring1 i+ i"Tod");
iii }
}

86

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

This will produce the following result −


8.4 Creating Format Strings
You ihave iprintf() iand iformat() imethods ito iprint ioutput iwith iformatted inumbers. iThe iString iclass
i has ian iequivalent iclass imethod, iformat(), ithat ireturns ia iString iobject irather ithan ia iPrintStream
i object.
Using iString's istatic iformat() imethod iallows iyou ito icreate ia iformatted istring ithat iyou ican ireuse,
i as iopposed ito ia ione-time iprint istatement. iFor iexample, iinstead iof i−
`
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
You can write −
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
8.5 String Methods
Here is the list of some methods supported by String class −

Sr.No. Method i& iDescription

1 char icharAt(int iindex)


Returns ithe icharacter iat ithe ispecified iindex.

2 int icompareTo(Object io)


Compares ithis iString ito ianother iObject.

3 int icompareTo(String ianotherString)


Compares itwo istrings ilexicographically.

87

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

4 int icompareToIgnoreCase(String istr)


Compares itwo istrings ilexicographically, iignoring icase idifferences.

5 String iconcat(String istr)


Concatenates ithe ispecified istring ito ithe iend iof ithis istring.

6 boolean icontentEquals(StringBuffer isb)


Returns itrue iif iand ionly iif ithis iString irepresents ithe isame isequence iof icharacters ias ithe
i specified iStringBuffer.

7 static iString icopyValueOf(char[] idata)


Returns ia iString ithat irepresents ithe icharacter isequence iin ithe iarray ispecified.

8 static iString icopyValueOf(char[] idata, iint ioffset, iint icount)


Returns ia iString ithat irepresents ithe icharacter isequence iin ithe iarray ispecified.

9 boolean iendsWith(String isuffix)


Tests iif ithis istring iends iwith ithe ispecified isuffix.

10 boolean iequals(Object ianObject)


Compares ithis istring ito ithe ispecified iobject.

11 boolean iequalsIgnoreCase(String ianotherString)


Compares ithis iString ito ianother iString, iignoring icase iconsiderations.

12 byte[] igetBytes()
Encodes ithis iString iinto ia isequence iof ibytes iusing ithe iplatform's idefault icharset, istoring ithe
i result iinto ia inew ibyte iarray.

13 byte[] igetBytes(String icharsetName)


Encodes ithis iString iinto ia isequence iof ibytes iusing ithe inamed icharset, istoring ithe iresult iinto
i a inew ibyte iarray.

14 void igetChars(int isrcBegin, iint isrcEnd, ichar[] idst, iint idstBegin)

88

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Copies icharacters ifrom ithis istring iinto ithe idestination icharacter iarray.

E-tivity 8
Numbering, 9
pacing and
sequencing
Title
Purpose The purpose of this e-tivity is to enable you operators in Java, and
their applications in writing java programs.
Brief summary Watch videos on these links
of overall task 1.https://www.youtube.com/watch?v=N63JCXwdd14 by Edureka
2. https://www.youtube.com/watch?v=r3DBIDyzLUI by Math and
Science
3. https://www.youtube.com/watch?v=zvA4fzyH1gs by Caleb Carry
Spark

Individual task (a)In how many ways you can create string objects in java?
(b) What is string constant pool?

Interaction a) Post itwo ithemes ithat iare icommon iin iString iin ijava iprogramming
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 3 hours

89

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

time
Next Looping

Assessment Questions
1 Which iof ithese iclass iis isuperclass iof iString iand iStringBuffer iclass?
A. ijava.util
B. ijava.lang
C. iArrayList
D. iNone iof ithe imentioned
2 Which iof ithese imethod iof iclass iString iis iused ito iobtain ilength iof iString iobject?
A. iget()
B. iSizeof()
C. ilengthof()
D. ilength()
3 Which iof ithese ioperators ican ibe iused ito iconcatenate itwo ior imore iString iobjects?
A. i+
B. i+=
C. i&
D. i||
4 Which iof ithese iconstructors iis iused ito icreate ian iempty iString iobject?
A. iString()
B. iString(void)
C. iString(0)
D. iNone iof ithe imentioned
5 Which iof ithese imethod iof iclass iString iis iused ito iextract ia isingle icharacter ifrom ia iString iobject?
A. iCHARAT()
B. icharat()
C. icharAt()
D. iChatAt()

90

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012) Core Java : Volume I-Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java

91

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 9
LOOPING IN JAVA
9.1 Loops in Java
Looping iin iprogramming ilanguages iis ia ifeature iwhich ifacilitates ithe iexecution iof ia iset iof
i instructions/functions irepeatedly iwhile isome icondition ievaluates ito itrue.
Java iprovides ithree iways ifor iexecuting ithe iloops. iWhile iall ithe iways iprovide isimilar ibasic
i functionality, ithey idiffer iin itheir isyntax iand icondition ichecking itime

9.2 while loop:


A iwhile iloop iis ia icontrol iflow istatement ithat iallows icode ito ibe iexecuted irepeatedly ibased ion ia
igiven iBoolean icondition. iThe iwhile i loop ican i be ithought iof ias ia irepeating i if istatement.

Syntax
1. while (boolean condition)
2. {
3. loop statements...
}

 While iloop istarts iwith ithe ichecking iof icondition. iIf iit ievaluated ito itrue, ithen ithe iloop
i body istatements iare iexecuted iotherwise ifirst istatement ifollowing ithe iloop iis iexecuted.
i For ithis ireason iit iis ialso icalled iEntry icontrol iloop
 Once ithe icondition iis ievaluated ito itrue, ithe istatements iin ithe iloop ibody iare iexecuted.
i Normally ithe istatements icontain ian iupdate ivalue ifor ithe ivariable ibeing iprocessed ifor
i the inext iiteration.
 When ithe icondition ibecomes ifalse, ithe iloop iterminates iwhich imarks ithe iend iof iits ilife
i cycle.

// Java program to illustrate while loop


class whileLoopDemo
{
public static void main(String args[])
{

92

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
System.out.println("Value of x:" + x);

// Increment the value of x for


// next iteration
x++;
}
}
}

9.3 for loop


The ifor iloop iprovides ia iconcise iway iof iwriting ithe iloop istructure. iUnlike ia iwhile iloop, ia ifor
istatement iconsumes ithe i initialization, icondition iand i increment/decrement i in ione i line ithereby

iproviding ia ishorter, ieasy ito idebug istructure iof i looping.

Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}

4. Initialization icondition: iHere, iwe iinitialize ithe ivariable iin iuse. iIt imarks ithe istart iof ia
i for iloop. iAn ialready ideclared ivariable ican ibe iused ior ia ivariable ican ibe ideclared, ilocal
i to iloop ionly.

93

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

5. Testing iCondition: iIt iis iused ifor itesting ithe iexit icondition ifor ia iloop. iIt imust ireturn ia
i boolean ivalue. iIt iis ialso ian iEntry iControl iLoop ias ithe icondition iis ichecked iprior ito
i the iexecution iof ithe iloop istatements.
6. Statement iexecution: iOnce ithe icondition iis ievaluated ito itrue, ithe istatements iin ithe
i loop ibody iare iexecuted.
7. Increment/ iDecrement: iIt iis iused ifor iupdating ithe ivariable ifor inext iiteration.
8. Loop itermination:When ithe icondition ibecomes ifalse, ithe iloop iterminates imarking
i the iend iof iits ilife icycle.

// Java program to illustrate for loop.


class iforLoopDemo i
{i
iiii public istatic ivoid imain(String iargs[]) i
iiii {i
iiiiiiii // ifor iloop ibegins iwhen ix=2 i
iiiiiiii // iand iruns itill ix i<=4 i
iiiiiiii for i(int ix i= i2; ix i<= i4; ix++) i
iiiiiiiiiiii System.out.println("Value iof ix:" i+ ix); i
iiii }i
}i

9.4 Enhanced For loop


Java also includes another version of for loop introduced in Java 5. Enhanced for loop
provides a simpler way to iterate through the elements of a collection or array. It is
inflexible and should be used only when there is a need to iterate through the elements in
sequential manner without knowing the index of currently processed element.
Also note that the object/variable is immutable when enhanced for loop is used i.e it
ensures that the values in the array can not be modified, so it can be said as read only loop
where you can’t update the values as opposite to other loops where values can be modified.
We recommend using this form of the for statement instead of the general form whenever

94

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

possible.
Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
Lets itake ian iexample ito idemonstrate ihow ienhanced ifor iloop ican ibe iused ito isimpify ithe iwork.
i Suppose ithere iis ian iarray iof inames iand iwe iwant ito iprint iall ithe inames iin ithat iarray. iLet’s isee ithe
i difference iwith ithese itwo iexamples

Enhanced for loop simplifies the work as follows.


// Java program to illustrate enhanced for loop
public iclass ienhancedforloop i
{i
iiii public istatic ivoid imain(String iargs[]) i
iiii {i
iiiiiiii String iarray[] i= i{"Ron", i"Harry", i"Hermoine"}; i
ii

iiiiiiii //enhanced ifor iloop i


iiiiiiii for i(String ix:array) i
iiiiiiii {i
iiiiiiiiiiii System.out.println(x); i
iiiiiiii }i
ii

iiiiiiii /* ifor iloop ifor isame ifunction i


iiiiiiii for i(int ii i= i0; ii i< iarray.length; ii++) i
iiiiiiii {i
iiiiiiiiiiii System.out.println(array[i]); i
iiiiiiii }i
iiiiiiii */
iiii }i
}

95

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

9.5 do while
do iwhile iloop iis isimilar ito iwhile iloop iwith ionly idifference ithat iit ichecks ifor icondition iafter
iexecuting ithe i statements, iand itherefore i is ian iexample iof iExit iControl iLoop.

Syntax:
2. do
3. {
4. statements..
5. }
6. while (condition);
0. do iwhile iloop istarts iwith ithe iexecution iof ithe istatement(s). iThere iis ino ichecking iof iany
i condition ifor ithe ifirst itime.
1. After ithe iexecution iof ithe istatements, iand iupdate iof ithe ivariable ivalue, ithe icondition iis
i checked ifor itrue ior ifalse ivalue. iIf iit iis ievaluated ito itrue, inext iiteration iof iloop istarts.
2. When ithe icondition ibecomes ifalse, ithe iloop iterminates iwhich imarks ithe iend iof iits ilife
i cycle.
3. It iis iimportant ito inote ithat ithe ido-while iloop iwill iexecute iits istatements iatleast ionce
i before iany icondition iis ichecked, iand itherefore iis ian iexample iof iexit icontrol iloop.

// Java program to illustrate do-while loop


class idowhileloopDemo i
{i
iiii public istatic ivoid imain(String iargs[]) i
iiii {i
iiiiiiii int ix i= i21; i
iiiiiiii do
iiiiiiii {i
iiiiiiiiiiii // iThe iline iwill ibe iprinted ieven i
iiiiiiiiiiii // iif ithe icondition iis ifalse i
iiiiiiiiiiii System.out.println("Value iof ix:" i+ ix); i
iiiiiiiiiiii x++; i
iiiiiiii }i

96

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiiiii while i(x i< i20); i


iiii }i
}

E-tivity 9
Numbering, 9
pacing and
sequencing
Title
Purpose The purpose of this e-tivity is to enable you operators in Java, and
their applications in writing java programs.
Brief summary Watch videos on these links
of overall task 1. https://www.youtube.com/watch?v=LGn-NhUzb6Q by Edureka
2. https://www.youtube.com/watch?v=tCJZiHEpHbg by Tech Raj
3https://www.youtube.com/watch?v=6djggrlkHY8 by codecourse
Spark

Individual task (a)Name the types of loops supported in java


(b) Explain the meaning of enhanced for loop

Interaction a) Post itwo ithemes ithat iare icommon iin iJava iloops
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 1 hours

97

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

time
Next Defining your own classes

Assessment Questions on Loops


What will be the output of the following program?
class ForSample
{

public static void main(String s[])


{
for(int i = 0; i <= 5; i++ )
{
System.out.println("i = " + i );
}
}
}
Assessment Questions
1. What types of loops does Java support?
2. What is an enhanced for loop?
4. How can you exit anticipatedly from a loop?
5. What is the difference between an unlabeled and a labeled break statement?

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6.O’reilly.com

98

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 10
DEFINING YOUR OWN CLASSES IN JAVA
10.1. Creating your own classes. Abstraction
In ithe ifuture, iyou iwill ihave ito iwrite iyour iown iclasses. iWhat ido iyou ineed ito ilook iout ifor iwhen iyou
i write ithem? iIf iwe're italking iabout ivariables, ithen iyou'll ineed ito imake iuse iof isomething icalled
i abstraction. iAbstraction iis ione iof ithe ifour ibasic iprinciples iof iobject-oriented iprogramming. iIt
i means iextracting ithe imost iimportant iand isignificant icharacteristics iof ian iitem, iand
i conversely, icasting iaside ithose ithat iare iminor ior iinsignificant. iFor iexample, ilet's icreate ia ifiling
i cabinet ifor icompany iemployees. iTo icreate iemployee iobjects, iwe've iwritten ian iEmployee iclass.
i What icharacteristics iare iimportant idescriptors iof ian iemployee ifor iour icompany's ifiling icabinet?
i Name, idate iof ibirth, iSSN, iand iemployee iID. iBut iit's iunlikely iwe'll ineed ithe iemployee's iheight,
i eye icolor, ior ihair icolor ifor ithe icompany's iemployee irecord. iCompanies idon't ineed ithis
i information. iSo, iin ithe iEmployee iclass, iwe ideclare ithe ifollowing ivariables: iString iname, iint iage,
i int isocialSecurityNumber, iand iint iemployeeId. iAnd iwe ileave iout iunnecessary iinformation i(like
i eye icolor). iIn iother iwords, iwe icreate ian iabstraction. iHowever, iif iwe're imaking ia ifiling icabinet
i for imodeling iagencies, ithe isituation ichanges idramatically. iA imodel's iheight, ieye icolor, iand ihair
i color iare iimportant icharacteristics, ibut iher iSSN iis iabsolutely iirrelevant ito ius. iSo, iin ithe iModel
i class, iwe ineed ito icreate ithe ifollowing ivariables: iString iheight, iString ihair, iString ieyes. iThat's ihow
i abstraction iworks—it's ieasy! i:) i
10.2 Constructors
Let's go back to our cat example.
public class Cat {

String name;
int age;

public static void main(String[] args) {


Cat smudge = new Cat();

System.out.println("Here the program does something for 2 hours...");

99

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

smudge.age = 3;
smudge.name = "Smudge";

}
}
Look iover ithis icode iand itry ito ifigure iout iwhat's iwrong iwith iour iprogram. iOur iprogram ihad ia icat
i with ino iname ior iage ifor i2 ihours! iOf icourse, ithis iis iinherently iwrong. iThe iveterinary iclinic's
i database ishouldn't iinclude icats iwith ino iinformation. iCurrently, iour icat iis iat ithe imercy iof ithe
i programmer. iWe itrust ithat ihe iwon't iforget ito ispecify ia iname iand iage, iand ithat ieverything iwill ibe
i okay. iIf ihe iforgets, ithe idatabase iwill ihave ia iproblem: iunnamed icats. iHow ican iwe isolve ithis
i problem? iWe imust isomehow iprevent icats ifrom ibeing icreated iwithout ia iname iand iage. iThis iis
i where iconstructors icome ito ithe irescue.

Let's give an example:


public iclass iCat i{

iiii String iname;


iiii int iage;

iiii // iConstructor ifor ithe iCat iclass


iiii public iCat(String iname, iint iage) i{
iiiiiiii this.name i= iname;
iiiiiiii this.age i= iage;
iiii }

iiii public istatic ivoid imain(String[] iargs) i{

iiiiiiii Cat ismudge i= inew iCat("Smudge", i5);


iiii }
}

100

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Essentially, a constructor is a template for objects of a class. In this case, we indicate that two
arguments, a String and an int, must be specified for each cat object. If we try to create a
nameless cat now, it won't work.
public class Cat {

String name;
int age;

public Cat(String name, int age) {


this.name = name;
this.age = age;
}

public static void main(String[] args) {

Cat smudge = new Cat(); // Error!


}
}
Now ithat ithe iclass ihas ia iconstructor, ithe iJava icompiler iknows iwhat ithe iobjects ishould ilook ilike,
i and idoesn't iallow iobjects ito ibe icreated iwithout ispecifying ithe iarguments. iNow, ilet's iinvestigate
i the ikeyword ithis, iwhich iyou isee iinside ithe iconstructor. iIt's isimple itoo. iThe ikeyword ithis iis ifor
i indicating ia iparticular iobject. iThe icode iin ithe iconstructor i

public Cat(String name, int age) {


this.name = name;
this.age = age;
}
can be interpreted almost verbatim: "The iname iof ithis icat i(the ione iwe iare icreating) i= ithe
i argument ipassed iin ifor ithe iconstructor's iname iparameter. iThe iage iof ithis icat i(the ione iwe iare
i creating) i= ithe iargument ipassed iin ifor ithe iconstructor's iage iparameter." iAfter ithe iconstructor
i runs, iyou ican iverify ithat iall iof ithe inecessary ivalues ihave ibeen iassigned ito iour icat: i

101

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

public class Cat {

String name;
int age;

public Cat(String name, int age) {


this.name = name;
this.age = age;
}

public static void main(String[] args) {

Cat smudge = new Cat("Smudge", 5);


System.out.println(smudge.name);
System.out.println(smudge.age);
}
}
And ithe ivalues iof ithe iarguments ipassed ito ithe iconstructor iwere iassigned ito ithe ismudge iobject
i (that's iwhat ithis irefers ito iin ithis icase). iIn ifact, ieven iif iyou idon't ideclare iany iconstructors iin ia iclass,
i it iwill istill icall ia iconstructor! iBut ihow iis ithat ipossible? iО_О iBecause, iall iJava iclasses ihave ia iso-
called idefault iconstructor. iIt idoesn't itake iany iarguments, ibut iit iis iinvoked ievery itime iyou icreate
i any iobject iof iany iclass. i
public class Cat {

public static void main(String[] args) {

Cat smudge = new Cat(); // The default constructor is invoked here


}
}

102

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

At ifirst iglance, ithis imay inot ibe iobvious. iWe icreated ian iobject, iso iwhat? iWhere iis ithe iconstructor
i doing ianything ihere? iTo isee iit, ilet's iexplicitly iwrite ian iempty iconstructor ifor ithe iCat iclass. iInside,
i it, iwe'll ioutput isome iphrase ito ithe iconsole. iIf ithe iphrase iis idisplayed, ithen ithe iconstructor iwas
i invoked. i
public class Cat {

public Cat() {
System.out.println("A cat has been created!");
}

public static void main(String[] args) {

Cat smudge = new Cat(); // The default constructor is invoked here


}
}
Console output: A cat has been created! There's ithe iconfirmation. iThe idefault iconstructor iis
i always iinvisibly ipresent iin iyour iclasses. iBut iyou ineed ito iknow ione imore ithing iabout iit. iThe
default iconstructor iis ieliminated ifrom ia iclass ionce iyou icreate ia iconstructor iwith iarguments.
i

i In ifact, iwe've ialready iseen iproof iof ithis iabove. iIt iwas iin ithis icode: i
public class Cat {

String name;
int age;

public Cat(String name, int age) {


this.name = name;
this.age = age;
}

public static void main(String[] args) {

103

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Cat smudge = new Cat(); // Error!


}
}
We icouldn't icreate ia iCat iwithout ia iname iand iage, ibecause iwe ideclared ia iCat iconstructor iwith
i string iand iint iparameters. iThis icaused ithe idefault iconstructor ito iimmediately ivanish ifrom ithe
i class. iSo ibe isure ito iremember ithat iif iyou ineed iseveral iconstructors iin iyour iclass, iincluding ia ino-
argument iconstructor, iyou'll ihave ito ideclare iit iseparately. iOur iclinic iwants ito ido igood ideeds
i and ihelp ihomeless ikittens iwhose inames iand iages iare iunknown. iThen iour icode ishould ilook ilike
i this: i
public class Cat {

String name;
int age;

// For cats with owners


public Cat(String name, int age) {
this.name = name;
this.age = age;
}

// For street cats


public Cat() {
}

public static void main(String[] args) {

Cat smudge = new Cat("Smudge", 5);


Cat streetCat = new Cat();
}
}

104

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Now ithat iwe ihave ispecified ian iexplicit idefault iconstructor, iwe ican icreate iboth itypes iof icats. iIn ithe
iconstructor, iyou ican iassign ivalues idirectly. iYou idon't ihave ito ialways itake ithem i from iarguments.

iFor iexample, iwe icould i label iall istreet icats iin ithe idatabase iusing "Street cat No. <count>" as a

template. :
public class Cat {

String name;
int age;

static int count = 0;

public Cat() {
count++;
this.name = "Street cat No. " + count;
}

public Cat(String name, int age) {


this.name = name;
this.age = age;
}

public static void main(String[] args) {

Cat streetCat1 = new Cat();


Cat streetCat2 = new Cat();
System.out.println(streetCat1.name);
System.out.println(streetCat2.name);
}
}
We ihave ia icount ivariable, iwhich icounts iour istreet icats. iEach itime ithe idefault iconstructor iis
i executed, iwe iincrease icount iby i1 iand iattach ithis inumber ito ithe icat's iname. iThe iorder iof

105

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

arguments iis ivery iimportant ifor iconstructors. iLet's iswap ithe iname iand iage iarguments ipassed
i

i to iour iconstructor. i
public class Cat {

String name;
int age;

public Cat(int age, String name) {


this.name = name;
this.age = age;
}

public static void main(String[] args) {

Cat smudge = new Cat("Smudge", 10); // Error!


}
}
We igot ian ierror! iThe iconstructor iclearly istipulates ithat iwhen ia iCat iobject iis icreated, iit imust ibe
i passed ia inumber iand ia istring, iin ithis iorder. iSo, iour icode idoesn't iwork. iBe isure ito iremember
i and irespect ithis irule iwhen ideclaring iyour iown iclasses: i
public Cat(String name, int age) {
this.name = name;
this.age = age;
}

public Cat(int age, String name) {


this.age = age;
this.name = name;
}
These iare itwo itotally idifferent iconstructors! iNow, icomplete ia icouple itasks ito isolidify iyour
i understanding iof ithe imaterial. i:) i

106

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

1. Museum iof iAntiquities.


Your itask iis ito idesign ian iArtifact iclass.
There iare ithree itypes iof iartifacts ikept iat ithe imuseum.
We iknow inothing iabout ithe ifirst itype iexcept ithe iserial inumber iassigned iby ithe imuseum
i (for iexample: i212121).
For ithe isecond itype, iwe iknow ithe iserial inumber iand ithe iculture ithat icreated iit i(for
i example: i212121, i"Aztecs").
For ithe ithird itype, iwe iknow ithe iserial inumber, ithe iculture ithat icreated iit, iand ithe icentury iit
i was icreated iin i(for iexample: i212121, i"Aztecs", i12).
Create ian iArtifact iclass ithat idescribes ithe iantiquities ikept iat ithe imuseum, iand iwrite ithe
i required iset iof iconstructors ifor ithe iclass. iThen, iin ithe imain() imethod, icreate ione iartifact iof
i each ikind.
public iclass iArtifact i{

iiii // iWrite iyour icode ihere

iiii public istatic ivoid imain(String[] iargs) i{


iiiiiiii // iWrite iyour icode ihere
iiii }
}

2. Dating website
3. Let's icreate ia iuser idatabase ifor ia idating iwebsite.
But ihere's ithe iproblem: iyou iforgot ithe irequired iorder iof ithe iarguments, iand ithere's ino
i technical idocumentation iavailable.
Design ia iUser iclass, iwhich iwill ihave ithe ifollowing ifields: iname i(String), iage i(short), iand
i height i(int).
4. Create ithe iappropriate inumber iof iconstructors, iso ithat ithe iname, iage, iand iheight ican ibe
i specified iin iany iorder.
public class User {

107

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

String name;
short age;
int height;

// Write your code here

public static void main(String[] args) {

}
}

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals
5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java
6.O’reilly.com

108

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

109

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

LESSON 11
INHERITANCE AND POLYMORPHISM
11.1 Inheritance
Inheritance ican ibe idefined ias ithe iprocess iwhere ione iclass iacquires ithe iproperties i(methods iand
i fields) iof ianother. iWith ithe iuse iof iinheritance ithe iinformation iis imade imanageable iin ia
i hierarchical iorder.
The iclass iwhich iinherits ithe iproperties iof iother iis iknown ias isubclass i(derived iclass, ichild iclass)
i and ithe iclass iwhose iproperties iare iinherited iis iknown ias isuperclass i(base iclass, iparent iclass).
11.2 iextends iKeyword
extends iis ithe ikeyword iused ito iinherit ithe iproperties iof ia iclass. iFollowing iis ithe isyntax iof
i extends ikeyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following iis ian iexample idemonstrating iJava iinheritance. iIn ithis iexample, iyou ican iobserve itwo
i classes inamely iCalculation iand iMy_Calculation.
Using iextends ikeyword, ithe iMy_Calculation iinherits ithe imethods iaddition() iand iSubtraction() iof
i Calculation iclass.
Copy iand ipaste ithe ifollowing iprogram iin ia ifile iwith iname iMy_Calculation.java
Example

class iCalculation i{
iii int iz;

110

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii public ivoid iaddition(int ix, iint iy) i{


iiiiii z i= ix i+ iy;
iiiiii System.out.println("The isum iof ithe igiven inumbers:"+z);
iii }

iii public ivoid iSubtraction(int ix, iint iy) i{


iiiiii z i= ix i- iy;
iiiiii System.out.println("The idifference ibetween ithe igiven inumbers:"+z);
iii }
}

public iclass iMy_Calculation iextends iCalculation i{


iii public ivoid imultiplication(int ix, iint iy) i{
iiiiii z i= ix i* iy;
iiiiii System.out.println("The iproduct iof ithe igiven inumbers:"+z);
iii }

iii public istatic ivoid imain(String iargs[]) i{


iiiiii int ia i= i20, ib i= i10;
iiiiii My_Calculation idemo i= inew iMy_Calculation();
iiiiii demo.addition(a, ib);
iiiiii demo.Subtraction(a, ib);
iiiiii demo.multiplication(a, ib);
iii }
}

Compile and execute the above code as shown below.


javac My_Calculation.java
java My_Calculation

111

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

In ithe igiven iprogram, iwhen ian iobject ito iMy_Calculation iclass iis icreated, ia icopy iof ithe icontents
i of ithe isuperclass iis imade iwithin iit. iThat iis iwhy, iusing ithe iobject iof ithe isubclass iyou ican iaccess
i the imembers iof ia isuperclass.

The iSuperclass ireference ivariable ican ihold ithe isubclass iobject, ibut iusing ithat ivariable iyou ican
i access ionly ithe imembers iof ithe isuperclass, iso ito iaccess ithe imembers iof iboth iclasses iit iis
i recommended ito ialways icreate ireference ivariable ito ithe isubclass.
If iyou iconsider ithe iabove iprogram, iyou ican iinstantiate ithe iclass ias igiven ibelow. iBut iusing ithe
i superclass ireference ivariable i( ical iin ithis icase) iyou icannot icall ithe imethod imultiplication(),
i which ibelongs ito ithe isubclass iMy_Calculation.
Calculation idemo i= inew iMy_Calculation();
demo.addition(a, ib);
demo.Subtraction(a, ib);
Note i− iA isubclass iinherits iall ithe imembers i(fields, imethods, iand inested iclasses) ifrom iits
i superclass. iConstructors iare inot imembers, iso ithey iare inot iinherited iby isubclasses, ibut ithe
i constructor iof ithe isuperclass ican ibe iinvoked ifrom ithe isubclass.
11.3 iThe isuper ikeyword
The isuper ikeyword iis isimilar ito ithis ikeyword. iFollowing iare ithe iscenarios iwhere ithe isuper
i keyword iis iused.
 It iis iused ito idifferentiate ithe imembers iof isuperclass ifrom ithe imembers iof isubclass, iif
i they ihave isame inames.
 It iis iused ito iinvoke ithe isuperclass iconstructor ifrom isubclass.
11.4 iDifferentiating ithe iMembers
If ia iclass iis iinheriting ithe iproperties iof ianother iclass. iAnd iif ithe imembers iof ithe isuperclass ihave
i the inames isame ias ithe isub iclass, ito idifferentiate ithese ivariables iwe iuse isuper ikeyword ias ishown
i below.
super.variable
super.method();
Sample iCode
This isection iprovides iyou ia iprogram ithat idemonstrates ithe iusage iof ithe isuper ikeyword.

112

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

In ithe igiven iprogram, iyou ihave itwo iclasses inamely iSub_class iand iSuper_class, iboth ihave ia
i method inamed idisplay() iwith idifferent iimplementations, iand ia ivariable inamed inum iwith
i different ivalues. iWe iare iinvoking idisplay() imethod iof iboth iclasses iand iprinting ithe ivalue iof ithe
i variable inum iof iboth iclasses. iHere iyou ican iobserve ithat iwe ihave iused isuper ikeyword ito
i differentiate ithe imembers iof isuperclass ifrom isubclass.
Copy iand ipaste ithe iprogram iin ia ifile iwith iname iSub_class.java.
Example

class iSuper_class i{
iii int inum i= i20;

iii // idisplay imethod iof isuperclass


iii public ivoid idisplay() i{
iiiiii System.out.println("This iis ithe idisplay imethod iof isuperclass");
iii }
}

public iclass iSub_class iextends iSuper_class i{


iii int inum i= i10;

iii // idisplay imethod iof isub iclass


iii public ivoid idisplay() i{
iiiiii System.out.println("This iis ithe idisplay imethod iof isubclass");
iii }

iii public ivoid imy_method() i{


iiiiii // iInstantiating isubclass
iiiiii Sub_class isub i= inew iSub_class();

iiiiii // iInvoking ithe idisplay() imethod iof isub iclass


iiiiii sub.display();

113

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iiiiii // iInvoking ithe idisplay() imethod iof isuperclass


iiiiii super.display();

iiiiii // iprinting ithe ivalue iof ivariable inum iof isubclass


iiiiii System.out.println("value iof ithe ivariable inamed inum iin isub iclass:"+ isub.num);

iiiiii // iprinting ithe ivalue iof ivariable inum iof isuperclass


iiiiii System.out.println("value iof ithe ivariable inamed inum iin isuper iclass:"+ isuper.num);
iii }

iii public istatic ivoid imain(String iargs[]) i{


iiiiii Sub_class iobj i= inew iSub_class();
iiiiii obj.my_method();
iii }
}

Compile and execute the above code using the following syntax.
javac Super_Demo
java Super
11.5 Invoking Superclass Constructor
If ia iclass iis iinheriting ithe iproperties iof ianother iclass, ithe isubclass iautomatically iacquires ithe
i default iconstructor iof ithe isuperclass. iBut iif iyou iwant ito icall ia iparameterized iconstructor iof ithe
i superclass, iyou ineed ito iuse ithe isuper ikeyword ias ishown ibelow.
super(values);
Sample iCode
The iprogram igiven iin ithis isection idemonstrates ihow ito iuse ithe isuper ikeyword ito iinvoke ithe
i parametrized iconstructor iof ithe isuperclass. iThis iprogram icontains ia isuperclass iand ia isubclass,
i where ithe isuperclass icontains ia iparameterized iconstructor iwhich iaccepts ia iinteger ivalue, iand iwe
i used ithe isuper ikeyword ito iinvoke ithe iparameterized iconstructor iof ithe isuperclass.
Copy iand ipaste ithe ifollowing iprogram iin ia ifile iwith ithe iname iSubclass.java

114

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Example
class iSuperclass i{
iii int iage;

iii Superclass(int iage) i{


iiiiii this.age i= iage; i i

iii }

iii public ivoid igetAge() i{


iiiiii System.out.println("The ivalue iof ithe ivariable inamed iage iin isuper iclass iis: i" i+age);
iii }
}

public iclass iSubclass iextends iSuperclass i{


iii Subclass(int iage) i{
iiiiii super(age);
iii }

iii public istatic ivoid imain(String iargs[]) i{


iiiiii Subclass is i= inew iSubclass(24);
iiiiii s.getAge();
iii }
}

11.6 Polymorphism

115

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

Polymorphism iis ithe iability iof ian iobject ito itake ion imany iforms. iThe imost icommon iuse iof
i polymorphism iin iOOP ioccurs iwhen ia iparent iclass ireference iis iused ito irefer ito ia ichild iclass
i object.
Any iJava iobject ithat ican ipass imore ithan ione iIS-A itest iis iconsidered ito ibe ipolymorphic. iIn iJava,
i all iJava iobjects iare ipolymorphic isince iany iobject iwill ipass ithe iIS-A itest ifor itheir iown itype iand
i for ithe iclass iObject.
It iis iimportant ito iknow ithat ithe ionly ipossible iway ito iaccess ian iobject iis ithrough ia ireference
i variable. iA ireference ivariable ican ibe iof ionly ione itype. iOnce ideclared, ithe itype iof ia ireference
i variable icannot ibe ichanged.
The ireference ivariable ican ibe ireassigned ito iother iobjects iprovided ithat iit iis inot ideclared ifinal.
i The itype iof ithe ireference ivariable iwould idetermine ithe imethods ithat iit ican iinvoke ion ithe iobject.
A ireference ivariable ican irefer ito iany iobject iof iits ideclared itype ior iany isubtype iof iits ideclared
i type. iA ireference ivariable ican ibe ideclared ias ia iclass ior iinterface itype.
Example
Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, ithe iDeer iclass iis iconsidered ito ibe ipolymorphic isince ithis ihas imultiple iinheritance.
i Following iare itrue ifor ithe iabove iexamples i−
 A iDeer iIS-A iAnimal
 A iDeer iIS-A iVegetarian
 A iDeer iIS-A iDeer
 A iDeer iIS-A iObject
When iwe iapply ithe ireference ivariable ifacts ito ia iDeer iobject ireference, ithe ifollowing ideclarations
i are ilegal i−
Example
Deer id i= inew iDeer();
Animal ia i= id;
Vegetarian iv i= id;
Object io i= id;

116

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

All ithe ireference ivariables id, ia, iv, io irefer ito ithe isame iDeer iobject iin ithe iheap.
11.7 iVirtual iMethods
In ithis isection, iI iwill ishow iyou ihow ithe ibehavior iof ioverridden imethods iin iJava iallows iyou ito
i take iadvantage iof ipolymorphism iwhen idesigning iyour iclasses.
We ialready ihave idiscussed imethod ioverriding, iwhere ia ichild iclass ican ioverride ia imethod iin iits
i parent. iAn ioverridden imethod iis iessentially ihidden iin ithe iparent iclass, iand iis inot iinvoked iunless
i the ichild iclass iuses ithe isuper ikeyword iwithin ithe ioverriding imethod.
Example
/* iFile iname i: iEmployee.java i*/
public iclass iEmployee i{
iii private iString iname;
iii private iString iaddress;
iii private iint inumber;

iii public iEmployee(String iname, iString iaddress, iint inumber) i{


iiiiii System.out.println("Constructing ian iEmployee");
iiiiii this.name i= iname;
iiiiii this.address i= iaddress;
iiiiii this.number i= inumber;
iii }

iii public ivoid imailCheck() i{


iiiiii System.out.println("Mailing ia icheck ito i" i+ ithis.name i+ i" i" i+ ithis.address);
iii }

iii public iString itoString() i{


iiiiii return iname i+ i" i" i+ iaddress i+ i" i" i+ inumber;
iii }

iii public iString igetName() i{


iiiiii return iname;

117

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii }

iii public iString igetAddress() i{


iiiiii return iaddress;
iii }

iii public ivoid isetAddress(String inewAddress) i{


iiiiii address i= inewAddress;
iii }

iii public iint igetNumber() i{


iiiiii return inumber;
iii }
}
Now isuppose iwe iextend iEmployee iclass ias ifollows i−
/* iFile iname i: iSalary.java i*/
public iclass iSalary iextends iEmployee i{
iii private idouble isalary; i// iAnnual isalary
iii

iii public iSalary(String iname, iString iaddress, iint inumber, idouble isalary) i{
iiiiii super(name, iaddress, inumber);
iiiiii setSalary(salary);
iii }
iii

iii public ivoid imailCheck() i{


iiiiii System.out.println("Within imailCheck iof iSalary iclass i");
iiiiii System.out.println("Mailing icheck ito i" i+ igetName()
iiiiii + i" iwith isalary i" i+ isalary);
iii }
iii

iii public idouble igetSalary() i{


iiiiii return isalary;

118

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii }
iii

iii public ivoid isetSalary(double inewSalary) i{


iiiiii if(newSalary i>= i0.0) i{
iiiiiiiii salary i= inewSalary;
iiiiii }
iii }
iii

iii public idouble icomputePay() i{


iiiiii System.out.println("Computing isalary ipay ifor i" i+ igetName());
iiiiii return isalary/52;
iii }
}
Now, iyou istudy ithe ifollowing iprogram icarefully iand itry ito idetermine iits ioutput i−
/* iFile iname i: iVirtualDemo.java i*/
public iclass iVirtualDemo i{

iii public istatic ivoid imain(String i[] iargs) i{


iiiiii Salary is i= inew iSalary("Mohd iMohtashim", i"Ambehta, iUP", i3, i3600.00);
iiiiii Employee ie i= inew iSalary("John iAdams", i"Boston, iMA", i2, i2400.00);
iiiiii System.out.println("Call imailCheck iusing iSalary ireference i--"); i i i
iiiiii s.mailCheck();
iiiiii System.out.println("\n iCall imailCheck iusing iEmployee ireference--");
iiiiii e.mailCheck();
iii }
}

E-tivity 11
Numbering, 11
pacing and

119

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

sequencing
Title Inheritance and Polymorphism
Purpose The purpose of this e-tivity is to enable you write code that is reusable
in java programs.
Brief summary Watch videos on these links
of overall task 1. https://www.youtube.com/watch?v=nixQyPIAnOQ by Edureka
2. https://www.youtube.com/watch?v=jg4MpYr1TBc by Edureka

Spark

Individual task (a)Describe inheritance in java using code


(b) Explain types of polymorphism in java

Interaction a) Post itwo ithemes ithat iare icommon iin iinheritance iand ipolymorphism
begins b) Provide ipositive iand iconstructive ifeedback ion ithe iteam ilearners
i‘views iand i ideas. iDo ithis ion ithe idiscussion i forum i2.2.1

E-moderator a) Ensure ithat ilearners iare ifocused ion ithe icontents iand icontext iof
interventions i discussion.
b) Stimulate ifurther ilearning iand igeneration iof inew iideas. i
c) Provide ifeedback ion ithe ilearning iprogress.
d) Round-up ithe ie-tivity
Schedule and This task should take 2 hours
time
Next Further practice in writing Java programs

References
1.https://www.geeksforgeeks.org/
2.https://www.tutorialspoint.com/java/index.htm
3.Deitel & Deitel (2015), Java How to Program
4. Horstmann, C. S/ Cornell, G. 8th ed Pearson,(2012)Core Java : Volume I – Fundamentals

120

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

5. Sierra, K/ Bates, B. 2nd ed Oreilly (2010),Head First Java


6.O’reilly.com

LESSON 12
PRACTICE WRITING JAVA PROGRAMS
12.1 Exception Handling
The ifollowing iis ian iarray ideclared iwith i2 ielements. iThen ithe icode itries ito iaccess ithe i3rd ielement
i of ithe iarray iwhich ithrows ian iexception.
// iFile iName i: iExcepTest.java
import ijava.io.*;

public iclass iExcepTest i{

iii public istatic ivoid imain(String iargs[]) i{


iiiiii try i{
iiiiiiiii int ia[] i= inew iint[2];
iiiiiiiii System.out.println("Access ielement ithree i:" i+ ia[3]);
iiiiii } icatch i(ArrayIndexOutOfBoundsException ie) i{
iiiiiiiii System.out.println("Exception ithrown i i:" i+ ie);
iiiiii }
iiiiii System.out.println("Out iof ithe iblock");

121

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

iii }
}
This iwill iproduce ithe ifollowing iresult i−

Output
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
For more about Exception Handling watch these videos:
1. https://www.youtube.com/watch?v=W-N2ltgU-X4
2. https://www.youtube.com/watch?v=K_-3OLkXkzY
12.2 Java Database Connectivity with MySQL
To iconnect iJava iapplication iwith ithe iMySQL idatabase, iwe ineed ito ifollow i5 ifollowing isteps.
In ithis iexample iwe iare iusing iMySql ias ithe idatabase. iSo iwe ineed ito iknow ifollowing iinformations
i for ithe imysql idatabase:
1. Driver iclass: iThe idriver iclass ifor ithe imysql idatabase iis icom.mysql.jdbc.Driver.
2. Connection iURL: iThe iconnection iURL ifor ithe imysql idatabase iis
i jdbc:mysql://localhost:3306/sonoo iwhere ijdbc iis ithe iAPI, imysql iis ithe idatabase,
i localhost iis ithe iserver iname ion iwhich imysql iis irunning, iwe imay ialso iuse iIP iaddress, i3306
i is ithe iport inumber iand isonoo iis ithe idatabase iname. iWe imay iuse iany idatabase, iin isuch
i case, iwe ineed ito ireplace ithe isonoo iwith iour idatabase iname.
3. Username: iThe idefault iusername ifor ithe imysql idatabase iis iroot.
4. Password: iIt iis ithe ipassword igiven iby ithe iuser iat ithe itime iof iinstalling ithe imysql idatabase.
i In ithis iexample, iwe iare igoing ito iuse iroot ias ithe ipassword.
Let's ifirst icreate ia itable iin ithe imysql idatabase, ibut ibefore icreating itable, iwe ineed ito icreate
i database ifirst.

1. create database sonoo;


2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with MYSQL database
In this example, sonoo is the database name, root is the username and password both.

122

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }

For more watch this video


https://www.youtube.com/watch?v=qRrMc99OYLM
References
1.https://www.oreilly.com/
2. https://www.youtube.com/watch?v=qRrMc99OYLM
3. Deitel & Deitel (2015, June) Java How to Program
4. https://www.tutorialspoint.com/java/index.htm

123

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

ANSWERS TO THE MODULE’S QUESTIONS


Answers to Assessment Questions:1
B
C
C
E
E
Answers to Assessment Questions:2
A
C
C
Answers to Assessment Questions:3
C
B
A
D
B

Answers to Assessment Questions:4


D
B
A
A
Answers to Assessment Questions:5
B
A
B
D
Aswers to Assessment Questions:6
D
A

124

Downloaded by Reeves Faraja ([email protected])


lOMoARcPSD|40753519

125

Downloaded by Reeves Faraja ([email protected])

You might also like