Вы находитесь на странице: 1из 135

Prepared by: Zerihun Mulugeta 2018

Wolkite University
Collage of Computing and Informatics
Department of Computer Science

Object Oriented Programming with JAVA

Lab Manual

Zerihun Mulugeta (MSc.)

(Lecturer in Department of Computer Science)

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.2. If statements ................................................................................................................................ 39


3.3. Switch Statements ....................................................................................................................... 43
3.4. Repetition (loop) statements ....................................................................................................... 45
3.4.1. The while Loop ................................................................................................................... 46
3.4.2. The do-while Loop .............................................................................................................. 49
3.4.3. The for Loop ....................................................................................................................... 50
3.5. Nested Loops .............................................................................................................................. 52
3.6. Break and continue keywords ..................................................................................................... 54
3.7. Array ........................................................................................................................................... 55
3.7.1. One-Dimensional Arrays .................................................................................................... 55
3.7.2. Multidimensional Arrays .................................................................................................... 57
3.7.3. Complex array ..................................................................................................................... 58
3.7.4. Alternative Array Declaration Syntax ................................................................................. 59
3.8. Mathematical and String type ..................................................................................................... 60
Review Questions ....................................................................................................................................... 68
Chapter four ................................................................................................................................................ 72
Class and Object ......................................................................................................................................... 72
4.1. Introducing class ......................................................................................................................... 72
4.2. Constructors in java .................................................................................................................... 73
4.3. Objects in java............................................................................................................................. 75
4.4. Methods in java ........................................................................................................................... 76
4.5. Access modifiers ......................................................................................................................... 79
4.6. Inner (Nested) class..................................................................................................................... 82
Review Questions ....................................................................................................................................... 87
Chapter five................................................................................................................................................. 91
Object oriented concepts ............................................................................................................................. 91
5.1. Introduction ................................................................................................................................. 91
5.2. Encapsulation .............................................................................................................................. 91
5.3. Inheritance................................................................................................................................... 93
5.4. Polymorphism ........................................................................................................................... 100
5.4.1. Method Overloading ......................................................................................................... 100
5.4.2. Method Overriding............................................................................................................ 102

3
Prepared by: Zerihun Mulugeta 2018

5.5. Static and Dynamic binding ...................................................................................................... 103


5.5.1. Static binding .................................................................................................................... 103
5.5.2. Dynamic binding ............................................................................................................... 104
5.6. Abstract class and Interface ...................................................................................................... 105
5.6.1. Abstract class .................................................................................................................... 105
5.6.2. Interfaces ........................................................................................................................... 108
Review Questions ..................................................................................................................................... 111
Chapter six ................................................................................................................................................ 115
Exception Handling in Java ...................................................................................................................... 115
6.1. Introduction .................................................................................................................................... 115
6.2. Exception Hierarchy ...................................................................................................................... 115
6.3. Types of Exception ........................................................................................................................ 116
6.4. Exception handling ........................................................................................................................ 118
6.5. Custom exception........................................................................................................................... 123
6.6. Chained Exception ......................................................................................................................... 125
Review questions ...................................................................................................................................... 126
References ................................................................................................................................................. 130

4
Prepared by: Zerihun Mulugeta 2018

Objectives
At the end of this lab manual, students able to

 Understand how to edit java programs, compile and execute it.


 Identify the basic difference b/n java application and java applet.
 Write a fundamental java program using conditional and repetition statements.
 Understand the basic concepts of object oriented programming in java like class, object,
inheritance, encapsulation, polymorphism, abstract class and interfaces; uses them to
solve real world problems.
 Understand how to access variables, methods and constructors in java
 Understand the concepts of package and import statements.
 Apply the concept of System and User defined Exception Handling mechanism

Recommended Hardware and Software Requirements:


 Processor: >=Intel Core i3/i5 Processor
 RAM: minimum requirement of 1GB.
 Operating system: WINDOWS 7/8/10 86/64 bit
 Software: JDK1.6 or latest and Notepad/JCreator/Eclipse/Netbeans

5
Prepared by: Zerihun Mulugeta 2018

Chapter one

Introduction

1.1. Introduction to java

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.

Who invented Java? Which company owns Java now?


Ans: java is invented by James Gosling, Sun Microsystems in 1991, now it is purchased by
Oracle in 2010.

