Java Exercices
Java Exercices
Quizmaster
for Beginners
L E AR N , T E S T AN D I M P R O VE YO UR J AVA S KI L L S I N
1 0 5 Q UI Z Z E S , 11 7 AS S I G N M E N T S AN D M AN Y C O D E
E X AM P L E S
Sar Maroof
Don't explain Java to me, but show me how it works!
Copyright © 2017 Sar Maroof
All rights reserved.
ISBN: 978-1-975-78178-1
Table of contents
Introduction 4
Chapter 1—Data Types &
Variables ................................................................. 16
Chapter 2—
Operators ................................................................................................
Chapter 3—Conditional
Statements ................................................................. 40
Chapter 4—Iteration (Loop)
Statements ...................................................... 64
Chapter 5—Classes, Objects And
Constructors ........................................ 87
Chapter 6—
Methods ...................................................................................................
Chapter 7—Strings &
Stringbuffer ................................................................ 121
Chapter 8—Packages & Access
Modifiers ................................................... 137
Chapter 9—Arrays &
Arraylist ........................................................................ 145
Chapter 10—Static
Members ................................................................................. 165
Chapter 11—
Inheritance ..........................................................................................
Chapter 12—Final Classes & The Final
Keyword ............................... 199
Chapter 13—Abstract
Classes ............................................................................ 207
Chapter 14—
Interfaces ........................................................................................... 220
Chapter 15—
Casting .................................................................................................
Chapter 16—Nested
Classes ................................................................................. 242
Chapter 17—
Exceptions ..........................................................................................
About the author
Sar Maroof is graduated from HBO Amsterdam “higher professional education”
when he had already a bachelor of science degree in Physics. In his academic
study, he also had the opportunity to study information technology. He was a
teacher when he decided to follow several professional trainings to start his
career as a Java, web developer. He has worked for many years for several big as
well as small companies and later as a freelancer.
The combination of his experiences and skills as a teacher and a Java web
developer inspired him to share his knowledge with enthusiastic younger
generations through writing books.
He handles his own method of teaching programming by focusing on a practical
way to learn it. This method is quite obvious in his books namely Java quizmaster
for beginners and Java assignment in practice.
About this book
Thousands of words cannot describe a face better than a picture. This principle
also applies to learning programming. When I followed several trainings, the
focus was on theoretical explanations. Each lesson contained many terms and
technical words. Because of my background and experience as a teacher, I
wondered if that boring method was the best way to learn programming.
In reality, working as a programmer is quite different than what the most
traditional trainings would teach you. In fact, no one asks whether you know a
particular term, but you will get hundreds of lines of code, and you must be able to
deal with it. You will be asked to build new features. Sometimes you need to
write Java classes or develop a program. If you are not familiar with the code, the
theory can do very little for you. The most efficient way is not to bother with
theories in the beginning, but spend time to work with Java code. Change the
variables, statements and test the code over and over again to see what happens.
This book offers many complete executable small programs (quizzes) to
practice programming from the very beginning. Unfortunately, a computer doesn't
explain how it comes with a specific result, and that is why this book provides a
step by step explanation of the right answers to all the quizzes.
This method helps beginners to focus on testing the code. When the result of
executing the programs doesn't match their expectations, they start to think about
solving the problem.
The good news is that as soon as you start to understand the code, you can't stop
working with it. Many programmers work in the evening or even in the night
because it is a very creative and interesting work. This book prepares students for
what is expected from them and prevents them to memorize technical terms
without understanding it.
I do not mean that theory is not important, but focusing on all kinds of theories
from the beginning is ineffective and slow. If you start with programming, you will
face many problems that require being solved. In such cases, you will also learn a
lot from theories, because it supports what you practice.
If you work as a programmer, you can expect a number of types of assignments.
It doesn't matter what kind of companies you work.
You can expect the following assignments:
1. Understanding code that has been written by other programmers.
2. Building new features for existing software.
3. Detecting bugs and fixing them in an existing program.
4. Developing new programs from scratch.
For the last point, you usually need a few years’ experience.
Each chapter in this book begins with a brief explanation about a particular
Java topic including one or more examples. Then you start to work with quizzes.
1. To choose the correct answer, you need to understand the code. That is
similar to the first point of our list. If you are unable to find the right
answer, you can read the step-by-step explanation of the answer. This is a
very practical method to understand the process.
2. After each quiz, you will be asked to add a small piece of your own code
to it to achieve a particular goal. Sometimes you will be asked to
investigate different variations to study other possible results.
3. In some quizzes, you will be warned why a certain change in the code can
lead to an infinite loop or a problem.
4. From the fifth chapter, you will get an assignment which requires you to
write a small program regards the whole chapter.
5.
Programming is solving problems, and that is the most interesting method to
learn it. If you have a problem, you start to think about a solution, and that helps
you to search for any information that can possibly help you to understand it. It has
also been taken into account that some Java-topics are not used so often, while
others you see almost in every program.
On www.sarmaroof.com, you can find more information about this book and
how to setup the code in Eclipse.
— Sar Maroof
Required knowledge
This book focuses on learning how to program by practicing with code. There
will be little theoretical explanation – just enough to solve the quizzes. That is a
challenge because it is not easy to write a tiny executable program about only one
Java topic. In every executable program, you see different topics. All the
programs demonstrate a particular Java topic. This book divides the Java
programming language into some subjects. In each chapter, a number of small
executable programs is offered regards that specific topic. To make this possible,
it is important to be familiar with the following basics. It's not required that you
understand all the points below properly because details will be covered later in
this book.
The only thing you need to learn to start with is what the role of these points is
for the program to compile and run. Each chapter of this book begins with a brief
explanation, after which the quizzes follow. The codes are complete that you can
test, compile, and run.
1. Java editor
We use as Java editor, Eclipse including JDK 7 (Java Development Kit) or higher.
Eclipse is a free Java IDE (integrated development environment). You can find
and download Eclipse on the Internet. The JDK tools are included, which is
necessary when editing Java-programs. The source codes of Java are files with
the extension .java. The compiled bytecode files have the extension .class. Java is
a platform-independent programming language, which is why you can run Java
programs on every operating system.
2. Compiling programs
Compiling is the translation of source code into machine language with the help of
a tool (compiler). After compiling a source code, the program is directly
executable.
3. Java classes and interfaces
Java programs contain classes and interfaces. These two concepts are covered in
details later in this book. You only need for now is to learn that a class in Java
begins with a statement as class Myclass. Myclass is the name of the class, and
you can decide the name of the class. Every class in Java is stored in a file with
the name of the class. The class Myclass should be stored in a file with the name
of the class and the extension .java. The name of the file in our example is thus
MyClass.java. Each class name begins with the keyword class, and each interface
name begins with the keyword interface. Classes and interfaces also have
members like variables and methods. Methods are a block code between curly
braces.
Example 1
class MyClass
{
// code
}
The following interface must also be stored in a file with the name
MyInterface.java.
Example 2
interface MyInterface
{
// code
}
4. Statements
Statements in Java are similar to sentences in natural languages, and they are
executable units. A statement is usually ended with a semicolon (;).
5. Code block in Java
Code in Java is within a start and an end brace. This is called block of code.
Below are some examples of block codes.
Block type Block style
Class class MyClass
{
// code
}
Method void myMethod
{
// code
}
The keyword void means that
the method doesn't return any
values.
Conditional if(x > 3)
{
// code
}
Iteration for( int i=0; i<5; i ++)
{
// code
}
6. The main method
The main method is a method that is needed to execute a Java program. The main
method begins as follows:
public static void main(String [] args)
For the moment it is important to learn the following about the main method. All
executable programs must have a main method such as below. The statements
within the main method are executed. The execution of the statements is done from
top to bottom. In the next example statement 1 is first executed, then statement 2
and at last statement 3. The following code writes 253 to the standard output.
Example 3
public class MyClass
{
// statements;
// main method
public static void main(String[] args)
{
System.out.print(2); // statement 1;
System.out.print(5); // statement 2;
System.out.print(3); // statement 3;
}
}
7. Writing values of variables and texts to the standard output
The statement System.out.println(); is used to test your program. It is not necessary
for now to understand all the details about this statement, but it is important to
know what you can do with this. You can use this statement to write values of
variables and texts to the standard output as shown in example 4.
Example 4
public class MyClass
{
public static void main(String[] args)
{
int x1 = 25; // Variable x1 is an integer
int x2 = 99; // Variable x2 is an integer
// statement 1 writes the value of x1 to the standard output
System.out.println(x1);
// statement 2 writes the value of x2 to the standard output
System.out.println(x2);
// statement 3 writes the text "My name is Emma." to the standard output
System.out.println("My name is Emma.");
/*
* statement 4 writes a combination of a text and
* a variable to the standard output
*/
System.out.println("Age: " + x1 + " year");
}
}
If you compile and run the code of example 4, the following will be written to the
standard output:
25
99
My name is Emma.
Age: 25 year
To write a text to the standard output, it must be between quotation marks, but for
the value of variables that is not required, see statement 1, 2 and 3 in the previous
example.
To write a combination of texts and variables to the standard output, you need
to use the plus (+) sign, see statement 4. To write the texts and the variables on
one line to the standard output you need to use print instead of println.
8. Comments
Comments are ignored by the compiler. Below are two ways to add comments to
your code.
1. Comment of a single line begins with two slashes //.
Everything on the right side of these characters, see Java as comments:
// comment of a single-line
2. Comment of multiple lines starts with /* and ends with */.
Everything between these two characters sees Java as comments:
/* here is a comment
of multiple lines */
9. Keywords
There are important keywords in Java that we use in the quiz codes such as static
and public. We use those keywords from the beginning because they help to write
small programs. The above-mentioned keywords will be explained in details later
in this book.
The Keyword static
The concept of static is important in Java, and it is treated in a separate chapter.
The only thing you need to learn for now is that this keyword helps to write small
executable programs. That is why we use the keyword static before the name of
some of the variables in the quiz codes. The following example makes this idea
clear.
Example 5
What happens when the following program is compiled and run?
public class MyClass
{
// static keyword before the variable name
static int x = 4;
// the main method to execute the program
public static void main(String[] args)
{
// statement 1: writes the value of the variable x
System.out.print(x);
// statement 2: writes the text "My Java code"
System.out.print(" My Java code");
}
}
The previous program writes 4 My Java code to the standard output. If you
remove the keyword static in the previous example, you get the following error
message:
Cannot make a static reference to the non-static field x.
In order to solve this problem, we need to create an object. Creating objects is
explained in chapter 5. Therefore, we declared the variable x static. This little
trick helps to avoid create objects in the beginning. That helps to create a small
executable program, and we focus on the subject that matter. The first statement in
the main method writes the value of the variable x to the standard output. The
second statement writes the text My Java code to the standard output. Don't forget
that we used here print instead of println, therefor the values of the variable and
the text are written on one line to the standard output.
The Keyword public
Java supports controlling access to the classes and class members by using
special keywords. Using the public keyword for the name of the class or the class
members (variables and methods) indicates that the class or the members are
accessible from other classes. This will be explained later in details.
10. Java standard API (Application Programming Interface)
Java provides a lot of code that can be reused by programmers. It is important for
every Java programmers to use this free rich library, which is why it is introduced
in this book. For some of the assignments, you need to open this document which
helps how to use the code. You can find Java standard API here:
https://docs.oracle.com/javase/8/docs/api/
11. Escape sequences
An escape sequence is a character preceded by a backslash. These characters
have a special meaning for the compiler. For example, if you have a double quote
within a double quote, you must use escape sequences. See the following example.
If you need to write the text “He says: “I go to London.”” to the standard output,
you should do that as follows.
System.out.print("He says: \"I go to Amsterdam\".");
Example 6
public class MyClass
{
public static void main(String[] args)
{
{
System.out.println("Apostrophe: " + "abcde\'fghij");
System.out.println("Double quotation mark : " + "abcde\"fghij");
System.out.println("Backslash: " + "abcde\\fghij");
System.out.println("New line: " + "abcde\nfghij");
System.out.println("New line 2: " + "abcde\ffghij");
System.out.println("Tab : " + "abcde\tfghij");
System.out.print("It was written \"Parking is not Allowed.\".");
}
}
}
If this code is compiled and run, the following is written to the standard output.
Apostrophe : abcde'fghij
Double quotation mark : abcde"fghij
Backslash : abcde\fghij
New line : abcde
fghij
New line 2 : abcdefghij
Tab : abcde fghij
It was written "Parking is not Allowed.".
The table of the escape sequences:
Escape sequence Description
\' single quote
\” double quote
\\ backslash character
\b backspace
\n newline
\r carriage return
\t tab
\f formfeed
Object Oriented Programming (OOP)
Java is an object oriented programming language. The basic idea of the object-
oriented programming is creating a number of objects that communicate with
each other. Each object contains variables, and they communicate thorough
methods. The important principles of the object-oriented programming are
inheritance, polymorphism, and Encapsulation.
1. Inheritance: Inheritance is an important principle of object oriented
programming. Java supports inheritance to allow reusing code and
extending new classes based on exiting ones. Read chapter 11 for more
details about inheritance.
2. Polymorphism: It is the ability to use one method name to invoke many
different methods. There are two types of polymorphism.
1. Overriding or Dynamic Polymorphism: For method
overriding the choice is determined at runtime.
2. Overloading or Static Polymorphism: For method
overloading the choice is determined at compile time.
Read chapter 11 for more details about Overriding
methods and overloading methods.
3. Encapsulation: It is the ability of hiding data implementation by
restricting access to public accessor and mutator methods. Accessors are
used to get information about the state of an object, while mutators allow
you to modify the state of an object.
Chapter 2—Operators
Operators are special symbols that are used to operate on one, two or three
operands and return a result. An example is:
age >= 40
In the previous example, age and 40 are operands of >=.
Java supports different types of operators such as: arithmetic, relational,
conditional, assignment, unary and comparison.
Arithmetic operators
Arithmetic operators are used by working with numbers and mathematical
expressions.
Arithmetic Description
operators
+ (Addition) 3 + 6 returns 9
- (subtraction) 8 – 6 returns 2
* (Multiplication) 4 * 5 returns 20
/ (Division) 20/4 returns 5
% (Modulus) Divides left operand by right
operand and returns remainder
17 % 5 returns 2, because
17/5 = 3 and the rest is 17 – (5
* 3) = 2
Relational operators
Relational operators are used by evaluating two operands for equality. The
answer is either true or false.
Relational Description
Operators
== Equal Checks the value of two
operands. If they are equal
returns true else returns false.
int x = 5, int y = 6;
(x == y) returns false.
!= Not equal Checks the value of two
operands. If they are not equal
returns true else returns false.
int x = 5, int y = 6;
(x != y) returns true.
> Greater than If the left operand value greater
than the right one returns true
else returns false.
(8 > 5) returns true.
< Less than If the left operand value is
smaller than the right one
returns true else returns false.
(8 < 5) returns false.
>= Greater or If the left operand value is
equal greater or equal to the right
one, returns true else returns
false.
(7 >= 7) returns true.
<= Less than or If the left operand value is
equal smaller or equal to the right one
returns true else returns false.
(6 <= 9) returns true
Conditional operators
Conditional operators are used by conditional statements. The conditional
statement types that Java supports are AND (&&) and OR( | | )
Conditional Description
operators
&& AND && combines two boolean
variables and returns true only
if both of its operands are true.
if (3 > 2 && 4 < 6 ) returns
true
if(6 > 3 && 3 < 2) returns false
| | OR | | combines two boolean
variables and returns true if one
or both of its operands are true.
If(1 > 2 | | 6 < 13) returns true
? : Ternary operator
Shorthand formulas
if-then-else statement
int n = 6;
int p = (n == 6) ? 4 :5;
The above statement means the
following.
if(n == 6) {
p = 4;
}
else {
p = 5;
}
Returns 4, because n is equal to
6.
Assignment operators
Assignment operators Description
= Assignment operator Assigns values to
variables.
x = a - b assigns the value
of a - b to x
+= Addition x += 5 is equivalent to x =
Assignment x + 5
-= Subtraction x -= 4 is equivalent to x = x
Assignment – 4
*= Multiplication x *= 3 is equivalent to x = x
Assignment * 3
/= Division x /= 2 is equivalent to x =
Assignment x/2
%= Modulus x %= 2 is equivalent to x =
Assignment x % 2
example 1
int x = 21;
x % 4; is equivalent to x =
x % 4
= 21 % 4 = 1.
x = 21 % 4 = the rest of 21
divided by 4 = 1.
example 2
int x = 17;
x % 3; means x = de rest
van 17/3 = 2.
Unary opeators
Unary operators Description
++ Increment Increments a value by 1.
int x = 20;
++ x returns 21
- - Decrement Decrements a value by 1
int x = 20;
- - x returns 19
! ! reverses the value of a
boolean expression.
boolean isDefected = false;
! isDefected returns true.
Type comparison operator
Comparison Description
operator
instanceof Compares an object to a
specified type.
Objects are later explained in
this book.
The if-block
The blocks of if-statements are only executed if the condition is true.
The following program writes XU to the standard output.
Example
public class IfBlock
{
public static void main(String[] args)
{
if (13 == 6)
{
System.out.print("N");
/*
* This Block is ignored. N is not written to
* the standard output, because 13 is not equal to 6
*/
}
if (12 <= 22)
{
System.out.print("X");
/*
* Writes X to the standard output,
* because 12 is less than 22
*/
}
if (21 > 8 && 3 != 5)
{
System.out.print("U");
/*
* Writes U to the standard output, because
* 21 is greater than 8 and 3 is not equal to 5
*/
}
}
}
Quiz 1: Arithmetic operators
What happens when the following program is compiled and run?
public class Calculate
{
public static void main(String[] args)
{
int x = 20;
int y = 5;
int z = 3;
double d = 2.2;
double d2 = 3.7;
System.out.print(x / y + ", ");
System.out.print(x * z + ", ");
System.out.print(x + y - z + ", ");
System.out.print(x / y + z * 2 + ", ");
System.out.print(d2 - d);
}
}
Select the correct answer:
a. This code writes "4, 60, 22, 10, 1.5" to the standard output.
b. This code writes "4, 60, 22, 14, 1.5 " to the standard output.
Explanation
This exercise is a simple calculation.
x/y = 20/5 = 4;
x*z = 20*3 = 60;
x+y-z = 20+5-3 = 22;
x/y + z*2 = 20/5 + 3*2 = 4 + 6 = 10;
d2- d = 3.7-2.2 = 1.5;
The correct answer is a.
Assignments
What does each of the following three statements write to the standard output if
you add them directly under the statement System.out.println(d2 - d);
System.out.print(x * y / 10 + ", ");
System.out.print(2 * d2 + 2.5 + ", ");
System.out.print(z * 3 - 6);
Quiz 2: Modulus
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
System.out.print(21 % 7 + ", ");
System.out.print(12 % 5 + ", ");
System.out.print(23 % 6);
}
}
Select the correct answer:
a. This code writes "3, 2, 3" to the standard output.
b. This code writes "0, 2, 5" to the standard output.
c. This code writes "3, 2, 5" to the standard output.
Explanation
Modulus % calculates the remainder of the left-hand operand divided by the right
one.
21/7 = 3. The remainder is 21 - (3 * 7) = 0.
12/5 = 2. The remainder is 12 - (5 * 2) = 12 -10 = 2.
23 % 6 = 3. The remainder is 23 - (6 * 3) = 23 -18 = 5
The correct answer is b.
Assignments
What does each of the following three statements write to the standard output if
you add them directly under the statement System.out.println(23 % 6);.
System.out.print(44 % 10 + ", ");
System.out.print(7 % 2 + ", ");
System.out.print(30 % 3);
Quiz 3: Increments & decrements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int x = 4;
int y = 6;
x--;
y++;
System.out.print(x + ", " + y);
}
}
Select the correct answer:
a. This code writes "4, 7" to the standard output.
b. This code writes "4, 6" to the standard output.
c. This code writes "3, 7" to the standard output.
d. This code writes "3, 6" to the standard output.
Explanation
x = 4 and y = 6.
x-- decrements the value of x by 1.
x = x - 1 = 4 -1 = 3;
y++ increments the value of y by 1.
y = y + 1 = 6 + 1 = 7
The correct answer is c.
Assignments
Research the following and execute the program to check out your expectation.
1. Add the statement x++; directly under the statement System.out.print(x + ",
" + y);.
2. Change the position of the statement x++; directly above the statement
System.out.print(x + ", " + y);.
Does the position of the statement x++; in de code make any difference?
Quiz 4: Relational operators
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int x = 3;
int y = 8;
int z = 3;
if (x == z)
{
System.out.print("N");
}
if (x >= y)
{
System.out.print("O");
}
if (x <= z)
{
System.out.print("P");
}
if (z > y)
{
System.out.print("Q");
}
if (y != z)
{
System.out.print("R");
}
}
}
Select the correct answer:
a. This code writes "NOPQR" to the standard output.
b. This code writes "NR" to the standard output.
c. This code writes "NPR" to the standard output.
d. This code writes nothing to the standard output.
Explanation
The conditional statement if(x == z) returns true, because both variables are equal
to 3.
N will be printed to the standard output.
The conditional statement if(x >= y) returns false because x is not greater or equal
to y.
The conditional statement if(x <= z) returns true, because x is equal to z and equal
to 3.
The letter P is written to the standard output.
The conditional statement if(z > y) is false because z = 3, but y = 8.
The conditional statement if(y != z) is true because z doesn't equal to y.
The letter R is written to the standard output.
The correct answer is c.
Assignments
1. What is written to the standard output if you make the following changes?
2. Assign a new value 15 to the variable x and add the statement
3. System.out.print("Z"); directly under the statement System.out.print("O");
4. Execute the program to check out your expectation.
Quiz 5: Conditional operators
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
boolean isDefect = true;
int x = 2;
int y = 7;
int z = 9;
if (x < y && x > 1)
{
System.out.print("N");
}
if (z > y || x > y)
{
System.out.print("O");
}
if (!isDefect)
{
System.out.print("P");
}
}
}
Select the correct answer:
a. This code writes "NO" to the standard output.
b. This code writes "OP" to the standard output.
c. This code writes "NP" to the standard output.
Explanation
The condition if(x < y && x > 1) returns true, because both operands are true.
The condition if(z > y || x > y) returns true, because the operand z > y is true.
|| (conditional or) returns true if one or both operands are true.
The condition if( ! isDefect) returns false, because isDetected is true and the sign !
reverses the value of the boolean.
The correct answer is a.
Assignments
What is written to the standard output if you make the following changes to the
program?
Compile and run the code to check out your expectation.
1. Assign the value false to the variable isDefect.
2. Assign the value 1 to the variable x.
Quiz 6: Conditional operators
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
boolean isOld = false;
int x = 5;
int y = 14;
int z = 18;
if (y > x && z > y && (x + 12) >= z)
{
System.out.print("P");
}
if (x >= 6 || z <= y || z <= 18)
{
System.out.print("Q");
}
if (!isOld || y > z)
{
System.out.print("R");
}
}
}
Select the correct answer:
a. This code writes "PR" to the standard output.
b. This code writes "QR" to the standard output.
c. This code writes "PQR" to the standard output.
d. This code writes "PQ" to the standard output.
Explanation
The condition if(y > x && z > y && (x + 12) >= z) returns false, because one of
the operands namely (x + 12) >= z returns false.
The condition if(x >= 4 || z <= y || z <= 18) returns true, because one of the
operands return true namely z <= 18.
if( ! isOld || y > z) returns true, because one of the operands namely !isOld is true.
The correct answer is b.
Assignments
What is written to the standard output if you make the following changes to the
program?
Compile and run the code to check out your expectation.
1. Assign the value "true" to the variable isOld.
2. Assign the value "17" to the variable "z".
Quiz 7: Assignment operators
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i1 = 3;
int i2 = 5;
int i3 = 12;
int i4 = 20;
i1 += 4;
i2 *= 3;
i3 /= 3;
i4 -= 12;
System.out.print(i1 + ", ");
System.out.print(i2 + ", ");
System.out.print(i3 + ", ");
System.out.print(i4 + " ");
}
}
Select the correct answer:
a. This code writes "3, 5, 12, 20" to the standard output.
b. This code writes "4, 3, 3, 12" to the standard output.
c. This code writes "7, 15, 3, 8" to the standard output.
d. This code writes "7, 15, 4, 8 " to the standard output.
Explanation
i1 += 4 is equivalent to i1 = i1 + 4 = 3 + 4 = 7
i2 *= 3 is equivalent to i2 = i2 * 3 = 5 * 3 = 15
i3 /= 3 is equivalent to i3 = i3 / 3 = 12 / 3 = 4
i4 -= 12 is equivalent to i4 = i4 - 12 = 20 - 12 = 8
The correct answer is d.
Assignments
What is written to the standard output if you add the following statements to the
program?
Compile and run the code to check out your expectation.
Add the following statements directly under the statement i4 -= 12;.
1. i1 ++ ;
2. i2 -= 3;
3. i3 *= 2;
4. i4 /= 4;
Quiz 8: Assignment operators
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i1 = 22;
int i2 = 17;
int i3 = 30;
i1 %= 6;
i2 %= 5;
i3 %= 6;
System.out.print(i1 + " ");
System.out.print(i2 + " ");
System.out.print(i3 + " ");
}
}
Select the correct answer:
a. This code writes "3, 3, 5" to the standard output.
b. This code writes "4, 2, 0" to the standard output.
c. This code writes "3, 3, 1" to the standard output.
d. This code writes "2, 2, 0" to the standard output.
Explanation
22 %= 6. is equal to 4
17%= 5 is equal to 2
30%= 3 is equal to 0
The correct answer is b.
Assignments
What is written to the standard output if you add the following statements to the
program?
Compile and run the program to check out your expectation.
Add the following statements directly under the statement i3 %= 6;.
1. i1 %= 3;
2. i2 %= 7;
Quiz 9: Ternary operator
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int x = 3;
int x2 = 8;
int y = (x == 3) ? 24 : 8;
int z = (x2 == 4) ? 33 : 21;
System.out.print(y);
System.out.print(z);
}
}
Select the correct answer:
a. This code writes "833" to the standard output.
b. This code writes "2433" to the standard output.
c. This code writes "821" to the standard output.
d. This code writes "2421" to the standard output.
Explanation
The statement int y = (x == 3) ? 24: 8; is equivalent to:
if x is equal to 3, y is equal to 24;
if x is not equal to 3, y is equal to 8.
This returns 24, because x is equal to 3.
The statement int y = (x2 == 4) ? 33 : 21; returns 21, because x2 is not equal to 4.
The correct answer is d.
Assignments
Assign the value 6 to the variable x and 4 to the variable x2. Wat is written to the
standard output if you compile and run the program?
Chapter 3—Conditional
Statements
if statements
The if statement tells the program to execute a certain block of code only if the
condition is true.
In the following example the statement if(11 != 11) returns false. Therefore the
body of the block is ignored. The letter A is not written to the standard output.
The statement if(12 > = 8) returns true, therefore the second block is executed,
and the letter B is written to the standard output.
The statement if(6 <= 13) returns true, therefore the third block is executed. The
letter C is written to the standard output.
The statement if(5 >= 7) returns false. Therefore the fourth block is ignored.
The letter D is not written to the standard output.
Example 1
public class MyClass
{
public static void main(String[] args)
{
// Block 1
if (11 != 11)
{
System.out.print("A");
}
// Block 2
if (12 >= 8)
{
System.out.print("B");
}
// Block 3
if (6 <= 13)
{
System.out.print("C");
}
// Block 4
if (5 >= 7)
{
System.out.print("D");
}
}
}
if/else statements
The if statement allows executing a certain block of code only if the condition is
evaluated as true. If the condition returns false, the else block will be executed. In
the following example, The statement if(8 != 9) returns true. Therefore the first
block is executed. The letter X is written to the standard output.
The statement if(6 >= 8) returns false. Therefore the second block is ignored.
The letter Y is not written to the standard output.
The else block (block 3) is executed because the last if-block (block 2) returns
false.
The letter Z is written to the standard output.
Example 2
public class MyClass
{
public static void main(String[] args)
{
// Block 1
if (8 != 9)
{
System.out.print("X");
}
// Block 2
if (6 >= 8)
{
System.out.print("Y");
}
// Block 3
else
{
System.out.print("Z");
}
}
}
if-/else-if statements
By working with a ladder of if/ else-if statements, the program starts with the first
if statement. As soon as a block is evaluated as true, the block associated with that
statement is executed. The remaining part of the ladder is ignored by the program.
If the condition returns false, the block is ignored, and the program continues with
the next else-if statement. As soon as a block is evaluated as true, the block is
executed and the program will ignore the remaining part of the else-if series.
In the following example, The statement if(6 == 9) returns false Therefore the
first block is ignored, and P is not written to the standard output. The program
continues with the next statement.
The statement if(4 >= 3) returns true, therefore the second block is executed.
The letter Q is written to the standard output. The rest of the blocks are ignored,
regardless whether the conditions return true or false.
Example 3
public class MyClass
{
public static void main(String[] args)
{
// Block 1
if (6 == 9)
{
System.out.print("P");
}
// Block 2
else if (4 >= 3)
{
System.out.print("Q");
}
// Block 3
else if (5 > 4)
{
System.out.print("R");
}
// Block 4
else
{
System.out.print("S");
}
}
}
switch-/case statements
The switch statement is used to make a choice from several options. In such cases,
if-else statements are not handy, because you need to write a lot of statements to
achieve the same goal that can be easier achieved with a switch statement. See
example 4. A switch statement starts with the keyword switch.
switch-expression
The switch expression starts after the keyword switch in switch statements. A
switch expression is between parentheses. The switch expression must be of type
int , char , byte, or short. An example is: switch(day) .
case-label
The constants that are behind the word case are case-labels. The case labels
are of the same variable type as the switch-expression, and they are ended with a
colon.
Examples
case 1: // A switch expression of the type int
case 'g': // A switch expression of the type char
Break statements
Without the break statement, the next case statement is executed. In most cases,
each case statement should use a break statement.
Default options
The default option is usually the last option in a switch statement. If none of the
cases match the switch expression, the default block will be executed. In example
4, an integer variable is declared, for the days of the week.
The day Sunday is 1, Monday is 2, and so on. If the variable day is equal to 1,
the statement after case, 1 is executed. In this case, Sunday is written to the
standard output. If the variable day is equal to 5, the statement under case 5 is
executed. In this case Thursday is written to the standard output, and so on.
If you choose a number that will not match with any of the case labels, the
default statement is executed. In that case, Invalid is written to the standard output.
Note that the execution of the program continues with the rest of the cases if you
remove all the break statements. In example 4, the day is an integer variable that is
equal to 5. Therefore, the statement after case 5 is executed, and Thursday is
written to the standard output. The program will not continue with the execution of
the rest of the statements because case 5 is ended with a break statement.
Example 4
public class Days
{
public static void main(String[] args)
{
int day = 5;
switch (day)
{
case 1:
System.out.print("Sunday");
break;
case 2:
System.out.print("Monday");
break;
case 3:
System.out.print("Tuesday");
break;
case 4:
System.out.print("Wednesday");
break;
case 5:
System.out.print("Thursday");
break;
case 6:
System.out.print("Friday");
break;
case 7:
System.out.print("Saturday");
break;
default:
System.out.print("Invalid");
}
}
}
You can also write the cases behind each other, as you see in example 5. If the
variable day is equal to 1, 2, 3, 4 and 5, the word Business day is written to the
standard output. If the variable day is equal to 6 or 7 the word Weekend is written
to the standard output. For all other numbers, the word Invalid is written to the
standard output.
Example 5
public class Days
{
public static void main(String[] args)
{
int day = 4;
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.print("Business day.");
break;
case 6:
case 7:
System.out.print("Weekend.");
break;
default:
System.out.print("Invalid");
}
}
}
You can write the previous program using if-else-statements.
Example 6
public class Days
{
public static void main(String[] args)
{
int day = 4;
if (day > 0 && day <= 5)
{
System.out.print("Business day.");
}
else if (day == 6 || day == 7)
{
System.out.print("Weekend.");
}
else
{
System.out.print("Invalid.");
}
}
}
Quiz 1: if statements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i = 2;
if (i > 0)
{
System.out.print("X");
System.out.print("Y");
}
if (i > 3)
{
System.out.print("Z");
}
}
}
Select the correct answer:
a. This code writes "X" to the standard output.
b. This code writes "XY" to the standard output.
c. This code writes "Z" to the standard output.
d. This code writes "XYZ" to the standard output.
Explanation
The statement if(i > 0) is true, therefore the block is executed.
The statement System.out.print(“X”); writes X to the standard output.
The statement System.out.print(“Y”); writes Y to the standard output.
The statement if(i > 3) is false, because i is equal to 2, therefore this if block is
ignored.
The correct answer is b.
Assignments
Add your own conditional statement to the program, and check out whether i is
equal to 2.
If your statement is true, the program should write "NXY" to the standard output.
Compile and run the program to check out your expectation.
Quiz 2: if statements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int a = 3;
int b = 1;
int x = 0;
if (a > b)
{
x++;
if (a > x)
{
x += 5;
}
x -= 4;
}
if (b == a)
{
x += 2;
if (x < b)
{
x += 3;
}
}
System.out.print(x);
}
}
Select the correct answer:
a. This code writes "0" to the standard output.
b. This code writes "1" to the standard output.
c. This code writes "3" to the standard output.
d. This code writes "2" to the standard output.
Explanation
The statement if(a > b) is true. Therefore, the program executes the block.
The statement x++; adds one to the initial value of x.
x = 0 + 1.
The statement if(a > x) returns true.
The statement x += 5; adds 5 to the value of x.
x = 1 + 5= 6
The statement x -= 4; is equivalent to x = x - 4 = 6 – 4 = 2.
The next if block is:
if(b == a) which returns false. That is why the whole block is ignored.
The correct answer is d.
Assignments
Add your own conditional statement to the program, and check out whether the
variable a is equal or smaller than 4.
If your statement returns true, the program should write 2G to the standard output.
Compile and run the program to check out your expectation.
Quiz 3: if-else statements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
char c1 = 'g';
char c2 = 'h';
if (c1 == 'k')
{
System.out.print('w');
}
if (c2 == 'h')
{
System.out.print('x');
System.out.print('p');
}
if (c1 != c2)
{
System.out.print('y');
}
else
{
System.out.print('z');
}
}
}
Select the correct answer:
a. This code writes "x" to the standard output.
b. This code writes "xpy" to the standard output.
c. This code writes "y" to the standard output.
d. This code writes "xz" to the standard output.
e. This code writes "xy" to the standard output.
Explanation
The first statement if(c1 == 'k') is false, therefore the block is ignored.
The Second statement if(c2 == 'h') is true, therefore the block is executed.
The letters x and p is printed to the standard output.
The third statement if(c1 != c2) is true, and the letter y is printed to the standard
output.
The last if statement is true, which is why the else block will not be executed.
The correct answer is b.
Assignments
Add your own conditional statement to the program, and check out whether c1 is
equal to 'd'.
If your statement is false, the program should write "xpyz" to the standard output.
Note that position of your control statement is important.
Compile and run the program to check out your expectation.
Quiz 4: if/else-if statements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int a = 2;
int b = 2;
int x = 5;
if (a == b)
{
x++;
}
else if (b == 2)
{
x += 2;
}
else
{
x += 3;
}
System.out.print(x);
}
}
Select the correct answer:
a. This code writes "5" to the standard output.
b. This code writes "6" to the standard output.
c. This code writes "8" to the standard output.
d. This code writes "7" to the standard output.
Explanation
The first statement if(a == b) is true.
The second statement else-if is also true, but it is ignored by the program.
By if-/else-if statements, only the first true condition is executed.
In this example, the first true statement is the first statement.
The statement x++; increments the value of x by one.
x = 5 + 1 = 6
The correct answer is b.
Assignments
Change the first conditional statement to if(a != b) and add your own conditional
statement to the program. Check out whether the variable b is equal or greater than
1. Your statement should be somewhere between the first statement if(a != b) and
the last else statement.
The program should write X5 to the standard output.
Quiz 5: if/else-if statements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i = 1;
int i2 = 4;
int x = 2;
if (i == (i2 - 3) && i2 > 5)
{
x++;
}
else if (i2 == 4)
{
x += 2;
}
else if (i2 > 3)
{
x += 3;
}
else
{
x += 4;
}
System.out.print(x);
}
}
Select the correct answer:
a. This code writes "2" to the standard output.
b. This code writes "3" to the standard output.
c. This code writes "4" to the standard output.
d. This code writes "7" to the standard output.
e. This code writes "5" to the standard output.
Explanation
The first if statement if(i == (i2 - 3) && i2 > (i + 3)) is false, because i2 is not
greater than
(i + 3).
The second statement else-if(i2 == 4) is true, therefore this block is executed. The
rest of the blocks are ignored because the first true else-if statement is found.
The statement x += 2 increments the value of x by 2.
x = 2 + 2 = 4.
The correct answer is c.
Assignments
Add another else-if statement to the program that checks out whether i + i2 = 5.
If your statement returns true, the program should write D2 to the standard output.
Compile and run the program to check out your expectation.
Quiz 6: A combination of conditional statements
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i1 = 3;
int i2 = 9;
int i3 = 12;
int x = 0;
if (x > -1)
{
x++;
if (i3 == (i1 + i2))
{
x += 4;
if (i1 < 5)
{
x += 2;
}
else if (i2 == 9)
{
x++;
}
else
{
x -= 2;
}
x -= 6;
}
if (i3 < 10)
{
x += 7;
}
else
{
x += 5;
}
}
System.out.print(x);
}
}
Select the correct answer:
a. This code writes "5" to the standard output.
b. This code writes "13" to the standard output.
c. This code writes "7" to the standard output.
d. This code writes "12" to the standard output.
e. This code writes "6" to the standard output.
Explanation
The first statement if(x > - 1) returns true, therefore the block is executed.
The statement x ++; adds one to the value of x.
x = 0 + 1 = 1;
The statement if(i3 == (i1 + i2)) also returns true.
The statement x += 4; adds 4 to the value of x.
x = 1 + 4 = 5;
The statement if(i1 < 5) returns true. The statement x += 2; adds 2 to the value of
x.
x = 5 + 2 = 7;
The rest of the if/else-if blocks are ignored. Read the explanation of if/else-if
statements.
The statement x -= 6; decrements the value of x by 6.
x = x - 6 = 7 - 6 = 1;
The statement if(i3 < 10) is false, therefore the block is ignored.
The else statement is executed because the last if statement if(i3 < 10) is false.
The statement x += 5; increments the value of x by 5.
x = x + 5 = 1 + 5 = 6;
The correct answer is e.
Assignments
Add another statement System.out.print(x); to this program.
Choose a position that the code writes "76" to the standard output.
Compile and run the program to check out your expectation.
Quiz 7: Conditional statements inside each other
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i = 2;
int i2 = 5;
int i3 = 9;
int x = 3;
boolean isSlow = true;
if (isSlow)
{
x++;
if (i >= 2 && i2 > 7)
{
x += 4;
System.out.print("x" + x + ", ");
if (i3 == 9)
{
x += 5;
System.out.print("x" + x + ", ");
}
}
else
{
x += 6;
System.out.print("x" + x + ", ");
if (i3 >= 3)
{
x += 7;
}
System.out.print("x" + x + ", ");
}
x += 3;
}
System.out.print("x" + x);
}
}
Select the correct answer:
a. This code writes "x8, x13, x10, x17, x20" to the standard output.
b. This code writes "x10, x17, x20" to the standard output.
c. This code writes "x8, x13, x16" to the standard output.
d. This code writes "x10, x10, x20" to the standard output.
e. This code writes "x10, x10, x17" to the standard output.
Explanation
The statement if(isSlow) returns true, the block is executed and the statement x++;
increments the value of x by 1.
x = 3 + 1 = 4;
The statement if(i >= 2 && i2 > 7) returns false, because i2 is not greater than 7.
The block is ignored.
The program starts to execute the else block. The statement x += 6; increments the
value of x by 6.
x = 4 + 6 = 10;
The statement System.out.print("x" + x + ", "); writes x10 to the standard output.
The statement if(i3 >= 3) returns true, therfore the statement x += 7; adds 7 to the
value of x.
x = 10 + 7 = 17;
The statement System.out.print("x" + x + ", "); writes x17 to the standard output.
The statement x+=3; increments the value of x by 3.
x = 17 + 3 = 20.
The statement System.out.print("x" + x ); writes x20 to the standard output.
The correct answer is b.
Assignment
What is written to the standard output if you add the statement
System.out.print("x" + x + ", "); to the program directly under the statement x ++.
Compile and run the program to check out your expectation.
Quiz 8: A simple switch statement
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int x = 8;
switch (x)
{
case 6:
x += 5;
case 7:
x += 3;
case 8:
x += 2;
case 9:
x++;
break;
default:
x += 4;
}
System.out.print(x);
}
}
Select the correct answer:
a. This code writes "8" to the standard output.
b. This code writes "15" to the standard output.
c. This code writes "10" to the standard output.
d. This code writes "11" to the standard output.
e. This code writes "14" to the standard output.
Explanation
The cases 6, 7 are ignored, because x is equal to 8
case 8 is executed, and the statement x+=2 adds 2 to the initial value of x.
x = 8 + 2 = 10.
case 8 doesn't end with a break statement, therefore case 9 is also executed.
The statement x++; increments the value of x by one.
x = 10 + 1 = 11; case 9 ends with a break statement, therefore the default block is
ignored.
The statement System.out.print(x); prints the value of x to the standard output.
The correct answer is d.
Assignments
1. What is written to the standard output if you remove the break statement?
2. What is written to the standard output if you add another break statement under
the statement x +=2; of the case 8.
Quiz 9: A switch statement to demonstrate the months of the year
What happens when the following program is compiled and run?
public class Year
{
public static void main(String[] args)
{
int intMonth = 10;
String strMonth;
switch (intMonth)
{
case 1:
strMonth = "JAN ";
case 2:
strMonth = "FEB ";
case 3:
strMonth = "MAR ";
case 4:
strMonth = "APR ";
case 5:
strMonth = "MAY ";
case 6:
strMonth = "JUN ";
case 7:
strMonth = "JUL ";
case 8:
strMonth = "AUG ";
case 9:
strMonth = "SEP ";
case 10:
strMonth = "OCT ";
case 11:
strMonth = "NOV ";
case 12:
strMonth = "DEC ";
break;
default:
strMonth = "INVALID ";
}
System.out.println(strMonth);
}
}
Select the correct answer:
a. This code writes "NOV" to the standard output.
b. This code writes "AUG SEP OCT NOV DEC" to the standard output.
c. This code writes "OCT NOV DEC" to the standard output.
d. This code writes "INVALID" to the standard output.
e. This code writes "DEC" to the standard output.
f. This code writes "OCT" to the standard output.
Explanation
case 10 matches the variable of the variable intMonth.
OCT is assigned to strMonth, but case 10 is not ended with a break statement.
That is why the case 11 is also executed and the value NOV is assigned strMonth.
Since there is no break in case 11, case 12 is also executed. The value DEC is
assigned to strMonth.
The correct answer is e.
Assignments
This program doesn't function correctly. The goal is that for each value of
intMonth the program should write the right month symbol to the standard output
as follows.
1. If intMonth is equal to 1, the code must write JAN to the standard output.
2. If intMonth is equal to 2, the code must write FEB to the standard output.
3. If intMonth is equal to 3, the code must write MAR to the standard output.
4. If intMonth is equal to 4, the code must write APR to the standard output.
5. If intMonth is equal to 5, the code must write MAY to the standard output.
6. If intMonth is equal to 6, the code must write JUN to the standard output.
7. If intMonth is equal to 7, the code must write JUL to the standard output.
8. If intMonth is equal to 8, the code must write AUG to the standard output.
9. If intMonth is equal to 9, the code must write SEP to the standard output.
10. If intMonth is equal to 10, the code must write OCT to the standard
output.
11. If intMonth is equal to 11, the code must write NOV to the standard
output.
12. If intMonth is equal to 12, the code must write DEC to the standard
output.
13. By other values, the program should write INVALID to the standard
output.
Compile and run the program for each value of intMonth to check out your answer.
Quiz 10: A switch statement represents student's grades
What happens when the following program is compiled and run?
public class Examen
{
public static void main(String args[])
{
char grade = 'C';
switch (grade)
{
case 'A':
System.out.print("Excellent! ");
break;
case 'B':
System.out.print("Very good ");
break;
case 'C':
case 'D':
System.out.print("Good ");
case 'E':
System.out.print("Try again ");
break;
default:
System.out.print("Invalid ");
}
}
}
Select the correct answer:
a. This code writes "Good" to the standard output.
b. This code writes "Try again" to the standard output.
c. This code writes "Invalid" to the standard output.
d. This code writes "Good Try again" to the standard output.
e. This code writes nothing to the standard output.
Explanation
There are no statements in case C not even a break. Therefore case D is executed.
case D writes Good to the standard output. There is no break in case D, therefore
case E is executed. The statement writes Try again to the standard output.
The correct answer is d.
Assignments
This program doesn't function correctly.
1. If the variable grade is equal to C, the program should write Good to the
standard output.
2. If the variable grade is equal to D, the program should write Fair to the
standard output.
3. What would happen if grade is equal to N? Compile and run the program to
check out your expectation.
Chapter 4—Iteration
(Loop) Statements
Iteration or loop statements are used to handle processes that are one or more
times repeated. There are three types of loops in Java namely: for, while and do
while.
A loop consists of two parts:
1. A control part: the repetitions are determined in the control part.
2. A body: the body contains the statements that have to be repeated.
for loop
The for-loop is used very frequently in Java. If you know in advance how often a
loop must be repeated, the for loop is probably the best choice. In the following
example, you see that the initial value of the integer variable i is 0. By each
execution of the body the statement i ++ increments the value of the variable i by
one. The repetition continues as long as the condition i < 4 is true.
1. In the beginning, the variable i is equal to 0 . The body is executed, and
the letter x is written to the standard output.
2. In the second repetition, the variable i is equal to 1. The body is for the
second time executed, and the letter x is again written to the standard
output.
3. In the third iteration, the variable i is equal to 2. The body is for the third
time executed, and the letter x is again written to the standard output.
4. In the fourth iteration, the variable i is equal to 3. The body is for the
fourth time is executed, and the letter x is again written to the standard
output.
After the fourth repetition the body is no longer executed, because after the fourth
time the variable i is equal to 4. This loop writes xxxx to the standard output.
Example 1
public class MyClass
{
public static void main(String[] args)
{
for (int i = 0; i < 4; i++) // the control part
{
System.out.print("x"); // the body
}
}
}
while loop
The while loop begins with an evaluation of a condition. If the condition returns
true, the body will be executed. The execution of the body of the loop is repeated
as long as the condition returns true. If the condition returns false the loop will be
terminated. In the following example, the variable number is equal to 1. As long
as the variable number is smaller than or equal to 5, the body of the loop is
executed. If the body is executed the statement number ++; increments the value of
the variable number by one. This loop writes 12345 to the standard output.
Example 2
public class MyClass
{
public static void main(String[] args)
{
int number = 1;
while (number <= 5) // the control part
{
System.out.print(number); // the body
number++;
}
}
}
do-while loop
The body of the do-while loop is executed at least once because the condition
is evaluated after executing the body. The execution of the loop is continued until
the condition returns false. When the condition is false, the loop is terminated. In
the following example, the loop starts with the statement i ++, which increments
the value of i by 1. As long as the variable i is unequal to 3, the body of the loop
is executed, and the letter z is written to the standard output. The following
example writes zz to the standard output.
Example 3
public class MyClass
{
public static void main(String[] args)
{
int i = 1;
do
{
i++;
System.out.print("z"); // the body
}
while (i != 3); // the control part
}
}
The break statement
Sometimes there is no need for a loop to continue, once a certain information is
found, or a specific goal is achieved. In this kind of cases, we can terminate the
loop with the break statement. In the following example, the execution of the loop
terminates as soon as the variable i is equal to 7. Without the break statement, the
repetition continues as long as the variable i is smaller than 20. The following
loop writes 0123456 to the standard output.
Example 4
public class MyClass
{
public static void main(String[] args)
{
for (int i = 0; i < 20; i++)
{
if (i == 7)
{
break;
}
System.out.print(i);
}
}
}
The continue statement
The continue statement skips a certain execution of a loop. The following loop
writes 12467 to the standard output because the continue statement is used. If the
variable i is equal to 3 or 5 the continue statement skips these two iterations, that
is why these two numbers are not written to the standard output.
Example 5
public class MyClass
{
public static void main(String[] args)
{
for (int i = 1; i <= 7; i++)
{
if (i == 3 || i == 5)
{
continue;
}
System.out.print(i);
}
}
}
The label
Labels are used to manage two or more loops within each other. Java supports
labels to refer to a specific line of the code. In the following example is a seat
number determined by its row number and column number. We are looking for a
seat with a row number 1 and column number 3. As soon as the seat is found, the
execution of the loops should be terminated. We first try to achieve this with the
break statement.
Example 6
package _04_iteration_statements.ex._06;
public class MyClass
{
public static void main(String[] args)
{
for (int row = 1; row < 3; row++)
{
for (int col = 1; col < 4; col++)
{
if (row == 1 && col == 3)
{
System.out.println("row: " + row + " col: " + col + " is found");
break;
}
System.out.println("row: " + row + " col: " + col + ", ");
}
}
}
}
After the seat has been found, the outer loop continues with the second row and
writes the seats of the second row to the standard output as shown below.
row: 1 col: 1,
row: 1 col: 2,
row: 1 col: 3 is found
row: 2 col: 1,
row: 2 col: 2,
row: 2 col: 3,
To terminate both loops, we need to label the first loop as outer for example. In
example 7 we use the statement break outer to terminate the loops when the seat is
found.
Example 7
public class MyClass
{
public static void main(String[] args)
{
outer:for (int row = 1; row < 3; row++)
{
for (int col = 1; col < 4; col++)
{
if (row == 1 && col == 3)
{
System.out.println("row: " + row + " col: " + col + " is found");
break outer;
}
System.out.println("row: " + row + " col: " + col + ", ");
}
}
}
}
If the code of example 7 is compiled and run, it writes the following to the
standard output.
row: 1 col: 1,
row: 1 col: 2,
row: 1 col: 3 is found
Quiz 1: While loop statement
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
int i = 4;
while (i > 1)
{
i--;
System.out.print(i);
}
}
}
Select the correct answer:
a. This code writes "4321" to the standard output.
b. This code writes "321" to the standard output.
c. This code writes "432" to the standard output.
d. This code writes "123" to the standard output.
e. This code writes "234" to the standard output.
f. This code writes "1234" to the standard output.
Explanation
The value of i is equal to 4.
The condition while(i > 1) is true, because i = 4.
i-- decrements the value of I by one.
i = 4 - 1 = 3.
The statement System.out.print(i); prints 3 to the standard output.
The condition while(i > 1) is still true, because i = 3.
i-- decrements the value of I by one.
i = 3 - 1 = 2
The statement System.out.print(i); prints 2 to the standard output.
The condition while(i > 1) is still true, because i = 2.
i-- decrements the value of i by one.
i = 2 - 1 = 1
The statement System.out.print(i); prints 1 to the standard output.
The condition while(i > 1) is false, because i = 1.
The loop is terminated.
The correct answer is b.
Assignments
1. Assign the value 3 to the variable i. What is written to the standard output if
you compile and run the program?
2. Assign the values 1, 2 and 5 to the variable i. Compile and run the program to
see what happens.
Quiz 2: While loop statement
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
int i = 8;
while (i > 1)
{
i++;
System.out.print(i);
i -= 5;
}
}
}
Select the correct answer:
a. This code writes "95" to the standard output.
b. This code writes "9876543" to the standard output.
c. This code writes "84" to the standard output.
d. This code writes "9753" to the standard output.
e. This code writes "975" to the standard output.
f. This code writes "864" to the standard output.
Explanation
The initial value of i is 8.
The condition while(i > 1 returns true, i++ increments i by one
i = 8 + 1 = 9.
The statement System.out.print(i); prints 9 to the standard output.
i -= 5 decrements i by 5.
i = 9 - 5 = 4.
The condition while(i > 1) is still true, because i is equal to 4.
i = i + 1 = 5.
The statement System.out.print(i); prints 5 to the standard output.
i -= 5 decrements i by 5.
i = 5 - 5 = 0.
The condition while(i > 1) returns false, because i is not greater than 1.
The loop is terminated.
The correct answer is a.
Assignments
If you remove the statement i -= 5 from the program, the program loops endlessly.
What is your explanation for that?
Quiz 3: do-While loop
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
int i = 2;
do
{
i += 5;
System.out.print(i);
}
while (i <= 12);
}
}
Select the correct answer:
a. This code writes "712" to the standard output.
b. This code writes "7" to the standard output.
c. This code writes "2712" to the standard output.
d. This code writes "2" to the standard output.
e. This code writes "71217" to the standard output.
f. This code writes nothing to the standard output.
Explanation
The first execution of the loop:
The initial value of i is 2.
I += 5; increments I by 5.
i = 2 + 5 = 7.
The statement System.out.print(i); prints 7 to the standard output.
The condition while(i <= 12); is true, because i = 7 and it is smaller than 12
The second execution of the loop:
i = 7 + 5 = 12.
The statement System.out.print(i); prints 12 to the standard output.
The condition while(i <= 12); is still true, because i = 12.
The third execution of the loop:
i = 12 + 5 = 17.
The statement System.out.print(i); prints 17 to the standard output.
The condition while(i <= 12); is false, because i = 17 and it is greater than 12.
The loop is terminated.
The correct answer is e.
Assignments
What is the result if you change the initial value of i to 4 and replace the statement
i += 5; with i += 6;? Compile and run the program to check out your expectation.
Quiz 4: do-While loop
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
int i = 1;
do
{
i += 3;
if (i != 4)
{
System.out.print("x");
}
else
{
System.out.print("y");
}
}
while (i != 10);
}
}
Select the correct answer:
a. This code writes "xyy" to the standard output.
b. This code writes "yxyy" to the standard output.
c. This code writes "xxy" to the standard output.
d. This code writes "yxxx" to the standard output.
e. This code writes "yxx" to the standard output.
f. This code writes nothing to the standard output.
Explanation
The first execution of the loop:
The initial value of i is 1, i += 3.
i = 1 + 3 = 4.
The condition if(i != 4) returns false, because i is equal to 4.
The statement System.out.print("y"); prints y to the standard output.
The condition while(i != 10); is true, because i = 4.
The second execution of the loop:
i = 4 + 3 = 7.
The condition if(i != 4) returns true, because i is equal to 7.
The statement System.out.print("x"); prints x to the standard output.
The condition while(i != 10); is true, because i = 7.
The third execution of the loop:
i = 7 + 3 = 10.
The condition if(i != 4) returns true, because i is equal to 10.
The statement System.out.print("x"); prints x to the standard output.
The condition while(i != 10); is false, because i = 10.
The loop is terminated.
The correct answer is e.
Assignments
1. What happens if you change the initial value of i to 2?
2. What is written to the standard output if you change the initial value of i to 2,
and you replace the statement while(i != 10) with the statement while(i < 10).
Compile and run the program to check out your expectation.
Quiz 5: for loop statement
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
for (int i = 4; i < 7; i++)
{
System.out.print(i);
}
}
}
Select the correct answer:
a. This code writes "4567" to the standard output.
b. This code writes "456" to the standard output.
c. This code writes "56" to the standard output.
d. This code writes "567" to the standard output.
e. This code writes "45" to the standard output.
f. This code writes "654" to the standard output.
Explanation
The first loop execution:
The condition for(int i = 4; i < 7; i ++ ) is true, because the initial value of i = 4
and that is smaller than 7.
As long as i is smaller than 7 the program adds one to the value of i executes the
body of the loop. The statement System.out.print(i); prints 4 to the standard output.
The second loop execution:
The condition for(int i = 4; i < 7; i ++ ) is still true, because i = 4 + 1 = 5.
5 is smaller than 7.
The statement System.out.print(i); prints 5 to the standard output.
The third loop execution:
The condition for(int i = 4; i < 7; i ++ ) is still true, because i = 5 + 1 = 6.
6 is smaller than 7.
The statement System.out.print(i); prints 6 to the standard output.
After that the loop is terminated, because i = 6 + 1 = 7 and that is not smaller than
7.
The correct answer is b.
Assignment
What happens when you replace the statement for(int i = 4; i < 7; i ++ ) with
for(int i = 1; i < 10; i += 3 )? Compile and run the program to check out your
expectation.
Quiz 6: for loop statement
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
int x = 1;
for (int i = 1; i < 7; i += 2)
{
x += i;
}
x -= 2;
System.out.print(x);
}
}
Select the correct answer:
a. This code writes "8" to the standard output.
b. This code writes "7" to the standard output.
c. This code writes "2" to the standard output.
d. This code writes "5" to the standard output.
e. This code writes "9" to the standard output.
f. This code writes "0" to the standard output.
Explanation
The first loop execution:
The condition for(int i = 1; i < 7; i += 2) is true, because the initial value of i = 1
and that is smaller than 7.
As long as i is smaller than 7 execute the body of the loop.
The initial value of x is 1.
x += i, x = 1 + i = 1 + 1 = 2.
The second loop execution:
The condition for(int i = 1; i < 7; i += 2) is ture, because the value of i = 1 + 2 = 3
and that is smaller than 7.
As long as i is smaller than 7 execute the body of the loop.
x += i, x = 2 + i = 2 + 3 = 5.
The third loop execution:
The condition for(int i = 1; i < 7; i += 2) is ture, because the value of i = 3 + 2 = 5
and that is smaller than 7.
As long as i is smaller than 7 execute the body of the loop.
x += i, x = 5 + 5 = 5 + 5 = 10.
The condition for(int i = 1; i < 7; i += 2) is now false because i = 5 + 2 = 7 and 7
is not smaller than 7.
The loop is terminated.
x -= 2 decreases two from the value of x. x = 10 - 2 = 8.
The statement System.out.print(x); prints the value of x, which is 8 to the standard
output.
The correct answer is a.
Assignment
What happens when you replace the statement for(int i = 1; i < 7; i += 2) with the
statement for(int i = 3; i < 13; i += 5)? Compile and run the program to check out
your expectation.
Quiz 7: for loop and if-else statements
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
char c = 'a';
char c2 = 'b';
for (int i = 4; i >= 0; i--)
{
if (i >= 3 || i == 1)
{
System.out.print(c2);
}
else
{
System.out.print(c);
}
}
}
}
Select the correct answer:
a. This code writes "baaba" to the standard output.
b. This code writes "baab" to the standard output.
c. This code writes "aaba" to the standard output.
d. This code writes "bbaba" to the standard output.
e. This code writes "aabab" to the standard output.
f. This code writes "aaba" to the standard output.
Explanation
The first loop execution.
By each execution of the loop body, the value of i decreases by one.
The condition for(int i = 4; i >= 0; i -- ) is true, the initial value of i = 4.
As long as i is greater or equal to 0 execute the body of the loop.
The initial value of i = 4.
The condition if(i >= 3 || i == 1) returns true. because i is greater than 3.
The statement System.out.print(c2); prints “b” to the standard output.
The second loop execution.
The condition for(int i = 4; i >= 0; i -- ) is true, i = 4 - 1 = 3.
As long as i is greater or equal to 0 execute the body of the loop.
The value of i = 3.
The condition if(i >= 3 || i == 1) returns true. because i is equal to 3.
The statement System.out.print(c2); prints “b” to the standard output.
The third loop execution.
The condition for(int i = 4; i >= 0; i -- ) is true, i = 3 - 1 = 2.
As long as i is greater or equal to 0 execute the body of the loop.
The value of i = 2.
The condition if(i >= 3 || i == 1) returns false. because i is equal to 2.
The statement System.out.print(c); prints “a” to the standard output.
The fourth loop execution.
The condition for(int i = 4; i >= 0; i -- ) is true, i = 2 - 1 = 1.
As long as i is greater or equal to 0 execute the body of the loop.
The value of i = 1.
The condition if(i >= 3 || i == 1) returns true. because i is equal to 1.
The statement System.out.print(c2); prints “b” to the standard output.
The fifth loop execution.
The condition for(int i = 4; i >= 0; i -- ) is true, i = 1 - 1 = 0.
As long as i is greater or equal to 0 execute the body of the loop.
The value of i = 0.
The condition if(i >= 3 || i == 1) returns false. because i is equal to 0.
The statement System.out.print(c); prints “a” to the standard output. The loop is
terminated.
The correct answer is d.
Assignment
What happens when you replace the statement if(i >= 3 || i == 1) with the statement
if(i < 2 || i == 4)? Compile and run the program to check out your expectation.
Quiz 8: for loop and break
What happens when the following program is compiled and run?
public class MyLoop
{
public static void main(String[] args)
{
int x = 17;
int y = 3;
for (int i = 0; i < 10; i++)
{
x += 2;
y += 5;
if (x >= 21)
{
break;
}
}
System.out.print(y);
}
}
Select the correct answer:
a. This code writes "53" to the standard output.
b. This code writes "18" to the standard output.
c. This code writes "13" to the standard output.
d. This code writes "23" to the standard output.
Explanation
The first loop execution.
The condition for(int i = 0; i < 10; i ++ ) is true, because the initial value of i = 0
and that is smaller than 10.
As long as i is smaller than 10 the program executes the body of the loop.
The initial value of x is 17.
x += 2, x = 17 + 2 = 19.
The initial value of y = 3;
y = 3 + 5 = 8;
The condition if(x >= 21) is false, because x is smaller than 21.
The second loop execution.
The condition for(int i = 0; i < 10; i ++ ) is true, because the value of i = 1 and that
is smaller than 10.
As long as i is smaller than 10 the program executes the body of the loop.
The value of x is 19.
x += 2, x = 19 + 2 = 21.
The value of y = 8;
y = 8 + 5 = 13;
The condition if(x >= 21) is true, because x is equal to 21.
The break statement is reached and it terminates the loop
The statement System.out.print(y); prints the last value of y to the standard output,
which is 13.
The correct answer is c.
Assignment
1. What happens when you change the initial value of x to 14 and y to 5?
2. Remove the break statement from the program to see the difference.
Compile and run the program to check out your expectation.
Quiz 9: for loop and continue
What happens when the following program is compiled and run?
public class LeapYear
{
public static void main(String[] args)
{
for (int year = 1993; year <= 2001; year++)
{
if ((year % 4 != 0))
{
continue;
}
System.out.print(year + " ");
}
}
}
Select the correct answer:
a. This code writes "1993 1994 1995 1996 1997 1998 1999 2000 2001" to the
standard output.
b. This code writes "1994 1996 1998 2000" to the standard output.
c. This code writes "1996 2000" to the standard output.
d. This code writes "1993 1994 1995 1997 1998 1999 2001" to the standard
output.
e. This code writes nothing to the standard output.
Explanation
The first loop execution.
The condition for(int year = 1993; year <= 2001; year ++) is true the body of the
loop is executed.
The condition if((year % 4 != 0)) means year/4 is not equal to 0.
When the above condition is true, the continue statement ignores that specific year.
When year/4 is equal to 0, the year is written to the standard output.
Only 1996 and 2000 are written to the standard output.
The correct answer is c.
Assignments
1. Change this program to write all the common (not leap) years between 2016 to
2040 to the standard output.
2. Remove the continue statement to see the difference.
Compile and run the code to test your changes.
Quiz 10: A combination of two loops
What happens when the following program is compiled and run?
public class MiniTheater
{
public static void main(String[] args)
{
for (int row = 1; row < 3; row++)
{
for (int column = 1; column < 4; column++)
{
System.out.print(row + "," + column + " ");
}
}
}
}
Select the correct answer:
a. This code writes "1,1 2,2 3,3" to the standard output.
b. This code writes "1,2 1,3 2,2 2,3" to the standard output.
c. This code writes "1,1 1,2 2,1 2,2" to the standard output.
d. This code writes "1,1 1,2 1,3 2,1 2,2 2,3" to the standard output.
e. This code writes nothing to the standard output.
Explanation
The first-time execution of the outer loop.
The condition for(int row = 1; row < 3; row ++ ) is true
The initial value of row = 1.
For each value of row, the loop body of the inner (col) loop is executed three
times.
when row = 1, col = 1, 2, 3.
The statement System.out.print(row + "," + col + " "); prints 1,1 1,2 1,3 to the
standard output.
The second time execution of the outer loop.
The condition for(int row = 1; row < 3; row ++ ) is true and the value of row is
equal to 2.
For each value of row, the inner loop is executed three times.
when row = 2, col = 1, 2, 3.
The statement System.out.print(row + "," + col + " "); prints 2,1 2,2 2,3 to the
standard output.
the value of the row is 3, and that is why for(int row = 1; row < 3; row ++ )
returns false, and
the outer loop is terminated followed by the termination of the inner loop.
The correct answer is: 1,1 1,2 1,3 2,1 2,2 2,3
The correct answer is d.
Assignments
1. In this program, you have two rows and three columns. Change the row
numbers to five instead of two.
2. Add a statement to this code to write only the rows 2, 4, 5 to the standard
output. The output must be 2,1 2,2 2,3 4,1 4,2 4,3 5,1 5,2 5,3. Compile and run
the code to test your changes.
Quiz 11: A combination of two loops with labels
What happens when the following program is compiled and run?
public class Theater
{
public static void main(String[] args)
{
outer:for (int row = 1; row < 4; row++)
{
for (int column = 1; column < 5; column++)
{
if (row == 2 && column == 3)
{
break outer;
}
System.out.print(row + "," + column + " ");
}
}
}
}
Select the correct answer:
a. This code writes "1,1 1,2 1,3 2,1 2,2 2,3" to the standard output.
b. This code writes "1,1 1,2 1,3 1,4 2,1 2,2" to the standard output.
c. This code writes "1,1 1,2 1,3 1,4 2,1 2,2 2,3" to the standard output.
d. This code writes "1,1 1,2 1,3" to the standard output.
e. This code writes nothing to the standard output.
Explanation
The first-time execution of the outer loop.
The condition for(int row = 1; row < 4; row ++ ) is true
The initial value of row = 1.
For each value of row, the inner loop is executed four times.
for(int col = 1; col < 5; col ++ )
when row = 1, col assigns the values 1, 2, 3, 4.
The statement System.out.print(row + "," + col + " "); prints 1,1 1,2 1,3 1,4 to the
standard output.
The second execution of the outer loop.
The condition for(int row = 1; row < 3; row ++ ) is true and the value of row is
equal to 2.
For each value of row, the inner loop is executed four times.
for(int col = 1; col < 5; col ++ )
when row = 2, col = 1, 2, 3, 4.
if(row == 2 && col == 3)
break outer; the program jumps to the outer loop and is terminated.
The statement System.out.print(row + "," + col + " "); prints 2,1 2,2 to the
standard output.
The correct answer is b.
Assignment
Give the loop for(int col = 1; col < 5; col ++ ) the label inner, and change the
statement break outer; to break inner;. What is written to the standard output if you
compile and run the code? Check out your expectation.
Chapter 5—Classes,
Objects & Constructors
What is a class?
A class is a sort template which can be used to instantiate objects. Java programs
contain either classes or interfaces, which would be discussed later in this book.
Each class has variables and methods, which are called class members. The class
name in Java starts with a capital letter. Programmers can choose an appropriate
class name. Class name examples are: Worker, Account, and Student.
What is an object?
By creating a class you have only the description, but no objects are created. You
can use a class to instantiate as many objects as you want. It is also said that an
object is an instance of a class. A class contains variables and methods, while An
object is the implementation of a class and represents the data.
The following class Student contains the variables name and gender. The
objects of the class Student represent the data, such as: William, man or Sophia
woman. The class determines which data you can have about the students.
Example 1
public class Student
{
// instance variable
String name;
// instance variable
char gender = 'm'; // m: male, f: female
}
In example 1 we can’t access information about William's or Sophia's age because
the class Student doesn’t contain the attribute age. If you want to know the age of
the students, you need to add an extra field to the class Student named age as
shown in example 2.
Example 2
public class Student
{
String name;
char gender = 'm'; // m: male, f: female
int age;
}
Creating objects from a class?
To create an object from a class we use the keyword new as follows:
ClassName objectName = new ClassName();
Student student; // student, is a reference to an object. Keep in mind that the
student object is created if you use the statement new Student();. The statement
Student student; creates only a reference student. The following statement
instantiates the object student from the class Student.
Student student = new Student();
To assign a value to an instance variable, we use the name of the object separated
from the variable name by a dot. The following statement assigns the value 25 to
the variable age of the object student.
student.age = 25;
To access the variables of the object student we use the name of the object and
the name of the variable separated by a dot.
student.age
Example 3
public class Student
{
String name;
char gender = 'm'; // m: male, f: female
int age;
public static void main(String[] args)
{
Student st = new Student();
st.name = "David";
st.age = 31;
System.out.println("Name: " + st.name);
System.out.println("Gender: " + st.gender);
System.out.println("Age: " + st.age);
}
}
If the previous example is compiled and run, the following is written to the
standard output.
Name: David
Gender: m
Age: 31
Object References
It is allowed in Java to create one or more references to a single object. Below,
we create three references namely student, student2, and student3 to an object.
Student student = new Student();
student.name = "Emma";
Student student2 = student;
Student student3 = student2;
All three references student, student2, and student3 refer to the same object, and
the value of the variable name of all the three objects is Emma.
student.name is Emma;
student2.name is Emma;
student3.name is Emma;
What is a constructor?
A constructor is a special method that has the same name as the class name in
which it exists. You can use a constructor to create an object. You can also use a
constructor to initialize the instance variables of a class. This will be explained
later in this chapter.
Example 4
public class Student
{
String name;
char gender = 'm'; // m: male, f: female
int age;
// no-argument constructor
public Student()
{
}
}
In the previous example, there is a no-argument constructor in the class Student.
You can use it to create the object student as follows:
Student student = new Student();
The parentheses can also include variables (arguments). We call the previous
Student () constructor a no-argument constructor because the constructor does not
contain variables (arguments). In every class, you can call the no-argument
constructor when the class doesn't have any constructor. The reason is that the no-
argument constructor is automatically arranged by Java.
How to define a constructor ?
It is important to understand that the default (no-argument) constructor, can only
call if the class doesn't have any constructor. When you define a constructor with
one or more arguments, you can no longer call the default constructor. You can use
a constructor with arguments to assign values to the instance variables. In the
following class Student a constructor with two arguments is defined, therefore you
can no longer call the default constructor to instantiate objects.
If you want to instantiate an object of the class Student, you can call the
constructor with two arguments as follows.
Student student = new Student("David", 31);
The statement this.name = name; assigns the value of the argument name in this
case David to the instance variable name and the statement this.age = age;
assigns the value 31 to the instance variable age.
Example 5
public class Student
{
String name;
int age;
// a constructor with two arguments
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public static void main(String[] args)
{
Student st = new Student("David", 31);
System.out.println("Name: " + st.name);
System.out.println("Age: " + st.age);
}
}
If the previous code is compiled and run the following is written to the standard
output.
Name: David
Age: 31
In the previous example you cannot call the no-argument constructor. If you
want to instantiate objects from the class Student by calling the no-argument
constructor, you need to add the following constructor to the code.
// no-argument constructor
public Student()
{
}
Calling a constructor within another constructor
You can define one or more constructors in one class. It is also possible to call a
constructor from another constructor. To call a constructor, within another
constructor we use the keyword this. In the following example, we call the
constructor with two arguments from the constructor with one argument by using
the statement this(name, 20);. If you call the one-argument constructor to create an
object, the value of 20 is assigned to the variable age. See the following program:
Example 6
public class Student
{
String name;
int age;
// one-argument constructor
public Student(String name)
{
// calling the two-argument constructor
this(name, 20);
}
// two-argument constructor
public Student(String name, int age)
{
this.name = name;
this.age = age;
}
public static void main(String[] args)
{
Student st = new Student("Emma");
System.out.println("Name: " + st.name);
System.out.println("Age: " + st.age);
}
}
If you compile an run the program, the following is written to the standard output.
Name: Emma
Age: 20
Quiz 1: Instantiating objects
What happens when the following program is compiled and run?
public class Employee
{
String name = "Anna";
int age = 22;
public static void main(String[] args)
{
Employee emp = new Employee();
Employee emp2 = new Employee();
emp.name = "John";
emp.age = 20;
System.out.print(emp.name + " ");
System.out.print(emp2.age + " ");
}
}
Select the correct answer:
a. This code writes "Anna 22" to the standard output.
b. This code writes "John 22" to the standard output.
c. This code writes "John 20" to the standard output.
d. This code writes "Anna 20" to the standard output.
e. This code writes nothing to the standard output.
Explanation
The statement Employee emp = new Employee(); create the object emp.
The statement emp.name = "John"; assigns the value John to the name variable.
The statement Employee emp2 = new Employee(); create the object emp2.
By default, the name and age of all the objects are assigned to Anna and 22.
That is why emp2.age prints 22 to the standard output.
The correct answer is b.
Assignments
1. We need to know extra information about each employee namely, their phone
numbers and the city where they live.
2. Create a new employee object called employee; name is Emma, age 25, phone
number 00233-786854 and she lives in New York.
3. Add a piece of code to write all the information (including phone number and
city) of "Emma" to the standard output.
4. Add a piece of code to write all the information about "John" to the standard
output. John lives in California and assume that his phone number is 00383-
384833
Quiz 2: Objects and object references
What happens when the following program is compiled and run?
public class MyClass
{
int x;
int y = 7;
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.x = 5;
mc.y = 8;
MyClass mc2 = new MyClass();
MyClass mc3 = mc;
System.out.print(mc.x + ", " + mc2.x + ", " + mc3.y);
}
}
Select the correct answer:
a. This code writes "5, 0, 8" to the standard output.
b. This code writes "5, 5, 7" to the standard output.
c. This code writes "5, 0, 7" to the standard output.
d. This code writes "5 5 8" to the standard output.
e. This code writes nothing to the standard output.
Explanation
MyClass contains two variables namely x & y.
The statement MyClass mc = new MyClass(); instantiates the object mc.
mc.x = 5; assigns the value of 5 to x.
The statement MyClass mc2 = new MyClass(); instantiates the object mc2.
The default value of x is 0, because x is not initialized.
mc2.x = 0;
The statement MyClass mc3 = mc; creates a reference mc3 to the object mc.
mc3.y is the same as mc.y, because mc3, mc are both references to the same
object.
mc.y = 8, and that is why mc3.y is also equal to 8.
The correct answer is a.
Assignments
Create an object called myClass and refer it to the object mc3. Add a statement to
the program to write the variables x and y of the object myClass to the standard
output.
Quiz 3: Three constructors in one class
What happens when the following program is compiled and run?
public class MyClass
{
int x = 2;
int y = 5;
// no-argument constructor
MyClass()
{
}
// one-argument constructor
MyClass(int x)
{
this.y = x;
}
// two-arguments constructor
MyClass(int x, int y)
{
this.x = x;
this.y = y;
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
MyClass mc2 = new MyClass(7);
MyClass mc3 = new MyClass(9, 3);
System.out.print(mc.y + ", " + mc2.y + ", " + mc3.x);
}
}
Select the correct answer:
a. This code writes "5, 7, 2" to the standard output.
b. This code writes "5, 2, 9" to the standard output.
c. This code writes "5, 2, 2" to the standard output.
d. This code writes "5, 7, 9" to the standard output.
e. This code does not compile.
Explanation
The statement MyClass mc = new MyClass(); creates the object mc.
mc.y = 5 the value of y is equal to 5.
The statement MyClass mc2 = new MyClass(7); creates the object mc2 using the
one-argument constructor.
The statement this.y = x; assigns 7 to the value of y.
The statement MyClass mc3 = new MyClass(9,3); uses the two-argument
constructor.
the value of x assigned to the first arg, which is 9.
this.x = x;
The correct answer is d.
Assignments
1. Call the third (two-argument) constructor within the first constructor so
that all the new created objects by default have x = 6 and y = 3.
2. Instantiate a new object called myObject using the first (no-argument)
constructor.
3. Add a statement to write both variables x and y of your object myObject
to the standard output.
The x value of your object should be 6 and the y value 3.
Quiz 4: Calling a constructor within a constructor
What happens when the following program is compiled and run?
public class Staff
{
String name = "Ron";
double salary = 400.0;
Staff(String name)
{
this(name, 780.0);
}
Staff(String name, double salary)
{
this.name = name;
this.salary = salary;
}
public static void main(String[] args)
{
Staff st = new Staff("Ben");
System.out.print(st.name + ", " + st.salary);
}
}
Select the correct answer:
a. This code writes "Ben, 780.0" to the standard output.
b. This code writes "Ron, 400.0" to the standard output.
c. This code writes "Ben, 400.0" to the standard output.
d. This code writes "Ron, 780.0 Ron 400.0" to the standard output.
e. This code does not compile.
Explanation
The statement Staff st = new Staff("Ben"); instantiate the object st.
By calling the one-argument constructor the statement this(name,780.0); calls the
two-argument constructor.
which assigns new values to the variables name and salary.
name = "Ben";
salary = 780.0;
The correct answer is a.
Assignments
1. Create n staff object called "staffObject" for Mary, her salary is 2000.55. Use
the (two-argument) constructor.
2. Add a statement to the program to write the name and the salary of the
staffObject to the standard output.
Compile and run the program to check out your answer.
Quiz 5: Calling a constructor within another constructor
What happens when the following program is compiled and run?
public class MyClass
{
int x = 3;
int y = 5;
MyClass()
{
this(4, 6);
}
MyClass(int x, int y)
{
this.y = y;
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
MyClass mc2 = new MyClass(9, 7);
System.out.print(mc.x + ", " + mc.y + ", " + mc2.x + ", " + mc2.y);
}
}
Select the correct answer:
a. This code writes "4, 6, 9, 7" to the standard output.
b. This code writes "3, 5, 9, 7" to the standard output.
c. This code writes "4, 6, 3, 7" to the standard output.
d. This code writes "3, 6, 3, 7" to the standard output.
e. This code does not compile.
Explanation
The statement MyClass mc = new MyClass(); instantiates the mc object.
The no-argument constructor calls the two-argument constructor by using the
statement this(4,6);
The two-argument constructor assigns the y parameter to the value of y by using
the statement this.y = y;
The value of x is not assigned to the x parameter, and that is why the x value
remains the initial value 3.
mc.x = 3;
The statement this(4,6); assigns the value of y to 6. mc.y = 6
The statement MyClass mc2 = new MyClass(9,7); assigns the value of y to 7, but x
remains 3.
mc2.x = 3;
mc2.y = 7;
The result is 3, 6, 3, 7
The correct answer is d.
Assignments
1. Add an uninitialized integer variable "z" to the class MyClass.
2. Add a three-argument constructor to MyClass, and pass all the variable x, y, z
to it.
3. Use your own created constructor to instantiate an object of MyClass called
mc3, and pass the values 7, 8, 9 to it.
4. Add a statement to write the values of the variables to the standard output.
Compile and run the program to check out your expectation.
Assignment chapter 5: Create a class Employee with and without a
constructor
1. Create a class Employee.
2. We want the following information about the employees: name, salary, and the
country of origin. Most employees have a standard monthly salary of $
2400.55 and most of them are from France.
3. Create the employee object for Olivia who is from Canada and her salary is $
3100.45.
4. Repeat step 3 for Daniel, his salary is $ 2400.55 and he is from France.
5. Add a piece of code to the program to write all the data of Olivia and Daniel
to the standard output. There are two methods to achieve the goal. Write the
program first by using a constructor and also without a constructor. The result
would be something like the following.
-------- Employees -----------
Name: Olivia
Salary: $ 3100.45
Country: Canada
-----------------
Name: James
Salary: $ 2400.55
Country: France
Chapter 6—Methods
Every class in Java has members, namely, variables and methods. You can't write
a useful class in Java without methods. In the previous chapters, we avoided
writing methods in the classes except for the main method. The reason was
because you were not familiar with methods yet. You will learn in this chapter to
write different types of methods. Each method has a block code that starts with an
opening curly brace and ends with a closing brace. The body of the method
contains the code between the curly braces.
A method name in Java begins with a lowercase letter and ends with an open
and a close parenthesis. Examples are: getNetSalary( ), setPrice(), getPrice(). The
empty parentheses indicate that there are no values passed to the method.
Methods allow you to decide what you want to do with objects. You can call a
method using the name of an object followed by the name of the method, separated
by a dot. In the following class Item, we define the method getDiscountPrice(). We
can call that method by creating an object of the class Item as follows:
Item item = new Item();
item.getDiscountPrice();
There are two types of methods, namely: methods that return a value and methods
that doesn't return any value.
1. Methods that return a value
If a method reads data, it usually returns a primitive variable or an object. If a
variable type or an object type appears before the name of the method, that method
returns that variable type. The data type for the name of the method is the same
type variable that the method returns. In Java, the keyword return is used before
the returned result. As soon as a return statement is reached, the rest of the body of
the method is ignored.
In example 1 the method getDiscountPrice calculates the price with a 20%
discount. The double variable before the name of the method means that the
method returns a value of the type of double.
Example 1
public class Item
{
double price = 160.0;
double getDiscounPrice()
{
double discount = price * 0.20;
double discountPrice = price - discount;
return discountPrice;
}
public static void main(String[] args)
{
Item itm = new Item();
System.out.println("Price with 20% $ " + itm.getDiscounPrice());
}
}
If the program is compiled and run, it writes the following to the standard output.
Price with 20% $ 128.0
2. Methods that doesn't return any value
The methods that you use to set or change values they usually don't return values.
If the keyword void appears before the name of the method means that the method
doesn't return any value.
With methods that don't return value, you can change or set values of the
variables. In the following example, the method setPrice increases the value of the
variable price by $ 10. This method doesn't return any value, therefore it begins
with the keyword void.
Example 2
public class Item
{
double price = 70.0;
// the following method changes the price
void setPrice()
{
this.price = 80.0;
}
public static void main(String[] args)
{
Item itm = new Item();
System.out.println("The price was: $ " + itm.price);
// when you invoke the method, the price will be changed
itm.setPrice();
System.out.println("The price is: $ " + itm.price);
}
}
This program writes the following to the standard output if it compiled and run.
The price was: $ 70.0
The price is: $ 80.0
The method setPrice changes the variable price from $ 70 to $ 80 .
If you need to change the price to other amounts this method is inconvenient. To
solve this problem we use parameters.
Parameters
A parameter could be a primitive variable or an object, and you can pass zero or
more parameters to a method. In the example 1, the method getDiscountPrice
calculates only the price with a discount of 20%. If we need to calculate different
discount rates to our choice, that method doesn't fit our need. To do this more
efficiently, we use a parameter. So We need to pass a value of a type double to the
method as follows:
double getPrice(double discountPercentage)
Parameters are listed between parentheses.
In the following, you can pass any discount percentage to the method, and the
method returns the right discount price.
Example 3
public class Item
{
double price = 160.0;
double getDiscounPrice(double discountPercentage)
{
double discount = price * discountPercentage;
double discountPrice = price - discount;
return discountPrice;
}
public static void main(String[] args)
{
Item itm = new Item();
System.out.println("12%: $" + itm.getDiscounPrice(0.12));
System.out.println("20%: $" + itm.getDiscounPrice(0.20));
System.out.println("25%: $" + itm.getDiscounPrice(0.25));
System.out.println("30%: $" + itm.getDiscounPrice(0.30));
}
}
If the program is compiled and run the following is written to the standard
output:
12%: $140.8
20%: $128.0
25%: $120.0
30%: $112.0
In the next method setPrice() you can assign any value you want to the variable
price. In this method, we can also pass any price as a parameter to the method.
Example 4
public class Item
{
double price = 70.0;
/* in the following method you can assign
* any value to the variable price
*/
void setPrice(double price)
{
this.price = price;
}
public static void main(String[] args)
{
Item itm = new Item();
System.out.println("The price was: $" + itm.price);
itm.setPrice(40.55);
System.out.println("The price is: $" + itm.price);
itm.setPrice(61.35);
System.out.println("The price is: $" + itm.price);
itm.setPrice(54.25);
System.out.println("The price is: $" + itm.price);
}
}
If the code is compiled and run the following is written to the standard output.
The price was: $70.0
The price is: $40.55
The price is: $61.35
The price is: $54.25
A method with three parameters
In the following example the method getSum calculates the sum of three integers
and returns the sum as an integer. We can pass any three desired integers we want
to the method.
Example 5
public class Calculation
{
int getSum(int number1, int number2, int number3)
{
int sum = number1 + number2 + number3;
return sum;
}
public static void main(String[] args)
{
Calculation cal = new Calculation();
System.out.println("17 + 340 + 23 = " + cal.getSum(17, 340, 23));
System.out.println("23 + 450 + 353 = " + cal.getSum(23, 450, 353));
System.out.println("354 + 12 + 578 = " + cal.getSum(354, 12, 578));
System.out.println("37 + 670 + 45 = " + cal.getSum(37, 670, 45));
}
}
If the program is compiled and run the following is to the standard output.
17 + 340 + 23 = 380
23 + 450 + 353 = 826
354 + 12 + 578 = 944
37 + 670 + 45 = 752
The variable sorts
The three sorts variables in Java are Instance variables, local variables and class
variables.
1. Instance variables
An instance variable is declared within a class, but outside of the methods,
constructors or other blocks. The instance variables are created when an object is
created. They are visible for all methods, constructors, and blocks in the class.
Instance variables don’t need to be necessarily initialized because they have
default values. The default values of the variables are already mentioned in
chapter 1 data Types and variables. To access the variables of the object em, use
the name of the object and the name of the variable separated by a dot, as shown
in example 6.
2 Local variables
A local variable is a variable that is declared within a method, constructor or a
block. Local variables must be initialized because they don't have default values.
Local variables are visible only within the method, constructor or block of code
in which they are located, such as the variable taxRate in Example 6.
3 Class variables
Class variables are also called static variables. They are declared inside a class
but outside the methods, constructors or blocks. There is only one copy of the
class variable available for all the objects. You can get access to a class variable
with the name of an object of the class as well as the name of the class separated
by a dot, as shown in example 6.
Example 6
The following program writes 3300.0, 300 to the standard output.
public class Employee
{
String name; // instance variable
double grossSalary = 3300; // instance variable
static int numberEmployees = 300; // class variable
public double getNetSalary()
{
double taxRate = 0.30; // local variable
double netSalary = grossSalary - (grossSalary * taxRate);
return netSalary;
}
public static void main(String[] args)
{
Employee em = new Employee();
System.out.print(em.grossSalary + ", ");
System.out.print(Employee.numberEmployees);
}
}
Wrapper classes
Java is an object oriented programming language and treats everything as an
object. Primitive variables in Java are not objects. Sometimes it is useful to
convert primitive variables to objects, and the other way around. For each
primary variable, there is a wrapper class in the Java-library, that has the same
name but starts with a capital letter. You sometimes need a wrapper object if a
method expects an object as parameter rather than a primitive variable. You can
also use methods of the wrapper classes to convert primitive variables to objects
or the other way around. You can find out more about Wrapper classes and their
methods in Java API-documentation.
Primitive type Wrapper class
boolean Boolean
byte Byte
char Character
double Double
float Float
int Integer
long Long
short Short
Example 7
In the following program the int variable is converted to an Integer object, and
the other way around.
public class WrapperClass
{
public static void main(String[] args)
{
int i = 23;
// convert an integer variable to an object
Integer intObject = new Integer(i);
// convert an object to an integer variable
int intVar = intObject.intValue();
}
}
Example 8
In the following program, a String representation of an integer is converted to
an int type. We use the wrapper Integer.
public class WrapperClass
{
public static void main(String[] args)
{
String str = "8";
Integer intObject = Integer.valueOf(str);
int intVar = intObject.intValue();
System.out.print(intVar);
}
}
Example 9
Another method to convert a String representation of an integer to an int type.
public class WrapperClass
{
public static void main(String[] args)
{
String str = "8";
int intVar = Integer.parseInt(str);
System.out.print(intVar);
}
}
Quiz 1: Calculate the price of gold/ silver in dollars
What happens when the following program is compiled and run?
public class PreciousMetal
{
double ocGoldPrice = 1300.0; // the price of one ounce of gold
double ocSilverPrice = 20.0; // the price of one ounce of silver
boolean isGold = true;
public double getMetalPrice(boolean isGold, int ounce)
{
if (isGold)
{
return ocGoldPrice * ounce;
}
else
{
return ocSilverPrice * ounce;
}
}
public static void main(String[] args)
{
PreciousMetal pm = new PreciousMetal();
System.out.print(pm.getMetalPrice(false, 4));
System.out.print(", ");
System.out.print(pm.getMetalPrice(true, 2));
}
}
Select the correct answer:
a. This code writes "20.0, 1300" to the standard output.
b. This code writes "2600.0, 80.0" to the standard output.
c. This code writes “80.0, 2600.0” to the standard output.
d. This code writes "5200.0, 40.0" to the standard output.
e. This code writes nothing to the standard output.
Explanation
The method getMetalPrice() calculates the price of gold and silver in dollar. If
the first parameter is true, that means the metal is gold other wise it is silver.
The second parameter is the amount of ounces of the metal to be calculated in
dollar. The double before the name of the method means that the method returns a
data type of double. The first statement mc.getMetalPrice(false, 4) calculates the
price of 4 ounces of silver, which is 4 * 20.0 = 80.0. The second statement
mc.getMetalPrice(true, 2) calculates the price of 2 ounces of gold, which is 2 *
1300.0 = 2600.0.
The correct answer is c.
Assignments
If you know that the price of one ounce of Platinum = $ 936.
1. Add a method to the class called getPlatinumPrice to calculate the price of the
amount ounces of Platinum in dollar.
2. Try to test your method whether it returns the price of $ 5148 for 5.5 ounces of
Platinum.
3. Test Your method further and find the prices of 4.5 ounces, 6 ounces of
Platinum.
Quiz 2: A method that returns an integer data type
What happens when the following program is compiled and run?
Explanation
By creating a new object, the constructor MyClass() is invoked.
The statement i += 4, increments the value of i by 4.
i = 3 + 4 = 7;
The statement i2 += 2, adds 2 to the initial value of i2.
i2 = 8 + 2 = 10.
The method public void print() does not return any data types because it is of the
type of void. The statement mc.print(); invokes the print method.
The body of the method is executed:
The value int x = i + i2 = 7 + 10 = 17;
The statement System.out.print(x); prints the value of x to the standard output.
The correct answer is c.
Assignments
1. Write a method called "getNetSalary" that calculates net salaries based on
gross salaries. Assume that the tax rate is 20%.
2. Test your method for each of the following gross salaries.
3. Repeat step 2 for the following gross salaries if tax rate is 30%.
a. $3000
b. $2400
c. $1466
Quiz 4: A method that doesn't return any value
Change the declaration of the array to "int[] arrayInt = new int[11];". What would
be the result?
Compile and run the program to test your expectation.
Quiz 2: Adding integer elements to an Array
What happens when the following program is compiled and run?
public class MyArray
{
public static void main(String[] args)
{
int[] arr = new int[5];
arr[0] = 3;
arr[1] = 7;
arr[4] = 3;
arr[3] = 1;
arr[1] = 8;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Select the correct answer:
a. This code writes "3 8 7 1 3" to the standard output.
b. This code writes "3 7 0 1 3" to the standard output.
c. This code writes "3 7 1 3 8" to the standard output.
d. This code writes "3 7 3 1 8" to the standard output.
e. This code writes "3 8 0 1 3" to the standard output.
Explanation
The statement int[] arr = new int[5]; creates an array of integer with 5 places.
The statement arr[0] = 3; assigns the value of the first (index = 0) element to 3.
The statement arr[1] = 7; sets the value of the second element to 7.
The statement arr[1] = 8; reassigns the value of the second element to 8.
The third element is not assigned, the default value is 0.
The statement arr[3] = 1; sets the fourth element to 1.
The statement arr[4] = 3; sets the fifth element to 3.
The correct answer is e.
Assignments
1. In the above program, we want to write to the standard output only the
elements that are greater or equal to 3, add your control to achieve that.
2. compile and run the code to test your expectation.
Quiz 3: Sorting elements of an array
What happens when the following program is compiled and run?
import java.util.Arrays;
public class Animal
{
public static void main(String[] args)
{
String[] arrAnimal = new String[5];
arrAnimal[0] = "Wolf ";
arrAnimal[1] = "Lion ";
arrAnimal[2] = "Leopard ";
arrAnimal[3] = "Elephant ";
arrAnimal[4] = "Tiger ";
// See the class "Arrays" of the Java standard API
Arrays.sort(arrAnimal);
for (int i = 0; i < arrAnimal.length; i++)
{
if (i > 1)
{
System.out.print(arrAnimal[i]);
}
}
}
}
Select the correct answer:
Chapter 10—Static
Members
Static members are variables, methods, or nested classes, the last one will be
explained later in this book. All objects have their own copy of the instance
variables, but for the static variable, there is only one copy available for all the
objects of the class. You can call static variables with the name of the class as
well as the name of each instance of the class. A static variable is also called
class variable; it starts with the keyword static.
Class variables
In the following class Student, we want to keep track of the numbers of objects we
instantiate from the class student. To do this, we need to declare a static int
variable numberStudents. Each time you instantiate a student object, the
constructor increments the number of students by one. In the following program,
three objects are created, namely st1, st2 and st3.
Example 1
public class Student
{
String name;
static int numberStudents;
public Student()
{
numberStudents++;
}
public static void main(String[] args)
{
Student st1 = new Student();
Student st2 = new Student();
Student st3 = new Student();
st1.name = "Allan";
st2.name = "Erica";
st3.name = "Emma";
System.out.println("Name st1: " + st1.name);
System.out.println("Number of students: " + st1.numberStudents);
System.out.println("Name st2: " + st2.name);
System.out.println("Number of students: " + st2.numberStudents);
System.out.println("Name st3: " + st3.name);
System.out.println("Number of students: " + st3.numberStudents);
/*
* you can access static variables using the Name of the class
*/
System.out.println("Number of students: " + Student.numberStudents);
}
}
The previous example writes the following to the standard output.
Name st1: Allan
Number of students: 3
Name st2: Erica
Number of students: 3
Name st3: Emma
Number of students: 3
Number of students: 3
This kind of information cannot be provided by the instance variables because
each object has information about itself. Objects have no information about the
history of their classes. If we remove the keyword static from the variable
numberStudents the number of students remains 1, regardless of the number of
objects that you create.
How to prevent instantiation of a class with only static
members?
It is unnecessary to instantiate classes that have only static variables and methods
such as the Math class of the Java standard API. To prevent instantiating such a
class you need to define its constructor private.
Static methods
You can call static members with the name of the class, and that also applies to the
static methods. You can call static methods with the name of the class as well as
the name of the objects.
There are some important rules, which apply to static methods.
1. The keyword this can't be used inside static methods because this is
associated with the current instance.
2. You can not have instance variables within a static method because the
instance probably does not exist at the time that the method is called.
An example of a static method is the following method, which returns the sum
of four integers. This method is static because there is no need to create an object
to calculate the sum of four integers. In order to call this method, we use the name
of the class.
Example 2
public class Calculate
{
public static int getSum(int i, int i2, int i3, int i4)
{
return i + i2 + i3 + i4;
}
public static void main(String[] args)
{
int x = getSum(5, 4, 6, 2);
// or
// int x = Calculate.getSum(5, 4, 6, 2);
System.out.print(x);
}
}
The previous example writes 17 to the standard output.
Quiz 1: Comparing static variables with instance variables
What happens when the following program is compiled and run?
public class Employee
{
int nr; // instance variable
static int stNr; // class variable
public Employee()
{
nr++;
stNr++;
}
public static void main(String[] args)
{
Employee emp1 = new Employee();
Employee emp2 = new Employee();
Employee emp3 = new Employee();
System.out.print(Employee.stNr + ", ");
System.out.print(emp1.nr + ", ");
System.out.print(emp2.nr + ", ");
System.out.print(emp3.nr);
}
}
Select the correct answer:
a. This code writes "3, 1, 2, 3" to the standard output.
b. This code writes ”3, 1, 1, 1” to the standard output.
c. This code writes "1, 1, 1, 1" to the standard output.
d. This code writes "3, 3, 3, 3" to the standard output.
e. This code writes nothing to the standard output.
Explanation
The no-argument constructor is called each time we create an employee object.
We have created 3 employee objects and by creating an object the statement
stNr++ adds one to the static variable. After creating the three objects stNr = 3.
For all the instances the stNr remains the same because it is static.
Usually, you don't need to use the name of objects to access static members. You
can also use the name of the class.
The instance variable nr belongs to the objects. The value of the instance variable
nr for all the objects is equal to one.
The correct answer is b.
Assignments
1. Create two more employee objects namely; emp4 and emp5.
2. Does the instantiation of the two previous objects affect the static variable
stNr?
3. Compile and run the program to test your expectation.
Quiz 2: Java static members
What happens when the following program is compiled and run?
public class MyClass
{
static int x = 3;
public MyClass()
{
x++;
}
public static int method(int i, int i2)
{
x += (i - i2);
return x;
}
public static void main(String[] args)
{
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
System.out.print(MyClass.x + ", ");
MyClass mc3 = new MyClass();
MyClass.method(8, 3);
System.out.print(MyClass.x);
}
}
Select the correct answer:
a. This code writes "0, 0" to the standard output.
b. This code writes "5, 5" to the standard output.
c. This code writes "11, 11" to the standard output.
d. This code writes "5, 11" to the standard output.
e. This code writes "3, 3" to the standard output.
Explanation
The no-argument constructor is called each time we create a MyClass object.
By instantiating the objects mc1 and mc2 the no-argument constructor adds each
time 1 to the
value of x which is initially equal to 3.
x = 3 + 1 + 1 = 5.
By instantiating the object mc3 the no-argument constructor adds one more to the
value of x.
x = 5 + 1 = 6.
The statement MyClass.method(8,3); invokes the method, which adds (i - i2) to
the value of x.
x = 6 + (8 - 3) = 11.
The correct answer is d.
Assignments
1. Write a method called resetX to reset the value of the variable x to any integer
number you wish.
2. Test your method.
Quiz 3: Class variables and instance variables
What happens when the following program is compiled and run?
public class MyClass
{
static int x = 6;
int y = 3;
MyClass()
{
x += 3;
y += 2;
}
void method(int i)
{
this.y = y - i;
x++;
}
public static void main(String[] args)
{
MyClass mc1 = new MyClass();
MyClass mc2 = new MyClass();
MyClass mc3 = new MyClass();
mc1.method(3);
System.out.print(MyClass.x + ", " + mc1.y);
}
}
Select the correct answer:
a. This code writes "16, 6" to the standard output.
b. This code writes "16, 2" to the standard output.
c. This code writes "12, 2" to the standard output.
d. This code writes "13, 5" to the standard output.
e. This code writes "15, 5" to the standard output.
Explanation
The statement MyClass mc1 = new MyClass(); creates the object mc1.
By creating an object, the program calls the no-argument constructor.
It adds 3 to the value of x and 2 to the value of y.
x = 6 + 3 = 9. x is static and it belongs to the class.
y = 3 = 2 = 5. y is an instance variable and its value belongs to the object mc1.
The statement MyClass mc2 = new MyClass(); creates the object mc2.
It calls the no-argument constructor and adds more 3 to the value of x.
x = 9 + 3 =12. The value of y of the object mc1 remains the same.
The statement MyClass mc3 = new MyClass(); creates the object mc3.
It calls the no-argument constructor and adds more 3 to the value of x.
x = 12 + 3 = 15.
The statement mc1.method(3); invokes the method, which adds one to the value of
x.
x = 15 + 1 = 16.
By invoking the method
this.y = (y - i)
The value of the variable y of the object mc1 is equal to 5.
y = 5 - i = 5 - 3 = 2.
The correct answer is b.
Assignments
1. Create five object references of the class MyClass namely mc4, mc5, mc6,
mc7 and mc8.
2. Does that affect the static variable x?
3. Test your code.
Quiz 4: Static variables and methods
What happens when the following program is compiled and run?
public class MyClass
{
static int x = 2;
MyClass()
{
x += 4;
}
static void methodA(int i)
{
x = x - i;
}
int methodB(int i)
{
return x + i;
}
public static void main(String[] args)
{
MyClass mc1 = new MyClass();
MyClass.methodA(2);
MyClass mc2 = new MyClass();
System.out.print(mc2.methodB(3));
}
}
Select the correct answer:
a. This code writes "11" to the standard output.
b. This code writes "12" to the standard output.
c. This code writes "14" to the standard output.
d. This code writes "7" to the standard output.
e. This code writes "9" to the standard output.
Explanation
The statement MyClass mc1 = new MyClass(); calls the no-argument constructor,
which adds 4 to the value of x.
x = 2 + 4 = 6.
The statement MyClass.methodA(2); invokes the methodA.
x = x - i = 6 - 2 = 4.
The statement MyClass mc2 = new MyClass(); calls the no-argument constructor,
which adds 4 to the value of x.
x = 4 + 4 = 8.
The statement System.out.print(mc2.methodB(3)); invokes the methodB.
x = x + i = 8 + 3 = 11.
The correct answer is a.
Assignments
1. What is the result if you replace the statement x += 4; with the statement x ++
2. Compile and run the program to test the result.
Quiz 5: A static StringBuffer example
What happens when the following program is compiled and run?
public class MyClass
{
static int x;
static StringBuffer sb = new StringBuffer();
public MyClass()
{
myMethod();
}
public void myMethod()
{
x += 3;
sb.append(x);
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
MyClass mc2 = new MyClass();
MyClass mc3 = new MyClass();
System.out.println(MyClass.sb);
}
}
Select the correct answer:
a. This code writes "333" to the standard output.
b. This code writes "0" to the standard output.
c. This code writes "3" to the standard output.
d. This code writes "369" to the standard output.
e. This code writes "18" to the standard output.
Explanation
The statement MyClass mc = new MyClass(), creates an object, which calls the
MyClass no-argument constructor.
The constructor invokes the method myMethod().
The statement x += 3 increments the value of x by 3, x = 0 + 3 = 3.
The statement sb.appends(x), appends the string representation of the x argument,
which is 3.
By creating the second object “mc2” the x += 3 increments the value of x by 3, x =
3 + 3 = 6.
The statement sb.appends(x), appends the string representation of the x argument,
which is 6.
By creating the third object “mc3” the x += 3 increments the value of x by 3, x = 6
+ 3 = 9.
The statement sb.appends(x), appends the string representation of the x argument,
which is 9.
Remember that x and sb are both static, and that is why both of them belong to the
class. The value of x and sb are the same for all the objects.
The correct answer is d.
Assignments
1. Remove the keyword static from the class variable x .
2. Does the previous step affect the program?
3. Compile and run the program to check your expectation.
4. Remove both static keywords from the class variables x and sb .
5. Do you think that the previous step changes the result of the execution of the
program?
6. Compile and run the program to check your expectation.
Assignment chapter 10: Track the names of programming languages in a
string
1. Create a new class ProgrammingLanguage.
2. Declare an integer variable numberOfLanguages and a String variable
language inside the class.
3. Instantiate the following five objects of the class ProgrammingLanguage as
follows: Java , C++ , Python , PHP and Ruby .
4. Each time an object is created, the variable language keeps the track of the
name of the objects as follows: Java , C++ , Python , PHP , Ruby .
5. The variable numberOfLanguages should also keep track the number of the
created objects.
6. Compile and run your program to test your code.
Use the operator += to keep track of the variable language of all the created
objects, as follows :
String language = "".
language += "Java".
language += "C++".. etc.
Chapter 11—Inheritance
Java supports inheritance to allow reusing code and extending new classes based
on existing ones. Inheritance is an important concept in object-oriented
programming.
An example of inheritance is an Employee class, which contains the fields,
name, age, and salary. If we need to know which programming language a
programmer use, we cannot add that field to the employee class. That is because
not every employee works with a programming language. The mentioned field
would be redundant for the managers and other employees, who are not
programmers.
Example 1
public class Employee
{
String name;
int age;
double salary;
String language; // redundant
public void printInfo()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary $ " + salary);
System.out.println("Language: " + language);
}
}
Another solution is creating a new class called programmer with the fields name ,
age , salary and language as following.
public class Programmer
{
String name; // redundant
int age; // redundant
double salary; // redundant
String language;
public void printInfo()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
System.out.println("Language: " + language);
}
}
This solution also uses unnecessary fields, because we have already defined the
fields name, age, and salary in the class Employee. To reuse the code of the class
Employee, we will extend the class Programmer with the keyword extends. In this
way, the class Programmer inherits all the fields and the behavior of the class
Employee. The class Programmer inherits the fields name, age, and salary from
the class Employee and keeps its own field language. The term superclass is used
for the parent class and the term subclass for the child class. In our example, the
class Programmer becomes a subclass of the superclass Employee as shown in
example 2. The keyword protected is used for the members of the superclass to
give the subclass access to those members. The method printInfo in the class
Employee writes the name, age, and salary of the employees to the standard
output. We can override this method in the class Programmer to write those
attributes of each programmer in addition to the programming language to the
standard output. We don't need to rewrite the whole method printInfo of the
superclass in the subclass, but we use the statement super.printInfo();. The
keyword super in the subclass Programmer refers to its superclass Employee.
Example 2
public class Employee
{
protected String name;
protected int age;
protected double salary;
public void printInfo()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
}
}
public class Programmer extends Employee
{
String language;
public void printInfo()
{
super.printInfo();
System.out.println("Language: " + language);
}
}
public class TestEmployee
{
public static void main(String[] args)
{
Employee emp = new Employee();
Programmer prog = new Programmer();
emp.name = "Jack";
emp.age = 23;
emp.salary = 2100.55;
prog.name = "Emma";
prog.age = 32;
prog.salary = 3200.45;
prog.language = "Java";
emp.printInfo();
prog.printInfo();
}
}
If the code is executed the following is written to the standard output.
Name: Jack
Age: 23
Salary: $ 2100.55
Name: Emma
Age: 32
Salary: $ 3200.45
Language: Java
Superclass constructor
When you instantiate an object of the subclass Programmer, the no-argument
constructor of the superclass Employee is called. The following program writes
Peter Eva to the standard output. By creating objects of the subclass Programmer,
the no-argument constructor of the superclass Employee is called, and this one
writes Peter to the standard output. Then the constructor of the subclass is called,
and this one writes Eva to the standard output.
Example 3
public class Employee
{
protected String name;
protected int age;
protected double salary;
public Employee()
{
System.out.print("Peter ");
}
}
public class Programmer extends Employee
{
String language;
public Programmer()
{
System.out.print("Eva");
}
}
public class TestEmployee
{
public static void main(String[] args)
{
Programmer prog = new Programmer();
}
}
If you pass the argument name to the constructor of the class Employee, the code
will have an issue. The reason is that by creating the object prog, the no-argument
constructor of the superclass is called.
If it does not exist, you need to call the constructor of the superclass explicitly.
You can use the keyword super to call the constructor of the superclass.
Example 4
public class Employee
{
protected String name;
protected int age;
protected double salary;
public Employee(String name)
{
this.name = name;
System.out.print(name + " ");
}
}
public class Programmer extends Employee
{
String language;
public Programmer()
{
// Calling one-argument constructor of the superclass
super("Peter");
System.out.print("Eva");
}
}
public class TestEmployee
{
public static void main(String[] args)
{
Programmer prog = new Programmer();
}
}
Overriding Methods
Overriding methods of super classes in subclasses allows the subclass to inherit
and modify the behavior of the superclass as needed. The overridden method has
the same name, type, and a number of parameters, and returns the same type of the
data as the method that overrides.
See the method printInfo() in the example 2. Remember that you don't need to
rewrite the printInfo() method of the super class Employee in the class
Programmer. The keyword super allows you to access variables and methods of
the superclass from the subclass.
The method printInfo in the superclass Employee.
public void printInfo()
{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $ " + salary);
}
The subclass Programmer override the method printInfo of its superclass.
public void printInfo()
{
super.printInfo();
System.out.println("Language: " + language);
}
It is not necessary to rewrite the whole method printInfo of the superclass in the
subclass. You can instead use the statement super.printInfo(); to access the method
printInfo of the superclass.
Overloading Methods
Overloading of methods is the possibility to reuse the same method name in a
class as often as needed. To do so the methods should comply with the following
requirements:
1. The methods can have the same name and a different number of parameters,
such as the method getNetSalary.
double getNetSalary()
double getNetSalary(double grossSalary)
double getNetSalary(double grossSalary, int taxRate)
2. The methods can have the same number of parameters, but their parameters
may not have the same data types. Below is the method name getNetSalary
reused and that is correct, because the data types of the parameters are
different.
double getNetSalary(double grossSalary)
double getNetSalary(int taxRate)
3. The parameters of the methods can have the same number of parameters and
the same data types, provided that the order of the parameters variable type is
different.
double getNetSalary(double grossSalary, int taxRate)
double getNetSalary(int taxRate, double grossSalary)
Note: the following two methods do not have the requirements of the overloaded
methods, although they return different data types.
int getNetSalary(double grossSalary)
double getNetSalary(double grossSalary)
See the method getNetSalary in the following program.
Example 5
public class Employee
{
public double getNetSalary()
{
double netSalary = 3000 - (3000 * 30) / 100;
return netSalary;
}
public double getNetSalary(double grossSalary)
{
double netSalary = -(grossSalary * 30) / 100;
return netSalary;
}
public double getNetSalary(int taxRate)
{
double netSalary = 2400 - (2400 * taxRate) / 100;
return netSalary;
}
public double getNetSalary(double grossSalary, int taxRate)
{
double netSalary = grossSalary - (grossSalary * taxRate) / 100;
return netSalary;
}
public double getNetSalary(int taxRate, double grossSalary)
{
double netSalary = grossSalary - (grossSalary * taxRate) / 100;
return netSalary;
}
public static void main(String[] args)
{
Employee emp = new Employee();
System.out.println(emp.getNetSalary());
System.out.println(emp.getNetSalary(2500.65));
System.out.println(emp.getNetSalary(25));
System.out.println(emp.getNetSalary(2000.0, 35));
System.out.println(emp.getNetSalary(40, 2000.0));
}
}
The previous program writes the following to the standard output.
2100.0
-750.195
1800.0
1300.0
1200.0
Quiz 1: A simple inheritance example
What happens when the following program is compiled and run?
public class MySuper
{
protected int x;
}
public class MySub extends MySuper
{
private int y = 3;
MySub()
{
x += 2;
y++;
System.out.print(x + ", " + y);
}
public static void main(String[] args)
{
MySub ms = new MySub();
}
}
Select the correct answer:
a. This code writes "0, 3" to the standard output.
b. This code writes "2, 3" to the standard output.
c. This code writes "2, 2" to the standard output.
d. This code writes "2, 4" to the standard output.
e. This code writes nothing to the standard output.
f. This code doesn't compile.
Explanation
The statement MySub ms = new MySub(); calls the no-argument constructor
MySub().
The statement x += 2; adds 2 to the value of x of MySuper class.
The variable x is equal to 0, because it is not initialized.
x = 0 + 2 = 2.
the statement y++ adds one to the value of y.
y = 3 + 1 = 4
The correct answer is d.
Assignments
1. What is written to the standard output if the value of x = 5 and y = 8;
2. Compile and run the program to test your expectation.
Quiz 2: A superclass constructor
What happens when the following program is compiled and run?
public class MySuper
{
protected int x = 1;
MySuper()
{
x += 2;
}
}
public class MySub extends MySuper
{
MySub(int y)
{
x += y;
}
public static void main(String[] args)
{
MySub ms = new MySub(4);
System.out.print(ms.x);
}
}
Select the correct answer:
a. This code writes "7" to the standard output.
b. This code writes "5" to the standard output.
c. This code writes "1" to the standard output.
d. This code writes "0" to the standard output.
e. This code writes nothing to the standard output.
f. This code doesn't compile.
Explanation
The statement MySub ms = new MySub(3); instantiate the object ms.
It calls the no-argument constructor of the super class, which adds 2 to the value
of x.
x = 1 + 2 = 3;
By creating the object ms, the program calls the one-argument constructor of
MySub.
the parameter y = 4.
x += y; is equivalent to x = 3 + 4 = 7;
The correct answer is a.
Assignments
1. Create a new MySub object called ms2, and pass the value 6 to the
constructor.
2. What would be the x value of the ms2 object?
Quiz 3: Overriding methods
What happens when the following program is compiled and run?
public class MySuper
{
protected char c = 'G';
void method()
{
System.out.print(c);
}
}
class MySub extends MySuper
{
char c2 = 'A';
MySub()
{
this('N');
System.out.print(c2);
}
MySub(char c)
{
System.out.print(c);
}
void method()
{
super.method();
System.out.print(c2);
}
public static void main(String[] args)
{
MySub mySub = new MySub();
mySub.method();
}
}
Select the correct answer:
a. This code writes "NGA" to the standard output.
b. This code writes "NAGA" to the standard output.
c. This code writes "AGA" to the standard output.
d. This code writes "GA" to the standard output.
e. This code writes nothing to the standard output.
f. This code doesn't compile.
Explanation
The statement MySub mySub = new MySub(); calls the the no-argument
constructor of MySub class.
The statement this('N'); calls the one-argument constructor of MySub class, which
prints "N" to the standard output.
The statement System.out.print(c2); prints "A" to the standard output.
The statement mySub.method(); invokes the method.
The statement super.method(); calls the method in the super class which prints "G"
to the standard output.
The statement System.out.print(c2); prints "A" to the standard output.
The result is NAGA
Chapter 12—Final
Classes & the Final Keyword
What is a final class?
Declaring a class final prevents programmers to use it as a superclass.
A final class in Java is a class that cannot be extended or cannot be subclassed,
but it can be a subclass of another class.
What is a final method?
A final method is a method that cannot be overridden in sub classes.
By declaring the method getSum final, you guarantee that the method cannot be
overridden in subclasses of MyClass.
Example 1
public class MyClass
{
final int getSum(int x, int y)
{
return x + y;
}
}
What is a final variable?
A final variable is actually a constant and its value may not be changed once it is
initialized. In the following example, the method changeIP tries to change the
value of the final variable PI, but that causes an error in the program. The reason
is that a final variable is a constant.
Example 2
public class Circle
{
final double PI = 3.14;
void changePI()
{
PI++;
}
}
Quiz 1: Final variables
What happens when the following program is compiled and run?
Chapter 13—Abstract
Classes
What is an abstract class?
An abstract class is a class in which one or more methods are abstract. All
abstract classes and abstract methods are provided with the keyword abstract. An
abstract method has no body and it is not defined, but only declared. In the
following example, the method getArea is abstract, therefore it has no body.
protected abstract double getArea();
It is important to know that you cannot instantiate objects from abstract classes,
because they are incomplete. A subclass of an abstract class must override all its
abstract methods, otherwise, it cannot be instantiated either.
Important concepts of abstract classes and methods
1. You cannot instantiate abstract classes.
2. The main purpose of abstract classes is extending them and overriding
their methods.
3. When a class contains one or more abstract methods, It should be
declared abstract.
4. Abstract methods do not have a body.
5. A class can be declared abstract even if they do not contain abstract
methods.
Subclasses of abstract classes
1. A subclass of an abstract class must override all the abstract methods of
its superclass, otherwise, it should also be declared abstract.
2. It is possible to instantiate a subclass of an abstract class that overrides
all the abstract methods of its superclass.
3. A subclass of an abstract class can also be declared abstract.
Using abstract classes
An example of using abstract classes is the two-dimensional shape. All 2D shapes
have an area and a circumference. By creating a class shape and declaring the two
abstract methods getArea and getPerimeter, we enforce any class that extends the
class shape implement those two methods. If a subclass does not override these
two methods, it should also be declared abstract. In the following example, we
enforce the subclasses Rectangle and Circle to override the methods getArea and
getPerimeter of their superclass Shape.
Don't forget that subclasses of the class Shape can override the abstract
methods on their own way, as shown in the following example.
Example
public abstract class Shape
{
protected abstract double getArea();
protected abstract double getPerimeter();
}
a. It is not allowed to change the name of the method getSum() (no-arg) of the
class MyClass. b. It is not allowed to change the name of the method getSum(int x)
of the class MyClass.
c. By executing this code, 12 is printed to the standard output.
d. By executing this code, 10 is printed to the standard output.
Explanation
You can change the method name getSum() no-argument to any name you wish, but
the getSum(int x) one-argument overrides the method in the abstract super class.
Any class that extends an abstract class must override all its abstract methods,
otherwise, you cannot instantiate it.
The initial value of x is equal to 6.
The statement MyClass mc = new MyClass(); creates an object of the type of
MyClass, which calls the no-argument constructor of the superclass MyAbstract
class.
The statement x += 2; adds 2 to the value of x.
x = 6 + 2 = 8;
The statement System.out.print(mc.getSum(4)); invokes the method getSum(int
arg) and prints the result to the standard output.
super.x + x = 8 + 4 = 12.
The correct answers are b and c.
Assignments
1. Add an abstract method printName that does not return value with one string
parameter.
abstract void printMyName(String name);
2. Override the method printName in the class MyClass. The method should
write the value of the parameter name to the standard output.
3. Compile and run the program to test the code.
Quiz 2: A subclass of a subclass of an abstract class
What happens when the following program is compiled and run?
public abstract class MyAbstract
{
MyAbstract()
{
System.out.print("n");
}
abstract void printLetter(char c);
}
public class MySuper extends MyAbstract
{
MySuper()
{
}
MySuper(int i)
{
System.out.print(i);
}
@Override
void printLetter(char c)
{
System.out.print(c);
}
}
public class MySub extends MySuper
{
MySub()
{
System.out.print("p");
}
public static void main(String[] args)
{
new MySub().printLetter('s');
}
}
Select the correct answer:
a. This code writes ps to the standard output.
b. This code writes pns to the standard output.
c. This code writes spn to the standard output.
d. This code requires nsip to the standard output.
e. This code requires nps to the standard output.
f. This code writes nothing to the standard output.
Explanation
The statement
new MySub().printLetter('s'); creates a new object of the subclass.
By creating a new object of the Subclass the no-argument constructor of its
superclass is called and this calls the no-argument constructor of its superclass
MyAbstract.
The statement System.out.print("n"); writes n to the standard output.
The no-argument constructor of the Superclass writes nothing to the standard
output.
The no-argument constructor of the Subclass writes p to the standard output.
The statement MySub.printLetter('s'); invokes the method printLetter.
This writes the parameter s of the method to the standard output.
The correct answer is e.
Assignments
1. What is written to the standard output if you add the statement super(10); right
above the statement System.out.print("p"); in the class MySub?
2. Compile and run the program to check.
Quiz 3: Demonstrating an abstract class
What happens when the following program is compiled and run?
abstract class MyAbstract
{
String str = "N";
MyAbstract()
{
this("O");
str += "L";
}
MyAbstract(String str)
{
str += str;
}
}
public class MyClass extends MyAbstract
{
MyClass()
{
this(2);
str += 7;
}
MyClass(int x)
{
str += x;
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
System.out.print(mc.str);
}
}
Select the correct answer:
a. This code writes "NL27" to the standard output.
b. This code writes "NOL27" to the standard output.
c. This code writes "N27" to the standard output.
d. This code writes "27NL" to the standard output.
e. This code writes "27NOL" to the standard output.
f. This code does not compile.
Explanation
By instantiating the object mc, the no-argument constructor of the superclass is
invoked.
string str = "N";
The statement this("O"); adds nothing to the value of str, because the one-argument
constructor MyAbstract(String str) {str += str;} refers to the parameter str not the
instance variable.
The statement str += "L"; adds "L" to the value of the str.
The value of str becomes "NL".
The no-argument constructor of the class MyClass calls the one-argument
constructor,
which adds 2 to the value of the str.
At last the statment str += 7; adds also 7 to the value of the String.
Chapter 14—Interfaces
Java allows to inherit from only a single class, but it supports multiple inheritance
from interfaces. Implementing interfaces, offers a solution for objects that have
multiple characteristics. To implement an interface the keyword implements is
used. The name of the interface starts as a class name with a capital letter.
What are interfaces and why they are used?
1. Subclasses that inherit a single superclass are related, but unrelated
classes can implement the same interface.
2. Interfaces offer the advantage of multiple inheritance in Java.
3. Interfaces do not have constructors and cannot be instantiated.
4. Interfaces are implemented by classes using the keyword implements, but
they are extended by other interfaces using the keyword extends.
5. If more than one interface is implemented, the names of the interfaces are
separated by a comma.
Interface methods
1. All the methods in an interface are implicitly abstract.
2. A class that implements an interface must override all the methods of that
interface.
3. Interface methods that are overridden by a class should be declared
public.
Interface constants
1. By default constants of an interface are public, static and final even if no
modifiers is mentioned.
2. Interface constants must be initialized.
3. It is not allowed to declare interface constants private or protected.
How to implement an interface?
In the following example the class MyArray implements the interface List
public class MyArray implements List
Chapter 15—Casting
1. Casting primitive variables
Implicit and explicit casting
Java supports implicit conversion to larger data types. However, casting to
smaller data types can only be done explicitly. In some cases, it is necessary that
the one variable is converted to another.
An example is dividing an int variable 31 by another int variable 2. The result
is 15 while the desired result is 15.5. To achieve this, we use casting as follows.
int i = 31;
int i2 = 2;
int x = i / i2 = 15;
The int type is an integer without decimal places. In order to show the decimal
value it is necessary to convert the result from int to a double type. We need to
cast the int types to double types.
double d1 = i;
double d2 = i2;
double d3 = d1 / d2 = 15.5;
It is also possible to have the result in one line as follows.
double d4 = (double) i / i2;
Example 1
public class MyClass
{
public static void main(String[] args)
{
int i = 31;
int i2 = 2;
int x = i / i2;
double d1 = i;
double d2 = i2;
double d3 = d1 / d2;
double d4 = (double) i / i2;
System.out.println(x);
System.out.println(d3);
System.out.println(d4);
}
}
This program writes the following to the standard output.
15
15.5
15.5
Other casting examples
short s = 20;
The following casting is valid, because int is larger than short:
int = 32 bits, short = 16 bit.
int i = s; // valid
int i2 = 200;
The following casting is invalid, because you cannot cast int directly to short.
short s2 = i2; // invalid
The following casting is valid. When converting from int to short an explicit
casting is required. That can be done as follows.
short s3 = (short) i2; // valid
It is important to understand that int is 32 bits and short is 16 bits. The result is
that 16 bits of the int variable are lost, because the value that is stored in an int is
too big to fit in a short variable.
Example 2
public class MyClass
{
public static void main(String[] args)
{
short s = 20;
int i = s; // valid
int i2 = 200;
short s2 = i2; // invalid
short s3 = (short) i2; // valid
System.out.println(s3);
}
}
2. Casting objects
It is allowed in Java to put an object into a more general type or cast up the
hierarchy implicitly. In the following example, the subclass Laptop has access to
all the members of its superclass Computer, while the Computer class doesn't
have access to all the members of the Laptop class.
The example below shows that the Laptop class extends the Computer class.
In our example, the Computer class has no access to the variable weight of the
Laptop class, but the Laptop class does have access to the variable brand of the
Computer class.
You can store a Computer object to a Laptop type reference without explicitly
casting. If you try to store a Laptop object to a Computer type reference, explicit
casting is required.
The following casting is valid.
Computer comp = new Laptop();
Laptop lap = (Laptop) comp;
The following casting is not valid.
Laptop lap = new Computer();
If we create an object of the class Computer the following casting causes error.
Computer comp2 = new Computer();
Laptop lap2 = (Laptop) comp2; // not valid
In the following way, it is possible to access the overridden methods in the
subclass. The variables of the object comp depend on the reference of the object,
but the methods depend on the object type that is created. See the following
example.
Example 3
public class Computer
{
protected String brand = "Dell";
protected double price = 200.0;;
public double getPrice()
{
return price;
}
}
public class Laptop extends Computer
{
private double weight;
public double getPrice()
{
return price - 20;
}
public static void main(String[] args)
{
Computer comp = new Laptop();
Laptop lap = (Laptop) comp;
System.out.println(comp.brand);
System.out.println(comp.price);
System.out.println(comp.getPrice());
}
}
If this program is compiled and run, the following is written to the standard outpt.
Dell
200.0
180.0
Quiz 1: Casting primitive variables
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i1 = 127;
int i2 = 134;
byte b1 = (byte) i1;
byte b2 = (byte) i2;
System.out.print(b1 + ", ");
System.out.print(b2);
}
}
Select the correct answer:
a This code writes to 127, 134 to the standard output.
b is The value of b1 is 127 , but the value of b2 is not printed as 134 .
Explanation
Byte is small and its value is between -128 and 127.
The value of b1 is 127 , but b2 is equal to 134 , which is greater than the
maximum
value of a byte .
The correct answer is b.
Assignments
1. Declare an int variable myInt.
2. Assign the value (i1 + i2) to the variable myInt.
3. Add a statement to your code to write the value of myInt to the standard output.
4. Declare a short variable with the name myShort .
5. Assign the value of i1 to myShort and run the program to see what happens.
Quiz 2: Casting primitive variables
What happens when the following program is compiled and run?
public class MyClass
{
public static void main(String[] args)
{
int i = 122;
double d = i;
System.out.print(d);
}
}
Select the correct answer:
a This code writes 122.0 to the standard output.
b This code writes 122 to the standard output.
c This program can not be compiled, because explicit casting is needed.
Explanation
The variable type double is 64 bits and this is larger than the int type which is 32
bits. In
this case, explicit casting is not needed. The variable type double is a decimal
type, therefore, is 122.0 written to the standard output.
The correct answer is a.
Assignments
1. Add the statement i = 187; add directly below the statement int
2. What is the value of the variable d ?
Run the program to get the answer to check.
Quiz 3: Casting objects
What happens when the following program is compiled and run?
public class MySuper
{
protected int i = 5;
public int method()
{
return 2 * i;
}
}
public class MySub extends MySuper
{
int i = 3;
public int method()
{
return 2 * i;
}
public static void main(String[] args)
{
MySuper s = new MySub();
System.out.print(" " + s.i);
System.out.print(" " + s.method());
}
}
Select the correct answer:
a. This code writes "3 6" to the standard output.
b. This code writes "5 10" to the standard output.
c. This code writes "5 6" to the standard output.
d. This code writes "3 10" to the standard output.
e. This code does not compile.
Explanation
By upcasting the class MySuper to MySub, The casted object accesses the
attributes of the superclass MySuper, but the overridden methods of the subclass
MySub.
s.i = 5.
The statement s.method(); ivokes the method that overridden in the subclass.
s.method(); prints 2 * i = 3 * 2 = 6. to the standard output.
The correct answer is c.
Assignments
1. Add the statement MySub ms = s; directly below the statement MySuper s =
new MySub();.
2. The statement of The first step causes an error. Try to solve the problem!
3. Add your own code to write the value of the variable i and the value that the
method returns to the standard output.
Quiz 4: Casting objects
What happens when the following program is compiled and run?
public class MySuper
{
protected int x;
MySuper()
{
x++;
System.out.print("N");
}
int myMethod()
{
return x + 3;
}
}
public class MySub extends MySuper
{
MySub()
{
x += 2;
System.out.print("P");
}
int myMethod()
{
return x + 4;
}
public static void main(String[] args)
{
MySuper ms = new MySub();
System.out.print(ms.myMethod());
}
}
Select the correct answer:
a. This code writes "NP7" to the standard output.
b. This code writes "NP5" to the standard output.
c. This code writes "P4" to the standard output.
d. This code writes "4" to the standard output.
e. This code writes "3" to the standard output.
f. This code does not compile.
Explanation
The statement MySuper ms = new MySub(); creates a new object of MySub,
which calls first the the no-argument constructor of MySuper class. This adds one
to the value of the variable x.
x = 0 + 1 = 1.
The statement System.out.print("N"); prints "N" to the standard output.
Creating the new object calls the no-argument constructor of MySub, which adds 2
to the value of x.
x = 1 + 2 = 3.
The statement System.out.print("P"); prints "P" to the standard output.
The statement System.out.print(ms.myMethod()); refers to the overridden method
in the class MySub.
The method myMethod return x + 4; adds 4 to the value of x.
x = 3 + 4 = 7.
The result is: NP7
The correct answer is a.
Assignments
1. Replace the statement MySuper ms = new MySub(); in the main method with
MySuper ms = new MySuper();
2. What would be the result of executing the program?
Quiz 5: Casting objects and overriding methods
What happens when the following program is compiled and run?
public class MySuper
{
public MySuper()
{
System.out.print("m");
}
public void method()
{
System.out.print("s");
}
public void method(int i)
{
method();
System.out.print("k" + i);
}
}
public class MySub extends MySuper
{
public void method()
{
System.out.print("t");
}
public static void main(String[] args)
{
MySuper ms = new MySub();
ms.method(3);
}
}
Select the correct answer:
a. This code writes "msk3" to the standard output.
b. This code writes "mtk3" to the standard output.
c. This code writes "tk3" to the standard output.
d. This code writes "mst" to the standard output.
e. This code does not compile.
Explanation
The statement MySuper ms = new MySub(); calls the no-argument constructor of
MySuper, which print "m" to the standard output.
The statement ms.method(3); invokes the method of int parameter which, invokes
the no-parameter method. The method is overridden in the class MySub, and that
is why it prints "t" to the standard output.
The statement System.out.print("k"+i), prints "k3" to the standard output, because
the parameter i is equal to 3.
The result is: mtk3.
The correct answer is b.
Assignments
1. Replace the statement MySuper ms = new MySub(); in the main method with
the statment MySuper ms = new MySuper();.
2. What is the output if you execute the program?
Assignment chapter 15: Working with Java API documentation
The class ArrayList implements the interface List .
1. Create a class with with the name MyList .
2. Declare two objects in MyList as follows.
a. List<String> list = new ArrayList<String>();
b. ArrayList<String> aList = new ArrayList<String>();
3. Try to invoke the method clone. Use the object names list and aList .
4. Why the object list does not have access to the method clone?
Chapter 16—Nested
Classes
A nested class is a member of another class, which is known as enclosing class or
an outer class.
The two main categories of nested classes are:
1. Static nested classes
A static nested class is directly connected to its outer class, but it does not have a
direct access to the instance members of its outer class. A static nested class can
access the members of its outer class through an object.
2. Inner classes
Inner classes have direct access to all members of their outer classes, even if they
are declared private.
The nested class and its outer class have a strong relationship, because their
existence depends on each other. An example is a building and its rooms. The
rooms of a building can not exist without the building in which they exist. Another
example is the relationship between a body and a heart. To create an object of a
nested class, An object of the outer class must be created.
Advantages of nested classes
1. Nested classes are only useful for their outer classes, therefore, it is logical to
keep them together. The definition of a nested class within an outer class
makes the code easier to maintain.
2. Nested classes are hidden for other classes.
Outer classes
1. An outer class can only be declared public or package (see chapter 8 access
modifiers).
2. An outer class does not have a direct access to the members of its nested
classes.
Static nested classes
1. A static nested class is associated with its outer class.
2. A static nested class does not have a direct access to the members of its outer
class, but it has access to those members through an object.
3. You can access static nested classes through the name of its outer class.
The creation of an object of a static nested class
Outer.Nest nest = new Outer.Nest();
Outer : the outer class
Nest : the static nested class
nest : an object of the nested class
Inner classes
1. An inner class is associated with an instance of the outer class.
2. An inner class has a direct access to the members of the object of the outer
class.
3. You can't create an object of an inner class without creating an object of the
outer class.
The creation of an object of an inner class
You can create an object of an inner class by creating an object of the outer class
as following.
Outer out = new Outer();
Inner in = out.new Inner();
Outer: the outer class
Inner: the inner class
out: an object of the outer class
in an object of the inner class
You can also create an object of an inner class in a single line.
Outer.Inner in = new Outer().new Inner();
Example
public class Face
{
private String faceShape = "Round";
private String skinColor = "Tinted";
public void printInfo()
{
System.out.println("Face shape: " + faceShape);
System.out.println("Skin color: " + skinColor);
}
class Eye
{
String color = "Brown";
String leftStrength = "- 2";
String rightStrength = "-1.5";
public void printInfo()
{
System.out.println("Eye color: " + color);
System.out.println("Left Strength: " + leftStrength);
System.out.println("Right Strength: " + rightStrength);
}
}
public static void main(String[] args)
{
Face face = new Face();
Eye eye = face.new Eye();
face.printInfo();
eye.printInfo();
}
}
Quiz 1: Access of Inner class to the members of its outer class
What happens when the following program is compiled and run?
public class Outer
{
int x;
Outer()
{
x += 4;
}
class Inner
{
int x;
private void methodA()
{
x++;
System.out.print(x);
}
}
public static void main(String[] args)
{
Inner inner = new Outer().new Inner();
inner.methodA();
}
}
Select the correct answer:
a. This program writes "0" to the standard output.
b. This program writes "4" to the standard output.
c. This program writes "5" to the standard output.
d. This program writes "1" to the standard output.
e. This program does not compile.
Explanation
The statement Inner inner = new Outer().new Inner(); calls the no-argument
constructor of the outer class, which adds 4 to the value of the variable "x" of the
outer class.
However, the methodA writes the value of the variable x of the inner class, which
is "0".
The statement x++ adds one to the value of x, and that is why this code writes "1"
to the standard output.
The correct answer is d.
Assignments
What is written to the standard output if you change the name of the variable x of
the inner class to y?
Quiz 2: A simple inner class
What happens when the following program is compiled and run?
public class Outer
{
private int a = 2;
Outer()
{
a += 4;
}
class Inner
{
Inner()
{
a++;
}
}
public static void main(String[] args)
{
Outer outer = new Outer();
Inner inner = outer.new Inner();
System.out.print(outer.a);
}
}
Select the correct answer:
a. This program writes "2" to the standard output.
b. This program writes "7" to the standard output.
c. This program writes "6" to the standard output.
d. This program writes "3" to the standard output.
e. This program does not compile.
Explanation
The statement Outer outer = new Outer(); calls the no-argument constructor of the
outer class, which adds 4 to the value of the varaible a.
a = 2 + 4 = 6
The statement Inner inner = outer.new Inner(); calls the no-argument constructor of
the inner class which increments the value of a by one.
A = 6 + 1 = 7.
The correct answer is b.
Assignments
What is the output if you change the initial value of the variable ' a' to 5?
Compile and run the program to test the result.
Quiz 3: Outer class one-argument constructor
What happens when the following program is compiled and run?
class Outer
{
private int x = 2;
Outer()
{
this(3);
x++;
}
Outer(int i)
{
x += i;
System.out.print(x);
}
class Inner
{
private void methodA()
{
x -= 3;
System.out.print(x);
}
}
public static void main(String[] args)
{
Inner inner = new Outer().new Inner();
inner.methodA();
}
}
Select the correct answer:
a. This program writes "63" to the standard output.
b. This program writes "5" to the standard output.
c. This program writes "53" to the standard output.
d. This program writes "52" to the standard output.
e. This program does not compile.
Explanation
The statement Inner inner = new Outer().new Inner(); calls the no-argument
constructor of the outer class.
The no-argument constructor calls the one-argument constructor of the outer class,
which increment the value of x by 3.
x = 2 + 3 = 5.
The statement System.out.print(x); prints 5 to the standard output.
x++; increments the value of x by one.
x = 5 + 1 = 6.
The statement inner.method(); invokes the method methodA, which decrements the
value of x by 3.
x = 6 - 3 = 3
The statement System.out.print(x); prints "3" to the standard output.
The correct answer is c.
Assignment
What is the output of this program if you replace the statement Outer.Inner inner =
new Outer().new Inner(); with the statement Outer.Inner inner = new Outer(7).new
Inner();?
Quiz 4: A static nested class
What happens when the following program is compiled and run?
class Outer
{
static int x = 3;
Outer()
{
x += 4;
}
static class Nested
{
Nested()
{
x += 2;
}
int method(int i)
{
System.out.print(x);
return i + x;
}
}
public static void main(String[] args)
{
Outer.Nested instance = new Outer.Nested();
System.out.print(instance.method(2));
}
}
Select the correct answer:
a. This program writes "1113" to the standard output.
b. This program writes "7" to the standard output.
c. This program writes "11" to the standard output.
d. This program writes "57" to the standard output.
e. This program does not compile.
Explanation
The statement Nested instance = new Outer.Nested(); calls the no-argument
constructor of the nested class.
The constructor increments the value of x by two.
x = 3 + 2 = 5;
The statement System.out.print(instance.method(2)); invokes the one parameter
method.
The statement System.out.print(x); prints the last value of x to the standard output,
which is 5.
The statement System.out.print(instance.method(2)); prints the number that is
returned by the method.
i + x = 2 + 5 = 7;
The correct answer is d.
Assignment
Add the statement Outer outer = new Outer(); as first statement of the main
method. What would be the output if you compile and run the program?
Assignment chapter 16: Working with Java API documentation
1. Create a class called Car. We need to know about the cars, the brand, the year
of manufacture and the license plate.
2. We need further to know information about the engines of the cars as: engine
code and the fuel.
3. Write a program which prints all the information about the cars to the standard
output.
4. By executing your program something like below would be printed to the
standard output.
Brand: BMW
Year of manufacture: 2016
License plate: XN-45-489
Engine code: N45B20A
Fuel: Petrol
Chapter 17—Exceptions
An exception is an abnormal condition, which might occur during the execution of
a program.
The exception objects in Java contain information about the errors. There are
two types of Exceptions: checked and unchecked Exceptions.
The following keywords are used to handle exceptions: try, catch, throw,
throws and finally.
Exceptions might cause by several reasons, for example, entering letters in a
field that is designed for calculating numbers, trying to access the seventh element
of an array of five-elements or trying to access a file, which doesn't exist.
All exceptions in Java are derived from the class Throwable. The following
methods of the class Throwable are used to get information about the cause of the
errors.
Diagram 1 shows the Exception class hierarchy in Java.
See for further information about the class Throwable the online documentation
of the Java standard API.
Method Return Description
type
printStackTrace() void Write the possible errors to
the standard
error-stream.
getMessage() String returns the message as a
String.
Diagram 1
The two subclasses of Exception: RunTimeException (unchecked) and
Other Exceptions (checked).
1. RunTimeException (unchecked)
The RuntimeException is unchecked and it is not enforced by the Java compiler.
Programmers are free to ignore the RunTimeException. However, it is wise to
handle these exceptions, so that the users receives a message that explains the
cause of the exception.
Examples of unchecked exceptions:
ArithmeticException
Divide-by-0.
ClassCastException
By illegal casting.
IndexArrayOutOfBoundsException
If you try to access element 8 of an array of 7 elements.
NullPointerException
When trying to access a member of an object reference before the object
is created.
2 Other exceptions (checked)
The checked exceptions cannot be ignored; they should be handled by
programmers. Examples of these are: the network connection is not found, a file is
not found and so on.
The try-catch block
In the following program, we divide a number by 0 without handling the
exception.
Example 1
public class MyClass
{
public static int division(int numerator, int denominator)
{
System.out.println("The method division()");
return numerator / denominator;
}
public static void printResult(int numerator, int denominator)
{
int average = division(numerator, denominator);
System.out.println("Average = " + average);
System.out.println("End printResult()");
}
public static void main(String[] args)
{
printResult(25, 0);
System.out.println("End main()");
}
}
Explanation
The statement printingResult (25, 0); in the main method invokes the method
printResult.
The statement int average = division(numerator, denominator); calls the method
division()
The statement System.out.print("The method of division()"); writes the text to The
method
the division sign() to the standard output.
The statement return numerator/denominator calculates 25 / 0 and here is
exception occur, because
the denominator is equal to zero. The program cannot go further because we
haven' t handled the exception.
The output of the program in the console window looks like the following.
division() Exception in thread "main"
The method division()
Exception in thread "main" java.lang.ArithmeticException: / by zero
at _17_exceptions.ex._01.MyClass.division(MyClass.java:8)
at _17_exceptions.ex._01.MyClass.printResult(MyClass.java:12)
at _17_exceptions.ex._01.MyClass.main(MyClass.java:18)
It is important that programmers handle this kind of exceptions and providing the
users with the correct message if an error occurs. You can handle the exception
with a try-catch block, see the following example.
Example 2
public class MyClass
{
public static int division(int numerator, int denominator)
{
System.out.println("The method division()");
return numerator / denominator;
}
public static void printResult(int numerator, int denominator)
{
try
{
int average = division(numerator, denominator);
System.out.println("Average = " + average);
}
catch (ArithmeticException ae)
{
System.out.println(ae);
System.out.println("Handeling the exception");
}
System.out.println("End printResult()");
}
public static void main(String[] args)
{
printResult(25, 0);
System.out.println("End main()");
}
}
Explanation
The statement printingResult (25, 0); invokes the method printResult.
The statement int average = division(numerator, denominator); calls the method
division().
The statement System.out.print("The method of division()"); writes the text “The
method the division()” to the standard output.
The statement return numerator / denominator calculates 25 / 0, and here the
exception occurs because the denominator is equal to zero.
The exception is in the first line of the try-block, and the block is further ignored.
The exception is caught in the catch block.
The statement System.out.println(ae); writes the exception type and its cause to the
standard output.
The program writes further the texts End printResult() and also End main() to the
standard output as follows.
The method division()
java.lang.ArithmeticException: / by zero
Handeling the exception
End printResult()
End main()
Assignment
1. Replace the statement printResult(25, 0); with the statement printResult(25, 5);
2. Compile and run the program to see what happens.
Answer
In this case, we divide the number 25 by 5, that is why the try-block is executed,
and the catch block is ignored. The program writes the following to the standard
output.
The method division()
Average = 5
End printResult()
End main()
You can use as many catch-blocks behind each other as you want, but you need to
keep in mind the order of the exceptions.
In the following example, the catch block Exception is under the catch-block
IndexOutOfBoundsException, because the class Exception is higher than the class
IndexOutOfBoundsException in the hierarchy of the exception classes. For the
same reason, the catch block of IndexOutOfBoundsException is under the catch-
block of ArrayIndexOutOfBoundsException. See Diagram 2.
Diagram 2
Example 3
public class MyClass
{
public static void main(String[] args)
{
try
{
// A code which may cause an exception
}
catch (ArrayIndexOutOfBoundsException ae)
{
// catch the exception ArrayIndexOutOfBoundsException
}
catch (IndexOutOfBoundsException ae)
{
// catch the exception IndexOutOfBoundsException
}
catch (Exception e)
{
// catch all other possible exceptions
}
}
}
The finally-block
The finally-block follows either the try or the catch block, and it is always
executed whether exceptions occurs or not. Finally is used for example to close a
network connection or to close a file. See the following example.
Example 4
public class MyClass
{
public static int division(int numerator, int denominator)
{
System.out.println("The method division()");
return numerator / denominator;
}
public static void printResult(int numerator, int denominator)
{
try
{
int average = division(numerator, denominator);
System.out.println("Average = " + average);
}
catch (ArithmeticException ae)
{
System.out.println(ae);
System.out.println("Handeling the exception");
}
finally
{
System.out.println("Finally block is always executed");
}
System.out.println("End printResult()");
}
public static void main(String[] args)
{
printResult(25, 0);
System.out.println("End main()");
}
}
Explanation
The difference between this example and example 2 is that in this example, the
block finally is always executed.
This code writes the following to the standard output.
The method division()
java.lang.ArithmeticException: / by zero
Handeling the exception
Finally block is always executed
End printResult()
End main()
The keywords throw and throws
A Java code can throw an exception with the keywords throw and throws. You can
catch these exceptions with a catch block. The keyword throws is used in the
header of the methods, but the keyword throw is used in the body of the methods.
See examples 5 and 6.
In the following program, a new object ArithmeticException("Division by
zero") is thrown if the denominator of the fraction is equal to 0.
Example 5
public class MyClass
{
public static int division(int numerator, int denominator)
{
System.out.println("The method division(()");
if (denominator == 0)
{
throw new ArithmeticException("Division by zero");
}
return numerator / denominator;
}
public static void printResult(int numerator, int denominator)
{
try
{
int average = division(numerator, denominator);
System.out.println("Average = " + average);
}
catch (ArithmeticException ae)
{
System.out.println(ae);
System.out.println("Exception is handled in the printResult()");
}
}
public static void main(String[] args)
{
printResult(25, 0);
System.out.println("End main()");
}
}
Explanation
This example is similar to example 2, except that here the control
if(denominator == 0) is used. If the denominator is equal to 0, the exception
ArithmeticException is thrown.
In the method printResult, the exception is caught. We have also passed a
customized exception text “ Division by zero” to the method. This replaces the
default message “/ by zero” .
This code writes the following to the standard output.
The method division(()
java.lang.ArithmeticException: Division by zero
Exception is handled in the printResult()
End main()
Create and throw your own exception class
In the following example, a customized exception class MyException is created.
This class is a checked exception because it is a subclass of the class Exception.
If an exception occurs, you can show your own customized text instead of the
default text.
Example 6
public class MyException extends Exception
{
MyException(String str)
{
super(str);
}
}
public class MyClass
{
public static int division(int numerator, int denominator) throws MyException
{
System.out.println("The method division(()");
if (denominator == 0)
{
throw new MyException("Division by zero");
}
return numerator / denominator;
}
public static void printResult(int numerator, int denominator)
{
try
{
int average = division(numerator, denominator);
System.out.println("Average = " + average);
}
catch (MyException me)
{
System.out.println(me);
System.out.println("Exception is handled in the printResult()");
}
}
public static void main(String[] args)
{
printResult(25, 0);
System.out.println("End main()");
}
}
This code writes the following to the standard output.
The method division(()
_17_exceptions.ex._06.MyException: Division by zero
Exception is handled in the printResult()
End main()
Errors
The Error class is a subclass of the class Throwable. Errors can occur at runtime
and programmers in most cases do not have control over them. Examples are:
StackOverflowError, OutOfMemoryError, and UnknowError.
Quiz 1: Unchecked exception (RunTimeException)
What happens when the following program is compiled and run?
public class MyClass
{
public void method()
{
try
{
System.out.print("x");
int x = Integer.parseInt("hi");
System.out.print("y");
}
catch (NumberFormatException e)
{
System.out.print("z");
}
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.method();
}
}
Select the correct answer:
a. This program writes "xyz" to the standard output.
b. This program writes "xz" to the standard output.
c. This program writes "xy" to the standard output.
d. This program writes "yz" to the standard output.
e. This program does not compile.
Explanation
The statement "System.out.print("x");" in the try block prints "x" to the standard
output.
The statement "int x = Integer.parseInt("hi");" tries to parse the string argument as
an integer,
which throws a NumberFormatException. The program jumps to the catch block.
The statement "System.out.print("z");" prints "z" to the standard output.
The correct answer is b.
Assignments
Use Java standard API and Search for the class Integer. You can find the link to the
Java standard API at the beginning of this book.
1. Find the method paraseInt("String str"), and read its description.
2. Replace the statement int x = Integer.parseInt("hi"); with int x =
Integer.parseInt("38");.
3. What is the output? Compile and run the program to test your expected result.
Quiz 2: Handling exceptions and the finally block
What happens when the following program is compiled and run?
public class MyClass
{
public void method()
{
try
{
int[] intArray = new int[5];
int z = intArray[6];
System.out.print("w");
}
catch (ArithmeticException e)
{
System.out.print("x");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.print("y");
}
finally
{
System.out.print("z");
}
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.method();
}
}
Select the correct answer:
a. This program writes "wz" to the standard output.
b. This program writes "yz" to the standard output.
c. This program writes "wyz" to the standard output.
d. This program writes "xz" to the standard output.
e. This program does not compile.
Explanation
The statement "int z = intArray[6];" tries to access the sixth element of the array
intArray, which doesn't exist.
This exception ArrayIndexOutOfBoundsException occurs and the statement
System.out.print("y"), prints "y" to the standard output.
The finally-block is always executed.
The statement System.out.print("z"), prints "z" to the standard output.
The correct answer is b.
Assignments
1. What happens if the finally-block is removed from the code?
2. Compile and run the program to check out your expectation.
Quiz 3: Unchecked exceptions and the finally block
What happens when the following program is compiled and run?
public class MyClass
{
String str;
public void method()
{
try
{
str.substring(1);
System.out.print("s");
}
catch (NullPointerException e)
{
System.out.print("x");
}
catch (Exception e)
{
System.out.print("y");
}
finally
{
System.out.print("z");
}
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.method();
}
}
Select the correct answer:
a. This program writes "xz" to the standard output.
b. This program writes "syz" to the standard output.
c. This program writes "yz" to the standard output.
d. This program writes "z" to the standard output.
e. This program does not compile.
Explanation
The String str is a reference to an object, which is not created.
String str = null;
By trying to access a substring of str, a NullPointerException occurs.
The statement System.out.print("x"), prints x to the standard output.
The finally block always executed.
The statement System.out.print("z"), prints z to the standard output.
The correct answer is a.
Assignments
1. Assign the value of "Boris" to the variable str.
2. What would be the output of the program?
3. Compile and run the code to test your expected result.
Quiz 4: Handling the exception of divided by zero
What happens when the following program is compiled and run?
public class MyClass
{
int x;
public void method()
{
try
{
int i = 2 / x;
System.out.print("a");
}
catch (NullPointerException n)
{
System.out.print("b");
}
catch (ArithmeticException e)
{
System.out.print("d");
}
finally
{
System.out.print("f");
}
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.method();
}
}
Select the correct answer:
a. This program writes "df" to the standard output.
b. This program writes "ab" to the standard output.
c. This program writes "bf" to the standard output.
d. This program writes "f" to the standard output.
e. This program does not compile.
Explanation
The catch block NullPointerException doesn't catch the exception because
dividing by zero is an ArithmeticException.
The catch block ArithmeticException is executed and prints “d” to the standard
output.
The finally block is always executed, and it prints “f” to the standard output.
The correct answer is a.
Assignments
1. Assign the value of 20 to the variable x.
2. What is the output if you compile and run the code?
3. Execute the program to test your answer.
Quiz 5: Which exception is caught?
What happens when the following program is compiled and run?
public class MyClass
{
StringBuffer sb;
int z;
public void myMethod()
{
try
{
z = 5 / 0;
sb.append("s");
}
catch (NullPointerException e)
{
System.out.print("n");
}
catch (ArithmeticException ae)
{
System.out.print("a");
}
}
public static void main(String[] args)
{
MyClass mc = new MyClass();
mc.myMethod();
}
}
Select the correct answer:
a. This code writes n to the standard output.
b. This code writes an to the standard output.
c. This code writes a to the standard output.
d. This code writes na to the standard output.
e. This code cannot be compiled.
Explanation
The two statements of the try block cause exceptions, but the first statement is first
executed. The first statement causes ArithmetcException , therefore, is the second
catch-block is executed.
The statement System.out.print("a"); writes a to the standard output.
The correct answer is c.
Assignments
1. What is the result of the execution of the program if the position of the
statements within the try block is changed as following?
sb.append("s");
z = 5/0;
2. Compile and run the program to check out your answer.
Quiz 6: Throwing an exception
What happens when the following program is compiled and run?
public class MyClass
{
static String str = "";
static void calculate(int x, int y)
{
str += "A";
if (y == 0)
{
throw new ArithmeticException();
}
int z = x / y;
str += "B";
}
public static void main(String[] args)
{
try
{
str += "C";
calculate(10, 0);
str += "D";
}
catch (ArithmeticException e)
{
str += "E";
}
catch (ArrayIndexOutOfBoundsException ae)
{
str += "F";
}
System.out.println(str);
}
}
Select the correct answer:
a. This code writes ABE to the standard output.
b. This code writes CAF to the standard output.
c. This code writes CAE to the standard output.
d. This code writes ABCD to the standard output.
e. This code can not be compiled.
Explanation
The statement str += "C"; inside the try-block adds the letter C to the String str.
The statement calculate(10, 0); calls the method calculate.
The statement str += "A" within the method calculate adds the letter A to the String
str .
The statement if(y == 0) returns true and the exception ArithmeticException is
thrown.
The catch block of the exception, ArithmeticException is caught.
The statement str += "E"; adds the letter E to the String str .
The correct answer is c.
Assignments
1. What is written to the standard output if the statement throw new
ArithmeticException(); is replaced with the statement throw new
ArrayIndexOutOfBoundsException(); ?
2. Compile and run the program to check.
Quiz 7: The keyword throw
What happens when the following program is compiled and run?
public class MyClass
{
public static void test(String str)
{
if (str == null)
{
throw new NullPointerException();
}
else
{
throw new RuntimeException();
}
}
public static void main(String[] args)
{
try
{
System.out.print("A");
test("");
}
catch (NullPointerException e)
{
System.out.print("B");
}
catch (Exception e)
{
System.out.print("C");
}
finally
{
System.out.print("D");
}
}
}
Select the correct answer:
a. This code writes the AD to the standard output.
b. This code writes ABCD to the standard output.
c. This code writes AC to the standard output.
d. This code writes ACD to the standard output.
e. This code can not be compiled.
Explanation
The statement System.out.print("A"); within the try-block writes A to the standard
output
The method test("") is invoked.
If the statement if(str == null) returns true, the exception NullPointerException is
caught, otherwise a RuntimeException.
The parameter of the method test("") is not equal to null , therefore, the
RuntimeException is thrown.
The catch block Exception is higher in the exception class hierarchy than the
RuntimeException, which is why it is caught. See diagram 2 for the exception
class hierarchy.
The statement System.out.print("C"); writes the letter C to the standard output.
The finally block is always executed, therefore, the letter D is also written to the
standard output.
The correct answer is d.
Assignments
1. What would be written to the standard output if the statement test(""); within
the try-block is replaced by the statement test(null);?
2. Compile and run the program to check out your answer.
Assignment chapter 17: Create your own exception class
In the following program, a customized exception class is created with the name
MyException. The method getMovie(int movieIndex) is invoked in the main
method, but the body of the method is missing.
1. Write the missing statements in the body of the method getMovie.
2. If the movieIndex is greater than 5, the program should write “the movie
does not exist”. Throw the exception MyException.
3. If a movieIndex exist, the program should write the title of the movie to
the standard output. For index 0 the program writes The Godfather to the
standard output. For index 1 the program writes Titanic to the standard
output, and so on.
4. Test your program whether it works properly.
5. Replace in the catch block, the statement
System.out.print(me.getMessage()); with the statement
me.printStackTrace();
6. Run the program to see the difference between the methods getMessage
and printStackTrace .
public class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}
import java.util.ArrayList;
public class Test
{
private static ArrayList<String> movieList = new ArrayList<String>();
public static void populateList()
{
movieList.add("The Godfather");
movieList.add("Titanic");
movieList.add("Dances with Wolves");
movieList.add("The Pianist");
movieList.add("Wall Street");
movieList.add("Amadeus");
}
public static String getMovie(int movieIndex) throws MyException
{
// the body
}
public static void main(String args[])
{
populateList();
try
{
String movie = getMovie(5);
System.out.print("The movie title is: " + movie);
}
catch (MyException me)
{
System.out.print(me.getMessage());
}
}
}
Index
abstract, 207
access modifiers, 137
accessors, 15
API documentation, 121
array, 145
ArrayList, 151
arrays. See array
boolean, 17
break statement, 44, 66
break statement, 44
byte, 16
casting, 230
catch block, 254
char, 17
class, 7, 87
class, 8
class variables, 18, 107, 108, 165
comment, 11
compile, 7
constants, 43
constructor, 89
continue statement, 67
encapsulation, 15
errors, 263
escape sequences, 13
exceptions, 252
final class, 199
final method, 199
finally, 259
float, 17
for loop, 64
if statements, 40
if/else statements, 41
if-/else-if statements, 42
if-block, 41
import, 137, 138
inheritance, 15, 177
inner class, 243, 244
instance variables, 107, 165
Instance variables, 18
integer, 16
interface, 8, 220
iteration statements, 64
label, 68
long, 16
loops, 64
method, 87, 102
method overloading, 15, 183
mutator, 15
class, 242
nested class, 242
object, 87
operand, 24
operators, 24
OR, 25
overloading, 15
overloading methods, 183
overriding, 15
package, 137
parameters, 104
plus, 11
polymorphism, 15
primary variable, 17
private, 138
protected, 137
public, 9, 137
RunTimeException, 253
short, 16
sort, 107, 148
standard output, 10
statement, 8
static, 11, 12, 108, 165
static methods, 166
static nested class, 242, 243
string, 121
StringBuffer, 121, 124
substring, 122
super, 178, 180
switch statement, 43
this, 91, 92, 167
throw, 252, 260
throwable, 252
throws, 252, 260
toString, 125
toUpperCase, 122
trim, 122
try, 254
try-catch-block. See try
variable, 16
while loop, 65
wrapper classes, 108