Laboratory Manual For OOP - Java
Laboratory Manual For OOP - Java
Laboratory Manual For OOP - Java
Laboratory Manual
for
Object-Oriented Programming (Java)
Table of Contents
Background ............................................................................................................................................... 5
Introduction: Basic Terminologies in Java programming language ................................................................ 6
Lesson-1. Setting up your Java development environment in your computer and writing, compiling and
running simple java programs...................................................................................................... 13
Lesson Prerequisite:..............................................................................................................................13
Lesson-1 Activity .................................................................................................................................13
Lesson-1 Exercises...............................................................................................................................17
Lesson-2. The structure /Anatomy/ of a Java class and accepting input from user ........................................ 18
Lesson Prerequisite:..............................................................................................................................18
Lesson-2 Activity .................................................................................................................................25
Lesson-2 Exercises...............................................................................................................................27
Lesson-3. Writing simple object-oriented programs with Java.................................................................... 28
Lesson Prerequisite:..............................................................................................................................28
Lesson-3 Activity .................................................................................................................................28
Lesson-3: Exercises ..............................................................................................................................29
Lesson-4. Further on working with java objects ........................................................................................ 31
Lesson Prerequisite:..............................................................................................................................31
Lesson-4 Activity .................................................................................................................................32
Lesson-4 Exercises...............................................................................................................................35
Lesson-5. Implementing Encapsulation Concepts ...................................................................................... 36
Lesson Prerequisite:..............................................................................................................................36
Lesson-5 Activity .................................................................................................................................36
Lesson-5 Exercise ................................................................................................................................40
Lesson-6. Implementing OOP Inheritance Concepts .................................................................................. 40
Objective: ............................................................................................................................................40
Lesson Prerequisite:..............................................................................................................................40
Lesson-6 Activity .................................................................................................................................42
Lesson-6 Exercise ................................................................................................................................45
Lesson-7. Polymorphism, Abstract class and Interfaces ............................................................................. 47
Lesson Prerequisite:..............................................................................................................................47
Lesson-7 Activity .................................................................................................................................48
Lesson-7 Exercise ................................................................................................................................52
Lesson-8. Exercises on Inner Classes ....................................................................................................... 55
Lesson Prerequisite:..............................................................................................................................55
Lesson-8 Activity .................................................................................................................................56
Lesson-8 Exercise ................................................................................................................................58
Lesson-9. Exception Handling Mechanism of Java.................................................................................... 60
Lesson Prerequisite:..............................................................................................................................60
Lesson-9 Activity .................................................................................................................................62
Lesson-9 Exercise ................................................................................................................................64
Lesson-10. Java GUI Programming............................................................................................................ 65
Lesson Prerequisite:..............................................................................................................................65
Lesson-10 Activities .............................................................................................................................66
Lesson-11 Exercise...............................................................................................................................70
Lesson-11. Java Database Connectivity [JDBC] and MVC Model................................................................ 71
Lesson Prerequisite:..............................................................................................................................71
Lesson-12. development with Java ............................................................................................................. 82
Project Title: Class Schedule Management System .................................................................................... 82
References
Background
A fundamental understanding of computing discipline enables students to be not just educated users
of technology, but the innovators capable of designing new computers and programs to improve the
quality of life for everyone. It is not an exaggeration to say that our lives depend upon computer
systems and the people who maintain them to keep us safe on the land and in air.
Without a deep-rooted understanding of computing, we are nobody but users who let their life to be
dependent on others and our country will continue containing a society in slavery to those who can
develop the new technology. Without understanding of computing principles (particularly,
programming principles), computer and software projects go wrong and we are likely to misuse or
use inappropriate technology with dangers for the life and liberty of our society.
We are living in a digitized, computerized and highly programmable world. And to make sense of it,
we need to give kernel focus to teaching computing. An engineer using a computer to design a bridge
must understand the limitations of the numerical methods used, how the maximum capacity estimates
were computed and how reliable they are. An educated citizen using governmental e-procurement, e-
banking systems (the ATM and the like), etc, should have a basic understanding of the underlying
algorithms of such conveniences, as well as the security and privacy issues that arise when
information is transmitted and stored digitally. These all are computing issues. Much more than this,
computing is becoming one of the leading disciplines helping us understand how the human mind
works, one of the great intellectual questions of our era.
To go in- line with this all and to fill the computing demand of our country, our school, the School of
Computing (SC), is teaching students the basic computing principles such as logical reasoning,
algorithmic thinking, mathematical problem solving and all inherent concepts and skills that are
valuable for solving the critical communal problems of our country. They are gaining awareness of
the resources required to implement and deploy a solution and how to deal with socioeconomic
problems that our society is facing. It is believed that these skills are applicable in many
developmental slots of the country, in solving or else minimizing the dangers and sufferings that our
society is living with.
Towards achieving the main aim of the school entirely and o f the computing discipline particularly in
making students competent system designers and programmers, I have prepared this laboratory
manual for the course Object-Oriented Programming - Java - so as to provide a very detailed and
The content of this manual is organized into lessons in parallel to the lecture content. And the code in
this manual is written (edited), compiled and run using the JCreator LE 5.0 and Netbeans 8.0 IDEs.
Each of the lessons does have objectives, prerequisites to the lesson, activities to be done at home and
during the laboratory session and at last, exercises to the respective lesson.
The objective of the lesson will describe the reason why you will be in the laboratory by that session.
That is, it will tell you what to achieve at the end of completing that session.
The prerequisite of the lesson will tell you the activities and studies that YOU SHALL WORK AT
HOME before you come and sit for the respective laboratory session. That is, it highlights the read ing
points that you must study before coming to that laboratory session.
The activities section of the lesson will tell you what to do during that session towards achieving the
objective of the lesson by giving at least one example and letting you dive into the remaining tasks
based on the given example. Besides, it provides a- line-by- line code analysis of the solved problem in
order to assist the students understand and solve similar problems with the same fashion. Note that all
students are intended to practice it at home and come to the laboratory for asking and further
deepening their understanding on the theme.
At last, all lessons do have exercises relevant to the respective lesson to help the students deepening
their skill and understanding of the matter of the lesson.
Program /የኮምፒዩተር ቀመር/:- is an organized list of instructions that, when executed, causes the
computer to behave in a predetermined manner. የኮምፒዩተር ቀመር መድበሇ ትእዛዛት ነው። ይህም የትእዛዛት ቅዯም
ተከታሊዊ ስብስብ ማሇት ነው። እያንዲንደ ትእዛዝ ኮምፒዩተሩ ምን ማድረግ እንዲሇበት የሚጠቁም ዓረፍተ ነገር ነው።
Prepared by: Desta Berihu Weldegiorgis Page 6
Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
Example:
ከሊይ የምናየው ቀመር (program) 15 ትእዛዛት (instructions) ይዟሌ። ኮምፒዩተሩ እነዚህ ትእዛዛትን በቅዯም ተከተሌ
በመተግበር አንድ የተሟሊ ተሌእኮ ይፈፅማሌ። በመሆኑም የእንዱህ ዓይነት ትእዛዛት መድበሌ (ስብስብ) የኮምፒዩተር ቀመር
ይባሊሌ።
Array /ዝርዝር/፡- Array is a list of data values of the same type, any element of which can be
referenced by an expression consisting of the array name followed by an indexing expression. Arrays
are part of the fundamentals of data structures, which, in turn, are a major fundamental of computer
programming.
የአንድ ዓይነት ምድብ ያሊቸው ነገሮች ዝርዝር ማሇት ነው። የተመሳሳይ ነገሮች ድርድር ማሇት ነው። በዝርዝሩ ሊይ ያለ ነገሮች ቅዯም ተከተሌ
የሊቸውም። ሇምሳላ፡ ሀ = {55፣32፣71፣42፣86} ። ይህ ስሙ ሀ የሚባሌ ድርድር/ዝርዝር/ ነው። አራት አባሊትም ይዞዋሌ። እነዚህም ሀ[0]፣
ሀ[1]፣ ሀ[2]፣ ሀ[3] በማሇት ሌንጠራቸውም ሌንጠቀማቸውም እንችሊሇን። የዝርዝሩ አባሊት ጠቋሚ /index/ የሚጀምረው ከ ዜሮ ነው።
Example:
int[] arr; // this is an array declaration. In this example arr is a reference variable pointing to the
memory where the list exists. The int[] is the data type telling that the type of the content of the
array is only integer.
Class/መዯብ/፡- Class is a named template or descriptor for a set of objects that share the same
attributes (fields), behaviors (methods) and relationships. It models /abstracts/ a real world entity.
አንድ ዓይነት መገሇጫዎች (attributes) ፣ ተግባራት (behaviours) እና ግንኝነቶች (relationshiops) ሇሚጋሩ ኣካሊት(objects)
የሚሰጥ የወሌ መጠርያ ስም ነው። ሇምሳላ፡- ኳስ የሚሌ መዯብ የእግር ኳስ፣ የመረብ ኳስ፣ የእጅ ኳስ፣ የሕፃናት መጫወቻ ኳስ እና
የመሳሰለት ሁለ ያጠቃሇሇ የጋራ መጠርያ ስም ነው።
class Student This is the declaration of the class. Note that a class should be
{ declared using the keyword „class‟.
……
}
class Student Here:
{
class – is a keyword used to declare a class in java.
int age;
Student – is the user-defined name of the class
public int getAge(){
return age; int – is data type of the field.
} age – is user-defined name of the field.
public - is an access modifier
getAge() – is the name of the method
{…} - used to enclose body of a given block.
return - is a keyboard in java used to return the value
returned by a certain functions/methods and the flow control.
Character /ቀሇም/:- is a general name for all letters, digits, punctuation marks and other symbols.
ቀሇም ማሇት በቀመሩ ውስጥ የምንፅፈው ማንኛውም ፊዯሌ ወይም ምሌክት ነው። ሇምሳላ፡- &, @, %, 1, 4, 2, a, v, n, ?, \, k, p, ...
Comment /አስተያየት/:- is a remark (human-readable-only explanation) in the source code which does
not affect the behavior of the program. It is ignored by the compiler. የኮምፒዩተር ቀመር/program/ በመንፅፍበት
ጊዜ ሇእያንዲንደ መምሪያ/Instruction/ ሇማብራራት የሚጨምሩት ማብራርያ ነው። በመሆኑም በአርታዔ ቀመር / compiler/ የሚታይ
እና የሚተረጏም አይዯሇም።
ይህ የዲታ መያዣ ነው። ሇጊዜው የሚይዘው ዲታ ስሇማይታወቅ ተተኪ /variable/ ተባሇ። ማንኛውም የኮምፒዩተር ቀመር የሚሰራው
ዲታ ሊይ ነው። ቀመሩ ዲታውን ጠቃሚ መረጃ (information) እስኪሆን ድረስ የማቀነባበር፣ የማዯባሇቅ፣ የማንዯባሇሌ፣ የመቀመር ወዘተ
ስራ ይስራሌ። ታዱያ ዲታው የሚያገኘው ከኪ ቦርድ፣ ከኔትዎርክ፣ ከራሱ ሃርድ ዱሰክ መዛግብት ወዘተ ሉሆን ይችሊሌ። ይህ ዲታ ቀመሩ
ሉጠቀምበት በሚችሌ መሌኩ የሚቀመጠው ዯግሞ በዲታ ማስቀመጫዎች (data structures) ውስጥ ነው። ከእነዚህ ዲታ ማስቀመጫዎች
አንደ ይሄው ‘የዲታ መያዣ’ ያሌነው ነው።
Example:-
double gpa; // Now, gpa is the name of the memory (i.e. the variable).
// double:- indicates two basic things – the dimension of the variable and the
// type of data that can be stored in variable gpa.
Keyword /ቁሌፍ ቃሌ/:- is a reserved word used to identify a specific command, function etc in the
programming language. በአንድ የኮምፒዩተር ቀመር ቋንቋ ውስጥ የሚገኙ የቋንቋው የራስ ቃልች ‘ቁሌፍ ቃሌ’ ይባሊለ።
Example:- int, for, while, break, continue, do, static, final, public, etc.
Constant /አይቀየሬ/:- Constant is a numeric or string value that is not calculated and, therefore, does
not change. In Java, constant variables are declared using the keyword final.
የኮምፒዩተር ቀመር በምንፅፍበት ወቅት የምንጠቀምበት፣ ዋጋው የማይቀያየር የዲታ መያዣ ‘አይቀየሬ’ ይባሊሌ። ሇምሳላ፡- የሒሳብ ቀመሮች
በምንሰራበት ወቅት የπ ዋጋ 3.14 በማድረግ ነው። ይህ ዋጋ መቼውም የማይቀየር የπ ዋጋ ነው። ስሇዚህ በኮምፒዩተር ቀመር ቋንቋ
ሲንገሌፀው ዋጋው የማይቀያየር የዲታ መያዣ ‘አይቀየሬ’ እንሇዋሇን።
Example:-
final double PI = 3.14
final float gravity = 9.8
Data type /የዲታ ዓይነት/:- is a classification or category of various types of data, which states the
possible values that can be taken, how they are stored, and what range of operations are allowed on
them. It determines two things about the data stored in a variable:
the space (memory) given to the data
the type of the data that can possibly be stored in that variable.
ኮምፒዩተር የሚሰራው ስራ በሙለ ዲታ ሊይ ያጠነጠነ ነው። እነዚህ ዲታዎች የተሇያዩ ዓይነቶች ናቸው። በመሆኑም ‘የዲታ ዓይነት’ ማሇት
በአንድ የዲታ መያዣ ወይም አይቀየሬ ሊይ የምናስቀምጠው ዲታ፣ ዓይነቱ የሚገሌፅሌን ቁሌፍ ቃሌ ነው። ከዚህ በተጨማሪ በተተኪው
(በዲታ መያዣው) ሊይ የሚቀመጠውን ዲታ መጠኑ (dimension) ምን ያህሌ ቢት/ባይት እንዯሆነ ይገሌፅሌናሌ።
Function or method /አስላ/:- Function (also called method in java) is a piece of code that operates as
a single logical unit. A function is called by name, accepts optional input parameters, and returns a
status and optional output parameters. It simulates the natural orders seen in human beings. i.e., it
operates by taking an input from the caller, processing the input, and finally returns its processed
value back to the caller. In short, functions simulate human beings, factories and any machine that
works following the basic operation-patterns namely: Input process output.
ሇስላት የሚጠቅሙት ግብኣቶች/parameters/ በመውሰድ አንድ ስላት ሰርቶ የሚመሌስ፣ ከቀመሩ ከማንኛውም ክፍሌ ሉጠራ የሚችሌ
የቀመሩ ኣካሌ ‘አስላ’ ይባሊሌ። አስላ ሁሇት ዋና ዋና ክፍልች አለት። እነርሱም የአስላ ስርዓት / method definition/ እና የአስላ አሰሪ
(ወይም ጠሪ) /method call/ ናቸው።
Example:-
Method definition /የአስላ ስርዓት/ መግሇጫ
11 int add (int firstNum, int secondNum) ይህ የአስላ ስርዓት ነው፡፡ ሁሇት ክፍልች አለት፡ አንዯኛው (11)
ተብል የተመሇከተው የአስላ መሇዮ(method signature)
{
እየተባሇ የሚጠራው ሲሆን ሁሇተኛው ዯግሞ (22) ተብል
int summation = 0;
የተመሇከተው (የአስላ ሰውነት) method body የሚባሇውን
22 summation = firstNum + secondNum;
ነው።
return summation;
} የአስላ መሇዮ ሶስት ነገሮችን የያዘ ነው፡- የመሌስ ዓይነት
(return type)፣ የአስላ ስም (method name) እና የአስላ
ግብአት (method parameter) ናቸው።
የአስላ ሰውነት አስላው ግብአቶችን ተቀብል የሚያሰሊበት
የስላት ትእዛዛት የያዘ (working instructions) በማዕቀፍ
ቅንፎች /{….}/ የተከበበው ዋና ሰውነቱ ነው።
Identifier /መሇዮ/:- Identifier is a formal name used in source code to refer to a variable, method,
class, package, etc.
የኮምፒዩተር ቀመር ፀሓፊው በቀመሩ ውስጥ የሚፅፋቸው ማንኛውም የዲታ መያዣ፣ የአይቀየሬ፣ የዲታ ዓይነት፣ የአስላ ወዘተ ስሞች ‘መሇዮ’
እንሊቸዋሇን። መሇዮዎች በምንፅፍበት ጊዜ እንዯ የኮምፒዩተሩ ቋንቋ የምንከተሊቸው ሕጎች አለ። በ ጃቫ ሁሇት ሕጎች አለን። ማንኛውም
መሇዮ በፊዯሌ ወይም በግርጌ ጭረት(underscore) ብቻ መጀመር አሇበት። ከመጀመርያው ቀጥል የሚፃፉት ሦስት ነገሮች [ማሇትም
ፊዯሊት፣ቁጥሮች ወይም የግርጌ ጭረት] ብቻ ናቸው።
ሇምሳላ፡
isSecondYearStudent 2ndIsSecondYearStudent
_isSecondYearStudent is2nd_YearStudent
isSecond YearStudent is2ndYearStudent
Lite ral /ጥሬ ዋጋ/:- is a value written into the source code of a computer program.
በአንድ የዲታ መያዣ ውስጥ የዲታ ዓይነቱ መሰረት በማድረግ የምናስቀምጠው ዋጋ ‘ጥሬ ዋጋ’ እንሇዋሇን።
ሇምሳላ፡- int a = 5; …………………………………….(1)
String str = ‚I am student of IoT-SCEE‛; ………...(2)
በቁጥር (1) የተመሇከተው ዋጋ /5/ የኢንተጀር ጥሬ ዋጋ ይባሊሌ።
በቁጥር (2) የተመሇከተው /I am student of IoT-SCEE/ የሚሌ ዋጋ የስትሪንግ ጥሬ ዋጋ ይባሊሌ።
Loop /ጥምጥም/:- is a sequence of instructions that should be executed repeatedly until or while a
particular condition is satisfied.
ቀመሩ አንድን ነገር መሊሌሶ እንዱሰራሌን ስንፈሌግ የምንጠቀምበት የቀመሩ አንደ ሰዋስው (programming construct) ነው። ይህም አንድ
ሂዯት ወይም ተግባር ብዙ ጊዜ ተዯጋግሞ እንዱሰሊ የሚያስችሌ ነው። ሇዚህ ዓሊማ የምንጠቀምባቸው የቀመር የጥምጥም ዓይነቶች ሦስት
ናቸው። እነዚህም፡- for loop, while loop, do---while loop ይባሊለ።
በሰው ዘንድ በገሃደ ዓሇም ህሌውናውን የታወቀ፣ በሰው ቋንቋ ሉገሇፅ የሚችሌ ቁስ አካሌ ወይም ተጨባጭ ነገር ነው።
(Ro)
ምድብ /class/
ምድብ የጃቫ ፕሮግራም ትንሹ ክፍሌ ነው። የገሃደ ዓሇም ነገርን ይወክሊሌ። ስሙም የገሃደ ዓሇም ነገር ስም ነው።
ምድብ በውስጡ ሁሇት ዋና ዋና ነገሮች ይይዛሌ። ይሄውም የገሃደ ነገር መገሇጫዎች የነበሩ የምድቡ fields፣ የገሃደ ነገር
/Class/ ተጋባራት የምድቡ methods ይሆናለ። በመሆኑም ምድብ ሁሇት የራስ አባሊት /logic al members/ አለት።
እነርሱም fields እና methods ናቸው።
ምድብ ተ ማሪ
{
መገሇጫዎች (fields)
ተግባራት (methods)
}
Programming Object
(P o )
Programming Object /Po/
ምድብ (class) በገሃደ ዓሇም ያሇ አንድን ነገር (entity) አርቅቆ (abstraction) እና ወክል የሚፃፍ የጃቫ ቀመር ትንሹ ክፍሌ
/automic unit/ ነው። የቀመሩ ኣካሌም (Object) የሚፈጠረው ይሄው ከዚሁ ምድብ ነው። ምድብ የመባለ ዋና ምክንያትም አንድ
ዓይነት መገሇጫዋችና አስላዎች የሚጋሩ፣ ተመሳሳይ ምድብ ውስጥ ሉመዯቡ የሚችላ አካሊት (ገሃዶች - instances) ስሇሚፈጠሩበት ነው።
በአጠቃሊይ ከአንድ ምድብ ብዙ የምድቡ ገሃዶች የሆኑት አካሊት (instances or objects) መፍጠር ይቻሊሌ።
የቀሇሞች ስብስብ ነው። ባዶ ወይም አንድ ወይም ከአንድ በሊይ ቀሇሞች ሉይዝ ይችሊሌ።
Field /መገሇጫ/:- is a variable associated with an object or class. የአንድ ኣካሌ (object) መገሇጫ ነዉ።
Objective: at the end of this laboratory session, you will be able to:
Configure a java environment (platform) so that you can write, compile and run
java programs in any computer.
Write, compile and run very simple java programs and understand each of their
parts clearly.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The difference between Java JDK and Java JRE
The various tools packed in the JDK and their role in running a given java application.
The phases that any java application passes thorough for execution.
The various tools bundled in JDK that are used for compiling, debugging and running
java app
The syntax and semantics of java class anatomy discussed in class!!
The syntax of declaring and defining java class!
Commonly used classes such as String, System etc in the package java.lang
Lesson-1 Activity
In order to write and run Java program, you need to install and configure the Java platform (i.e., the
Java Development Kit- JDK) on your computer system.
To configure the JDK, you have to set the JAVA_HOME environment variable to the root location of
the JDK installation directory in your computer. For Example, assume that your Java is installed in
C:\Program Files\Java\jdk1.6.0_06; where jdk1.6.0_06 is the version of the JDK you installed. Then,
use either of the following ways to set the JAVA_HOME environment variable:
Next set the PATH environment variable to include the JDK bin directory. The PATH variable tells
the operating system where to find the java interpreter and the javac compiler. Use either of the above
two ways. If you choose to use the first way, the statement you should write in the command prompt
is: C:\> set PATH=%PATH%;%JAVA_HOME%\bin
To make sure that you have configured the JDK successfully, use the java -version command to see
the JDK version and the path it is installed in.
Task-2: Open either of the java editors discussed in class [such as notepad, JCreator, etc] and then
write the following simple program.
Here, please be sure to name the text file as OopStudBiT.java (Note: please name your class in the
program with your own name by making the first letter of your name capital letter). Java program is
case sensitive, so if you type the code in yourself, pay particular attention to the capitalization (Eg.
Write OopStudBiT instead of oopStudBiT to name your java class).
//A very simple java program which prints first and second name of the programmer.
public class OopStudBiT{ // line-1
public static void main(String[] ethiopia) { // line-2
String firstName = "Yohannes"; // line-3
String secondName = "Zekarias"; // line-4
System.out.println("Your Full Name is:" + firstName+""+secondName); // line-5
}
}
Now, compile and run the program and you will see the following output.
In line-5:
System :- is name of abuilt- in class in Java library. It contains the standard input/out streams. It is
found in the package java.lang
.(dot) :- is an access operator. It is used to access members (fields and methods) of a class or an
object.
out :- is a static reference variable to the standard output stream object of type PrintStream.
print() :- is an instance method defined inside of the PrintStream class. It is an overloaded
method with different parameters. It has also another version of its type called println(). The
suffix ln means „line‟. By this, println is meant to print the output in new line.
"Your Full Name is:":- is a literal string. Everything under double quotes is a literal string.
+(plus sign):- is a concatenation operator. When it comes between non-string numeric values,
it is a mathematical addition operator. However, if either of its operands is String, then it becomes a
concatenation operator.
Task-3:- Write the following java program on notepad and run it from the command prompt.
Create a temporary folder C:\BiTScee. Using Notepad or another text editor, create a small Java file
OopStudBiT.java with the following text:
Save your file as OopStudBiT.java in C:\BiTScee. To make sure your file name is
OopStudBiT.java, (not OopStudBiT.java.txt), first choose "Save as file type:" All files, then type
in the file name OopStudBiT.java.
Run Command Prompt (found under All Programs/Accessories in the Start menu). Type C:\> cd \
BiTScee. This makes C:\ BiTScee the current directory. And then, type C:\ BiTScee> dir. This
displays the directory contents. You should see OopStudBiT.java among the files.
Now, it is time to compile your program. To compile your program, you use javac.exe, which
is the java compiler, as follows: C:\ BiTScee> javac OopStudBiT.java
Now, you should see nothing but the next system prompt: C:\ BiTScee >
The compiler javac creates the OopStudBiT.class file. You should see OopStudBiT.java and
OopStudBiT.class among the files.
To run your program, you use java, which is the java interpreter, as follows:
C:\ BiTScee> java OopStudBiT. This runs the Java interpreter.
Finally, you should see the program output as: OOP, BiT-SCEE!
If the system cannot find javac, check the set path command. If javac runs but you get errors, check
your Java program. If the program compiles but you get an exception, check the spelling and
capitalization in the file name and the class name and the java OopStudBiT command.
አስተውሌ ! አስተውሌ ! አስተውሌ ! Java is case-sensitive!
Lesson-1 Exercises
1) Write a program that accepts two numbers from the keyboard. The main() method should first
accept the two numbers and then passes these values to methods named add(), sub(), mul() and
div(), to calculate the sum, difference, product and quotient of the numbers, respectively. Finally,
the main() method should accept the returned result and display it on the consol. [Hint: your java
program will have five methods of which one is the mandatory main() method. ]
2) Write a program that calculates the area of a rectangle. The main() method should first accept the
width and height of the rectangle and then passes these values to method named
rectangleArea(). Method rectangleArea() calculates the area of the rectangle using the
formula width*height and return the result. main() method should accept the returned result and
display it.
3) What do you think is the output of the following code fragmentation?
final int N = 100;
for (int i=0;i<N/2;++i){
for(int j=N;j>=2;--j){
Sytem.out.println(“I am learning Java!!”);
}
Sytem.out.println(“I found it simple, portable and secured!!”);
Lesson-2. The structure /Anatomy/ of a Java class and accepting input from user
Objective : at the end of this laboratory session, you will be able to:
Implement and understand the java class anatomy.
Write simple java application which accepts inputs from the keyword.
You will see some mechanisms of accepting input from keyword.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The syntax and semantics of java class anatomy discussed in class!!
The Java class libraries used for accepting input from the standard input device such as
Scanner, JOptionPane, BufferedReader, etc…
The syntax of importing these built- in classes to your class.
The Syntax of instantiating objects from classes
Here the Java class anatomy which we will try to apply it throughout the course.
Points to be re membered:
Only comments can exist everywhere in the program.
Package statement, if it exist, should be the first line of code in the program. And we can have
only one package statement in a program.
Import statement(s), if they exist, should follow the package statement. They can possibly be
many lines of codes.
Except the package and import statements, every code should be written inside of a class.
The following are some of the ways that Java offers us to accept input from a standard input device,
the keyboard.
import java.util.Scanner;
This tells java that you want to use a particular class in a particular library - the Scanne r class, which
is located in the java.util library [i.e., the package where the class is located].
The next thing you need to do is to create an object from the Scanner class. (A class is just a bunch of
code. It doesn't do anything until you create a new object from it.)
So instead of setting up an int variable or a String variable, we're setting up a Scanne r variable.
We've called ours userInput. After an equals sign, we have the keyword new. This is used to create
new objects from a class. The object we're creating is from the Scanner class. In between round
brackets we have to tell java that this will be System Input (System.in).
To get the user input, you can call into action one of the many methods available to your new Scanner
object. One of these methods is called next(). This gets the next string of text that a user types on the
keyboard:
This is the same code, except that java will now store whatever the user types into our secondName
variable instead of our firstName variable.
We've set up another String variable, full_name. We're storing whatever is in the two variables
firstName and secondName. In between the two, we've added a space. The final line prints it all out in
the Output window.
So, all together, your entire code looks the following code:
Now compile and run your program until your output window displays the following:
Java is now pausing until you enter something on your keyboard. It won't progress until you hit the
enter key. Type a first name, and then hit the enter key on your keyboard.
After you hit the enter key, java will take whatever was typed and store it in the variable name to the
left of the equals sign. For us, this was the variable called first_name.
The user input has now finished, and the rest of the program executes. This is the output of the two
names. The final result should like this:
So we used the Scanner class to get input from a user. Whatever was typed was stored in variables.
The result was then printed to the output window.
Another useful class for accepting user input, and displaying results, is the JOptionPane class. This
is located in the javax.swing library. The JOptionPane class allows you to have input boxes like
this one:
Let‟s see the change to our program above when we use JOptionPane class for accepting an input:
This tells java that we want to use the JOptionPane class, located in the javax.swing library.
You can start a new project for this, if you prefer not to adapt your previous code. (You should know
how to create a new project by now. Just remember to change the name of the Class to a name of
your conform word. We're going to have the class name InputBoxes for ours case. Our package name
will be userinput.)
Add the import line to your new project, and your code window should look like something like this:
To get an input box that the user can type into, we can use the showInputDialog() method of
JOptionPane. We'll store the input straight into a first name variable again, just like last time. So
add the following line to your main method:
String first_name;
first_name = JOptionPane.showInputDialog("First Name");
And add the following code so that we can get the user's second name:
String second_name;
second_name = JOptionPane.showInputDialog("Family Name");
In between the round brackets we first have the word null. This is a java keyword and just means
that the message box is not associated with anything else in the program. After a comma comes the
text we want to display in the message box. The whole of your code should look like this:
Now compile and run your code. You'll see the First Name input box. Type something into it, then
click OK:
When the Second Name input box appears, type a second name and click OK:
Task-1: Open JCreator (or any editor of your preference) and write the following program.
// the following program accepts the height and width of a rectangle and displays its area.
Now, when you compile and run the above program, you will see the following output.
Task-2:- Write a java program which receives a number and determine whether it is odd or even.
(Hint: use the Scanner class for accepting an input).
Task-3:- Write a java program which calculates displacement of an object using the following
formula: s = ut + ½ at 2 . (Hint: use the JOptionPane class for accepting an input).
Lesson-2 Exercises
1. Input boxes and Message boxes can be formatted further. Try the following for your Input boxes:
showInputDialog("First Name", "Enter Your First Name");
showInputDialog("Second Name", "Enter Your Second Name");
4. Input boxes are not just used for text: they can accept numbers as well. Write a program that
prompts the user for two numbers, the width of a rectangle and the height of a rectangle. Use a
message box to calculate the area of the rectangle.
5. The program will crash if you enter floating point values for the width and height. How would you
solve this?
6. When you have solved the above exercise, do you really want Integer.parseInt()? What
else do you think you can use?
However, you can't multiply two strings together. You need to convert the Strings to integers.
You can convert a string to an integer like this:
Integer.parseInt( string_to_convert )
So you type Integer then a full stop. After the stop, type parseInt( ). In between the round
brackets of parseInt, type the name of the string variable you're trying to convert.
Set up an int variable for the area. You can then multiply and assign on the same line;
int area = Integer.parseInt( string_one ) * Integer.parseInt( string_two);
You can use any of the MESSAGE symbols for your message box.
Objective: at the end of this laboratory session, you will be able to:
write an object-oriented java programs thereby understand how to instantiate an
object and how to read/write data from/to an object.
NB: please apply the same fashion to solve all the exercises in this lesson. All of you should solve all problems given in this lesson.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The syntax and semantics of java application anatomy discussed in class!!
The syntax of declaring and defining java class!
The logical members of a class (the fields and methods), the syntax of writing static
fields, constants, instance fields, methods, etc.
The static and non-static members of a class.
The syntax of creating an object.
Lesson-3 Activity
Task-1:- Write a java program which adds even numbers between 0 and any positive integer number
given by the user.
2𝑥 + 𝑦 2+4𝑥𝑦
b. 𝑟𝑒𝑠𝑢𝑙𝑡 =
2𝑧
c. If x =10, y=2 and z=3, then what is the value of the following algebraic expression
i. x2+2y/z, assume data type of x, y and z is integer
ii. ++x - 2Y++ z*y
𝑥𝑦 +𝑥/𝑦
iii.
𝑧−2
7) Write a java program which takes D number of days and displays the number of Y years, M months, W
weeks and d days from the entered number D. (If entered value of D is 544, the output should be:
544 days is equal to 1 year, 5 months, 4 weeks, and 1 day).
8) Write a java program which takes D number of days and displays the number of H hours, M minutes and
S seconds from the entered number D. (If entered value of D is 544, the output should be: 544
days is equal to 6528 hours or 391680 or 23500800 seconds).
9) Write a java program which calculates petrol (gas) consumption. It should accept the distance
travelled (in kilometers) and the amount of petrol used (in liters) and compute the consumption in
km/liter as well as in liters per 100 km. Write some helpful headings, so that your output will look
like as follows:
Distance Lite rs used Km/L L/100Km
528 46.23 11.42 8.76
10) Write a java program which accepts an integer and reverse digits
11) Write a java program which computes sum of prime numbers between 0 and 1000. Your program
which contains a method isPrime(int a) to check if the number is prime number.
12) Write a java program which computes the following mathematical expressions.
a. 1+1/2+1/3+1/4+…1/15
b. 1! + 2! + 3! + 4! + …n!
30 𝑖
c. 𝑖 =1 3 ∗2
13) Write a java program which prints out the numbers 10 through 49 in the following manner
10 11 12 13 14 15 16 17 18 19
20 21 22 23 2 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
a) b) c) d) e)
A *
A Bc ** ****** *
AB Def *** ***** ***
ABC Gehi **** **** *****
ABCD Jklmn ***** ***
*******
ABCDE Opqrst ****** **
ABCDEF *********
*
***********
Objective: at the end of this laboratory session, you will be able to:
write different classes, create several objects from these classes and make them communicate
among each other. You will also apply the access control modifiers to see their effect
practically.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The syntax and semantics of declaring reference variables
The four basic tasks done during creating an object from a given class.
The syntax of using static and non-static members of a class.
The syntax of creating an array in java.
The role and syntax of writing a constructor for a given class.
Lesson-4 Activity
Task-1: [Shapes]
a) Write a java class which defines a Circle and calculates its area and circumference by
accepting its radius from the keyboard.
Here below is the code for Circle class. Please note that the detail explanation of all the lines of codes
in this class is given in the form of comments. Try to understand the skeleton and flesh of this
program critically and then, you will begin writing and understanding any object-oriented code
written in java appropriately.
package shapes; // this is package declaration. If it exists, it MUST be the first line in your code.
/*
* @(#)Circle.java
*
*Please read properly the comments in this program and apply them in other programs too!!
*
*Again remember that all java programs must have at least one class and that class must be declared as
*public. You can‟t have more than one public class in a given one program though.
*Once you understand each and every element in this program, you can write similar programs for
*triangle, rectangle, and others too. For this reason, look at the steps of this program critically please!!!!!
*
* @author Desta Berihu
* @version 1.00 14/02/2007 E.C
*/
import javax.swing.JOptionPane; // here, I am just importing the JOptionPane class for use
public class Circle { // this is the declaration of the class Circle using the keyword 'class'
private double radius; //A circle object has only radius for as its internal data.
final static public float PI = 3.14f; // this is a constant static field
/*Remember the three steps which we should write them under main method. i,e.
* (1) accepting an input from the keyboard
* (2) creating an object from the class
* (3) displaying the content of the object created from the class. Accordingly, look
* at the following steps.
*/
// Step-1: Accepting an input from the keyboard!
// a local string variable to hold the string value which comes from the keyboard
String rad;
/*Prepared
a localby: Desta Berihu
double to hold the double value obtained by the converting the string(i.e, rad)Page
Weldegiorgis
variable 33
to inputted
Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
//you can abrivate the above three statements in to one statement as follows:
System.out.println("The radius of the circle is:" + c.radius + "\n The area of the circle is:" +
c.area()+ "\n The circumference of the circle is:" + c.circumference());
b) Write a class which defines a Rectangle and calculates its area by accepting its width and
height from the keyboard using the input dialogue box. [Hint: use
JOptionPane.showInputDialog(String str)method of the JOptionPane class
found in the javax.swing package]
c) Define class Shape as:
public class Shape
{
// detail is omitted for u!
}
and create an array of shapes to contain different shape objects [Circles, Rectangles,
Triangles and Squares] in it. [NB: know that it is possible to create array of different objects
as so]. Finally, display the name and area of each of the objects in tabular form as follows:
Shape Name Area
Circle x.yy
Rectangle yy
Triangle ww.nn
Square aa.bb
Lesson-4 Exercises
1) [Student] Write a Student class in package named studentProfile that registers students by
defining their attributes namely: first and second name, department, id, age, sex and gpa.
The class also defines additional field noOfStudents to count the number of students registered
in the program. Try to accept the students detail from the keyboard using the Scanner class in the
main() method of your class. And then create instances (objects) of the class in the main()
method and display the list of the students registered to the consol in tabular form as follows:
No. First Name Second Name ID Department Age Sex GPA
1 Kelem Dawit Eng/345/02 CS 23 F 3.8
2 Aster Belete Eng/347/02 CSE 22 F 4.0
3 Yared Asteraye Eng/349/02 IS 24 M 3.2
4 Jacob Belay Eng/343/02 CSE 20 M 3.9
5 Alljakim Abeje Eng/340/02 IE 25 M 3.7
… … … … … … … …
2) [Student] Write another class named StudentRecord in the same package as class Stude nt which
accepts the details of the students from a keyboard and finally displays their detail to the consol
with tabular format shown in #1 above. [Please compare and contrast these two approaches of
writing a program and write your observance and finally, report them on paper].
3) [Hunger Predication System]
a) Write a program in java (define class HungerPredication) which determines the hunger status
of a given country by accepting the political stability (polStat), GDP (cgdp), development
level (devpLevel), annual rain fall amount (rainFall ), population size (populSize) and
previous‟s years harvest (prevYearHarv) of the country. Use computation formula for
predicting the hunger level as:
(polStat+devpLevel+rainfall+prevYearHarv)/(cgdp*0.1)*popuSize
b) Modify the above program to accept the status of six countries [Ethiopia, Kenya, Sudan,
Djibouti, Eritrea, and Egypt] and compare them, and finally display them in order of their
hunger status based on the computation in a tabular format.
Objective : at the end of this laboratory session, you will be able to:
Write a code which uses the concepts of data encapsulation (data hiding) by writing classes
of the same and different package.
Understand the use of access modifiers and accessor/mutator method in realizing
encapsulation.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The four access modifie rs and their effect in encapsulating data of a class
The syntax of writing getter/ setter methods
The semantics of getters/ setter methods
Points to be remembered:
The terms encapsulation and information hiding are used interchangeably. By exposing object
functionality only through methods, you can prevent your private variables from being assigned
any values that don‟t fit your requirements.
One of the best ways to create a well-encapsulated class is to define its instance variables as
private variables and allow access to these variables using public methods.
Java protects class members from unauthorized access using the four access modifiers.
Java uses the public and default access modifiers to protect a given class not to be accessed out of
its package.
Java offers public getter/setter instance methods for legally accessing the internal content of a class.
The setIsbn() method should make sure that the length of the isbn code of the book is
exactly ten characters [e.g: 9876545674]. The authorName should also begin with upper
case letter.
Now, when you compile and run the above program, you find something like the following
output.
Please answer the following questions by looking the program given in this lesson.
a) What is the difference between line-70 and line-71? As you can see from the output of
the program, they display the same output. Why? Please put your justification clearly.
b) What is line-72 doing?
c) Why is the end line of the program display value NULL?
Lesson-5 Exercise
1) Write another class named BookTest in the same package as class Book which accepts the details
of the book from a keyboard and finally displays it to the consol with tabular format. [Now answer
the following questions:
i) What type problem did you face while attempting to access the author name and isbn of
the book from within the BookTest class?
ii) Then, what did you do to solve the problem?].
2) Assume that the BookTest class is written in a separate package. Now, answer the
following questions:
i) Did you access the field title directly by its name?
ii) What happened to your BookTest class when you try to access the fields authorName and isbn
directly by their name.
iii) What happened to your BookTest class when you try to access the field price directly by its simple
name?
Lesson-6. Implementing OOP Inheritance Concepts
Objective: at the end of this laboratory session, you will be able to:
Write a code which uses the principal concepts of inheritance such as inheriting members,
hiding members, overriding members, casting,..etc.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The syntax of writing classes which have an is-a relationship among each other. i.e.,
the syntax of extending sub class from super class.
The syntax of accessing hidden/shadowed/ fields and methods
The syntax of overriding methods of super class from within its sub class.
How to access content of a class from another class of the same package and different
package.
The syntax of using class fields (both static and non-static) from within their class
and outside of their class.
The syntax of casting one reference variable to another.
Points to be remembered:
A class can inherit the properties and behavior of another class.
A class can implement multiple interfaces.
An interface can inherit zero or more interfaces. An interface cannot inherit a class.
Inheritance enables you to use existing code.
A class that inherits another class is called a derived class or subclass.
A class that is inherited is called a parent or base class.
Private members of a base class cannot be inherited in the derived class.
A derived class can only inherit members with the default access modifier if both the base class
and the derived class are in the same package.
A class uses the keyword extends to inherit a class.
An interface uses the keyword extends to inherit another interface.
A class uses the keyword implements to implement an interface.
A class can implement multiple interfaces but can inherit only one class.
An interface can extend multiple interfaces.
The method signatures of a method defined in an interface and in the class that implements the
interface must match; otherwise, the class won‟t compile.
An abstract class can inherit a concrete class, and a concrete class can inherit an abstract class.
With inheritance, you can also refer to an object of a derived class using a variable of a base
class or interface.
An object of a base class can‟t be referred to using a reference variable of its derived class.
When an object is referred to by a reference variable of a base class, the reference variable can
only access the variables and members that are defined in the base class.
When an object is referred to by a reference variable of an interface implemented by a class, the
reference variable can access only the variables and methods defined in the interface.
You may need to access an object of a derived class using a reference variable of the base class
to group and use all the classes with common parent classes or interfaces.
Casting is the process of forcefully making a variable behaves as a variable of another type.
Keywords super and this are object references. These variables are defined and initialized
by the JVM for every object in its memory.
The reference always points to an object‟s own instance.
You can use the keyword this to refer to all methods and variables that are accessible to a class.
If a method defines a local variable or method parameter with the same name as an instance
variable, the keyword this must be used to access the instance variable in the method.
You can call one constructor from another constructor by using the keyword this. super, an
object reference, refers to the parent class or the base class of a class.
The reference variable super can be used to access a variable or method from the base class if
there is a clash of these names. This situation normally occ urs when a derived class defines
variables and methods with the same names as in the base class.
The reference variable super can also be used to refer to the constructors of the base class in a
derived class.
Lesson-6 Activity
Task-1: Given the following code for the Cat class, write the lines of codes which can display the
detail of the Cat object in the testing class, DisplayCatInfo.
package animals; package animals;
public class Cat { public class DisplayCatInfo {
private String name;
private String color; public static void main(String str[]){
public static final float SIZE = 3.56f; System.out.println("Here is the details of the
cat!!");
public Cat() { .
name = "shewit"; . //detail is left for you
color = "BlueWhite"; .
} .
System.out.println("Meew"); }
}
protected boolean isDomestic(){
return true;
}
}
Since name and color fields of the Cat class are both private fields, they cannot be accessed outside
of their class. For this reason, you must add public getter/setter methods for each of the private
methods inside of the Cat class , for example, as follows:
…
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
And then, you can access now the name and color of the Cat from within the class DisplayCatInfo
as follows:
Cat cat = new Cat();
System.out.println("The name of the Cat is: "+cat.getName());
System.out.println("The color of the Cat is: "+cat.getColor());
Since the the size field is public, you can access it directly by its name as follows:
System.out.println("The size of the Cat is: "+ cat.SIZE);
You can print the sound type of the cat simply by writing the following statement. Note that the
hasSound() is a public method. So, you can call from anywhere.
System.out.println(“The sound type of the cat is:”);
cat.hasSound();
The isDomestic() is a protected method and hence, you can call it from all classes of the same
package. Since the Cat and DisplayCatInfo are in the same package, you can use it by invoking it
inside of the DisplayCatInfo as follows:
System.out.println("Is cat demostic animal? "+cat.isDemostic());
Once you build the above code, compile and run it. You will see the following output:
Task-2: Repeat the above question (take-1 of this lesson) by composing the two classes in two
different packages and try to compile them. And finally analyze your observation ! And try to compile
them by correcting the possible errors.
Lesson-6 Exercise
1. Assume that you have two classes namely class A and B. Class B is the subclass of class A. Given
the following class definition for each of them, write the output by hand which can be obtained for
each of the cases given in the testing class, the HidingOverridingTesting class below, and at last,
compare your result with the actual system output after typing it on the editor. [Please report the
output you did by hand to your laboratory instructors].
System.out.println("k="+k);
System.out.println("this.k="+this.k);
System.out.println("super.k="+super.k);
System.out.println();
}
}
B b = new B();
b.displayContentOfB(); // case-A
System.out.println("b.k="+b.k); //case-B
System.out.println("((A)b).k="+ ((A)b).k);
System.out.println();
A a = b;
A x = (B)b;
System.out.println("casted x.i = "+x.i); //case-E
System.out.println("casted x.f() = "+x.f());
System.out.println("casted x.g() = "+x.g());
System.out.println("Casted A.g() = "+A.g());
System.out.println();
A y = new A();
System.out.println("Instance of A: y.i = "+y.i); //case-F
System.out.println("Instance of A: y.f() = "+y.f());
System.out.println("Instance of A: y.g() = "+y.g());
System.out.println("Instance of A: A.g() = "+A.g());
System.out.println();
}
}
2. Assume that you have three classes namely Animal, Cat and Dog. Classes Cat and Dog are both
subclasses of class Animal. Write a java program which makes use of this classes, so that the
common properties of all animals should be written in the Animal class and specific charactertics
should be written in each of the subclasses as given below:
Class Animal {
Has name
Has color
Has sound
Is either domestic or wild
}
Class Cat {
Is an animal
Jumps to catch rats
Has its own unique sound …. Meeeew
Drinks cow milk
}
Class Dog{
Is an animal
Jumps to catch thieves
Has its own unique sound….. Woooow
beats thieves leg
}
Objective: at the end of this laboratory session, you will be able to:
write a java program which the polymorphism concepts
write a java program which implements the abstract class and interfaces you learnt in class.
write code analysis by hand based on the theoretical concepts of abstract classes and
interface discussed in class. Finally, compare your output with the output of the machine.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The polymorphic nature of reference variables and methods in java.
The syntax and semantics of writing overridden methods in subclasses
The syntax and semantics of writing overloaded methods in classes
The syntax and semantics of writing abstract classes.
The difference between concrete class, abstract class and interface
The syntax and semantics of implementing interfaces by their sub classes
The syntax and semantics of abstract methods
The difference between abstract methods and non-abstract class in java.
When implementing polymorphism with interfaces, a method defined in the base interface is
always abstract.
A class can inherit zero or one class.
A class uses the keyword extends to inherit a class.
A class can implement multiple interfaces.
A class uses the keyword implements to implement an interface.
An interface can‟t implement any class.
An interface can inherit zero or more interfaces.
An interface uses the keyword extends to inherit interfaces.
An abstract class can extend a concrete class and vice versa.
An abstract class can implement interfaces.
An abstract class can extend another abstract class.
The first concrete class in the hierarchy must supply actual method imp lementations for all abstract methods.
Lesson-7 Activity
Task-1: Write a java program which does fulfill the following description:
has an interface Humanity which provides two methods:
o String eatLunch();
o String goesToToilet();
has an interface Nature which provides one method:
o String hasNaturalLawGiven();
has an abstract class Person which contains:
o fields: firstName, secondName, id, telNo, sex, age;
o method: abstract String hasAgeCatagory();
has a concrete class PolyStudents which implements the Humanity and Nature interfaces
and extends the Person class. It also contains its own:
o fields:
Field name Data type Possible values of the field
siniorityStatus String Fresh, sophomore, junior, senior
semesterStatus String Failed, Warning, Promoted
dailyReadingHours int [1-24]hours
o methods:
Prepared by: Desta Berihu Weldegiorgis Page 48
Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
Abstract class Person can contain static/non-static fields, constructors and methods similar to concrete
class PolyStudent.
The keyword this on line-17 is refereeing the current instance (object) of the class. It is the default
reference variable to instance of the given class.
The method this() on line-22 is a constructor call. It invokes a constructor in this class with exactly the
same number of parameters to the arguments in the call. In this case, it is invoking the constructor given
from line-16 to line-20.
Notice the repetition of the identifier id in line-19. The one to the left side of the assignment operator is the
field id declared on line-12. And the other to the right side is the parameter variable declared on line-16 as
one of the parameters in the constructor. Now, if you want to give a local variable (parameter variable) name
as a field name, prefix the field with the reference variable this as what is given in this line.
Line-30 is showing that the concrete class PolyStudent is sub-classing the abstract class Person and
implementing the interfaces Humanity and Nature. Notice the order!! Extending a class should come
first and then implementing interfaces is followed, if there is any.
Class PolyStudent is implementing all abstract methods (un-implemented methods) of the interfaces and
abstract class that it has inhered. Accordingly,
o Line-43 to line-48 is the implementation of the abstract methods in the interface Humanity.
o Line-49 to line-51 is the implementation of the abstract method of the interface Nature.
o Line-52 to line-54 is the implementation of the abstract method of the class Person.
Class PolyStudent has a total of nine fields (s ix of them inherited and three of them are declared in its
body). Notice: inheriting means „making one‟s own‟!
The equals() method in line-56 is used to compare equality of objects in content. This method is applied
only to compare objects and not primitive values.
The operator = = is used to compare only primitive values. This operator is not applied for comparing
equality of objects. But still, we can use to test if reference variables are referring to the same object.
The methods on line-55, line-68 and line-74 are defined with the same name but different in number and
type of parameters. For this reason, they are said to be overloaded methods.
Given the above code, the following statements are valid.
o PolyStudent ps = new PolyStudent ("Nigus", "Solomon", "980BC", "+251913567789", 'M', 26); // or
o Person p = new PolyStudent("Nigus","Solomon","980BC"); // or
o Nature n = new PolyStudent("Solomon","Dawit","1000BC"); //or
o Humanity h = new PolyStudent("Yohannis","Zekarias","20AD"); //or
o Humanity h = ps;
....
አዋጅ አዋጅ አዋጅ! ከረቂቅ ምድብ (abstract class) እና ከመጋነኛ ምድብ (interface) አካሌ (object) መፍጠር አይቻሌም። ኣካሌ
Task-2: At last, write a public class StudentBehaviour which contains the main() method to display the
student profile and behavior by creating instances of the other classes defined above. The output should
contain but not limited to:
The natural behavior of a person labeled as student
The humanity behavior (eating, going to toilet,..) of all persons labeled as student.
All possible natural laws given to persons labeled as student.
The age category of persons labeled as student.
Detailed profile of a student and his/her behavior determinations, etc.
Lesson-7 Exercise
1. the following program, answer the questions following it:
/** Interface DisplayObject ****/
interface DisplayObject{
String showInfo();
void displayInTabular();
}
interface YeguaroAtkilt{
//String hasTest(YeguaroAtkilt yag);
boolean hasTest();
String hasColor();
}
System.out.println(biru); 6
7
System.out.println("Birtukan always does have seed? : "+hasSeed(biru));
System.out.println("Is black Birtukan sweet?"+isSweet(biru)); 8
Objective: at the end of this laboratory session, you will be able to:
write top-level classes and inner classes to model the has-a composition relationship of objects.
make code analysis by hand based on the concepts of how to write inner classes discussed in class.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The type of inner classes in java
The syntax and semantics of all the four inner classes in java
Points to be remembered:
Java supports four types of nested classes: static nested classes, inner classes, local inner classes,
and anonymous inner classes.
Static nested classes may have static members, whereas the other flavors of nested classes can‟t.
Static nested classes and inner classes can access members of an outer class (even private
members). However, static nested classes can access only static members of outer class.
Local classes (both local inner classes and anonymous inner classes) can access all variables
declared in the outer scope (whether a method, constructor, or a statement block).
Pictorially,
Lesson-8 Activity
Task-1: Compose, compile and run the following code.
Lesson-8 Exercise
1. Given the following program, identify all the source of the errors. Fix all the possible errors.
Finally, tell the output of the program. [Please know that this program is not the implementation
of the above class diagram.]
1 package employees;
2
3 public class Employee {
4
5 private String firstName, secondName,id;
6 private char sex;
7
8 public Employee(String firstName, String secondName, char sex){
9 this.firstName = firstName;
10 this.secondName = secondName;
11 this.sex = sex;
12 }
13 public String getFirstName(){
14 return firstName;
15 }
16 public String secondName(){
17 return secondName;
18 }
19 public char getSex(){
20 return sex;
21 }
22
23 private class Address{
24 private int kebele;
25 final int POB = 1176;
26 private String woreda;
27 public Address(int kebele, String woreda){
28 this.kebele = kebele;
29 this.woreda = woreda;
30 }
31 public String getWoreda(){
32 return woreda;
33 }
34 public int getKebele(){
35 return kebele;
36 }
37 public static void main(String[] str){
Objective : at the end of this laboratory session, you will be able to:
Understand and identify exceptions arising in code
Determine how exceptions alter the normal program flow
Understand the need to handle exceptions separately in your code
Use try-catch-finally blocks to handle exceptions
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The definition of exception in java.
The difference between checked exceptions, runtime exceptions and errors
The exception handling model in java
The syntax and semantics of declaring and throwing an exception
The syntax and semantics of try...catch…finally contract
The syntax and semantics of try-with resources contract.
A try block may be followed by either a catch or a finally block or both. But a finally
block alone wouldn‟t suffice if code in the try block throws a checked exception. In this case,
you need to catch the checked exception or declare it to be thrown by your method. Otherwise
your code won‟t compile.
The try, catch, and finally blocks can‟t exist independently.
The finally block can‟t appear before a catch block.
A finally block always executes, regardless of whether the code throws an exception.
Lesson-9 Activity
Task-1: Write a java program which accepts the mass „M‟ of an object and the force „F‟ exerted by that object
and then displays the acceleration „A‟ of the object. The program should handle the exception such
as accepting incompatible data and dividing a number by zero. [Hint: use A = F/M formula to
calculate the acceleration].
Here below is the answer to the above task.
When you compile and run the program by feeding the indicated input, then you will see the following output:
Task-2: Write a Java program which accepts an array of numbers from a keyboard and:
i. sorts it in ascending order and then, displays it to the consol.
ii. displays 1/n, for all n elements of the array.
Lesson-9 Exercise
1. Given the following java program, answer each of the questions following under each case.
1 import java.util.*;
2 public class OOPCSE3rdTutotialExceptionExercise {
3 public static void main(String str[]){
4
try{
5 int co = (new java.util.Scanner(System.in)).nextInt();
6 go(co);
7 System.out.println("Respect others for to live with the other! Go!");
8 System.out.println("Abstaining to something not allowed is at the focal of humanity!");
9 }
10 catch(InputMismatchException ext){
11 System.out.println("Obey to the rules of the university to get trained in it!");
12 }
13 }
14 public static void go(int comp){
15 String str = "Be clever!";
16 try{
17 moveOneStep(str);
18 System.out.println("moving one step up at a time is symptom of growing!");
19 System.out.println("You can reach at a stage you need to hold on!"+ comp);
20 }
21 catch (ArithmeticException e){
22 System.out.println("Hey, you encoutered error!"+e);
23 }
24 }
25 public static void moveOneStep(String msg)throws ArithmeticException, InputMismatchException{
26 try{
27 int z = (new java.util.Scanner(System.in)).nextInt();
28 z = (z*z+12)/z;
29 System.out.println("go up high to hold it and u will be great and calm!"+z);
30 jumpToPick(msg+" and hold your goal on");
31 }
32 catch (InputMismatchException fail){
33 System.out.println("If not, you may not do it ever again on the future!"+fail);
34 }
35 catch (NumberFormatException fail){
36 System.out.println("If not you try to go up just now, you may not do it ever agin!"+fail);
37 }
Case 1: When the number inserted from keyboard in line #5 is 100 and in line # 27 is 50:
a) What is the output of the program?
b) Which lines of each of the methods are executed and which are not?
Case 2: when the number inserted from keyboard in line #5 is xyz and in line #27 is 50:
a) What is the output of the program?
b) Which lines of each of the methods are executed and which are not?
Case 3: when the number inserted from keyboard in line #5 is 100 and in line #27 is xyz?
a) What is the output of the program?
b) Which lines of each of the methods are executed and which are not?
Case 4: when the number inserted from keyboard in line #5 is 100 and in line #27 is 0?
a) What is the output of the program?
b) Which lines of each of the methods are executed and which are not?
Objective: at the end of this laboratory session, you will be able to:
Design and implement different kinds of user interfaces using the Swing and AWT APIs.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The Swing and AWT APIs
The Swing and AWT components
Event handling mechanism in java
Layout managers
Line-46 to line-51 is also adding an event listener for the second button labeled as „Cancel‟.
The method setText() on line-48 and line-49 is used to rewrite (reset) the content of the text field or
password field to the value passed as an argument to it. Now, it is setting the two fields to empty string.
Line-52 and line-53 are adding the buttons to the container, i.e., the frame.
Line-56 to line-60 is the main() method.
Line-57 is creating the instance of the frame.
The setVisible() method on line-58 makes the frame visible or not. To make frame visible, this
methods takes „true‟ as its argument, and to make the frame false, it takes argument „false‟. This method is
also defined in the JFrame class and is one of the inherited methods by the class
UserAuthenticationFinal.
The setSize() method on line-59 is also inherited method of the JFrame and is taking two arguments
which specify the width and height of the frame to be displayed.
Task-2: Design the following user interface using java which determines the hunger status of a given
country by letting the user to enter የፖሇቲካ ዕድገት (polStat), ጂዱፒ (cgdp), የዕድገት ዯረጃ
(devpLevel), ዓመታዊ የዝናብ መጠን (rainFall), የሕዝብ ብዛት (populSize) and የዓመቱ የሰብሌ
ምርት መጠን (prevYearHarv) of the country. Your program should continuously accept the
status of six countries [Ethiopia, Kenya, Sudan, Djibouti, Eritrea, and Egypt], compare
them and finally display them in order of their hunger status in a tabular format. Try to use
the following computation formula for predicting the hunger level of each of the countries.
(polStat+devpLevel+rainfall+prevYearHarv)/(cgdp*0.1)*popuSize
Lesson-11 Exercise
1. [Simple calculator]: Design the following simple calculator and write an intensive program to
manipulate all the operations shown on the interface.
Objective: at the end of this laboratory session, you will be able to:
understand how 3-tire applications are designed and developed.
develop an application by implementing the MVC model.
connect java applications with database using the JDBC API.
Lesson Prerequisite:
Students! Before you sit for this lesson in the laboratory, make sure that you have studied:
The JDBC API. i.e., the classes and interfaces found in the package java.sql
The types of JDBC drivers and their role during program-database communication
The steps followed to connect java program with database
For standalone [desktop] applications, the user interface is developed using GUI components. These
interfaces can be installed separately in one machine, which usually is the client machine. The
business logic part is developed using any programming language [in our case, using java] and acts as
a middle tier between the user interface and the database. It accepts the user input from the client
[from the user interface] and does certain tasks [eg. validation and other computation tasks] and sends
them to the database. It can also query the database based on the user input from the interface and
returns the result of the query from the database back to the user in a formatted and understandable
way [e.g using tables and other output representation features]. The three tiers can reside on separate
computers that are connected to a network.
recommended to use the following much agreeable approach to design your systems: the so called
MVC design model.
Here is the idea of the model. The key point of using MVC is to separate lo gic into three distinct
units: the Model, the View, and the Controller. In a desktop application [in other application such as
dynamic web-based application too], we commonly classify the parts of the application as business
logic, user interface [presentation], and data source [e.g. database]. Business logic is the term used
for the manipulation of an application's data [answers the question what data does the application
has? How is it going to be processed or used; the basic algorithm of application which process the
input which comes from the interface and/or from the data source]. The user interface [presentation]
refers to how the application data is entered and/or displayed from/to the user [e.g, position of the
data, font, and size – the appearance of the output seen by the end- users]. And finally, data source
[database] is the backbone source of data of your application which can be manipulated by the
business logic tier. The business logic manipulates the database by insert/update/delete or search data
to/from it. In MVC terms, the Model corresponds to business logic, the View to the user interface,
and the Controller to the data source.
This method takes a string representing a fully qualified class name (i.e., one that includes package names) and
loads the corresponding class. This call could throw a ClassNotFoundException , so should be inside of a
try/catch block. Here is an example:
NB: Method getConnection() throws an SQLException, so you need to use a try/catch block.
d. Create a Statement
A Statement object is used to send queries and commands to the database and is created from the
Connection instance as follows:
Statement statement = con.createStatement();
e. Execute a Query
Once you have a Statement object, you can use it to send SQL queries by using the executeQuery method,
which returns an object of type ResultSet. Here is an example:
String query = "SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet = statement.executeQuery(query);
አስተውሌ፡To insert, update and delete a data to/from a database use execute() instead of executeQuery(),
and supply a string that is used to insert a single row to a database table.
The simplest way to handle the results is to process them one row at a time, using the ResultSet‟s next()
method to move through the table one row at a time. Within a row, ResultSet provides various getXxx
methods that take a column index or column name as an argument and return the result as a variety of different
Java types. For instance, use getInt if the value should be an integer, getString for a String, and so on
for most other data types. If you just want to display the results, you can use getString regardless of the
actual column type. However, if you use the version that takes a column index, note that columns are indexed
starting at 1 (following the SQL convention),
not at 0 as with arrays, vectors, and most other data structures in the Java programming language.
while(resultSet.next()) {
System.out.println(results.getString(1) + " " +
results.getString(2) + " " + results.getString(3));
}
In addition to the getXxx and next methods, other useful methods in the ResultSet class include
findColumn (get the index of the named column), wasNull (was the last getXxx result SQL NULL?
Alternatively, for strings you can simply compare the return value to null), and getMetaData (retrieve
information about the ResultSet in a ResultSetMetaData object).
The getMetaData method is particularly useful. Given only a ResultSet, you have to know about the name,
number, and type of the columns to be able to process the table properly. For most fixed-format queries, this is
a reasonable expectation. For ad hoc queries, however, it is useful to be able to dynamically discover high-
level information about the result. That is the role of the ResultSetMetaData class: it lets you determine the
number, names, and types of the columns in the ResultSet. Useful ResultSetMetaData methods include
getColumnCount (the number of columns), getColumnName(colNumber) (a column name, indexed starting
at 1), getColumnType (an int to compare against entries in java.sql.Types ), isReadOnly (is entry a
read-only value?), isSearchable (can it be used in a WHERE clause?), isNullable (is a null value
permitted?), and several others that give details on the type and precision of the column. ResultSetMetaData
does not include the number of rows, however; the only way to determine that is to repeatedly call next on
the ResultSet until it returns false.
You should postpone this step if you expect to perform additional database operations, since the overhead of
opening a connection is usually large.
This is the user interface which is developed using NetBeans IDE. Now, when the fields in this form are filled
with an appropriate data and the button „መዝግብ’ is clicked, the data will be passed to the business logic part for
validation and processing purpose, and further to be stored to the database.
The following is the business logic which does the aforementioned functionalities.
From the above code, you can see that the business logic is communicating with a database designed using MS
SQL Server with line of codes under the method createConnection().
1. Adding the JDBC driver. To do this, go to the services menudatabase node righ-click on the
Drivers sub-node.
2. We then need to select a JAR file containing the JDBC driver for our RDBMS, NetBeans guesses
the name of the driver class containing the JDBC driver. If more than one driver class is found in
the JAR file, the correct one can be selected from the drop down menu labeled Driver Class. We
need to click on the OK button to add the driver to NetBeans.
For our case, I have added the JDBC driver for the MS SQL Server. [ sqljdbc4-2.0.jar is a jar file
which contains the JDBC Driver for the SQL Server and it is freely available on the internet.]
By doing this, our new JDBC driver is displayed in the list of registered drivers as is given below.
3. Right click on the newly added (i.e., your own) driver and then click on Connect Using... on the
resulting popup menu.
4. Then we need to enter the JDBC URL, username, and password for our database.
አስተውል :- ከላይ እንደተመለከተው የግንኝነት መረጃ በአግ ባቡ ከሞላህ/ሽ በኃላ ‘Test Connection’ የሚለውን
እርካብ (Button) ጨቁን። ይህንን ካደረግህ/ሽ በኃላ ከላይ በምስሉ ላይ እንደሚታየው „Connection
Succeeded.‟ የሚሌ የግንኙነት ማረጋገጫ መሌእክት ከታየህ ግንኝነቱ በአግባቡ ተመስርቷሌ ማሇት ነው።
Once you fill the necessary details for the connection as depicted on the screenshot above, test the
connection by clicking the button „Test Connection’. If you see the confirmation message
„Connection Succeeded‟ as shown in the above shot, then it means the connection is established
successfully.
Then, it means the connection is not established. The reason for this may be beca use of DBMS
service is not started. Or the TCP for the JDBC is disabled. And the default TCP port is not set.
Now, go through the following techniques to get around the problem:
Open the „SQL Server Configuration Manager‟ of the SQL Server from the start menu.
Navigate to the „SQL Server Network Configuration’ node
Enable all the protocols of the server.
Right-click on the TCP/IP prope rties IP Addresses tab roll down to the end of the
dialog box and find the IPAll entry and set the TCP Port of this entry to 1433.
N.B: Note that 1433 is the default port number for the MS SQL Server.
5. After clicking on the Next button, NetBeans may ask your to select a database schema.
For our case, use the dbo (to mean database object) schema. After selecting the schema and
clicking on the Next button and then Finis h button, our database is shown in the list of databases
6. We can connect to it by right-clicking on it, selecting Connect from the resulting pop up, then
entering our username and password for the database (we can choose not to allow NetBeans to
"remember" the password when we add the database) as shown below.
StudentCourse
Course courseCode
courseCode
sId
courseTitle
room
credit
gpa
TeacherCourse
tId Student *
Teacher
courseCode id
id
semester firstName
firstName
room lastName
scondName
department
department
age
position
sex
2. Now, change the desktop application you developed for #1 above to web-based
application by touching only the interface /the View part/ and the business logic
/Controller part/ so that:
a. The interface of the application will be developed using HTML, CSS and
JavaScript and Java Server Pages.
b. All your business classes will be Java Bean classes.
c. You may add again some utility classes /actually, Java servlets/ for user data
validation, page navigation manipulation.
[For this part, you can use Java server Faces- JSF mainly for the interface development]
References:
1. Herbert Schildt. Java the Complete Reference. Eighth Edition. McGraw-Hill companies. 2011.
2. Kishori Sharan. Beginning Java 8 Fundamentals. Language Syntax, Arrays, Data Types, Objects
and Regualr Expressions. Apress. 2014.
3. Kishori Sharan. Beginning Java 8 Language Features: Lambda Expressions, Inner Classes,
Threads, I/O, Collections and Streams. Apress. 2014.
4. S.G. Gandesh, Tushar Sharma. Oracle Certified Professional Java SE 7: Comprehensive OCP
JP7 Certification Guide. Apress, 2014.
5. Mala Gupta. OCA Java SE 7 Programmer I Certification Guide. Manning, 2014. www.it-
ebooks.info
6. Kathy Sierra, Bert Bates. OCA/OCP Java SE 7 Programmer I & II Study Guide. McGraw-Hill
Education. 2015.
7. Richard M. Reese. Oracle Certified Associate, Java SE 7 Programmer Study Guide. Packt
Publishing. 2012.
============================//END//=========================