Java JDK, API and IDE

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.2. Setting-up software’s


1.2.1. JDK Installation Steps

1
Prepared by: Zerihun Mulugeta 2018

1. Go to your directory and install JDK first.

2. Click next and the following will be displayed

This is installation
directory of the JDK.

3. Click Next again, and wait a till this window is displayed

2
Prepared by: Zerihun Mulugeta 2018

4. Click Next, and wait the progress bar is completed

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

1.2.2. Install Notepad

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.

1.2.3. Setting-up JDK for Command Prompt Environment

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.

Setting Environment variable steps

1. Go to the directory where JDK was installed. i.e. “C:\Program Files\java\jdk1.7.0_45”

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

5. Click System and Security, then this will be displayed

6. Click System, then the following window will be displayed.

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.

Don’t change this value!

Insert semicolon (;) after the


existed value and then paste
the JDK path after semicolon!

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.

1.3. A Simple java application program editing, compilation and execution


Java has two kinds of programs
 Java Application: has a main method and; execution is always starting from this method.
 Java Applet: has not a main method and can be embedded with web browsers.(will be
described later)

1.3.1. Editing a java code

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

Table 1.1. Special characters

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

The following program gives an example of evaluating

Output:

The multiplication operator in Java is *. As you can see, it is a straightforward process to


translate an arithmetic expression to a Java expression.

1.3.2. Compiling a java code

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

To compile a java code on the command prompt

1. Go to start, click All programs ->Accessories->command prompt

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 cd is a command used to change a working directory.

3. Then the command to compile a java code on a command prompt is:


. .
javac Welcome.java

Where javac is a command to compile a java code and Welcome.java is the name of the file.

Used to make your source file


directory as a “working directory”!

Javac is a command used


to compile a java code.

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

1.3.3. Executing a java code

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.

Java is a command used to


execute a java code!
Welcome is the name of the
file!

This is the output


of the program
after execution!
14
Prepared by: Zerihun Mulugeta 2018

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

1.4. Java programming style and documentation

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.

1.4.1. Appropriate comment and comment styles

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.

1.4.2. Proper Indentation and Spacing

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

1.4.3. Block Styles

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.

1.5. Programming Errors

Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors.

1.5.1. Syntax 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

1. The keyword void is missing before main in line


2. The string Welcome to Java should be closed with a closing quotation mark in line 3.

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.

1.5.2. Runtime 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

Errors happen when we


execute a program! Also
known as Exceptions

1.5.3. Logic Errors

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.

1.5.4. Common Errors

Missing a closing brace, missing a semicolon, missing quotation marks for strings, and misspelling names
are common errors for new programmers.

Common Error 1: Missing Braces


The braces are used to denote a block in the program. Each opening brace must be matched by a
closing brace. A common error is missing the closing brace. To avoid this error, type a closing
brace whenever an opening brace is typed, as shown in the following example.
public class Welcome {
} Type this closing brace right away to match the opening brace.
If you use an IDE such as NetBeans and Eclipse, the IDE automatically inserts a closing brace
for each opening brace typed.

Common Error 2: Missing Semicolons:

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.

public static void main(String[] args)


{ System.out.println("Programming is fun!");
System.out.println("Fundamentals First");
System.out.println("Problem Driven")
} Missing a semicolon.
20
Prepared by: Zerihun Mulugeta 2018

Common Error 3: Missing Quotation Marks


