Laboratory Manual For OOP - Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 84

Bahir Dar University

Bahir Dar Institute of Technology


Faculty of Computing

Laboratory Manual
for
Object-Oriented Programming (Java)

Prepared By: Desta Berihu (MSc.)


Reviewed By: Workneh Chekol (MSc.)

Sept. 2009 E.C


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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

Prepared by: Desta Berihu Weldegiorgis Page 2


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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

Prepared by: Desta Berihu Weldegiorgis Page 3


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Prerequisite for all the laboratory lessons:


 Knowing the naming conventions in java
 Knowing the syntax and semantics of the basic programming
elements in Java. These are:
o Identifier, variable, keyword, comment, data type, operator,
constant, literal, expression and statement.
 Knowing the syntax and semantics of the basic programming
contracts in Java. These are:
 Conditional statements [if, switch],
 Jumping keywords[break, continue, label]
 Loops [for, while, do while and for each]
 Understanding the syntax and semantics of arrays and methods
(functions) in java.
 Understanding Strings in java.

Prepared by: Desta Berihu Weldegiorgis Page 4


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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

Prepared by: Desta Berihu Weldegiorgis Page 5


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

deep-rooted understanding on the implementation of the object-oriented programming paradigm with


Java.

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.

Introduction: Basic Terminologies in Java programming language


Alike to natural languages, formal languages do also have their own glossary. As one of the formal
languages, Java has its own basic terminologies and definitions. To this end, Java students ought to
understand the exact meaning and/or concept of the following common programming terminologies. I
have tried to put some Amharic statements hopping that they may help the students better understand
the concepts clutched under each terminology.

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:

Fig-1: Content of a computer program

ከሊይ የምናየው ቀመር (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.

Prepared by: Desta Berihu Weldegiorgis Page 7


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

አንድ ዓይነት መገሇጫዎች (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/ የሚታይ
እና የሚተረጏም አይዯሇም።

// this is a single comment


/* */ is the multiline comment in Java.
Variable /የዲታ መያዣ/:- is a named memory location in which a program can store intermediate results
and from which it can read them for use.

ይህ የዲታ መያዣ ነው። ሇጊዜው የሚይዘው ዲታ ስሇማይታወቅ ተተኪ /variable/ ተባሇ። ማንኛውም የኮምፒዩተር ቀመር የሚሰራው
ዲታ ሊይ ነው። ቀመሩ ዲታውን ጠቃሚ መረጃ (information) እስኪሆን ድረስ የማቀነባበር፣ የማዯባሇቅ፣ የማንዯባሇሌ፣ የመቀመር ወዘተ
ስራ ይስራሌ። ታዱያ ዲታው የሚያገኘው ከኪ ቦርድ፣ ከኔትዎርክ፣ ከራሱ ሃርድ ዱሰክ መዛግብት ወዘተ ሉሆን ይችሊሌ። ይህ ዲታ ቀመሩ

Prepared by: Desta Berihu Weldegiorgis Page 8


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

ሉጠቀምበት በሚችሌ መሌኩ የሚቀመጠው ዯግሞ በዲታ ማስቀመጫዎች (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

Prepared by: Desta Berihu Weldegiorgis Page 9


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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) በማዕቀፍ
ቅንፎች /{….}/ የተከበበው ዋና ሰውነቱ ነው።

የመሌስ ዓይነት (return type)፡- አስላው ስላቱን ሰርቶ


የሚመሌሰው መሌስ፣ የመሌሱ ዓይነት የሚገሌፅ ነው።
የአስላው ስም (method name)፡- የአስላው ስያሜ ነው።
ማንኛውም መሇዮ (identifier) መሆን ይችሊሌ።
የስላት ግብአት (method parameter)፡- አስላው
ሇሚያካሂዯው ስላት የሚወስዯው ግብአት ማሇት ነው። ነገር ግን
አስላው ግብአት ሳይወስድም መስራት ይችሊሌ።

Identifier /መሇዮ/:- Identifier is a formal name used in source code to refer to a variable, method,
class, package, etc.

የኮምፒዩተር ቀመር ፀሓፊው በቀመሩ ውስጥ የሚፅፋቸው ማንኛውም የዲታ መያዣ፣ የአይቀየሬ፣ የዲታ ዓይነት፣ የአስላ ወዘተ ስሞች ‘መሇዮ’
እንሊቸዋሇን። መሇዮዎች በምንፅፍበት ጊዜ እንዯ የኮምፒዩተሩ ቋንቋ የምንከተሊቸው ሕጎች አለ። በ ጃቫ ሁሇት ሕጎች አለን። ማንኛውም
መሇዮ በፊዯሌ ወይም በግርጌ ጭረት(underscore) ብቻ መጀመር አሇበት። ከመጀመርያው ቀጥል የሚፃፉት ሦስት ነገሮች [ማሇትም
ፊዯሊት፣ቁጥሮች ወይም የግርጌ ጭረት] ብቻ ናቸው።
ሇምሳላ፡

Prepared by: Desta Berihu Weldegiorgis Page 10


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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 ይባሊለ።

Object /አካሌ/:- Object, in object-oriented programming, is an instance of a class. An object comprises


data and methods that act on the data, and is treated as a discrete entity. Entity is anything in the
physical world that can be described by its attributes and behaviors (activities).

በሰው ዘንድ በገሃደ ዓሇም ህሌውናውን የታወቀ፣ በሰው ቋንቋ ሉገሇፅ የሚችሌ ቁስ አካሌ ወይም ተጨባጭ ነገር ነው።

Prepared by: Desta Berihu Weldegiorgis Page 11


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Real world Object or Entity /R o/


በግሃደ ዓሇም የምናውቃቸው ነገሮች ስም አሊቸው። በቋንቋ ስንገሌፃቸውም በ ሁሇት ነገሮቻቸው ነው። ይሄውም
በመገሊጫዎቻቸው/attributes/ እና በተግባሮቻቸው /behaviors/ ብቻ ነው። ሇምሳላ፡- ተማሪ አንድ ግሃድ ነገር
/real entity/ ነው። ስሙ ተማሪ ነው። መገሊጫዎቹም ዕድሜ፣ መታወቂያ ቁጥር፣ ውጤት፣ ት /ት ክፍሌ፣ ወዘተ
ናቸው። ተግባራቱም ማንበብ፣ ሪፓርት መፃፍ፣ መመራመር፣ መብሊት፣መተኛት፣ መማር፣ ወዘተ ናቸው።

Re al world Object / entity

(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) መፍጠር ይቻሊሌ።

String /ፅሑፍ/:- String is sequence of characters.

የቀሇሞች ስብስብ ነው። ባዶ ወይም አንድ ወይም ከአንድ በሊይ ቀሇሞች ሉይዝ ይችሊሌ።

Field /መገሇጫ/:- is a variable associated with an object or class. የአንድ ኣካሌ (object) መገሇጫ ነዉ።

Prepared by: Desta Berihu Weldegiorgis Page 12


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-1. Setting up your Java development environment in your computer


and writing, compiling and running simple java programs

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

Task-1:- Install and configure the Java platform in your computer.

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:

i. By writing the following statement in the command prompt:


C:\> set JAVA_HOME= C:\Program Files\Java\jdk1.6.0_06

Prepared by: Desta Berihu Weldegiorgis Page 13


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

ii. Right click on My ComputerPropertiesAdvanced System SettingsEnvironment


Variables; in the system variables part click New button and then write JAVA_HOME in the
variable name field and C:\Program Files\Java\jdk1.6.0_06 in the variable value. Click
OK on the path edit box and OK on the Environment Variables box. The new setting will
go into effect next time you run Command Prompt.

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.

Prepared by: Desta Berihu Weldegiorgis Page 14


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Code analysis on the above program


 In Line-1:
 public :- is a keyword used to indicate that the class OopStudBiT can be accessed publically by
any class from anywhere.
 class:- is a keyword used to declare a class in java.
 OopStudBiT: - is the name of the class. It can be any legal identifier with one or group of words.
 In line-2:
 public :- tells that the main method can be called from within the class or anywhere outside of the
class.
 static:- tells that the method is associated with its class and not with the instances of its class.
 void:- is the return type of the method. It means that the method returns nothing.
 main:- is the name of the method.
 ():- these brackets are method markers. They are used to indicate the input (parameters) of the
method.
 String:- is the built- in class in the java library which represents collection of characters. It is found
in the package java.lang
 [] :- is an array marker. Now, see that the main() method takes array of strings as an input (as its
parameter).
 ethiopia:- is name of the reference variable of the parameter array.
 In line-3:
 String :- is a class name. Classes are data types in java. So, it is the data type of the variable
firstName.
 firstName:- is reference variable name. It is user defined name. It can be any words but should be
legal identifier.
 = :- is the assignment operator. It is assigning the value in the right of it to the variable to the right
side of it.
 "Yohannes":- is a string literal. It is being assigned to a string variable on the left of the
assignment operator.
 ;(semicolon) :- is end of statement marker. In Java, all simple statements end with a semicolon.
 In line-4:
 This is the same as what is in line-3. So, try to understand it as what is there in line-3.

Prepared by: Desta Berihu Weldegiorgis Page 15


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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:

public class OopStudBiT


{
public static void main(String[] args)
{
System.out.println("OOP, BiT-SCEE!");
}
}

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.

Prepared by: Desta Berihu Weldegiorgis Page 16


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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!!”);

Prepared by: Desta Berihu Weldegiorgis Page 17


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
}

