Sma391 Object Oriented Programming
Sma391 Object Oriented Programming
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)
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
Week 3: Methods
In this lesson, we introduce Java method declaration, method body, return types and method
calls.
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.
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.
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
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
10
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.
11
12
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.
In this chapter, we will discuss on the different aspects of setting up a congenial environment
for Java.
13
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'
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
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
You iwill ibe iable ito isee i' iHello iWorld i' iprinted ion ithe iwindow.
16
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.
17
knowledge
Spark
Assessment Questions
1.Who is Father of Java?
A. James Bong
B. James Gosling
C. Gosling Trump
D. Non of the Above
18
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
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
21
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() {
}
22
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();
Example
This example explains how to access instance variables and methods of a class.
public iclass iPuppy i{
iii int ipuppyAge;
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
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
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
iiiiiiii a i= i10;
iiiiiiii b i= i20;
iiii }
iiiii
class iTest
{
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
28
iiii }
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
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.
30
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*/
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
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{
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
34
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 }
35
}
}
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");
}
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
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");
}
37
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
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
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
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
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
42
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 −
43
"\"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 −
\n Newline (0x0a)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t tab
\\ backslash
44
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
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 }
46
47
import ijava.io.*;
public iclass iEmployee i{
iii // ithis iinstance ivariable iis ivisible ifor iany ichild iclass.
iii public iString iname;
48
Example
import java.io.*;
49
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
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
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
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
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
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
iiiiii try i{
iiiiiiiii in i= inew iFileInputStream("input.txt");
iiiiiiiii out i= inew iFileOutputStream("output.txt");
iiiiiiiii
54
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{
iiiiii try i{
iiiiiiiii in i= inew iFileReader("input.txt");
iiiiiiiii out i= inew iFileWriter("output.txt");
iiiiiiiii
55
iiiiii }
iii }
}
import ijava.io.*;
public iclass iReadConsole i{44
56
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
2. https://www.youtube.com/watch?v=SslMi6ptwH8 By Edureka
Spark
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?
58
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.
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.
Example
import ijava.util.Date;
public iclass iDateDemo i{
59
import java.util.*;
import java.text.*;
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
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
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
62
!= 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
63
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
65
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
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
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
67
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
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
if(condition)
{ //statements, when condition is true
}
else
{
//statements, when condition is false
}
Class Great{
int a = 3, b = 5;
if(a>b)
69
else
70
System.out.print(“Institute2”);
}
else{
System.out.print(“Intellipaat”);
}
}
}
switch (expression)
{
case ‘value1’:
//statements
break;
case ‘value2’:
//statements
break;
case ‘value3’:
//statements
break;
…
default:
//statements
71
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
(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
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
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
76
iiiiii }
iiiii
77
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
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;
}
79
i arrays iare iequal. iSame imethod icould ibe iused iby iall iother iprimitive idata itypes i(Byte, ishort,
i Int, ietc.)
80
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
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
(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
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
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.
86
87
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.
88
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
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
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
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
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.
92
int x = 1;
Syntax:
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
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.
94
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
95
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.
96
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
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
time
Next Defining your own classes
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
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;
99
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.
100
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;
101
String name;
int age;
102
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!");
}
i In ifact, iwe've ialready iseen iproof iof ithis iabove. iIt iwas iin ithis icode: i
public class Cat {
String name;
int age;
103
String name;
int age;
104
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;
public Cat() {
count++;
this.name = "Street cat No. " + count;
}
105
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;
106
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
String name;
short age;
int height;
}
}
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
109
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
111
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
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;
113
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
Example
class iSuperclass i{
iii int iage;
iii }
11.6 Polymorphism
115
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
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;
117
iii }
iii public iSalary(String iname, iString iaddress, iint inumber, idouble isalary) i{
iiiiii super(name, iaddress, inumber);
iiiiii setSalary(salary);
iii }
iii
118
iii }
iii
E-tivity 11
Numbering, 11
pacing and
119
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
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
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.*;
121
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.
122
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. }
123
124
125