A string must be placed inside the quotation marks. Often, a new programmer forgets to place a
quotation mark at the end of a string, as shown in the following example.
System.out.println("Problem Driven );
Missing a quotation mark
If you use an IDE such as NetBeans and Eclipse, the IDE automatically inserts a closing
quotation mark for each opening quotation mark typed.

Common Error 4: Misspelling Names

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

7. What are the input and output of a Java compiler?


8. What is the command to compile a Java program?
9. What is the command to run a Java program?
10. What is the JVM?
11. Can Java run on any machine? What is needed to run Java on a computer?
12. If a NoClassDefFoundError occurs when you run a program, what is the cause of the error?
13. If a NoSuchMethodError occurs when you run a program, what is the cause of the error?
14. (Display five messages) Write a program that displays Welcome to Java five times.
15. (Display a pattern) Write a program that displays the following pattern:

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

Basics in java programming

2.1. Introduction to Programming in java

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.

Primitive data types


1. Integer types: are types used to represent integer number only.
byte: a one byte signed integer data type.
short: a two byte signed integer data type.
int : a four byte signed integer data type.
Long: an eight byte signed integer data type.
2. Floating- point types: are used to represent floating point numbers or real numbers.
float: a four byte floating number data type
double: an eight byte floating number data type.
3. Character data type
char: a two byte character data type
4. Boolean algebra type
boolean: used to represent a Boolean value true or false.
23
Prepared by: Zerihun Mulugeta 2018

Syntax to declare a variable


type varname; e.g. int age; char $letter; float average; boolean _enabled;

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.

Compute the area of


a circle (πr2).

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.

2.2. Reading input from console

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

The print method in line 9


System.out.print("Enter a number for radius: ");
is identical to the println method except that println moves to the beginning of the next line after
displaying the string, but print does not advance to the next line when completed.

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.

Reading multiple input from the console

The below program reads three numbers and displays their average.
Import java.util package
to use Scanner class!

28
Prepared by: Zerihun Mulugeta 2018

Accept three inputs.

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.

Reading Different Type Numbers from the Keyboard

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.

Table 2.1. Methods for a Scanner object

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

Java supports four kinds of operators. These are


1. Arthimetic (e.g. addition(+), subtraction(-), division(/), modulus(%), multiplication(*))
2. Relational(less than(<),greater than(>),equal to(==),not equal to(!=),less than or
equalto(<=) and greater than or equalto(>=)
3. Bitwise(and(&),or(|), xor(^),left shift(<<), right shift(>>)
4. Logical (and(&&),or(||),short circuit and(&), short circuit or(|))

30
Prepared by: Zerihun Mulugeta 2018

2.3.1. Operator precedence


The operators in the following table are listed according to precedence order. The closer to the
top of the table an operator appears, the higher its precedence. Operators with higher precedence
are evaluated before operators with relatively lower precedence. Operators on the same line have
equal precedence. When operators of equal precedence appear in the same expression, a rule
must govern which is evaluated first. All binary operators except for the assignment operators
are evaluated from left to right; assignment operators are evaluated right to left.

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.

After executing line 10, the value of k,a,b,d and res is

K=70
A=11
B=6
D=8
Res=85

33
Prepared by: Zerihun Mulugeta 2018

2.4. Type casting or conversion

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.

Syntax of explicit type casting

Example: float a=4.5f;


var2=(target-type) var1;

short b= (short) a; //converting float type to short type.

The program written below shows, how implicit casting is done in java programming language.

ImplicitCasting.java

Implicit casting (widening)

Short -> float

Output:

34
Prepared by: Zerihun Mulugeta 2018

a=10
c=10.0

At line 5, the short data type is converted to a wider type float.

The program written below shows explicit casting in java.

Explicit Casting (Narrowing)

double -> byte

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

Decision and Repetition Statement

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

Two-Way if-else Statements


An if-else statement decides the execution path based on whether the condition is true or false.
A one-way if statement performs an action if the specified condition is true. If the condition is
false, nothing is done. But what if you want to take alternative actions when the condition is
false? You can use a two-way if-else statement. The actions that a two-way if-else statement
specifies differ based on whether the condition is true or false.
Here is the syntax for a two-way if-else statement:

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

Nested if and Multi-Way if-else Statements


An if statement can be inside another if statement to form a nested if statement.
The statement in an if or if-else statement can be any legal Java statement, including another if or
if-else statement. The inner if statement is said to be nested inside the outer if statement. The
inner if statement can contain another if statement; in fact, there is no limit to the depth of the
nesting. For example, the following is a nested if statement:

The if (j > k) statement is nested inside the if (i > k) statement.


The nested if statement can be used to implement multiple alternatives. The statement given in
(a), for instance, prints a letter grade according to the score, with multiple alternatives.

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

Common errors and pitfalls

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.

3.3. Switch Statements

A switch statement executes statements based on the value of a variable or an expression.

Overuse of nested if statements makes a program difficult to read. Java provides a switch
statement to simplify coding for multiple conditions.

Here is the full syntax for the switch statement:


switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

The switch statement observes the following rules:


 The switch-expression must yield a value of char, byte, short, int, or String type and must
always be enclosed in parentheses. (The char and String types will be introduced in the
next chapter.)
 The value1, . . ., and valueN must have the same data type as the value of the
switchexpression. Note that value1, . . ., and valueN are constant expressions, meaning
that they cannot contain variables, such as 1 + x.

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

3.4. Repetition (loop) statements

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.

3.4.1. The while Loop


A while loop executes statements repeatedly while the condition is true.

The syntax for the while loop is:

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.

Here is another example to help understand how a loop works.

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.

What happens if the loop is mistakenly written as follows?

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.

3.4.2. The do-while Loop

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.

3.4.3. The for Loop

A for loop has a concise syntax for writing loops.

Often you write a loop in the following common form:

A for loop can be used to simplify the preceding loop as:


50
Prepared by: Zerihun Mulugeta 2018

In general, the syntax of a for loop is:

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:

The initial-action, i = 0, initializes the control variable, i. The loop-continuation-condition, i <


100, is a Boolean expression. The expression is evaluated right after the initialization and at the
beginning of each iteration. If this condition is true, the loop body is executed. If it is false, the
loop terminates and the program control turns to the line following the loop.
The action-after-each-iteration, i++, is a statement that adjusts the control variable. This
statement is executed after each iteration and increments the control variable. Eventually, the
value of the control variable should force the loop-continuation-condition to become false;
otherwise, the loop is infinite.
The loop control variable can be declared and initialized in the for loop. Here is an example:

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

3.5. Nested Loops

A loop can be nested inside another loop.

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.

3.6. Break and continue keywords

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.

3.7.1. One-Dimensional Arrays

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:

int month_days[] = new int[12];

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

3.7.2. Multidimensional Arrays

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:

int twoD[ ][ ] = new int[4][5];

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:

3.7.3. Complex array

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.

int twoD[][] = new int[4][];


twoD[0] = new int[3];
twoD[1] = new int[1];
twoD[2] = new int[4];
twoD[3] = new int[2];

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:

The array created by this program looks like this:

3.7.4. Alternative Array Declaration Syntax

There is a second form that may be used to declare an array:


59
Prepared by: Zerihun Mulugeta 2018

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.

3.8. Mathematical and String type

Java mathematical methods


Java provides many useful methods in the Math class for performing common mathematical
functions.
Trigonometric Methods
The Math class contains the following methods for performing trigonometric functions:

60
Prepared by: Zerihun Mulugeta 2018

Example: a program on trigonometric methods

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:

The Rounding Methods


The Math class contains five rounding methods as shown below

Example:

Output:

The min, max and abs methods


The min and max methods return the minimum and maximum numbers of two numbers (int,
long, float, or double). For example, max(4.4, 5.0) returns 5.0, and min(3, 2) returns 2.

The abs method returns the absolute value of the number (int, long, float, or double). For
example,
62
Prepared by: Zerihun Mulugeta 2018

Output:

The random Method


This method generates a random double value greater than or equal to 0.0 and less than 1.0 (0 <=
Math.random() < 1.0). You can use it to write a simple expression to generate random numbers
in any range. For example,
(int)(Math.random() * 10) ---------------Returns a random integer between 0 and 9.
50 + (int)(Math.random() * 50) --------Returns a random integer between 50 and 99.
In general
a + Math.random() * b---------------Returns a random integer between a and a+b, excluding a + b.

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

Methods in Character class

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.

Simple Methods for String Objects

Example:

Output:

Comparing string methods

65
Prepared by: Zerihun Mulugeta 2018

Example:

Output:

The String class contains the methods for obtaining substrings

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.

Finding a Character or a Substring in a String


The String class provides several versions of indexOf and lastIndexOf methods to find a
character or a substring in a string, as shown below.

Example

67
Prepared by: Zerihun Mulugeta 2018

Output:

Convert String type to character array


To convert strings to an array, you can use toCharArray method. For example:

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.

6. What is wrong in the following code?

7. Checking palindrome.(write a java program which check wheteher a number is


palindrome or not).
8. Write a java program to display a prime numbers from 1 to 100.
9. How many times is the println statement executed?

10. Write a java program to

69
Prepared by: Zerihun Mulugeta 2018

i. Convert decimal to hexadecimal


ii. Decimal to binary
iii. Decimal to octal
11. Convert the following for loop statement to a while loop and to a do-while loop:

12. Identify and fix the errors in the following code:

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

4.1. Introducing class

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.

The General Form of a Class

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.

4.2. Constructors in java

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.

The constructor is denoted as


ClassName(parameterType parameterName){
//constructor body
}
Let’s begin by defining a simple constructor that simply sets the dimensions of each box to the
same values.

Instance variables

Class variable

Constructor

With no- parameter

A Method
definition With no-
parameter

74
Prepared by: Zerihun Mulugeta 2018

Two objects are created.


Each line call the
constructor
“Box” automatically

Method calling

Java source file rule

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

4.3. Objects in java

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

classname var=new classname(); or


classname var;
var=new classname();

Objects are used to access variables and methods. To access variables and methods of an object ,
you should have to use .(dot) operator.

Syntax to access variable Syntax to access(call) method


Objname.varname; objname.methodname();

4.4. Methods in java

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.

The syntax for defining a method is as follows:

modifier returnValueType methodName(list of parameters) {


// Method body;
76
Prepared by: Zerihun Mulugeta 2018

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

Example: A java program which defines and call max method.

max() method is invoking here

max() method definition

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

4.5. Access modifiers

Access modifiers can be used to specify the visibility of a class and its members.

Access modifiers for class


 public: a class with public modifier can be accessed anywhere.
 default(no modifier): a class with no modifier can be accessed inside its own
package.
Note
Packages can be used to organize classes. To do so, you need to add the following line as the first
noncomment and nonblank statement in the program:
package packageName;
If a class is defined without the package statement, it is said to be placed in the default package. Java
recommends that you place classes into packages rather than using a default package. For simplicity,
however, this manual uses default package.

Access modifiers for methods

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

Access modifier for instance variables


 private : a variable with private modifier can be accessed inside its own class
 public: a variable with public modifier can be accessed anywhere
 protected: a variable with protected modifier can be accessed inside its own class and the
subclass.
 Default(no modifier): a variable with no modifier can be accessed inside the package.

Access modifiers for constructors


 private: can be accessed inside its own class
79
Prepared by: Zerihun Mulugeta 2018

 public: can be accessed anywhere.


 protected: can be accessed by the subclass and superclass.
 default: can be accessed inside the package. To access public
class in another
Let’s see visibility modifiers in (a) and (b). package, we
should have to
package p1; package p2; import their
public class A { import p1.A; package inside
public static void main (String[] args) { class B { another package.
System.out.println("A class method"); public static void main (String[] args) {
B obj=new B(); // compiler error System.out.println("B class method");
} A obj=new A(); // we can access class A here
} (a)
}
Example: java variable and method access modifier (b)
} program

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

// ob.c = 100; // Error!


then you would not be able to compile this program because of the access violation.

Example: Java constructor access modifier

Compiler error because


the default constructor
has a private access
modifier

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

TestConstructor t=new TestConstructor ();


the system will display a compiler error.

4.6. Inner (Nested) class

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.

Instantiating an inner class


To instantiate an instance of inner class, there should be a live instance of outer class. An inner
class instance can be created only from an outer class instance. An inner class shares a special
relationship with an instance of the enclosing class. Instantiating an inner class from within code
in 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

Method–Local inner classes


A method local inner class is defined within a method of the enclosing class. If you want to use
inner class, you must instantiate the inner class in the same method, but after the class definition
code. Only two modifiers are allowed for method-local inner classes which are abstract and final.
The inner class can use the local variables of the method (in which it is present), only if they are
marked final.

The inner class


can’t access non
final variable
“name”.

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.

Anonymous Inner Classes

It is a type of inner class which


 has no name

84
Prepared by: Zerihun Mulugeta 2018

 can be instantiated only once


 is usually declared inside a method or a code block ,a curly braces ending with
semicolon.
 is accessible only at the point where it is defined.
 does not have a constructor simply because it does not have a name
 cannot be static

Example:

This is
Anonymous
inner class.

Static Nested Classes


Static nested classes are the inner classes marked with static modifier. Because this is static in
nature so this type of inner class doesn’t share any special kind of relationship with an instance
of outer class. A static nested class cannot access non static members of outer class.
Example:

85
Prepared by: Zerihun Mulugeta 2018

A static nested class can be instantiated like this:

Java static nested class example with instance method:

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?

13. What is the output of 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?

16. What is wrong in the following code?

88
Prepared by: Zerihun Mulugeta 2018

17. Show the output of the following code:

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

 A method named getPerimeter() that returns the perimeter.


19. (The Stock class) Following the example of the Circle class in Section 9.2, design a class
named Stock that contains:
 A string data field named symbol for the stock’s symbol.
 A string data field named name for the stock’s name.
 A double data field named previousClosingPrice that stores the stock price for the
previous day. A double data field named currentPrice that stores the stock price
for the current time.
 A constructor that creates a stock with the specified symbol and name.
 A method named getChangePercent() that returns the percentage changed from
previousClosingPrice to currentPrice.
20. (The Account class) Design a class named Account that contains:
 A private int data field named id for the account (default 0).
 A private double data field named balance for the account (default 0).
 A private double data field named annualInterestRate that stores the current
interest rate (default 0). Assume all accounts have the same interest rate.
 A private Date data field named dateCreated that stores the date when the account
was created.
 A no-arg constructor that creates a default account.
 A constructor that creates an account with the specified id and initial balance.
 The accessor and mutator methods for id, balance, and annualInterestRate.
 The accessor method for dateCreated.
 A method named getMonthlyInterestRate() that returns the monthly interest rate.
 A method named getMonthlyInterest() that returns the monthly interest.
 A method named withdraw that withdraws a specified amount from the account.
 A method named deposit that deposits a specified amount to the account.

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.

To achieve encapsulation in Java:

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

Inheritance is one of the cornerstones of object-oriented programming because it allows the


creation of hierarchical classifications. Using inheritance, you can create a general class that
defines traits common to a set of related items. This class can then be inherited by other, more
specific classes, each adding those things that are unique to it. In the terminology of Java, a class
that is inherited is called a superclass(parent or base class). The class that does the inheriting is
called a subclass(child or derived class). Therefore, a subclass is a specialized version of a
superclass. It inherits all of the members defined by the superclass and adds its own, unique
elements.

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:

class subclass-name extends superclass-name {


// body of class
}

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 B inherit from A

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.

Consider the below example: We cannot extend 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.

Example: super is used to invoke parent class constructor

invoke
This line invokes the
parent(Animal) class
constructor

Output:
Animal is created
Dog is created

95
Prepared by: Zerihun Mulugeta 2018

A Second Use for super


The second form of super acts somewhat like this, except that it always refers to the superclass of the
subclass in which it is used. This usage has the following general form:
super.member;

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.

Let’s take an example to understand this concept:

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.

Single Inheritance example program

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.

Multilevel Inheritance example program:

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.

Hierchichal inheritance example program:

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.

5.4.1. Method Overloading

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

Declaring Overloaded Methods

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.

This line will call a


method with integer
parameter.

This line will call a


method with double
parameter.

Output

The compiler distinguishes overloaded methods by their signature—a combination of the


method’s name and the number, types and order of its parameters. Method calls cannot be
distinguished by return type. When two methods have the same signature and different return
types, the compiler issues an error message indicating that the method is already defined in the
class. Overloaded methods can have different return types if the methods have different
parameter lists.

101
Prepared by: Zerihun Mulugeta 2018

5.4.2. Method Overriding

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

5.5. Static and Dynamic binding


5.5.1. Static binding

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

5.5.2. Dynamic binding

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.

Let’s see dynamic binding using a program

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.

5.6. Abstract class and Interface


5.6.1. Abstract class

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

Summary about abstract class


 Abstract class should not be declared final. Because final class can’t be inherited.
 Abstract class should not have a private constructor.
 Abstract class can contain abstract or concrete methods.
 Abstract methods do not provide implementations
 Abstract method should not be static. Because static method can’t be overridden.
 Abstract method shouldn’t be declared final, because final method can’t be overridden.
 A class that contains any abstract methods must be declared as an abstract class. Each
concrete subclass must provide implementations of each of the super class’s abstract
methods.

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!

Summary about interface

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

 “interface myInterface” defines an interface named “myInterface”.


 “void compareNumbers ( )” defines an empty method “void compareNumbers( )”.
 “class MaxNum implements myInterface { }” means class “MaxNum” implements
“myInterface” interface.
 “class MinNum implements myInterface { }” means class “MinNum” implements
“myInterface” interface.
 “public void compareNumbers( ){ }” implements the empty method compareNumbers( ) in
interface.

110
Prepared by: Zerihun Mulugeta 2018

Review Questions

1. True or false? A subclass is a subset of a superclass.


2. What keyword do you use to define a subclass?
3. What is single inheritance? What is multiple inheritance? Does Java support multiple
inheritance?
4. How does a subclass invoke its superclass’s constructor?
5. True or false? When invoking a constructor from a subclass, its superclass’s no-arg
constructor is always invoked.
6. True or false? You can override a private method defined in a superclass.
7. True or false? You can override a static method defined in a superclass.
8. How do you explicitly invoke a superclass’s constructor from a subclass?
9. How do you invoke an overridden superclass method from a subclass?
10. Explain the difference between method overloading and method overriding.
11. If a method in a subclass has the same signature as a method in its superclass with the
same return type, is the method overridden or overloaded?
12. If a method in a subclass has the same signature as a method in its superclass with a
different return type, will this be a problem?
13. If a method in a subclass has the same name as a method in its superclass with different
parameter types, is the method overridden or overloaded?
14. What is the benefit of using the @Override annotation?
15. What is polymorphism? What is dynamic binding?
16. Indicate true or false for the following statements:
 You can always successfully cast an instance of a subclass to a superclass.
 You can always successfully cast an instance of a superclass to a subclass.
17. Private members of a class are inherited to sub class. True or false?

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

19. Which of the following classes defines a legal abstract class?

20. True or false?


a. An abstract class can be used just like a non abstract class except that you cannot use the new
operator to create an instance from the abstract class.
b. An abstract class can be extended.
c. A subclass of a non abstract superclass cannot be abstract.
d. A subclass cannot override a concrete method in a superclass to define it as abstract. e. An
abstract method must be non static.

112
Prepared by: Zerihun Mulugeta 2018

21. Write the output of the following code.

22. Write the output of the following program

23. Write the output of the following code

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.

Why an exception occurs?


There can be several reasons that can cause a program to throw exception. For example: Opening
a non-existing file in your program, Network connection problem, bad input data provided by
user etc.

6.2. Exception Hierarchy

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.

There is an important subclass of Exception, called RuntimeException. Exceptions of this type


are automatically defined for the programs that you write and include things such as division by
zero and invalid array indexing.

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.

6.3. Types of Exception

6.3.1. Checked Exception

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.

6.3.2. Unchecked Exception

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.

There is no problem at compile time.

ArithimeticException at run time.

117
Prepared by: Zerihun Mulugeta 2018

6.4. Exception handling

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.

General syntax of try-catch and 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:

Statements which throw


an exception should be
written inside try block.

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

A catch block can handle


multiple exceptions in a
single line.

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.

Three components of exception handling model

 Declaring exception: use a keyword “throws” to declare an exception for a method or


constructor.
 Throwing exception: use a keyword “throw” to throw an exception which happens
inside the method or constructor.
 Catching exception: use try catch block to handle an exception which is thrown by a
method or constructor.

Syntax of declaring exception for a method

modifier returntype myMethod() throws Exceptiontype{ //exception declaration


//method body
}

120
Prepared by: Zerihun Mulugeta 2018

Syntax of throwing exception

modifier returntype myMethod() throws Exceptiontype{ //exception declaration


throw new exceptiontype(); // this line throws an exception of type exceptiontype.
}

Let see this with example Exception declaration

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

Catch an exception which is


thrown by validate() method

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

A test program that uses the CircleWithException class is given below

6.5. Custom exception

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

6.6. Chained Exception

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

9. What RuntimeException will the following programs throw, if any?

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:

Answer the following questions:


 Will statement3 be executed?
 If the exception is not caught, will statement4 be executed?
 If the exception is caught in the catch block, will statement4 be executed?

127
Prepared by: Zerihun Mulugeta 2018

15. What is displayed when the following program is run?

16. What is displayed when the following program is run?

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:

> java Area L 10.5 B 5.0


Length: 10.5 Breadth: 5.0
Area: 52.5
> java Area B 5.0 L 10.5
Length: 10.5 Breadth: 5.0
Area: 52.5
The program should throw a NumberFormatException if the sides are not legal values. The program
should check the information read from the command line and give suitable feedback.

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

Вам также может понравиться