a) how many “I am learning Java” is printed? _________


b) how many “I found it simple, portable and secured!!” is printed? ________

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.

Prepared by: Desta Berihu Weldegiorgis Page 18


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

How to accept input from the keyword?

The following are some of the ways that Java offers us to accept input from a standard input device,
the keyboard.

a) Using the Scanner class


One of the strengths of Java is the huge libraries of code available to you. This is code that has been
written to do specific jobs. All you need to do is to reference which library you want to use, and then
call a method into action. One really useful class that handles input from a user is called the
Scanner class. The Scanner class can be found in the java.util library. To use the Scanner
class, you need to reference it in your code. This is done with the keyword import.

import java.util.Scanner;

The import statement needs to go just above the Class statement:


import java.util.Scanner;
public class StringVariables
{

}

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.)

To create a new Scanner object the code is this:


Scanner userInput = new Scanner( System.in );

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).

Prepared by: Desta Berihu Weldegiorgis Page 19


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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:

String firstName; የቴክኖልጂ ትምህርት በኢትዮጲያኛ ብንማረውና ብንረዲው፣


በኢትዮጲያኛ ብንተነትነው፣ ሇኢትዮጵያ እናውሇዋሇን!
firstName = userInput.next( );
So after our userInput object we type a dot to access all instance fields and methods of the
Scanner class.
String firstName ;
System.out.print("Enter your first name: ");
firstName = userInput.next();
Notice that we've used print rather than println like last time. The difference between the two is
that println will move the cursor to a new line after the output, but print stays on the same line.

We'll add a prompt for a second name, as well:


String secondName;
System.out.print("Enter your family name: ");
secondName = userInput.next( );

This is the same code, except that java will now store whatever the user types into our secondName
variable instead of our firstName variable.

To print out the input, we can add the following:


String full_name;
full_name = firstName + " " + secondName;
System.out.println("You are " + full_name);

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:

Prepared by: Desta Berihu Weldegiorgis Page 20


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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 program then moves on to the next line of code:

Type a second name, and hit the enter key again:

