Академический Документы
Профессиональный Документы
Культура Документы
Wolkite University
Collage of Computing and Informatics
Department of Computer Science
Lab Manual
1
Prepared by: Zerihun Mulugeta 2018
Table of Contents
Chapter one ................................................................................................................................................... 1
Introduction ................................................................................................................................................... 1
1.1. Introduction to java ....................................................................................................................... 1
1.2. Setting-up software’s .................................................................................................................... 1
1.2.1. JDK Installation Steps ........................................................................................................... 1
1.3. A Simple java application program editing, compilation and execution ...................................... 8
1.3.1. Editing a java code ................................................................................................................ 8
1.3.2. Compiling a java code......................................................................................................... 12
1.3.3. Executing a java code ......................................................................................................... 14
1.4. Java programming style and documentation ............................................................................... 16
1.4.1. Appropriate comment and comment styles ......................................................................... 16
1.4.2. Proper Indentation and Spacing .......................................................................................... 16
1.4.3. Block Styles ........................................................................................................................ 17
1.5. Programming Errors.................................................................................................................... 17
1.5.1. Syntax Errors ............................................................................................................................ 17
1.5.2. Runtime Errors .......................................................................................................................... 18
1.5.3. Logic Errors .............................................................................................................................. 19
1.5.4. Common Errors ......................................................................................................................... 20
Review Questions ....................................................................................................................................... 21
Chapter two ................................................................................................................................................. 23
Basics in java programming .................................................................................................................... 23
2.1. Introduction to Programming in java .......................................................................................... 23
2.2. Reading input from console ........................................................................................................ 26
2.3. Operators in java ......................................................................................................................... 30
2.4. Type casting or conversion ......................................................................................................... 34
2.5. Naming Conventions .................................................................................................................. 36
Review questions ........................................................................................................................................ 36
Chapter three ............................................................................................................................................... 39
Decision and Repetition Statement ............................................................................................................. 39
3.1. Introduction ................................................................................................................................. 39
2
Prepared by: Zerihun Mulugeta 2018
3
Prepared by: Zerihun Mulugeta 2018
4
Prepared by: Zerihun Mulugeta 2018
Objectives
At the end of this lab manual, students able to
5
Prepared by: Zerihun Mulugeta 2018
Chapter one
Introduction
Java is a powerful and versatile programming language for developing software running on
mobile devices, desktop computers, and servers. Its rapid rise and wide acceptance can be traced
to its design characteristics, particularly its promise that you can write a program once and run it
anywhere. As stated by its designer, Java is simple, object oriented, distributed, interpreted,
robust, secure, architecture neutral, portable, high performance, multithreaded, and dynamic
programming language.
The above three are the basic software components which used to write, compile and execute a
java code. The JDK is the software for developing and running Java programs (without JDK we
can’t compile or execute a java code), the Java library is defined in the Java API(Application
Programming Interface). An IDE is an integrated development environment for rapidly
developing programs (like Eclipse, Netbeans, jdeveloper so on).
1
Prepared by: Zerihun Mulugeta 2018
This is installation
directory of the JDK.
2
Prepared by: Zerihun Mulugeta 2018
5. You are successfully installed JDK, click Close to finish the installation.
Now there has to be a folder named with “java” inside C:\Program Files\ directory. The java
folder also contains two folders with name “jdk1.7” and “jre7”.
In this lab manual, Notepad editor will be used to write a java code and; compilation and
execution will be done using Command Prompt (cmd) for the sake of students, to improve their
programming and problem solving skill.
Every windows based computers have a pre installed Notepad and Command Prompt software
environment under Accessories directory. Hence, no need of installing this environment again. If
3
Prepared by: Zerihun Mulugeta 2018
Notepad environment is corrupted or deleted, you can reinstall it by downloading from the
internet.
To compile and execute a java program using Command Prompt (cmd), initially you should
have to set JDK installation directory on the Environment Variable path value once. After that,
no need of re-setting the environment variable path value again and again.
2. Double Click on bin folder and then the following window is will be displayed.
4
Prepared by: Zerihun Mulugeta 2018
“Java” file
is used for
execution
“Javac” file
is used for
compilation
3. Copy the path which is shown by the blue bold arrow, i.e. “C:\Program
Files\Java\jdk1.7.0_45\bin”
4. Now go to Start and click Control Panel, the following window will be displayed
5
Prepared by: Zerihun Mulugeta 2018
7. Now click Advanced system setting on the left panel of the window
6
Prepared by: Zerihun Mulugeta 2018
8. Click Advance tab and then click Environment variable, the following window will be
displayed.
Used to edit
“JDK path”
7
Prepared by: Zerihun Mulugeta 2018
9. Now under System variables, select Path variable and click Edit button, this window
will be displayed.
10. Now you should not change the variable name “Path” but on the variable value text box
put semicolon (;) at the end of information and paste the path you have copied earlier
on step (3).
11. Finally click Ok button three times i.e. on step (9), step (8), and step (7) windows.
A java program can be edited using different development environment like Notepad,
Eclipse,Netbeans, JDeveloper so on. In this manual, programs will be written and edited using
Notepad environment and the source code should be saved with dot java (filename.java)
extension.
Let’s begin with a simple Java program that displays the message Welcome to Java! on the
console. Console input means to receive input from the keyboard, and console output means to
display output on the monitor.) The program is shown in below program.
8
Prepared by: Zerihun Mulugeta 2018
Output:
Note that the line numbers are for reference purposes only; they are not part of the program.
So, don’t type line numbers in your program.
Line 1 defines a class. Every Java program must have at least one class. Each class has a name. By
convention, class names start with an uppercase letter. In this example, the class name is Welcome.
Line 2 defines the main method. The program is executed from the main method. A class may
contain several methods. The main method is the entry point where the program begins
execution.
A method is a construct that contains statements. The main method in this program contains the
System.out.println statement. This statement displays the string Welcome to Java! on the console
(line 4). String is a programming term meaning a sequence of characters. A string must be
enclosed in double quotation marks. Every statement in Java ends with a semicolon (;), known as
the statement terminator.
Reserved words, or keywords, have a specific meaning to the compiler and cannot be used for
other purposes in the program. For example, when the compiler sees the word class, it
understands that the word after class is the name for the class. Other reserved words in this
program are public, static, and void.
Line 3 is a comment that documents what the program is and how it is constructed. Comments
help programmers to communicate and understand the program. They are not programming
9
Prepared by: Zerihun Mulugeta 2018
statements and thus are ignored by the compiler. In Java, comments are preceded by two slashes
(//) on a line, called a line comment, or enclosed between /* and */ on one or several lines, called
a block comment or paragraph comment. When the compiler sees //, it ignores all text after // on
the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */.
A pair of curly braces in a program forms a block that groups the program’s components. In
Java, each block begins with an opening brace ({) and ends with a closing brace (}). Every class
has a class block that groups the data and methods of the class. Similarly, every method has a
method block that groups the statements in the method. Blocks can be nested, meaning that one
block can be placed within another, as shown in the following code.
You have seen several special characters (e.g., { }, //, ;) in the program. They are used in almost
every program. Table 1.1 summarizes their uses. The most common errors you will make as you
learn to program will be syntax errors. Like any programming language, Java has its own syntax,
and you need to write code that conforms to the syntax rules.
10
Prepared by: Zerihun Mulugeta 2018
If your program violates a rule—for example, if the semicolon is missing, a brace is missing, a
quotation mark is missing, or a word is misspelled—the Java compiler will report syntax errors.
Try to compile the program with these errors and see what the compiler reports.
The program written above displays one message. Once you understand the program, it is easy to
extend it to display more messages. For example, you can rewrite the program to display three
messages, as shown in below.
Output:
Further, you can perform mathematical computations and display the result on the console.
11
Prepared by: Zerihun Mulugeta 2018
Output:
Java source file must end with the extension .java and must have the same exact name as the
public class name. For example, the file for the source code in the above program should be
named Welcome.java, since the public class name is Welcome.
A Java compiler translates a Java source file into a Java bytecode (.class) file. The following
command compiles Welcome.java
12
Prepared by: Zerihun Mulugeta 2018
2. First you should have to know the exact location where the source file (“Welcome.java”)
is saved.
Note
For simplicity and consistency, all source-code and class files used in this manual are placed
under C:\LabManual\ unless specified otherwise.
To change the working directory to the folder where the source file is placed, you should have to
write the following command on the command prompt and press Enter key.
cd C:\LabManual
Where javac is a command to compile a java code and Welcome.java is the name of the file.
4. If there aren’t any syntax errors, the compiler generates a bytecode file with a .class
extension on the same directory of the source file. Thus, the preceding command
generates a file named Welcome.class in the directory “C:\Users\Markan\Desktop\Java”
like shown on the following window.
13
Prepared by: Zerihun Mulugeta 2018
The
directory
where
the
source
file and This file is created by itself, if the
bytecode a source file which is source code is compiled
are created by a successfully (without syntax error)!
saved! programmer!
It is known as Bytecode
It has .java extension!
It has .class extension
A Java Virtual Machine (JVM) is responsible to execute a compiled java code (bytecode). You
can execute the bytecode on any platform (Operating System) with a JVM, which is an
interpreter. It translates the individual instructions in the bytecode into the target machine
language code one at a time rather than the whole program as a single unit.
To execute a java code, write the following command in the command prompt
Java Welcome
Where java is a command used to execute a bytecode and Welcome is the name of the file
without extension.
As you have seen on the above window, the output of welcome.java source file after execution is
“Welcome to java!”.
Note
To compile and execute a java code, always you should have to follow the above
compilation and execution steps which described in Section (1.3.2 and 1.3.3).
. (a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any
computer with a Java Virtual Machine.
Caution
Do not use the extension .class in the command line when executing the program. Use java
ClassName to run the program. If you use java ClassName.class in the command line, the system
will attempt to fetch ClassName.class.class.
Tip
If you execute a class file that does not exist, a NoClassDefFoundError will occur. If you execute
a class file that does not have a main method or you mistype the main method (e.g., by typing
Main instead of main), a NoSuchMethodError will occur.
Note
When executing a Java program, the JVM first loads the bytecode of the class to memory using a
program called the class loader. If your program uses other classes, the class loader dynamically
loads them just before they are needed. After a class is loaded, the JVM uses a program called
the bytecode verifier to check the validity of the bytecode and to ensure that the bytecode does not
violate Java’s security restrictions. Java enforces strict security to make sure that Java class files
are not tampered with and do not harm your computer.
15
Prepared by: Zerihun Mulugeta 2018
Good programming style and proper documentation make a program easy to read and help
programmers prevent errors.
Programming style deals with what programs look like. Java is a free form programming
language so a java program can compile and run properly even if written on only one line, but
writing it all on one line would be bad programming style because it would be hard to read.
Documentation is the body of explanatory remarks and comments pertaining to a program.
Programming style and documentation are as important as coding. Good programming style and
appropriate documentation reduce the chance of errors and make programs easy to read.
Appropriate Comments and Comment Styles Include a summary at the beginning of the program
that explains what the program does, its key features, and any unique techniques it uses. In a long
program, you should also include comments that introduce each major step and explain anything
that is difficult to read. It is important to make comments concise so that they do not crowd the
program or make it difficult to read. In addition to line comments (beginning with //) and block
comments (beginning with /*), Java supports comments of a special type, referred to as javadoc
comments. javadoc comments begin with /** and end with */. They can be extracted into an
HTML file using the JDK’s javadoc command.
A consistent indentation style makes programs clear and easy to read, debug, and maintain.
Indentation is used to illustrate the structural relationships between a program’s components or
statements. Java can read the program even if all of the statements are on the same long line, but
humans find it easier to read and maintain code that is aligned properly. Indent each
subcomponent or statement at least two spaces more than the construct within which it is nested.
A single space should be added on both sides of a binary operator, as shown in the following
statement:
System.out.println(3+4*4); Bad style
System.out.println(3 + 4 * 4); Good style
16
Prepared by: Zerihun Mulugeta 2018
A block is a group of statements surrounded by braces. There are two popular styles, next-line style and
end-of-line style, as shown below.
The next-line style aligns braces vertically and makes programs easy to read, whereas the end-of-
line style saves space and may help avoid some subtle programming errors. Both are acceptable
block styles. The choice depends on personal or organizational preference. You should use a
block style consistently—mixing styles is not recommended. This manual uses the end-of-line style
to be consistent with the Java API source code.
Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors.
Errors that are detected by the compiler are called syntax errors or compile errors. Syntax errors result
from errors in code construction, such as mistyping a keyword, omitting some necessary punctuation, or
using an opening brace without a corresponding closing brace. These errors are usually easy to detect
because the compiler tells you where they are and what caused them. For example, the program written
bellow has a syntax error, as shown below
ShowSyntaxErrors.java
Four errors are reported, but the program actually has two errors:
17
Prepared by: Zerihun Mulugeta 2018
Since a single error will often display many lines of compile errors, it is a good practice to fix
errors from the top line and work downward. Fixing errors that occur earlier in the program may
also fix additional errors that occur later.
Compile the
source file
Four Syntax
errors
Tip
If you don’t know how to correct it, compare your program closely, character by character, with similar
examples in the text. In the first few weeks of this course, you will probably spend a lot of time fixing
syntax errors. Soon you will be familiar with Java syntax and can quickly fix syntax errors.
Runtime errors are errors that cause a program to terminate abnormally. They occur while a
program is running if the environment detects an operation that is impossible to carry out. Input
mistakes typically cause runtime errors. An input error occurs when the program is fix syntax
errors runtime errors 1.10 Programming Errors 21 waiting for the user to enter a value, but the
user enters a value that the program cannot handle. For instance, if the program expects to read
in a number, but instead the user enters a string, this causes data-type errors to occur in the
program. Another example of runtime errors is division by zero. This happens when the divisor
18
Prepared by: Zerihun Mulugeta 2018
is zero for integer divisions. For instance, the program in the below would cause a runtime error,
as shown below
ShowRuntimeErrors.java
Logic errors occur when a program does not perform the way it was intended to. Errors of this
kind occur for many different reasons. For example, suppose you wrote the program below to
convert Celsius 35 degrees to a Fahrenheit degree:
ShowLogicErrors.java
Output
19
Prepared by: Zerihun Mulugeta 2018
You will get Fahrenheit 67 degrees, which is wrong. It should be 95.0. In Java, the division for
integers is the quotient—the fractional part is truncated—so in Java 9 / 5 is 1. To get the correct
result, you need to use 9.0 / 5, which results in 1.8
In general, syntax errors are easy to find and easy to correct because the compiler gives
indications as to where the errors came from and why they are wrong. Runtime errors are not
difficult to find, either, since the reasons and locations for the errors are displayed on the console
when the program aborts. Finding logic errors, on the other hand, can be very challenging. In the
upcoming chapters, you will learn the techniques of tracing programs and finding logic errors.
Missing a closing brace, missing a semicolon, missing quotation marks for strings, and misspelling names
are common errors for new programmers.
Each statement ends with a statement terminator (;). Often, a new programmer forgets to place a
statement terminator for the last statement in a block, as shown in the following example.
Java is case sensitive. Misspelling names is a common error for new programmers. For example,
the word main is misspelled as Main and String is misspelled as string in the following code. 1
Review Questions
1. What is a keyword? List some Java keywords.
2. Is Java case sensitive? What is the case for Java keywords?
3. What is a comment? Is the comment ignored by the compiler? How do you denote a comment line
and a comment paragraph?
4. What is the statement to display a string on the console?
5. Show the output of the following code:
6. What is the Java source filename extension, and what is the Java bytecode filename extension?
21
Prepared by: Zerihun Mulugeta 2018
16. (Print a table) Write a program that displays the following table:
17. (Area and perimeter of a circle) Write a program that displays the area and perimeter of a
circle that has a radius of 5.5 using the following formula:
perimeter = 2 * radius * π
area = radius * radius * π
18. (Average speed in miles) Assume a runner runs 14 kilometers in 45 minutes and 30
seconds. Write a program that displays the average speed in miles per hour. (Note that 1
mile is 1.6 kilometers.)
22
Prepared by: Zerihun Mulugeta 2018
Chapter two
A variable represents a value stored in the computer’s memory. Rather than using x and y as
variable names, choose descriptive names: like radius for radius, and area for area variables. To
let the compiler know what radius and area are, specify their data types. That is the kind of data
stored in a variable, whether integer, real number, or something else. This is known as declaring
variables. Every variable has a name, a type, a size, and a value. Java provides simple data types
for representing integers, real numbers, characters, and Boolean types. These types are known as
primitive data types or fundamental types.
Identifier in java
Identifier is the name of variable, method, class, constructors, interfaces and packages.
Java valid identifier should start with letter or underscore or dollar sign and can be followed by
digit or letter.
Note
Variables should be declared before we use them.
Variable declaration!
The program declares radius and area as variables. The reserved word double indicates that
radius and area are floating-point values stored in the computer.
Variable initialization
Initialization means assigning a value for a variable. For instance, if you want to initialize radius
variable value; and compute the area. Here is the complete program below.
24
Prepared by: Zerihun Mulugeta 2018
Initialization of
radius variable.
The result of the program after compilation followed by execution is on the below window.
Compile
Run/execute
Output/result
Variables such as radius and area correspond to memory locations. Every variable has a name, a
type, a size, and a value. Line 3 declares that radius can store a double value. The value is not
defined until you assign a value. Line 7 assigns 20 into variable radius. Similarly, line 4 declares
variable area, and line 10 assigns a value into area. The following table shows the value in the
memory for area and radius as the program is executed. Each row in the table shows the values
of variables after the statement in the corresponding line in the program is executed. This method
of reviewing how a program works is called tracing a program. Tracing programs are helpful for
understanding how programs work, and they are useful tools for finding errors in programs.
25
Prepared by: Zerihun Mulugeta 2018
The plus sign (+) has two meanings: one for addition and the other for concatenating
(combining) strings. The plus sign (+) in lines 13–14 is called a string concatenation operator. It
combines two strings into one. If a string is combined with a number, the number is converted
into a string and concatenated with the other string. Therefore, the plus signs (+) in lines 13–14
concatenate strings into a longer string, which is then displayed in the output. Strings and string
concatenation will be discussed further later.
Named Constants
A named constant is an identifier that represents a permanent value. The value of a variable may
change during the execution of a program, but a named constant, or simply constant, represents
permanent data that never changes. In our ComputeArea program, p is a constant. If you use it
frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for p.
Here is the syntax for declaring a constant:
final datatype CONSTANTNAME = value;
A constant must be declared and initialized in the same statement. The word final is a Java
keyword for declaring a constant.
Reading input from the console enables the program to accept input from the user.
26
Prepared by: Zerihun Mulugeta 2018
Java uses System.out to refer to the standard output device and System.in to the standard input
device. By default, the output device is the display monitor and the input device is the keyboard.
To perform console output, you simply use the println method to display a primitive value or a
string to the console. Console input is not directly supported in Java, but you can use the Scanner
class to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner
input declares that input is a variable whose type is Scanner. The whole line Scanner input = new
Scanner(System.in) creates a Scanner object and assigns its reference to the variable input. An
object may invoke its methods. To invoke a method on an object is to ask the object to perform a
task. You can invoke the nextDouble() method to read a double value as follows:
double radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the number to radius
Output:
Line 9 displays a string "Enter a number for radius: " to the console. This is known as a prompt,
because it directs the user to enter an input. Your program should always tell the user what to
enter when expecting input from the keyboard.
27
Prepared by: Zerihun Mulugeta 2018
Line 6 creates a Scanner object. The statement in line 10 reads input from the keyboard.
double radius = input.nextDouble();
After the user enters a number and presses the Enter key, the program reads the number and
assigns it to radius.
More details on objects will be introduced later. For the time being, simply accept that this is
how to obtain input from the console.
The Scanner class is in the java.util package. It is imported in line 1. There are two types of
import statements: specific import and wildcard import. The specific import specifies a single
class in the import statement. For example, the following statement imports Scanner from the
package java.util.
import java.util.Scanner;
The wildcard import imports all the classes in a package by using the asterisk (*) as the wildcard.
For example, the following statement imports all the classes from the package java.util.
import java.uitl.*;
The information for the classes in an imported package is not read in at compile time or runtime
unless the class is used in the program. The import statement simply tells the compiler where to
locate the classes. There is no performance difference between a specific import and a wildcard
import declaration.
The below program reads three numbers and displays their average.
Import java.util package
to use Scanner class!
28
Prepared by: Zerihun Mulugeta 2018
Compute average
Output:
The code for importing the Scanner class (line 1) and creating a Scanner object (line 6) are the
same as in the preceding example as well as in all new programs you will write for reading input
from the keyboard.
Line 9 prompts the user to enter three numbers. The numbers are read in lines 10–12. You may
enter three numbers separated by spaces, then press the Enter key, or enter each number followed
by a press of the Enter key, as shown in the sample runs of this program.
If you entered an input other than a numeric value, a runtime error would occur. In last chapter,
you will learn how to handle the exception so that the program can continue to run.
29
Prepared by: Zerihun Mulugeta 2018
You know how to use the nextDouble() method in the Scanner class to read a double value
from the keyboard. You can also use the methods listed in Table 2.2 to read a number of the
byte, short, int, long, and float type.
If you enter a value with an incorrect range or format, a runtime error would occur. For example,
you enter a value 128 for line 3, an error would occur because 128 is out of range for a byte type
integer.
2.3. Operators in java
30
Prepared by: Zerihun Mulugeta 2018
31
Prepared by: Zerihun Mulugeta 2018
Precedence.java
a=10;
e=10;
c=10;
b=6;
d=6;
f=6;
32
Prepared by: Zerihun Mulugeta 2018
At line 4, the values of each variable a,e and c becomes 10. On line 5, the values of each variable
b,d and f is 6;
Line 6 performs two bitwise operation (or) and (right shift). Right shift operation has a highest
precedence order over bitwise (or) operation. After execution of the statement on line 6, a=11
and f=1.
Line 7 first will perform pre increment of the variable d, and then the multiplication of e by d
will be performed. After execution the result of d=7 and e=70.
Line 8 performs pre-decrement the value of b first and divide the value of c by b, then the result
will be assigned to variable c. after execution b=5 and c=2.
At line 9 there is a ternary operation (?:), if the value of a>d, then k=e else k= b. so that the value
of k=70.
K=70
A=11
B=6
D=8
Res=85
33
Prepared by: Zerihun Mulugeta 2018
Type casting is a process in which one data type is converted into another data type.
There are two types of data type casting: implicit and explicit casting.
Implicit (widening) casting: small size type converted into larger size data type. It is done
automatically. E.g. convert byte to int ; short to long and the like.
Explicit (narrowing) casting: larger size type converted to small size data type. It is done by the
programmer explicitly. There might be a loss of data while conversion is done. E.g. convert int
to byte; double to float so on.
The program written below shows, how implicit casting is done in java programming language.
ImplicitCasting.java
Output:
34
Prepared by: Zerihun Mulugeta 2018
a=10
c=10.0
Output:
a=200.5
c=-56
At line 5, the double data type is converted to a smaller size type byte.
Note
Casting does not change the variable being cast. For example, a is not changed after casting in the above
code.
35
Prepared by: Zerihun Mulugeta 2018
2.5.Naming Conventions
Sticking with the Java naming conventions makes your programs easy to read and avoids errors.
Make sure that you choose descriptive names with straightforward meanings for the variables,
constants, classes, and methods in your program. As mentioned earlier, names are case sensitive.
Listed below are the conventions for naming variables, methods, and classes.
Use lowercase for variables and methods. If a name consists of several words, concatenate
them into one, making the first word lowercase and capitalizing the first letter of each
subsequent word—for example, the variables radius and area and the method print.
Capitalize the first letter of each word in a class name—for example, the class names
ComputeArea and System.
Capitalize every letter in a constant, and use underscores between words—for example, the
constants PI and MAX_VALUE.
It is important to follow the naming conventions to make your programs easy to read.
Caution
Do not choose class names that are already used in the Java library. For example, since the
System class is defined in Java, you should not name your class System.
Review questions
1. Identify and fix the errors in the following code:
36
Prepared by: Zerihun Mulugeta 2018
2. How do you write a statement to let the user enter a double value from the keyboard?
What happens if you entered 5a when executing the following code?
double radius = input.nextDouble();
3. Are there any performance differences between the following two import statements?
import java.util.Scanner; import java.util.*;
4. What does an explicit casting from a double to an int do with the fractional part of the double
value? Does casting change the variable being cast?
5. Show the following output:
float f = 12.5F;
int i = (int)f;
System.out.println("f is " + f);
System.out.println("i is " + i);
6. Show the output of the following code:
double amount = 5;
System.out.println(amount / 2);
System.out.println(5 / 2);
7. Write a java program which compute and display area of a rectangle and circle.
Area of rectangle= length * width
Area of circle= 3.14 * r * r
accept the value of length, width and radius from the user.
8. Write a java program which compute speed of a car.
Speed= distance / time
You should have to accept the value of distance and time from the user and display the
speed of the car.
37
Prepared by: Zerihun Mulugeta 2018
9. (Compute the volume of a cylinder) Write a program that reads in the radius and length
of a cylinder and computes the area and volume using the following formulas:
area = radius * radius * pi
volume = area * length
10. (Convert feet into meters) Write a program that reads a number in feet, converts it to
meters, and displays the result. One foot is 0.305 meter.
11. (Convert pounds into kilograms) Write a program that converts pounds into kilograms.
The program prompts the user to enter a number in pounds, converts it to kilograms, and
displays the result. One pound is 0.454 kilograms.
12. (Find the number of years) Write a program that prompts the user to enter the minutes
(e.g., 1 billion), and displays the number of years and days for the minutes. For
simplicity, assume a year has 365 days.
38
Prepared by: Zerihun Mulugeta 2018
Chapter three
3.1. Introduction
The program can decide which statements to execute based on a condition. Java has several
types of selection statements: one-way if statements, two-way if-else statements, nested if
statements, multi-way if-else statements, switch statements, and conditional expressions.
3.2. If statements
An if statement is a construct that enables a program to specify alternative paths of execution.
A one-way if statement executes an action if and only if the condition is true. The syntax for a
one-way if statement is:
If the boolean-expression evaluates to true, the statements in the block are executed. As an example, see
the following code:
If the value of radius is greater than or equal to 0, then the area is computed and the result is
displayed; otherwise, the two statements in the block will not be executed.
The boolean-expression is enclosed in parentheses. For example, the code in (a) is wrong. It
should be corrected, as shown in (b).
39
Prepared by: Zerihun Mulugeta 2018
The block braces can be omitted if they enclose a single statement. For example, the following
statements are equivalent.
Note
Omitting braces makes the code shorter, but it is prone to errors. It is a common mistake to forget the
braces when you go back to modify the code that omits the braces.
The below program prompts the user to enter an integer. If the number is a multiple of 5, the
program displays HiFive. If the number is divisible by 2, it displays HiEven.
SimpleIfDemo.java
Output:
40
Prepared by: Zerihun Mulugeta 2018
The program prompts the user to enter an integer (lines 6–7) and displays HiFive if it is divisible
by 5 (lines 9–10) and HiEven if it is divisible by 2 (lines 12–13).
If the boolean-expression evaluates to true, the statement(s) for the true case are executed;
otherwise, the statement(s) for the false case are executed. For example, consider the following
code:
If radius >= 0 is true, area is computed and displayed; if it is false, the message "Negative input"
is displayed. As usual, the braces can be omitted if there is only one statement within them. The
braces enclosing the System.out.println("Negative input") statement can therefore be omitted in
the preceding example.
Here is another example of using the if-else statement. The example checks whether a number is
even or odd, as follows:
41
Prepared by: Zerihun Mulugeta 2018
The execution of this if statement proceeds as you have shown on the above code. The first
condition (score >= 90.0) is tested. If it is true, the grade is A. If it is false, the second condition
(score >= 80.0) is tested. If the second condition is true, the grade is B. If that condition is false,
the third condition and the rest of the conditions (if necessary) are tested until a condition is met
or all of the conditions prove to be false. If all of the conditions are false, the grade is F. Note
that a condition is tested only when all of the conditions that come before it are false.
The if statement in (a) is equivalent to the if statement in (b). In fact, (b) is the preferred coding
style for multiple alternative if statements. This style, called multi-way if-else statements, avoids
deep indentation and makes the program easy to read.
42
Prepared by: Zerihun Mulugeta 2018
Forgetting necessary braces, ending an if statement in the wrong place, mistaking == for =, and
dangling else clauses are common errors in selection statements. Duplicated statements in if-else
statements and testing equality of double values are common pitfalls.
Overuse of nested if statements makes a program difficult to read. Java provides a switch
statement to simplify coding for multiple conditions.
43
Prepared by: Zerihun Mulugeta 2018
When the value in a case statement matches the value of the switch-expression, the
statements starting from this case are executed until either a break statement or the end of
the switch statement is reached.
The default case, which is optional, can be used to perform actions when none of the
specified cases matches the switch-expression.
The keyword break is optional. The break statement immediately ends the switch
statement.
Caution
Do not forget to use a break statement when one is needed. Once a case is matched, the
statements starting from the matched case are executed until a break statement or the end of
the switch statement is reached. This is referred to as fall-through behavior. For example,
the following code displays Weekdays for day of 1 to 5 and Weekends for day 0 and 6.
Tip
To avoid programming errors and improve code maintainability, it is a good idea to put a
comment in a case clause if break is purposely omitted.
Now let us write a program to find out the Chinese Zodiac sign for a given year. The Chinese
Zodiac is based on a twelve-year cycle, with each year represented by an animal— monkey,
rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, or sheep—in this cycle, as shown
below.
Note that year % 12 determines the Zodiac sign. 1900 is the year of the rat because 1900 % 12 is
4. The below program prompts the user to enter a year and displays the animal for the year.
44
Prepared by: Zerihun Mulugeta 2018
A loop can be used to tell a program to execute statements repeatedly. Suppose that you need to
display a string (e.g., Welcome to Java!) a hundred times. It would be tedious to have to write the
following statement a hundred times:
45
Prepared by: Zerihun Mulugeta 2018
So, how do you solve this problem? Java provides a powerful construct called a loop that
controls how many times an operation or a sequence of operations is performed in succession.
Using a loop statement, you simply tell the computer to display a string a hundred times without
having to code the print statement a hundred times, as follows:
The variable count is initially 0. The loop checks whether count < 100 is true. If so, it executes
the loop body to display the message Welcome to Java! and increments count by 1. It repeatedly
executes the loop body until count < 100 becomes false. When count < 100 is false (i.e., when
count reaches 100), the loop terminates and the next statement after the loop statement is
executed. Loops are constructs that control repeated executions of a block of statements. The
concept of looping is fundamental to programming. Java provides three types of loop statements:
while loops, do-while loops, and for loops.
The part of the loop that contains the statements to be repeated is called the loop body. A one-
time execution of a loop body is referred to as an iteration (or repetition) of the loop. Each loop
contains a loop-continuation-condition, a Boolean expression that controls the execution of the
body. It is evaluated each time to determine if the loop body is executed. If its evaluation is true,
46
Prepared by: Zerihun Mulugeta 2018
the loop body is executed; if its evaluation is false, the entire loop terminates and the program
control turns to the statement that follows the while loop. The loop for displaying Welcome to
Java! a hundred times introduced in the preceding section is an example of a while loop.
loop-continuation-condition is count < 100 and the loop body contains the following two statements:
In this example, you know exactly how many times the loop body needs to be executed because
the control variable count is used to count the number of executions. This type of loop is known
as a counter-controlled loop.
Note
The loop-continuation-condition must always appear inside the parentheses. The braces
enclosing the loop body can be omitted only if the loop body contains one or no statement.
If i < 10 is true, the program adds i to sum. Variable i is initially set to 1, then is incremented to
2, 3, and up to 10. When i is 10, i < 10 is false, so the loop exits. Therefore, the sum is 1 + 2 + 3
+ ... + 9 = 45.
47
Prepared by: Zerihun Mulugeta 2018
This loop is infinite, because i is always 1 and i < 10 will always be true
Note
Make sure that the loop-continuation-condition eventually becomes false so that the loop will
terminate. A common programming error involves infinite loops (i. e., the loop runs forever). If
your program takes an unusually long time to run and does not stop, it may have an infinite loop.
If you are running the program from the command window, press CTRL+C to stop it.
The following code gives a program that prompts the user to enter an answer for a question on
addition of two single digits. Using a loop, you can the program to let the user repeatedly enter a
new answer until it is correct.
RepeatAdditionQuiz.java
Output
What is 32 + -6? 13
Wrong answer. Try again. What is 32 + -6? 26
You got it!
48
Prepared by: Zerihun Mulugeta 2018
The loop in lines 15–19 repeatedly prompts the user to enter an answer when number1 +
number2 != answer is true. Once number1 + number2 != answer is false, the loop exits.
Caution
Don’t use floating-point values for equality checking in a loop control. Because floating point
values are approximations for some values, using them could result in imprecise counter values
and inaccurate results.
A do-while loop is the same as a while loop except that it executes the loop body first and then
checks the loop continuation condition.
The do-while loop is a variation of the while loop. Its syntax is:
The loop body is executed first, and then the loop-continuation-condition is evaluated. If the
evaluation is true, the loop body is executed again; if it is false, the do-while loop terminates.
The difference between a while loop and a do-while loop is the order in which the loop-
continuation-condition is evaluated and the loop body executed. You can write a loop using
either the while loop or the do-while loop. Sometimes one is a more convenient choice than the
other. For example, you can rewrite the while loop written above using a do-while loop, as
shown below.
49
Prepared by: Zerihun Mulugeta 2018
TestDoWhile.java
Tip
Use a do-while loop if you have statements inside the loop that must be executed at least once, as
in the case of the do-while loop in the preceding TestDoWhile program. These statements must
appear before the loop as well as inside it if you use a while loop.
A for loop generally uses a variable to control how many times the loop body is executed and
when the loop terminates. This variable is referred to as a control variable. The initial-action
often initializes a control variable, the action-after-each-iteration usually increments or
decrements the control variable, and the loop-continuation-condition tests whether the control
variable has reached a termination value. For example, the following for loop prints Welcome to
Java! a hundred times:
If there is only one statement in the loop body, as in this example, the braces can be omitted.
51
Prepared by: Zerihun Mulugeta 2018
Tip
The control variable must be declared inside the control structure of the loop or before the loop.
If the loop control variable is used only in the loop, and not elsewhere, it is a good programming
practice to declare it in the initial-action of the for loop. If the variable is declared inside the
loop control structure, it cannot be referenced outside the loop. In the preceding code, for
example, you cannot reference i outside the for loop, because it is declared inside the for loop.
Note
The initial-action in a for loop can be a list of zero or more comma-separated variable
declaration statements or assignment expressions. For example:
The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements.
For example:
This example is correct, but it is a bad example, because it makes the code difficult to read. Normally, you
declare and initialize a control variable as an initial action and increment or decrement the control
variable as an action after each iteration.
Note
If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given
below in (a), which is an infinite loop, is the same as in (b). To avoid confusion, though, it is better to use
the equivalent loop in (c).
52
Prepared by: Zerihun Mulugeta 2018
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop is
repeated, the inner loops are reentered, and started anew.
The below program presents a code that uses nested for loops to display a multiplication table.
MultiplicationTable.java
The program displays a title (line 5) on the first line in the output. The first for loop (lines 9–10)
displays the numbers 1 through 9 on the second line. A dashed (-) line is displayed on the third
line (line 12). The next loop (lines 15–22) is a nested for loop with the control variable i in the
outer loop and j in the inner loop. For each i, the product i * j is displayed on a line in the inner
loop, with j being 1, 2, 3, . . ., 9.
Note
Be aware that a nested loop may take a long time to run. Consider the following loop nested in three
levels:
53
Prepared by: Zerihun Mulugeta 2018
The action is performed one trillion times. If it takes 1 microsecond to perform the action, the total time to
run the loop would be more than 277 hours. Note that 1 microsecond is one millionth (10– 6) of a second.
The break and continue keywords provide additional controls in a loop. You have used the keyword
break in a switch statement. You can also use break in a loop to immediately terminate the loop.
You can also use the continue keyword in a loop. When it is encountered, it ends the current
iteration and program control goes to the end of the loop body. In other words, continue breaks
out of an iteration while the break keyword breaks out of a loop.
54
Prepared by: Zerihun Mulugeta 2018
3.7. Array
An array is a group of like-typed variables that are referred to by a common name. Arrays of any
type can be created and may have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of grouping related information.
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first
must create an array variable of the desired type. The general form of a one-dimensional array
declaration is
type var-name[ ];
Here, type declares the element type (also called the base type) of the array. The element type
determines the data type of each element that comprises the array. Thus, the element type for the
array determines what type of data the array will hold. For example, the following declares an
array named month_days with the type “array of int”:
int month_days[];
Although this declaration establishes the fact that month_days is an array variable, no array
actually exists. To link month_days with an actual, physical array of integers, you must allocate
one using new and assign it to month_days. new is a special operator that allocates memory. You
will look more closely at new in a later chapter, but you need to use it now to allocate memory
for arrays. The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type [size];
55
Prepared by: Zerihun Mulugeta 2018
Here, type specifies the type of data being allocated, size specifies the number of elements in the
array, and array-var is the array variable that is linked to the array. That is, to use new to allocate
an array, you must specify the type and number of elements to allocate. The elements in the array
allocated by new will automatically be initialized to zero (for numeric types), false (for boolean),
or null (for reference types, which are described later).
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further, all
elements in the array will be initialized to zero.
Putting together all the pieces, here is a program that creates an array of the number of days in
each month:
Array Declaration
Array Instantiation
Output
April has 30 days.
56
Prepared by: Zerihun Mulugeta 2018
When you run this program, it prints the number of days in April. As mentioned, Java array
indexes start with zero, so the number of days in April is month_days[3] or 30.
It is possible to combine the declaration of the array variable with the allocation of the array
itself, as shown here:
Here is one more example that uses a one-dimensional array. It finds the average of a set of
numbers.
Output:
Average is 12.3
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays. However, as you will see, there are a couple of
subtle differences. To declare a multidimensional array variable, specify each additional index
using another set of square brackets. For example, the following declares a two dimensional
array variable called twoD:
57
Prepared by: Zerihun Mulugeta 2018
This allocates a 4 by 5 array and assigns it to twoD. Internally, this matrix is implemented as an
array of arrays of int.
The following program numbers each element in the array from left to right, top to bottom, and
then displays these values:
Output:
When you allocate memory for a multidimensional array, you need only specify the memory for
the first (leftmost) dimension. You can allocate the remaining dimensions separately. For
example, this following code allocates memory for the first dimension of twoD when it is
declared. It allocates the second dimension manually.
58
Prepared by: Zerihun Mulugeta 2018
For example, the following program creates a two-dimensional array in which the sizes of the second
dimension are unequal:
Output:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable. For
example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the same
time. For example,
int[] nums, nums2, nums3; // create three arrays
Creates three array variables of type int. It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type for a
method.
60
Prepared by: Zerihun Mulugeta 2018
Output:
Exponent Methods
There are five methods related to exponents in the Math class as shown below.
Example:
61
Prepared by: Zerihun Mulugeta 2018
Output:
Example:
Output:
The abs method returns the absolute value of the number (int, long, float, or double). For
example,
62
Prepared by: Zerihun Mulugeta 2018
Output:
character type
A character data type represents a single character.
The character data type, char, is used to represent a single character. A character literal is
enclosed in single quotation marks.
Escape sequence characters
63
Prepared by: Zerihun Mulugeta 2018
Example:
Output:
String type
A string is a sequence of characters.
64
Prepared by: Zerihun Mulugeta 2018
The char type represents only one character. To represent a string of characters, use the data type
called String. For example, the following code declares message to be a string with the value
"Welcome to Java".
String message = "Welcome to Java";
String is a predefined class in the Java library, just like the classes System and Scanner. The
String type is not a primitive type. It is known as a reference type. Any Java class can be used as
a reference type for a variable. The variable declared by a reference type is known as a reference
variable that references an object. Here, message is a reference variable that references a string
object with contents Welcome to Java.
Example:
Output:
65
Prepared by: Zerihun Mulugeta 2018
Example:
Output:
Example:
66
Prepared by: Zerihun Mulugeta 2018
Output:
Note
If beginIndex is endIndex, substring(beginIndex, endIndex) returns an empty string with length 0. If
beginIndex > endIndex, it would be a runtime error.
Example
67
Prepared by: Zerihun Mulugeta 2018
Output:
Output:
m
Review Questions
1. Write an if statement that assigns 1 to x if y is greater than 0.
2. Write an if statement that increases pay by 3% if score is greater than 90.
68
Prepared by: Zerihun Mulugeta 2018
3. Write an if statement that increases pay by 3% if score is greater than 90, otherwise
increases pay by 1%.
4. What is the output of the code in (a) and (b) if number is 30? What if number is 35?
5. Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the
output if x = 3 and y = 4? What is the output if x = 2 and y = 2? Draw a flowchart of the
code.
69
Prepared by: Zerihun Mulugeta 2018
13. What are the differences between a while loop and a do-while loop? Convert the
following while loop into a do-while loop.
14. What is x after the following if-else statement is executed? Use a switch statement to
rewrite it.
70
Prepared by: Zerihun Mulugeta 2018
15. Write a switch statement that displays Sunday, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday, if day is 0, 1, 2, 3, 4, 5, 6, accordingly.
16. (Algebra: solve quadratic equations) The two roots of a quadratic equation ax 2 + bx + c = 0 can
be obtained using the following formula:
b2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the equation has two
real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots.
Write a program that prompts the user to enter values for a, b, and c and displays the result based
on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0,
display one root. Otherwise, display “The equation has no real roots”. Note that you can use
Math.pow(x, 0.5) to compute .
17. (Use the &&, || and ^ operators) Write a program that prompts the user to enter an integer
and determines whether it is divisible by 5 and 6, but not both.
18. Write a four separate java program using nested do while loop which design the
following pattern.
19. Write a java program using nested while loop which design the following pattern.
71
Prepared by: Zerihun Mulugeta 2018
20. Write a java program which count the number of characters and words in a sentence.
21. (Count vowels and consonants) Assume letters A, E, I, O, and U as the vowels. Write a
program that prompts the user to enter a string and displays the number of vowels and
consonants in the string.
22. (Count uppercase letters) Write a program that prompts the user to enter a string and
displays the number of the uppercase letters in the string.
23. (Longest common prefix) Write a program that prompts the user to enter two strings and
displays the largest common prefix of the two strings. Here are some sample runs:
Chapter four
Class and Object
The class is at the core of Java. It is the logical construct upon which the entire Java language is
built because it defines the shape and nature of an object. As such, the class forms the basis for
object-oriented programming in Java. Any concept you wish to implement in a Java program
must be encapsulated within a class. Because the class is so fundamental to Java, this and the
next few chapters will be devoted to it. Here, you will be introduced to the basic elements of a
72
Prepared by: Zerihun Mulugeta 2018
class and learn how a class can be used to create objects. You will also learn about methods,
constructors, and the “this” keyword.
Perhaps the most important thing to understand about a class is that it defines a new data type.
Once defined, this new type can be used to create objects of that type. Thus, a class is a template
for an object, and an object is an instance of a class. Because an object is an instance of a class,
you will often see the two words object and instance used interchangeably.
A class is declared by use of the class keyword. The classes that have been used up to this point
are actually very limited examples of its complete form. Classes can (and usually do) get much
more complex. A simplified general form of a class definition is shown here:
class classname {
// instance-variables;
// Constructors
Class members
// methods
// nested class, interfaces
}
The name of the class can be any valid identifier. However, by convention class name should
start with a capital letter.
Variables declared within a class outside any method, constructor and blocks are called instance
variables because each instance of the class (that is, each object of the class) contains its own
copy of these variables. Thus, the data for one object is separate and unique from the data for
another. An instance variable declared using static keyword is known as class variable. A
variable declared inside a method, constructor or blocks is known as local variables.
A constructor initializes an object immediately upon creation. It has the same name as the class
in which it resides and is syntactically similar to a method. Once defined, the constructor is
automatically called when the object is created, before the new operator completes. Constructors
73
Prepared by: Zerihun Mulugeta 2018
look a little strange because they have no return type, not even void. This is because the implicit
return type of a class’ constructor is the class type itself. It is the constructor’s job to initialize the
internal state of an object so that the code creating an instance will have a fully initialized, usable
object immediately.
Instance variables
Class variable
Constructor
A Method
definition With no-
parameter
74
Prepared by: Zerihun Mulugeta 2018
Method calling
A java source file can have only one public class and many non public classes. If there is a
public class in the source file, the name of the file should similar with the public class name
and saved with .java extension.
If a java source file doesn’t contain a public class, the name of the source file can be any
valid file name with .java extension.
A class may or may not have a main method.
As you have seen on the above program, a single source file contains two non-public class named “Box”
and “BoxDemo”. BoxDemo class has a main method hence the execution of the program is start from
this class.
Classes are definitions for objects and objects are created from classes. So object is an instance
of a class. An object comprises two things state (fields) and behavior (methods).
Declaring objects
As just explained, when you create a class, you are creating a new data type. You can use this
type to declare objects of that type. However, obtaining objects of a class is a two-step process.
First, you must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual,
physical copy of the object and assign it to that variable. You can do this using the new operator.
75
Prepared by: Zerihun Mulugeta 2018
The new operator dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it. This reference is, more or less, the address in memory of the object
allocated by new. This reference is then stored in the variable. Thus, in Java, all class objects
must be dynamically allocated. Let’s look at the details of this procedure.
In the preceding sample programs, a line similar to the following is used to declare an object of
type Box:
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
A general syntax to create an object from class
Objects are used to access variables and methods. To access variables and methods of an object ,
you should have to use .(dot) operator.
Methods can be used to define reusable code and organize and simplify coding. It is a collection
of statements grouped together to perform an operation.
Defining methods
A method definition consists of its method name, parameters, return value type, and body.
}
Example:
public void sum(int a,int b){
int sum=a+b;
System.ou.println(“sum=”+sum);
}
Calling a Method
Calling a method executes the code in the method. In a method definition, you define what the
method is to do. To execute the method, you have to call or invoke it. There are two ways to call
a method, depending on whether the method returns a value or not.
This program contains the main method and the max method. The main method is just like any
other method except that it is invoked by the JVM to start the program. The main method’s
77
Prepared by: Zerihun Mulugeta 2018
header is always the same. Like the one in this example, it includes the modifiers public and
static, return value type void, method name main, and a parameter of the String[] type. String []
indicates that the parameter is an array of String.
The statements in main may invoke other methods that are defined in the class that contains the
main method or in other classes. In this example, the main method invokes max(i, j), which is
defined in the same class with the main method. When the max method is invoked (line 6),
variable i’s value 5 is passed to num1, and variable j’s value 2 is passed to num2 in the max
method. The flow of control transfers to the max method, and the max method is executed. When
the return statement in the max method is executed, the max method returns the control to its
caller (in this case the caller is the main method). This process is illustrated below.
When the max method is invoked, the flow of control transfers to it. Once the max method is
finished, it returns control back to the caller.
Caution
A return statement is required for a value-returning method.
Note
Methods enable code sharing and reuse. The max method can be invoked from any class, not just
TestMax. If you create a new class, you can invoke the max method using
ClassName.methodName (i.e., TestMax.max).
78
Prepared by: Zerihun Mulugeta 2018
Access modifiers can be used to specify the visibility of a class and its members.
private: a private modifier method only accessed inside its own class.
public: a public modifier method can be accessed anywhere.
protected: a protected modifier method can be accessed in the subclass and super class
only.
default(no modifier): a method with no modifier can be accessed inside the package.
Output
a, b and c: 10 20 100
80
Prepared by: Zerihun Mulugeta 2018
As you can see, inside the Test class, a uses default access, which for this example is the same as
specifying public. b is explicitly specified as public. Member c is given private access. This
means that it cannot be accessed by code outside of its class. So, inside the AccessTest class, c
cannot be used directly. It must be accessed through its public methods: setc( ) and getc( ). If you
were to remove the comment symbol from the beginning of the following line
Output:
Constructor with default modifier
Constructor with public modifier
As you have seen on the above program, the default constructor has a private access modifier;
hence we can’t call the constructor outside its own class. If you uncomment the line
81
Prepared by: Zerihun Mulugeta 2018
Inner classes are defined inside the body of another class (known as outer class). These classes
can have access modifier or even can be marked as abstract and final. Inner classes have special
relationship with outer class instances. This relationship allows them to have access to outer
class members including private members too.
Inner classes can be defined in four different following ways as mentioned below:
Inner class
Method – local inner class
Anonymous inner class
Static nested class
Inner class
An inner class is declared inside the curly braces of another enclosing class. Inner class is coded
inside a Top level class as shown below:-
“MyInnerClassDemo” is
inner (nested) class.
Inner class acts as a member of the enclosing class and can have any access
modifiers: abstract, final, public, protected, private, static. Inner class can access all members of
82
Prepared by: Zerihun Mulugeta 2018
the outer class including those marked private as shown in the above example where inner class
is accessing the private variable "myVar" of outer class.
Output:
Outer value of x is: 1
Instantiating an inner class from outside the outer class Instance Code:
The public static void main code in the above example can be replaced with this one. It will also
give the same output.
83
Prepared by: Zerihun Mulugeta 2018
The above code will throw a compilation error as Inner class cannot use the non-final variables
of the method, in which it is defined.
This is how it can be fixed: If we mark the variable as final then inner class can use it.
84
Prepared by: Zerihun Mulugeta 2018
Example:
This is
Anonymous
inner class.
85
Prepared by: Zerihun Mulugeta 2018
Output:
data is 30
86
Prepared by: Zerihun Mulugeta 2018
Review Questions
1. Describe the relationship between an object and its defining class.
2. How do you define a class?
3. How do you declare an object’s reference variable?
4. How do you create an object?
5. What are the differences between constructors and methods?
6. When will a class have a default constructor?
7. Which operator is used to access a data field or invoke a method from an object?
8. What is an anonymous object?
9. Describe the role of this and super keywords.
10. What are the benefits of data field encapsulation?
11. If class A is an inner class in class B, what is the .class file for A? If class B contains two
anonymous inner classes, what are the .class file names for these two classes?
12. What is wrong in the following code?
87
Prepared by: Zerihun Mulugeta 2018
14. Suppose that the class F is defined in (a). Let f be an instance of F. Which of the
statements in (b) are correct?
15. Can you invoke an instance method or reference an instance variable from a static
method? Can you invoke a static method or reference a static variable from an instance
method? What is wrong in the following code?
88
Prepared by: Zerihun Mulugeta 2018
18. (The Rectangle class) Following the example of the Circle class above, design a class
named Rectangle to represent a rectangle. The class contains:
Two double data fields named width and height that specify the width and height
of the rectangle. The default values are 1 for both width and height.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified width and height.
A method named getArea() that returns the area of this rectangle.
89
Prepared by: Zerihun Mulugeta 2018
90
Prepared by: Zerihun Mulugeta 2018
Chapter five
Object oriented concepts
5.1. Introduction
The three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism.
5.2. Encapsulation
Encapsulation is the process of bundling data and operations on the data together in an entity
called class. In encapsulation, the variables of a class will be hidden from other classes, and can be
accessed only through the methods of their current class. Therefore, it is also known as data hiding.
Tip
Encapsulation and information hiding are two distinct concepts of object-oriented programming. The
existence of one does not imply the existence of the other.
The private keyword can be used when declaring object variables and methods to protect them from
manipulation by external program code. The object should then include public methods to retrieve the
values and call the methods. This technique neatly encapsulates the variables and methods within the
object structure. It is demonstrated in the following program (SafeInstance.java).
91
Prepared by: Zerihun Mulugeta 2018
Output
92
Prepared by: Zerihun Mulugeta 2018
5.3. Inheritance
To inherit a class, you simply incorporate the definition of one class into another by using the
extends keyword.
The general form of a class declaration that inherits a superclass is shown here:
To see how, let’s begin with a short example. The following program creates a superclass called
A and a subclass called B. Notice how the keyword extends is used to create a subclass of A.
93
Prepared by: Zerihun Mulugeta 2018
Class A is : Class B is :
superclass or subclass or
parent class or child class or
base class derived class
An object of the child class (subOb) can access the members of the parent as well as its own
class members. However, the parent class object can’t access the members of the child class but
it can access its own class members only.
Final Classes
A final class that’s declared final cannot be a super class (i.e., a class cannot extend a final class). All
methods in a final class are implicitly final. The built in class String is an example of a final class.
94
Prepared by: Zerihun Mulugeta 2018
Output:
As you have seen on the output of the above program, class ABC cannot subclass the final class
XYZ.
Super keyword
Using “super” to Call Superclass Constructors
In sub class, “super” is a keyword used to call the constructor of parent class.
“super ( argument );” is placed the first line in the constructor of sub class, to call the constructor
of parent class.
invoke
This line invokes the
parent(Animal) class
constructor
Output:
Animal is created
Dog is created
95
Prepared by: Zerihun Mulugeta 2018
Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name
in the superclass.
96
Prepared by: Zerihun Mulugeta 2018
Output:
Child class method
Parent class method
Types of inheritance
Single inheritance
A java class may inherit directly from only one superclass. This restriction is known as single
inheritance. The below flow diagram shows that class B extends only one class which is A.
97
Prepared by: Zerihun Mulugeta 2018
Output:
Base class method
Child class method
Multilevel inheritance
A mechanism in OO technology where one can inherit from a derived class, thereby making this
derived class the base class for the new class. As you can see in below flow diagram C is
subclass or child class of B and B is a child class of A.
Output:
Class X method
Class Y method
98
Prepared by: Zerihun Mulugeta 2018
Class Z method
Hierarchical inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B
and C inherits the same class A.
99
Prepared by: Zerihun Mulugeta 2018
Output:
Class Mango and class Apple inherit from class Fruit, and this two class can access the member
fruitInfo method which is defined in the Fruit class.
Multiple Inheritance
Some programming languages allow you to derive a subclass from several classes. This
capability is known as multiple inheritance. Java, however, does not allow multiple inheritance.
Nevertheless, multiple inheritance can be achieved through interfaces, which will be introduced
later. In below example class C inherits from class A and class B.
5.4. Polymorphism
Polymorphism means the ability to have many forms.
Methods of the same name can be declared in the same class, as long as they have different sets
of parameters (determined by the number, types and order of the parameters)—this is called
method overloading. When an overloaded method is called, the compiler selects the appropriate
method by examining the number, types and order of the arguments in the call. Method
overloading is commonly used to create several methods with the same name that perform the
same or similar tasks, but on different types or different numbers of arguments.
100
Prepared by: Zerihun Mulugeta 2018
Class MethodOverload (Fig. below) includes two overloaded versions of method square— one
that calculates the square of an int (and returns an int) and one that calculates the square of a
double (and returns a double). Although these methods have the same name and similar
parameter lists and bodies, think of them simply as different methods. It may help to think of the
method names as “square of int” and “square of double,” respectively.
Output
101
Prepared by: Zerihun Mulugeta 2018
Overriding means to provide a new implementation for a method in the subclass. To override a
method, the method must be defined in the subclass using the same signature and the same
return type.
Let us use an example to show the differences between overriding and overloading. In (a) below,
the method p(double i) in class A overrides the same method defined in class B. However, the
class B has two overloaded methods: p(double i) and p(int i).
Overloaded method
Overriden method
Note
Overridden methods are in different classes related by inheritance; overloaded methods
can be either in the same class or different classes related by inheritance.
Overridden methods have the same signature and return type; overloaded methods have
the same name but a different parameter list.
To avoid mistakes, you can use a special Java syntax, called override annotation, to place
@Override before the method in the subclass.
102
Prepared by: Zerihun Mulugeta 2018
A final method in a superclass cannot be overridden in a subclass—this guarantees that the final
method implementation will be used by all direct and indirect subclasses in the hierarchy.
Methods that are declared private are implicitly final, because it’s not possible to override them
in a subclass. Methods that are declared static are also implicitly final. A final method’s
declaration can never change, so all subclasses use the same method implementation, and calls to
final methods are resolved at compile time—this is known as static binding.
Example:
Here we have two classes Human and Boy. Both the classes have same method walk() but the
method is static, which means it cannot be overriden so even though I have used the object of
Boy class while creating object obj, the parent class method is called by it. Because the reference
is of Human type (parent class). So whenever a binding of static, private and final methods
happen, type of the class is determined by the compiler at compile time and the binding happens
then and there.
103
Prepared by: Zerihun Mulugeta 2018
Output:
Human walks
Human walks
Most method calls are resolved at execution time, based on the type of the object being
manipulated. This process is known as dynamic binding or late binding. Dynamic binding works as
follows: Suppose an object o is an instance of classes C1, C2, . . . , Cn-1, and Cn, where C1 is a subclass
of C2, C2 is a subclass of C3, . . . , and Cn-1 is a subclass of Cn. That is, Cn is the most general class,
and C1 is the most specific class. In Java, Cn is the Object class. If o invokes a method p(), the JVM
searches for the implementation of the method p() in C1, C2, . . . , Cn-1, and Cn, in this order, until it is
found. Once an implementation is found, the search stops and the first-found implementation is invoked.
Output:
104
Prepared by: Zerihun Mulugeta 2018
Method m (line 9) takes a parameter of the Object type. You can invoke m with any object (e.g.,
new GraduateStudent(), new Student(), new Person(), and new Object()) in lines 3–6).
When the method m(Object x) is executed, the argument x’s toString method is invoked. x may
be an instance of GraduateStudent, Student, Person, or Object. The classes GraduateStudent,
Student, Person, and Object have their own implementations of the toString method. Which
implementation is used will be determined by x’s actual type at runtime.
Invoking m(new GraduateStudent()) (line 3) causes the toString method defined in the
Student class to be invoked. Invoking m(new Student()) (line 4) causes the toString method
defined in the Student class to be invoked; invoking m(new Person()) (line 5) causes the
toString method defined in the Person class to be invoked; and invoking m(new Object()) (line
6) causes the toString method defined in the Object class to be invoked.
Matching a method signature and binding a method implementation are two separate issues. The
declared type of the reference variable decides which method to match at compile time. The
compiler finds a matching method according to the parameter type, number of parameters, and
order of the parameters at compile time. A method may be implemented in several classes along
the inheritance chain. The JVM dynamically binds the implementation of the method at runtime,
decided by the actual type of the variable.
An abstract class cannot be used to create objects. An abstract class can contain abstract
methods, which are implemented in concrete subclasses.
Abstract class works as a parent class, which will be extended by its sub class. The method of
sub class will override the abstract method of abstract class.
105
Prepared by: Zerihun Mulugeta 2018
“abstract class books{ }” defines a abstract class. To create an abstract class you should
have to use “abstract” keyword after modifier of the class.
“abstract int read( )” defines a abstract method.
“class eBooks extends books { }” means a sub class “eBooks ”extends the parent class
”books”.
“int read ( ) { }” means this method in sub class overrides the abstract method in parent class.
Example:
Output
Overrides the abstract method!
106
Prepared by: Zerihun Mulugeta 2018
107
Prepared by: Zerihun Mulugeta 2018
5.6.2. Interfaces
Interface is a special class, which will be implemented by a class. It is used to declare a special
type of class that only contains abstract or default methods, constant (static final) fields and static
interfaces. It can later be implemented by classes that declare the interface with the implements
keyword.
Output:
100
“interface books” defines an interface named “books”. To create an interface, you should
have to use the keyword “interface” after modifier.
“int booknumber( )” defines an empty method(abstract method) “booknumber”.
“class eBooks implements books{ }” means class “eBooks” implements “books” interface.
“public int booknumber( ){ }” implements the booknumber( ).
108
Prepared by: Zerihun Mulugeta 2018
Output:
Implement the empty method!
Interface can’t be instantiated (you can’t create an object from interface but we can
declare an object).
e.g. Books obj=new Books()// compiler error (Books is an interface as you have seen on
the above program)
Books obj; // correct
Interface doesn’t have any constructor.
Interface doesn’t have instance variable.
109
Prepared by: Zerihun Mulugeta 2018
Output:
110
Prepared by: Zerihun Mulugeta 2018
Review Questions
111
Prepared by: Zerihun Mulugeta 2018
18. What is the output of running the class C in (a)? What problem arises in compiling the
program in (b)?
112
Prepared by: Zerihun Mulugeta 2018
113
Prepared by: Zerihun Mulugeta 2018
24. (The Person, Student, Employee, Faculty, and Staff classes) Design a class named
Person and its two subclasses named Student and Employee. Make Faculty and Staff
subclasses of Employee. A person has a name, address, phone number, and email
address. A student has a class status (freshman, sophomore, junior, or senior). Define the
status as a constant. An employee has an office, salary, and date hired. A faculty member
has office hours and a rank. A staff member has a title. Override the toString method in
each class to display the class name and the person’s name. Write a test program that
creates a Person, Student, Employee, Faculty, and Staff, and invokes their toString()
methods.
114
Prepared by: Zerihun Mulugeta 2018
Chapter six
Exception Handling in Java
6.1. Introduction
An exception is a condition that may arise during the execution of a Java program when a
normal path of execution is not defined. For example, a Java program may encounter a numeric
expression that attempts to divide an integer by zero. Such a condition may occur during the
execution of the following snippet of code:
int x = 10, y = 0, z;
z = x / y; // Divide-by-zero (ArithimeticException)
or If you enter a double value when your program expects an integer, you will get a runtime error
with an InputMismatchException.
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top
of the exception class hierarchy. Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches. One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch. This is also the class that you will
subclass to create your own custom exception types.
115
Prepared by: Zerihun Mulugeta 2018
The other branch is topped by Error, which defines exceptions that are not expected to be
caught under normal circumstances by your program. Exceptions of type Error are used by the
Java run-time system to indicate errors having to do with the run-time environment, itself. Stack
overflow is an example of such an error. This chapter will not be dealing with exceptions of type
Error, because these are typically created in response to catastrophic failures that cannot usually
be handled by your program.
All exceptions other than RuntimeExceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not. If these
exceptions are not handled/declared in the program, you will get compilation error. For example,
SQLException, IOException, ClassNotFoundException etc. For example the below program
throw a checked FileNotFoundException(a subclass of IOException).
Throw an exception
while compilation.
116
Prepared by: Zerihun Mulugeta 2018
Line 4 throws a FileNotFoundException when the file “test.dat” doesn’t exist in the local disk.
Let see the exception while compiling the program.
Throw FileNotFoundException
at compile time.
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked
at compile-time so compiler does not check whether the programmer has handled them or not but
it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Compiler will never force you to catch such exception or force you to declare it in the method
using throws keyword. Let’s understand this with an example.
The above program will not have an exception during compilation process but it will throw an
ArthimeticException during execution of the program because we can’t divide a number 3 by 0.
117
Prepared by: Zerihun Mulugeta 2018
Exception handling enables a program to deal with exceptional situations and continue its normal
execution. If the exception is not handled, the program will terminate abnormally. How can you
handle the exception so that the program can continue to run or else terminate gracefully?
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Briefly, here is how they work. Program statements that you want to monitor for exceptions are
contained within a try block. If an exception occurs within the try block, it is thrown. Your code
can catch this exception (using catch) and handle it in some rational manner. System-generated
exceptions are automatically thrown by the Java runtime system. To manually throw an
exception, use the keyword throw. Any exception that is thrown out of a method must be
specified as such by a throws clause. Any code that absolutely must be executed after a try block
completes is put in a finally block.
try {
// statements which might throw an exception will be written here:
}
catch(Exception1 ex1){
handle ex1;
}
catch(Exception2 ex2){
handle ex2;
}
catch(ExceptionN exN){
handle exN;
}
finally{ finalstatments; }
The code in the finally block is executed under all circumstances, regardless of whether an
exception occurs in the try block or is caught. Consider three possible cases:
If no exception arises in the try block, finalStatements is executed, and the next statement
after the try statement is executed.
118
Prepared by: Zerihun Mulugeta 2018
If a statement causes an exception in the try block that is caught in a catch block, the rest
of the statements in the try block are skipped, the catch block is executed, and the finally
clause is executed. The next statement after the try statement is executed.
If one of the statements causes an exception that is not caught in any catch block, the
other statements in the try block are skipped, the finally clause is executed, and the
exception is passed to the caller of this method.
The finally block executes even if there is a return statement prior to reaching the finally block.
Note
The catch block may be omitted when the finally clause is used.
For example to handle an exception that is thrown by the above CheckedException program
using try catch block is:
Line 4,5,6 is a try block, statements which might throw IOException is written inside it. Catch
block (line 7,8,9) handle IOException or subclass of IOException which might thrown by the
try block.
For example to handle two exception that is thrown by the above CheckedException and
UnCheckedException program using a single try catch block is:
119
Prepared by: Zerihun Mulugeta 2018
printStackTRace() is a method
used to get information about
the exception.
A try block in (line 4,5,6,7) might throw IOException or ArithimethicException and the catch
block in(line 8,9,10) handle either of the IOException or ArithimeticException. The
printStackTrace() method in line 9 is a built in method of Throwable class which used to get
information about the exception type. Other built in methods used to get information about
exception types are getMessage() and toString() methods. Finally block (11,12,13) statements are
executed always, whether there is an exception in the try block or not. Most of the time finally
block is used to close a file, database or network connection.
120
Prepared by: Zerihun Mulugeta 2018
Exception throwing
Output:
As you have seen on the above program, line 2 declares an ArithimeticException; and it is
thrown when the value of age less than 18 in line 4. The exception thrown by the validate
method is not caught by the caller (main) method. Now let’s modify the above program by
adding exception catching block.
121
Prepared by: Zerihun Mulugeta 2018
A try–catch block (line 9 to13) handle an exception which is thrown by a validate method.
Example : declaring , throwing and catching exception
This example demonstrates declaring, throwing, and catching exceptions by defining the
setRadius method in the CircleWithException class. The setRadius method throws an exception
if the radius is negative.
122
Prepared by: Zerihun Mulugeta 2018
Java provides quite a few exception classes. Use them whenever possible instead of defining
your own exception classes. However, if you run into a problem that cannot be adequately
described by the predefined exception classes, you can create your own exception class, derived
from Exception or from a subclass of Exception, such as IOException.
For example: a custom exception class with a name “InvalidRadiusException” which will be
thrown when a user enter a radius value less than zero is shown below.
123
Prepared by: Zerihun Mulugeta 2018
Constructor
of custom
exception
Call constructor of
the super class
(Exception)
This custom exception class extends java.lang.Exception (line 1). The Exception class extends
java.lang.Throwable. All the methods (e.g., getMessage(), toString(), and printStackTrace()) in
Exception are inherited from Throwable. The Exception class contains four constructors. Among
them, the following two constructors are often used:
java.lang.Exception
+Exception() Default constructor
+Exception(message: String)
String type parameter constructor
Line 4 invokes the superclass’s constructor with a message. This message will be set in the
exception object and can be obtained by invoking getMessage() on the object.
Tip
Most exception classes in the Java API contain two constructors: a no-arg constructor and a
constructor with a message parameter. To create an InvalidRadiusException, you have to pass a
radius. Therefore, the findArea method in the below program can be defined as shown below.
124
Prepared by: Zerihun Mulugeta 2018
Allows one exception describes causes of another exception. For example, NullPointerException
might be the initial cause of NumberFormatException.
The getCause( ) method in line 9 returns the exception that underlies the current exception. If
there is no underlying exception, null is returned.
125
Prepared by: Zerihun Mulugeta 2018
The initCause( ) method in line 15 associates NullPointerException with the invoking exception
and returns a reference to the exception.
Review questions
1. What is the advantage of using exception handling?
2. Which of the following statements will throw an exception?
System.out.println(1 / 0);
System.out.println(1.0 / 0);
3. Point out the problem in the following code. Does the code throw any exceptions?
long value = Long.MAX_VALUE + 1;
System.out.println(value);
4. What does the JVM do when an exception occurs? How do you catch an exception?
5. What is the output of the following code?
6. What would be the output if the line int value = 30; were changed to int value = 50;
7. Show the output of the following code.
8. Describe the Java Throwable class, its subclasses, and the types of exceptions.
126
Prepared by: Zerihun Mulugeta 2018
10. What is the purpose of declaring exceptions? How do you declare an exception, and where? Can
you declare multiple exceptions in a method header?
11. What is a checked exception, and what is an unchecked exception?
12. How do you throw an exception? Can you throw multiple exceptions in one throw statement?
13. What is the keyword throw used for? What is the keyword throws used for?
14. Suppose that statement2 causes an exception in the following try-catch block:
127
Prepared by: Zerihun Mulugeta 2018
17. Which exceptions will the following code throw during execution?
a) String str = null; int in = str.length();
b) Object objRef = new String("aba"); Integer intRef = (Integer) objRef;
c) int[] array = new int[10]; array[array.length] = 100;
128
Prepared by: Zerihun Mulugeta 2018
d) int j = Integer.parseInt(“1two1”);
18. Write a class Temperature that converts temperature between Fahrenheit (F) and Celsius (C). The
formulas for conversion between the two units are:
● fahrenheit = (9.0 * celsius) / 5.0 + 32.0
● celsius = (fahrenheit – 32.0) * 5.0 / 9.0 288
The program reads the degrees from the command line, for example:
> java Temperature 50.0 C 50.0 C is 122.0 F
> java Temperature 122.0 F 122.0 F is 50.0 C
The program should throw an exception of the type NumberFormatException if the number of
degrees is not a legal floating-point number. The program should check the data from the
command line and give suitable feedback.
19. Write a class Area that calculates the area of a rectangle, using the following formula:
area = length * breadth
The program reads the length (L) and the breadth (B) from the command line, for example:
129
Prepared by: Zerihun Mulugeta 2018
References
[1]. K. Sharan, Beginning Java 9 Fundamentals: Arrays, Objects, Modules, JShell, and Regular
Expressions second edition, Montgomery, Alabama, USA.
[2]. Y. Daniel, Introduction to java programming comprehensive version, 10th edition,
Armstrong Atlantic State University.
[3]. Deitel, P., & Deitel, H. Java How to program. 9th edition, Prentice Hall Press, USA.
[4]. Herbert Schildt, java the Complete Reference, 9th edition, McGraw-Hill Education,
USA(2014)
[5]. M. Kotiyana, Java for Dummies: Become Programmer from Scratch, USA, 2017.
[6]. K. Kousen Modern Java Recipes Simple Solutions to Difficult Problems in Java 8 and 9,
O’Reilly Media, Inc., CA, USA, 2017.
130