Prepared by: Desta Berihu Weldegiorgis Page 21


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

b) Using the JOptionPane class

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:

And message boxes like this:

Prepared by: Desta Berihu Weldegiorgis Page 22


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Let‟s see the change to our program above when we use JOptionPane class for accepting an input:

The first thing to do is to import the library/package we want to use:


import javax.swing.JOptionPane;

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");

Join the two together, and add some text:

Prepared by: Desta Berihu Weldegiorgis Page 23


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
String full_name;
full_name = "You are " + first_name + " " + second_name;

To display the result in a message box, add the following:

JOptionPane.showMessageDialog( null, full_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:

Prepared by: Desta Berihu Weldegiorgis Page 24


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

After you click OK, the message box will display:

Click OK to end the program.


Lesson-2 Activity

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.

Fig-2. Sample code for lesson-2

Now, when you compile and run the above program, you will see the following output.

Prepared by: Desta Berihu Weldegiorgis Page 25


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Code analysis on fig-2 above


 Line-1:- is the package statement. It is declaring the name of the package in which the byte code of
the class resides. Java‟s package means simply folder or directory, where the byte code file (the
.class file created after compilation) resides. In this statement:
 package :- is the keyword used to define the name of the package.
 shapes:- is the name of the package
 Line-3:- is an import statement. It is importing the Scanner class found in the package
java.util to our code so that we can make use of its members. In this statement:
 import:-is a keyword used to include (to bring in) a class in found in another package to
our source code. It is equivalent to the keyword „include‟le of C++.
 java:- is a name of a package (folder) where the subfolder util is found in.
 util:- is a name of a sub-package (subfolder) found under the java package.
 Scanner:- is the name of the wanted built- in class found in the indicated path.
Altogether, we can say that it is the path in the file system of the computer where the wanted class (in
this case, the Scanner class) resides in. Its equivalent windows path writing style is
java\util\Scanner.
 Line-5 :- is the declaration of the class that its name is Circle. Starting from line-5 down to line-
35 is the definition of the class. This class contains two fields (line-6 and line-7), one constructor
(line-9 to line-11), and two methods (line-12 to line-14 and line-16 to line-34). Mind you that
fields and methods are the only two logical members of a class.
 Line-24:- is instantiating (creating) an instance (an object) from the Scanner class. The new
keyword is used to create an object from a given class.
 Line-27:- is accepting a double value input from the keyword using the instance method
nextDouble() of class Scanner. Since the nextDouble()is an instance method, it should be
preceded by the name of its instance where it is found in.

Prepared by: Desta Berihu Weldegiorgis Page 26


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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");

2. For your Message boxes try this:


showMessageDialog(null, full_name, "Name", JOptionPane.INFORMATION_MESSAGE);

3. Instead of JOptionPane.INFORMATION_MESSAGE try these:


ERROR_MESSAGE
PLAIN_MESSAGE
QUESTION_MESSAGE
WARNING_MESSAGE

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?

የዚህ መሌመጃ ጕርሻ [tip]:


You have to use the String variable to get your numbers from the user:
String breadth;
breadth = JOptionPane.showInputDialog("Rectangle Breadth");

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.

Prepared by: Desta Berihu Weldegiorgis Page 27


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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);

For the message box, use concatenation:


"answer = " + area

You can use any of the MESSAGE symbols for your message box.

Lesson-3. Writing simple object-oriented programs with Java

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.

Important points to remember:


 Class is a template to create an object. Many objects can be created from the same class.
Object created from the same class are said to be „objects of the same type‟.
 Class is a reference data type. For this reason, the variable declared using a class is called
reference variable.
 An object is created /instantiated/ from its class using the „new‟ operator.
 Reference variable stores the reference of the object and not the object itself.

Lesson-3 Activity
Task-1:- Write a java program which adds even numbers between 0 and any positive integer number
given by the user.

Here below is the code to the above program.

Prepared by: Desta Berihu Weldegiorgis Page 28


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Task-2:- Write an object-oriented program which computes:


a. area of triangle after the user has entered its height and base.
b. area of triangle after the user has entered the three sides of triangle.
c. area and circumference of a circle.
d. volume and surface area of a sphere given radius of the sphere. [Note that volume =
¾π(radius)3 and area = 4π(radius)2 . Take π to be 3.14159265]
Task-3:- Write an object-oriented program which receives list of numbers and display the largest
number.

Lesson-3: Exe rcises


1) Write a java program which finds the average, maximum, minimum, and sum of three numbers
given by the user.
2) Write a java program which accepts radius of a circle and displays its area.
3) Write a java program which reads 10 integers from the keyboard in the range 0 - 100, and count
how many of them are larger than 50, and display this result.
4) Write a java program which takes an integer from the user and display the factorial of that
number.
5) Write a java program which accepts a number and compute square root of the number
6) Write a java program which accepts three numbers x, y and z and compute the following
algebraic expression
Prepared by: Desta Berihu Weldegiorgis Page 29
Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
2𝑥 +𝑦
a. 𝑟𝑒𝑠𝑢𝑙𝑡 =
𝑧−2

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

Prepared by: Desta Berihu Weldegiorgis Page 30


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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

14) Write a java program which displays the following shapes:

a) b) c) d) e)
A *
A Bc ** ****** *
AB Def *** ***** ***
ABC Gehi **** **** *****
ABCD Jklmn ***** ***
*******
ABCDE Opqrst ****** **
ABCDEF *********
*
***********

15) How do you read/ write data from/to a variable?


16) How do you read/write data from/to an array?
17) How do you read/write data from/to an object?

Lesson-4. Further on working with java objects

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.

Important points to be remembered:


 One instance/object of a class means one being or one reality of that category, i.e the class. Now, we can
have as many instances /objects from the same class. We can store these instances in an array of the type
the class.
 An array in Java is treated as an object, and hence, should be created and manipulated as an object.

To demonstrate these concepts, try to proceed with the following activity.


Prepared by: Desta Berihu Weldegiorgis Page 31
Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Prepared by: Desta Berihu Weldegiorgis Page 32


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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

//This is the constructor of the circle object


public Circle(double radius) {
this.radius = radius;
}

// This is the area instance method


public double area(){
return radius*radius*PI;
}

//This is the circumference instance method


public double circumference(){
return 2*PI*radius;
}
//This is the main method of the circle class
public static void main(String[] str){

/*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

from keyboard to double; */


double radi;

rad = JOptionPane.showInputDialog("Enter the radius of the circle?"); // now rad contains a


//string inputed from keyboard.
radi = Integer.parseInt(rad); // now radi contains an double equivalent of rad, which was a string.

// Step-2: creating an object from the class.


Circle c = new Circle(radi); // this is the syntax how to create an object.

// Step-3: displaying the content of the object created in step-2 above.


//you can display it to the consol (to the monitor) using the following syntax.
System.out.println("The radius of the circle is:" + c.radius);
System.out.println("The area of the circle is:" + c.area());
System.out.println("The circumference of the circle is:" + c.circumference());

//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());

//you can display it using the message dialog box as follows:


JOptionPane.showMessageDialog(null,"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

Prepared by: Desta Berihu Weldegiorgis Page 34


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Prepared by: Desta Berihu Weldegiorgis Page 35


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-5. Implementing Encapsulation Concepts

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.

To demonstrate these concepts, try to proceed with the following activity.


Lesson-5 Activity
Task-1: Write a program which models a book. A book has title, authorName, isbn and
price as its attributes as shown in the following UML-based class diagram:
Book
+ title : String
- authorName : String
- isbn : String
# price : double
-hasSoldAt():void
+getAuthorName() : String
+setAuthorName() : void
+getIsbn() : String
+setIsbn() : void

Prepared by: Desta Berihu Weldegiorgis Page 36


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Here below is the program to this task:

Prepared by: Desta Berihu Weldegiorgis Page 37


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Fig-3. Sample code for lesson-5

Prepared by: Desta Berihu Weldegiorgis Page 38


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Now, when you compile and run the above program, you find something like the following
output.

Code analysis on fig.3


 The first compartment in the class diagram was the name of the class. Now, it is mapped
in the code as indicated in line-5.
 The attributes in the class diagram are all mapped to fields in the class as indicated from
line-7 to line-10.
 The behaviors in the class diagram are all mapped to methods in the class as indicated
from line-19 to line-47.
 The +, - and # access control symbols in the class diagram are mapped to their java
equivalent public, private and protected access modifier keywords. They are
indicated from line-7 to line-10. This is also true for the methods.
 The data types of the attributes and method parameters are all mapped to Java
equivalents.
 Setters/ getters methods make sure whether a data is valid or not. This is also indicated
from line-31 and 47.
 In order to create an object of the Book class, a constructor with defined parameters is
needed. For this reason, constructor is added to the class starting from line -12 to line-17.
 The Scanner class is used to accept the input.

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?

Prepared by: Desta Berihu Weldegiorgis Page 39


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Prepared by: Desta Berihu Weldegiorgis Page 40


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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.

Prepared by: Desta Berihu Weldegiorgis Page 41


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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.

To demonstrate these concepts, try to proceed with the following activity.

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"; .

} .

public void hasSound(){ }

System.out.println("Meew"); }

}
protected boolean isDomestic(){
return true;
}
}

The output should contain:


 The name, color and size of the cat
 The sound type of the cat
 Whether this animal is demotic category!

Here below is the answer for the above question:

Prepared by: Desta Berihu Weldegiorgis Page 42


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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());

Altogether, the code should look like the following:

Prepared by: Desta Berihu Weldegiorgis Page 43


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Fig-6: Sample code for lesson-6

Once you build the above code, compile and run it. You will see the following output:

Prepared by: Desta Berihu Weldegiorgis Page 44


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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].

class A{ class B extends A{


protected int i=12, k=6; protected int i=10;

public int f(){ public int f(){


return i+=2; return i;
} }
protected int h(){ public static String g(){
return k*=k; return "This is the static method of B";
} }
public static String g(){ public void displayContentOfB(){
return "This is the staic method of A";
} System.out.println("i="+i);
} System.out.println("this.i="+this.i);
System.out.println("super.i="+super.i);
System.out.println("((A)this).i="+((A)this).i);
System.out.println();

System.out.println("k="+k);
System.out.println("this.k="+this.k);
System.out.println("super.k="+super.k);
System.out.println();
}
}

public class HidingOverridingTesting {


public static void main(String str[]){

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();

System.out.println("b.i = "+b.i); //case-C


System.out.println("b.f() = "+b.f());
System.out.println("b.g() = "+b.g());
System.out.println("B.g() = "+B.g());
System.out.println();

A a = b;

Prepared by: Desta Berihu Weldegiorgis Page 45


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

System.out.println("a.i = "+a.i); //case-D


System.out.println("a.f() = "+a.f());
System.out.println("a.g() = "+a.g());
System.out.println("A.g() = "+A.g());
System.out.println();

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
}

Prepared by: Desta Berihu Weldegiorgis Page 46


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-7. Polymorphism, Abstract class and Interfaces

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.

Important points to be re membered:

 The literal meaning of the word “polymorphism” is “many forms.”


 In Java, polymorphism comes into the picture when there‟s an inheritance relationship between
classes, and both the base and derived classes define methods with the same name.
 The polymorphic methods are also called overridden methods.
 Overridden methods should define methods with the same name, same argument list, same list of method
parameters. The return type of the overriding method can be the same, or a subclass of the return type of
the overridden method in the base class, which is also known as covariant return type.
 Access modifiers for an overriding method can be the same or less restrictive but can‟t be more
restrictive than the method being overridden.
 A derived class is said to override a method in the base class if it defines a method with the same
name, same parameter list, and same return type as in the derived class.
 If a method defined in a base class is overloaded in the derived classes, then these two methods
(in the base class and the derived class) are not called polymorphic methods.
 When implementing polymorphism with classes, a method defined in the base class may or may
not be abstract.

Prepared by: Desta Berihu Weldegiorgis Page 47


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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.

To demonstrate these concepts, go down to work out the following activity.

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

 getter and setters for all its fields


 beginBehaveAs(String seniorityStatus)
 beginBehaveAs(String seniorityStatus, String semesterStatus)
 beginBehaveAs(String seniorityStatus, String semesterStatus, int dailyReadingHours)

Factors combination Begin behaving as


Fresh Studies much, get serious for s/he joined BDU!
Sophomore Adapts the campus and saying I am this and that!
Junior Begins looking into his/her profile and thinks how to increase up grade!
Senior Begins thinking about the look like of his/her „finishing‟! And begins
simulating life after graduation!
Fresh, Failed S/he cries much, and graduates in January!!
Fresh, Warning, 18hrs Stops to give greeting to others for she/he get tensioned on
Sophomore, promoted, 16hrs Get proud of it and say “I am …!”. Do you know that I am … from my batch?
He prefer to have walk around the Alma, Summerland and St. George streets.
Junior, Failed, 23hrs …….
Senior , promoted, 16hrs ….
….

Here below is the code for the above task-1 question.

Prepared by: Desta Berihu Weldegiorgis Page 49


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Fig-7: Sample code for lesson-7


Code analysis on fig-7:
 Line-2 to line-5 and line-7 to line-9 are the Humanity and Nature interfaces, respectively.
 The methods in both of the interface classes are by default abstract methods.
 The keyword abstract is used to make a class and a method abstract as indicated in line-11 and line-27.

Prepared by: Desta Berihu Weldegiorgis Page 50


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) መፍጠር አይቻሌም። ኣካሌ

Prepared by: Desta Berihu Weldegiorgis Page 51


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

(Object) መፍጠር የሚቻሇው ከተጨባጭ ምድብ (concrete class) ብቻ ነው።


 So, one way of implementing polymorphism is the possibility of referring to an object of the sub-class by a
reference variable declared with the super class in addition to the ordinary one (i.e., referring an object of the
class by a reference variable of its own type.)

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 ****/

interface YeguaroAtkilt{
//String hasTest(YeguaroAtkilt yag);
boolean hasTest();
String hasColor();
}

/** Abbstract class FiraFire ****/

abstract class FiraFire{


protected String name, color, test;
protected int seedNumber;
public FiraFire(){
;
}

public FiraFire(String name, String color, String test, int seedNumber){


this(name,color, test);
this.seedNumber = seedNumber;
}

Prepared by: Desta Berihu Weldegiorgis Page 52


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
public FiraFire(String name, String col,String test){
this.name = name;
color = col;
this.test = test;
}
static String FiraFireLogic(){
return "Ethiopian FiraFire can be wild or farmerised!";
}
abstract boolean hasSeed();
abstract boolean hasCaffine();
protected abstract boolean isSweet(String color);

/***** the Birtukan class *******/

class Birtukan extends FiraFire implements YeguaroAtkilt,DisplayObject {


public Birtukan(){
;
}
public Birtukan(String name, String col, String test, int seedNumber){
super(name,col,test,seedNumber);
}
public static String FiraFireLogic(){
return "Hulum Birtukuanoch bicha hibr alachew!";
}
public boolean hasTest(){
if(!test.equals(""))
return true;
else
return false;
}
protected boolean isSweet(String color){
if(color.equals("Yellow")){
return true;
}
else
return false;
}

public String hasColor(){


return color;
}
public boolean hasSeed(){
return true;
}
public boolean hasCaffine(){
return false;
}

public void displayInTabular(){


System.out.println("Here is the Birt ukan Info in Tabular form!");
System.out.println("Name\tcolor\ttest\tseedNumber");
System.out.println(name+"\t"+color+"\t"+test+"\t"+seedNumber);
}
}
/**************class Muzz ***********/

Prepared by: Desta Berihu Weldegiorgis Page 53


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
class Muzz extends FiraFire implements DisplayObject,YeguaroAtkilt{
public Muzz(){
;
}
public Muzz(String name, String col, String test, int seedNumber){
super(name,col,test,seedNumber);
}
static String FiraFireLogic(){
return "Ethiopian MUUZ is only farmerised type!";
}
protected boolean isSweet(String color){
if(color.equals("YellowGreen")){
return true;
}
else
return false;
}
public String showInfo(){
return ("Muzz Info =>"+name +" "+ color +" "+ test);
}
public void displayInTabular(){
System.out.println("Here is the Muuz Info in Tabular form!");
System.out.println("Name\tcolor\ttest\tseedNumber");
System.out.println(name+"\t"+color+"\t"+test+"\t"+seedNumber);
}
public boolean hasSeed(){
return false;
}
public boolean hasCaffine(){
return false;
}
}
/***** class TutorialExcersiseOnOOPConcepts contains the main method ***/

public class TutorialExcersiseOnOOPConcepts{

public static void main(String str[]){


Muzz mz = new Muzz();

Muzz m = new Muzz("Guuradaa", "Bichaa","Tafach", 0);


1
System.out.println(mz);
2
System.out.println("Does Muuz has seed? : "+hasSeed(m));
System.out.println("Is Green muuz sweet?"+isSweet(m)); 3
displayInTabular(m); 4

Birtukan biru = new Birtukan("Methara","YellowGreen","Tafach",9); 5

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

System.out.println("What is the usual test of Birtukan? :8"+biru.test); 9


displayInTabular(biru); 10
}

public static boolean hasSeed(FiraFire fru){


return fru.hasSeed();
}
public static boolean isSweet(FiraFire fru){
return fru.isSweet("Green");

Prepared by: Desta Berihu Weldegiorgis Page 54


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
}
public static boolean hasTest(YeguaroAtkilt yeg){
return yeg.hasTest();
}
public static void displayInTabular(DisplayObject disObj){
disObj.displayInTabular();
}
}
i) Identify and fix all the errors [bugs] in the program?
ii) Generate the output of the program [the sentences labeled as 1 to 10 above]?

Lesson-8. Exercises on Inner Classes

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,

Prepared by: Desta Berihu Weldegiorgis Page 55


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-8 Activity
Task-1: Compose, compile and run the following code.

Prepared by: Desta Berihu Weldegiorgis Page 56


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Fig-8: Demonstration for inner classes


Code analysis on fig-8
 In this code, there are two inner classes namely the Inner and InnerClassDemo.
 Among the classes in this code, only the InnerClassDemo is the executable class (i.e., a class
with a main method)
 The inner class is given from line-10 to line-15. The inner class contains a single method
display().
 Instance of the inner class is created in line-5 and the method display() of the inner class is
invoked in line-6. Now, mind you that the members of the inner class can be accessed by the
outer class ONLY through creating an instance of the inner class.
 The inner class can access every member (whether private or non-private member) of the outer
class.

Task-2: Implement the following class-diagram. Address is a multivalue attribute of an Employee


and hence, is recognized as one embedable class of Employee.

Prepared by: Desta Berihu Weldegiorgis Page 57


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

[Hint: we have two ways of implementing the ‘has-a’ relationship in java.


i) By referencing the „part‟ class, in this case – Address –, from within the „whole‟ class, in
this case– Employee.
ii) By embedding the „part‟ class inside of the „whole‟ class; in our case, by writing the
definition of the Address class inside of the Employee class.]

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.]

Prepared by: Desta Berihu Weldegiorgis Page 58


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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){

38 Employee e = new Employee("Awi","Belete",'F');


39 Employee.Address add = e.new Address(10,"Bahir Dar");
40 System.out.println("The second name of "+e.firstName+" is: "+e.secon dName);
41 System.out.println("The woreda of the employee is: "+add.woreda);
42 System.out.println("The kebele of the employee is: "+add.kebele);
43 }
44 }
45 public static void main(String str[]){
46 Employee emp = new Employee("Aster","Dawit",'F');
47 System.out.println("The first name of the employee is: "+ emp.firstName);
48 System.out.println("the sex of the employee is: "+ emp.sex);
49
50 Employee.Address add = emp.new Address(3,"Bahir Dar");
51 System.out.println("The kebele of the employee is: "+add.getKebele());
52 System.out.println("The woreda of the employee is: "+add.getWoreda());
53 System.out.println("The woreda of the employee is: "+add.woreda);
54 System.out.println("The kebele of the employee is: "+add.kebele);
55 }
56 }

Prepared by: Desta Berihu Weldegiorgis Page 59


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-9. Exception Handling Mechanism of Java

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.

The major Exceptions APIs in java


Important points to be remembered:-
 Exceptions are divided into three categories: checked exceptions, runtime (or unchecked
exceptions), and errors. These three categories share IS-A relationships (inheritance).

 An exception is an object of the class java.lang.Throwable.


 When a piece of code hits an obstacle in the form of an exceptional condition, it creates an object
of subclass java.lang.Throwable, initializes it with the necessary information (such as its
type and optionally a textual description and the offending program‟s state), and hands it over to
the JVM.
 A try block may be followed by multiple catch blocks, and the catch blocks may be followed
by a single finally block.

Prepared by: Desta Berihu Weldegiorgis Page 60


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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.

Reason for the exception Exception Demo


 The size of the array students is 3.

 Trying to access the element at array position


5 is an exceptional condition and it throws
ArrayIndexOutOfBoundsExcepton

 The file file.txt doesn‟t exit.


 If you try to compile this code without
enclosing it within a try block or catching
this exception, your code will fail to comp ile.

 The constructor of the class


FileInputStream throws a checked
exception FileNotFoundException.
 the method myMethod calls itself
recursively, without specifying an exit
condition.

 These recursive calls result in a


StackOverflowError at runtime.

Prepared by: Desta Berihu Weldegiorgis Page 61


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Fig-9: lesson-9 demonstration code

When you compile and run the program by feeding the indicated input, then you will see the following output:

Prepared by: Desta Berihu Weldegiorgis Page 62


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Code analysis on fig-9


 Line-2 and line-3 are importing two classes, the Scanner and the InputMismatchException to
our own class. Since both of them are found in the same package, we can shortened these two
statements as:
import java.util.*;
where the * represents „all classes‟ in this package.
 Line-4 is declaring a package-level-accessible class.
 Line-5 is declaring two instance fields to store the force and mass of the object.
 Line-6 to line-8 is the default constructor. This constructor is added to our class by the compiler only if
there is no any constructor in the class which is defined by our self. If we write our constructor, then the
compiler doesn‟t include the default one. And hence, we should add it by our self. Java‟s
recommendation is to always write it in our classes.
 Line-9 to line-12 is our own constructor with two parameters. It is used to initialize the two fields.
 Line-13 to line-15 is an instance method which returns the acceleration of the object. This method may
throw an exception of type ArithmeticException incase the mass value is zero.
 Line-16 to line-29 is the static method which accepts the input from the keyword and displays the
acceleration of the object.
o This method is declared static because we want to call it from the static main() method without
instantiating an object of the class.
o This method has declared two possible exceptions which may possibly be thrown on its body.
InputMismatchException can be thrown when the input on line-21 or on line-24 is non-
numeric. ArithmeticException can be thrown when the call to the
calculateAcceleration() method throws the ArithmeticException.
 Line-28 to line-36 is the main method. Main() method called the static method acceptInput() to accept
the input and display the output. Because of this call, main() method may encounter an exception on its
body. And it has two possibilities: throwing it to the JVM or handling it by itself. This method choosen to
handle the exception using the try---catch handling model. Since the possible exceptions to be
encountered are two, it has put two catchs, one for each.

Prepared by: Desta Berihu Weldegiorgis Page 63


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

To do this, define three methods namely, acceptList(), sortList(), inverseList() to accept


the list from keyboard, to sort the list, and to find the inverse of each of the elements of the array,
respectively. main() method calls acceptList(); acceptList() calls sortList(); and finally,
sortList() calls inversList(). Each of the methods should have exception handlers or else, throw
the possible exceptions which they can encounter up high to their caller. [Hint: throw
InputMismatchException in case you entered a non-numeric value to a number variable;
ArithmeticException in case you divide by zero; ArrayIndexOutOfBoundsException in
case you attempt to access beyond array size.]

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 }

Prepared by: Desta Berihu Weldegiorgis Page 64


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
38 catch (ArithmeticException fail){
39 throw new ArithmeticException();
40 }
41 }
42 public static void jumpToPick(String msg)throws NumberFormatException{
43 try{
44 int success = Integer.parseInt(msg);
45 System.out.println(msg);
46 System.out.println("go up high to hold it and u will be great and calm!");
47 }
48 catch (NumberFormatException fail){
49 throw new NumberFormatException();
50 }
51 }
52 }

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?

Lesson-10. Java GUI Programming

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

Prepared by: Desta Berihu Weldegiorgis Page 65


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Important points to be remembered:


 Try to know and understand the various GUI components discussed in class.
 All useful components are found inside of the package javax.swing.
 Java has flow layout managers to manage the layout of the components in a frame or panel.
 Java lets us to use menus for cases when multiple options are business requirements.
 To design an attractive and easy-to-use GUI:-
o Identify what GUI component to use to the data you want to enter.
o Choose one of the containers to display your GUI components
o Decide the layout of the components on the container
o Sketch the final look like of the interface on paper to make sure that it is easy-to-use
by the end users of your system.
Lesson-10 Activities
Task-1: Design the following user interface using java that lets a user to enter her/his user name and
password. Finally, the program, when you click the button OK and if the user name and password
entered is found to be correct, displays “Your user name and password is correct! ” using the message
dialog box. Otherwise, it displays “Invalid user name and password” using the message dialog box.

Here below is the code for the above task:

Prepared by: Desta Berihu Weldegiorgis Page 66


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Fig-10: lesson-10 demonstration code

Prepared by: Desta Berihu Weldegiorgis Page 67


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Code analysis on fig-10:

 Line-1 is the package statement


 Line-2 to line-5 are import statements of the required classes to design the GUI
 Line-7 is declaration of our class. Our class is a frame as its extending the JFrame class.
 Line-9 to line-13 is the declaration of the reference variables to the required GUI components.
 Line-15 to line-54 is the constructor of the class.
 The super() on Line-16 is calling constructor of the super class, JFrame. And it is passing the string to be
written on the title bar of the frame.
 Line-17 is creating an instance of the FlowLayout class which will be used to determine the layout of
the components on the frame.
 The setLayout() on line-19 is adding the layout manager to the frame. Behold, this method is one of
the inherited methods from the JFrame.
 Line-21 and line-22 are creating instances of the JLabel class. The argument of the JLabel()
constructor is the text of the label on the interface.
 Line-23 is creating a text field of length 15.
 Line-24 is creating a password field of length 15.
 Line-25 and line-26 are creating two buttons with label „Ok‟ and „Cancel‟, respectively.
 The add() method is used to add the components to the frame. Line-28 to line-31 are adding the
components to the frame. Again see that the method add() is inherited method of the JFrame class.
 Line-33 to line-44 is an anonymous class definition. This anonymous class is intended to add an event
listener to the button.
o The method addActionListener()on line-46 is a method defined in the class JButton to
add the event listener to a button of type JButton. Now, this method is taking the instance of the
anonymous class which implemented the interface ActionListener as its argument.
o The anonymous class has defined only one method with the name actionPerformed(). This
method takes the ActionEvent object as its parameter and contains the statements that must be
executed when the button is clicked.
 The method getText() on line-35 is reading the input data written by the user on the user name text
field of the interface. It is defined in the class JTextField and returns a string. The returned value is
then assigned to the reference variable userName.
 The method getPassword() on line-36 is also doing the same as the getText() of line-35 except
that it returns char[].
 Line-38 is testing the validity of the user name and password coming from the interface.

Prepared by: Desta Berihu Weldegiorgis Page 68


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

 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

Prepared by: Desta Berihu Weldegiorgis Page 69


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Prepared by: Desta Berihu Weldegiorgis Page 70


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-11. Java Database Connectivity [JDBC] and MVC Model

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

The MVC components of a given application.


I. How to design and develop 3-tier applications
Many of today's applications [whether desktop or web-based applications] are three-tier distributed
applications consisting of a user interface, business logic and a 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.

II. Use of MVC model for developing three-tier applications


Most of you are developing a project which has database at its heart. In addition, your project has
user interfaces of different type which lets the user to enter her/his data and to see the output
generated from the application. You have also a third body which accepts the input from the interface,
validate and process it, and, if found important, communicating with database [writes/reads data
to/from the database]. Now, you can easily see that your project has three basic tiers, by which it can
run pleasantly [also called wings, with which it can fly nicely]. If that is so, you are highly

Prepared by: Desta Berihu Weldegiorgis Page 71


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

III. Basic Steps in Using JDBC


There are seven standard steps in querying databases:
a) Load the JDBC driver.
b) Define the connection URL.
c) Establish the connection.
d) Create a statement object.
e) Execute a query or update.
f) Process the results.
g) Close the connection.

Here are some details of the process.


a. Load the Driver
The driver is the piece of software that knows how to talk to the actual database server. To load the driver, all
you need to do is to load the appropriate class using Class.forName; a static block in the class itself
automatically makes a driver instance and registers it with the JDBC driver manager.

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:

Prepared by: Desta Berihu Weldegiorgis Page 72


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException klasYelem) {
System.err.println("Error loading driver: " + klasYelem);
}
አስተውሌ፡ In principle, you can use Class.forName() for any class in your CLASSPATH. In practice, however,
most JDBC driver vendors distribute their drivers inside JAR files. So, be sure to include the path to the JAR
file in your CLASSPATH setting!!

b. Define the Connection URL


Once you have loaded the JDBC driver, you need to specify the location of the database server. URLs referring
to databases use the jdbc: protocol to specify the data source of your database. Besides the username and
password of the database is also needed. See the example below:
String dbUrl = "jdbc:odbc:ServletDataSource";

c. Establish the Connection


To make the actual network connection, pass the URL, the database username, and the password to the
getConnection method of the Driver-Manager class, as illustrated in the following example:

String dbUrl = "jdbc:odbc:ServletDataSource, user = "sa", databasePassword = "desta*9EE26?&";


Connection con = DriverManager.getConnection(dbUrl, user, databasePassword);

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.

f. Process the Results

Prepared by: Desta Berihu Weldegiorgis Page 73


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

g. Close the Connection


connection.close();
To close the connection explicitly, you would do:

You should postpone this step if you expect to perform additional database operations, since the overhead of
opening a connection is usually large.

አስተውሌ፡ In fact, reusing existing connections is such an important optimization!!!

Prepared by: Desta Berihu Weldegiorgis Page 74


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

IV. Developing a 3-tier Desktop Application


As it is already discussed above, by 3-tier it means an application which has three different components
namely the user interface, the business logic and the database which can be installed in separate machines. Let
us demonstrate this by example:
 The following user interface is designed to register details of a student to a database.

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.

Prepared by: Desta Berihu Weldegiorgis Page 75


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
id = idTextField.getText();
firstName = firstNameTextField.getText();
secondName = secondNameTextField.getText();
department = departmentTextField.getText();
sgpa = Double.parseDouble(sgpaTextField.getText());
sex = (String) sexComboBox.getSelectedItem();
try {
createConnection();
stmt.execute("insert into StudentRegistrationTa ble values('"+id+"','"+firstName+"'," +
"'"+secondName+"','"+sex+"','"+department+"','"+sgpa+"')");
flag = true;
} catch (SQLException exe) {
JOptionPane.showMessageDialog(null, exe, "Hello Man! Error:", 1);
}
if(flag = = true){
JOptionPane.showMessageDialog(null, "The Student is successfully registered", "Message", 1);
}
}
And at last, the business logic tier will send the data to the database after validating the input data. The operation can be
adding, searching, deleting or updating the database based on the requirement of the user. The following code fragmentation
is used to connect the business logic with database to do the above mentioned operation:
public void createConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(dbUrl, user, databasePassword);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
} catch (ClassNotFoundException exe) {
JOptionPane.showMessageDialog(null, "Class Not Found" + exe, "Hello Man! Error:", 1);
} catch (SQLException exe) {
JOptionPane.showMessageDialog(null, exe, "Hello Man! Error:", 1);
}
}

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().

V. Steps to connect Java Applications to a SQL Server database from Netbeans

1. Adding the JDBC driver. To do this, go to the services menudatabase node  righ-click on the
Drivers sub-node.

Prepared by: Desta Berihu Weldegiorgis Page 76


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Prepared by: Desta Berihu Weldegiorgis Page 77


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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.

Prepared by: Desta Berihu Weldegiorgis Page 78


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

አስተውል :- ከላይ እንደተመለከተው የግንኝነት መረጃ በአግ ባቡ ከሞላህ/ሽ በኃላ ‘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.

However, if the displayed message is something like:

Then, it means the connection is not established. The reason for this may be beca use of DBMS

Prepared by: Desta Berihu Weldegiorgis Page 79


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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

Prepared by: Desta Berihu Weldegiorgis Page 80


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

in the Services window.

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.

We have now successfully connected NetBeans to our DBMS.

Prepared by: Desta Berihu Weldegiorgis Page 81


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

Lesson-12. Project development with Java

Project Title: Class Schedule Management System

Objective: The main objective of this exercise is to enable students:


 develop a database-driven GUI-based desktop application
 understand changing a java desktop application to a java web-based application
 develop a web-based application which makes use of HTML, CSS, JavaScript as
client-side technologies, for designing the interface part and Java Servlets, JSP
and Java Bean Components as server-side technologies to develop the main
application.

1. Write a database-driven desktop application named Class Schedule Management System


[CSMS] which, for our case only, contains five database tables as given below. Now,
create the database with a name „CSMS_DB‟ and the five tables under it. Besides, design
an appropriate user interface, using which, end users can register the details of the courses,
the students and the teachers. Keep the relationship of the tables as is given in the diagram
below. Do not forget to apply the MVC application design model.
The class diagram is given here below:

Prepared by: Desta Berihu Weldegiorgis Page 82


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

The database schema design is given here 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]

Prepared by: Desta Berihu Weldegiorgis Page 83


Bahir Dar University, Bahir Dar Institute of Technology, Faculty of Computing, Object-Oriented Programming - Java Meskerem
2009 E.C

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//=========================

Prepared by: Desta Berihu Weldegiorgis Page 84

You might also like