Fundamentals of Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 69

UNIT I – Introduction to Computer Programming

1.1 Learning Objectives


In this section you will learn about the computer's basic components, both
hardware and software. You’ll also learn about brief overview of programming
languages and the life cycle of software creation. Ultimately, you will learn the
different number systems and conversions from one type to another.
At the end of the lesson, you should be able to:
• Identify the different components of a computer
• Know about programming languages and their categories
• Understand the program development life cycle and apply it in problem
solving
• Learn the different number systems and their conversions
1.2 Introduction
A computer is a machine that performs a variety of tasks according to
specific instructions. It is a data processing machine which accepts data via an
input device and its processor manipulates the data according to a program.
The computer has two major components.
• The first one is the Hardware which is the tangible part of the computer. It
is composed of electronic and mechanical parts.
• The second major component is the Software which is the intangible part of
a computer. It consists of data and the computer programs.
1.3 Basic Components of Computer

1.3.1 Hardware
1.3.1.1 The Central Processing Unit
The processor is the “brain” of the computer. It contains millions of
extremely tiny electrical parts. It does the fundamental computing within the
system.
Examples of processors are Pentium, Athlon and AMD.
1.3.1.2 Memory
The memory is where data and instructions needed by the CPU to do its
appointed tasks can be found. It is divided into several storage locations which

pg. 1
have corresponding addresses. The CPU accesses the memory with the use of
these addresses.

1. Main Memory
The main memory is very closely connected to the processor. It is
used to hold programs and data, that the processor is actively working with.
It is not used for long-term storage. It is sometimes called the RAM
(Random Access Memory).
The computer's main memory is considered as volatile storage. This
means that once the computer is turned off, all information residing in the
main memory is erased.
2. The Secondary Memory
The secondary memory is connected to main memory. It is used to
hold programs and data for long term use. Examples of secondary memory
are hard disks and CD-ROM.
Secondary memory is considered as non-volatile storage. This
means that information residing in secondary memory is not erased after
the computer is turned off.
1.3.1.3 Input and Output Devices
Input and output devices allow a computer system to interact with the
outside world by moving data into and out of the system.
Examples of input devices are keyboards, mice and microphones.
Examples of output devices are monitors, printers and speakers.
1.3.2 Software
A software is the program that a computer uses in order to function. It is
kept on some hardware device like a hard disk, but it itself is intangible. The data
that the computer uses can be anything that a program need. Programs acts like
instructions for the processor.
Some Types of Computer Programs:
1. Systems Programs
Programs that are needed to keep all the hardware and software systems
running together smoothly

pg. 2
Examples: Operating Systems like Linux, Windows, Unix, Solaris, MacOS
2. Application Programs
Programs that people use to get their work done
Examples: Word Processor, Game programs, Spreadsheets
3. Compilers
The computer understands only one language: machine language.
Machine language is in the form of ones and zeros. Since it is highly impractical
for people to create programs out of zeros and ones, there must be a way of
translating or converting a language which we understand into machine
language, for this purpose, there exists compilers.
1.4 Overview of Computer Programming Languages
1.4.1 What is a Programming Language?
A programming language is a standardized communication technique for
expressing instructions to a computer. Like human languages, each language has
its own syntax and grammar.
Programming languages enable a programmer to precisely specify what
data a computer will act upon, how these data will be stored/transmitted, and
precisely what actions to take under various circumstances.
There are different types of programming languages that can be used to
create programs, but regardless of what language you use, these instructions are
translated into machine language that can be understood by computers.
1.4.2 Categories of Programming Languages
1. High-level Programming Languages
A high-level programming language is a programming language that is more
user- friendly, to some extent platform-independent, and abstract from low-level
computer processor operations such as memory accesses. A programming
statement may be translated into one or several machine instructions by a
compiler.
Examples are Java, C, C++, Basic, Fortran
2. Low-level Assembly Language
Assembly languages are similar to machine languages, but they are much
easier to program in because they allow a programmer to substitute names for

pg. 3
numbers. Assembly languages are available for each CPU family, and each
assembly instruction is translated into one machine instruction by an assembler
program.
Note: The terms "high-level" and "low-level" are inherently relative. Originally,
assembly language was considered low-level and COBOL, C, etc. were considered
high-level. Many programmers today might refer to these latter languages as
lowlevel.
1.5 The Program Development Life Cycle
Programmers do not sit down and start writing code right away when trying
to make a computer program. Instead, they follow an organized plan or
methodology, that breaks the process into a series of tasks.
Here are the basic steps in trying to solve a problem on the computer:
1. Problem Definition
2. Problem Analysis
3. Algorithm design and representation (Pseudocode or flowchart)
4. Coding and debugging
In order to understand the basic steps in solving a problem on a computer, let
us define a single problem that we will solve step-by-step as we discuss the
problemsolving methodologies in detail.
1.5.1 Problem Definition
A programmer is usually given a task in the form of a problem. Before a
program can be designed to solve a particular problem, the problem must be well
and clearly defined first in terms of its input and output requirements.
A clearly defined problem is already half the solution. Computer programming
requires us to define the problem first before we even try to create a solution.
Let us now define our example problem:

“Create a program that will determine the number of times a name occurs in a list.”

1.5.2 Problem Analysis


After the problem has been adequately defined, the simplest and yet the
most efficient and effective approach to solve the problem must be formulated.

pg. 4
Usually, this step involves breaking up the problem into smaller and simpler
subproblems.

Example Problem:
Determine the number of times a name occurs in a list
Input to the program: list of names, name to look for
Output of the program:
the number of times the name occurs in a list
1.5.3 Algorithm design and representation
Once our problem is clearly defined, we can now set to finding a solution. In
computer programming, it is normally required to express our solution in a step-
bystep manner.
An Algorithm is a clear and unambiguous specification of the steps needed
to solve a problem. It may be expressed in either Human language (English,
Tagalog), through a graphical representation like a flowchart or through a
pseudocode, which is a cross between human language and a programming
language.
Now given the problem defined in the previous sections, how do we express
our general solution in such a way that it is simple yet understandable?
Expressing our solution through Human language:
1. Get the list of names
2. Get the name to look for, let's call this the keyname
3. Compare the keyname to each of the names in the list
4. If the keyname is the same with a name in the list, add 1 to the count 5. If all
the names have been compared, output the result

pg. 5
1.5.3.1 Flowcharting Symbols and their meanings
A flowchart is a design tool used to graphically represent the logic in a solution.
Flowcharts typically do not display programming language commands. Rather,
they state the concept in English or mathematical notation.

Here are some guidelines for commonly used symbols in creating flowcharts. You
can use any symbols in creating your flowcharts, as long as you are consistent in
using them.
Symbol Name Meaning
Process Represents the process of executing a
defined operation or groups of operations
Symbol
that results in a change in value, form, or
location of information. Also functions as
the default symbol when no other symbol
is available.

pg. 6
Input/Output Represents an I/O function, which makes
data available for processing (input) or
(I/O) Symbol
displaying (output)of processed
information.

Flowline Represents the sequence of available


information and executable operations.
Symbol
The lines connect other symbols, and the
arrowheads are mandatory only for
rightto-left and bottom-to- top flow.

Decision Represents a decision that determines


which of a number of alternative paths is to
Symbol
be followed.

Terminal Represents the beginning, the end, or a


point of interruption or delay in a program.
Symbol
Connector Represents any entry from, or exit to,
another part of the flowchart. Also serves
Symbol
as an off-page connector.

Table 2: Flowchart Symbols

1.5.4 Coding and Debugging


After constructing the algorithm, it is now possible to create the source code.
Using the algorithm as basis, the source code can now be written using the chosen
programming language.

Most of the time, after the programmer has written the program, the
program isn't 100% working right away. The programmer has to add some fixes to
the program in case of errors (also called bugs) that occurs in the program. This
process of is called debugging.

There are two types of errors that a programmer will encounter along the
way.
The first one is compile-time error, and the other is runtime error.

pg. 7
Compile-Time Errors occur if there is a syntax error in the code. The
compiler will detect the error and the program won't even compile. At this point,
the programmer is unable to form an executable that a user can run until the error
is fixed.

Forgetting a semi-colon at the end of a statement or misspelling a certain


command, for example, is a compile-time error. It's something the compiler can
detect as an error.
Compilers aren't perfect and so can't catch all errors at compile time. This is
especially true for logic errors such as infinite loops. This type of error is called
runtime error.
For example, the actual syntax of the code looks okay. But when you follow
the code's logic, the same piece of code keeps executing over and over again
infinitely so that it loops. In such a case, compilers aren't really smart enough to
catch all of these types of errors at compile-time, and therefore, the program
compiles fine into an executable file. However, and unfortunately, when the end-
user runs the program, the program (or even their whole computer) freezes up due
to an infinite loop. Other types of run-time errors are when an incorrect value is
computed, the wrong thing happens, etc.

1.6 Number Systems


Numbers can be represented in a variety of ways. The representation
depends on what is called the BASE. The following are the four most common
representations.
1.6.1 Decimal
We normally represent numbers in their decimal form. Numbers in decimal form are
in base 10. This means that the only digits that appear are 0-9. Here are examples
of numbers written in decimal form:
12610 (normally written as just 126)
1110 (normally written as just 11)

pg. 8
1.6.2 Binary
Numbers in binary form are in base 2. This means that the only legal digits are 0
and 1. We need to write the subscript 2 to indicate that the number is a binary
number.
Here are examples of numbers written in binary form:
11111102 10112
1.6.3 Octal
Numbers in octal form are in base 8. This means that the only legal digits are 0-7.
We need to write the subscript 8 to indicate that the number is an octal number.
Here are examples of numbers written in octal form:
1768 138

1.6.4 Hexadecimal
Numbers in hexadecimal form are in base 16. This means that the only legal digits
are 0-9 and the letters A-F (or a-f, lowercase or uppercase does not matter). We
need to write the subscript 16 to indicate that the number is a hexadecimal number.
Here are examples of numbers written in hexadecimal form:

7E16 B16
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B C D E F
Decimal
Equivalent 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Table 3: Hexadecimal Numbers and their Equivalence to decimal numbers

1.7 Assessment Tasks


1.7.1 Writing Algorithms

Given the following set of tasks, create an algorithm to accomplish the following
tasks. You may write your algorithms using pseudocodes or you can use flowcharts.
1. Baking Bread
2. Logging into your laboratory's computer
3. Getting the average of three numbers

pg. 9
1.7.2 Number Conversions

Convert the following numbers:


1. 198010 to binary, hexadecimal and octal
2. 10010011012 to decimal, hexadecimal and octal
3. 768 to binary, hexadecimal and decimal
4. 43F16 to binary, decimal and octal

pg. 10
Unit II – Introduction to Java

2.1 Learning Objectives


In this section, you will be able to discover a little bit of Java history and
what is Java Technology.
At the end of the lesson, you should be able to:
• Create a Java program using and IDE
• Differentiate between syntax-errors and runtime errors
• Create a Java program using NetBeans
2.2 Java Background
2.2.1 A little Bit of History
Java was created in 1991 by James Gosling et al. of Sun Microsystems.
Initially called Oak, in honor of the tree outside Gosling's window, its name was
changed to Java because there was already a language called Oak. The original
motivation for Java was the need for platform independent language that could be
embedded in various consumer electronic products like toasters and refrigerators.
One of the first projects developed using Java was a personal hand-held remote
control named Star 7. At about the same time, the World Wide Web and the
Internet were gaining popularity. Gosling et. al. realized that Java could be used for
Internet programming.
2.2.2 What is Java Technology?
2.2.2.1 A programming language
Java can create all kinds of applications that you could create using any
conventional programming language.
2.2.2.2 A development environment
Java technology provides you with a large suite of tools: a compiler, an
interpreter, a documentation generator, a class file packaging tool, and etc.
2.2.2.3 An application environment
Java technology applications are typically general-purpose programs that run on
any machine where the Java runtime environment (JRE) is installed.
2.2.2.4 A deployment environment
There are two main deployment environments: First, the JRE supplied by
the
pg. 11
Java 2 Software Development Kit (SDK) contains the complete set of class files
for all the Java technology packages, which includes basic language classes, GUI
component classes, and so on. The other main deployment environment is on
your web browser. Most commercial browsers supply a Java technology
interpreter and runtime environment.
2.3 My First Java Program
2.3.1 Integrated Development Environment or IDE
An IDE is a programming environment integrated into a software application
that provides a GUI builder, a text or code editor, a compiler and/or interpreter and
a debugger.
2.3.2 Hello World Program
public class HelloWorld {
/* My first java program */
public static void main (String []args) {
System.out.println("Hello, World!");
}
}

2.3.3 Errors
What you’ve known so far is a Java program wherein you didn't encounter any
problems in compiling and running. However, this is not always the case. You
usually encounter errors along the way.
These are two types of errors. The first one is a compile-time error or also called
as syntax error. The second one is the runtime error.

2.3.3.1 Syntax Errors


Syntax errors are usually typing errors. You may have misspelled a command
in Java or forgot to write a semi-colon at the end of a statement. Java attempts
to isolate the error by displaying the line of code and pointing to the first
incorrect character in that line. However, the problem may not be at the exact
point. Other common mistakes are in capitalization, spelling, the use of
incorrect special characters, and omission of correct punctuation.

pg. 12
As a rule of thumb, if you encounter a lot of error messages, try to correct the
first mistake in a long list, and try to compile the program again. Doing so may
reduce the total number of errors dramatically.
2.3.3.2 Run-time Errors
Run-time errors are errors that will not display until you run or execute your
program. Even programs that compile successfully may display wrong answers if
the programmer has not thought through the logical processes and structures of
the program.

2.4 Assessment
2.4.1 Hello World!
Using an IDE, create a class named: [YourName]. The program should output on
the screen:

Welcome to Java Programming [YourName]!!!

2.4.2 The Tree


Using an IDE, create a class named: TheTree. The program should output the
following lines on the screen:

I think that I shall never see, a


poem as lovely as a tree.
A tree whose hungry mouth is pressed
Against the Earth’s sweet flowing breast.

Unit III – Programming Fundamentals

3.1 Learning Objectives


In this section, you will be exploring the basic parts of a Java program. You will
start by trying to explain the basic parts of the Hello.java program introduced in the
previous section. You will also learn about coding guidelines or code conventions
along the way to help in effectively writing readable programs.

pg. 13
At the end of the lesson, you should be able to:
• Identify the basic parts of a Java program
• Differentiate among Java literals, primitive data types, variable types,
identifiers and operators
• Develop a simple valid Java program using the concepts learned in this unit.
3.2 Dissecting my first Java program
Now, you'll try to the dissect your first Java program:
public class HelloWorld {
/* My first java program */
public static void main (String []args) {
//prints the string "Hello world" on screen
System.out.println("Hello, World!");
}
}

The first line of the code,


public class HelloWorld
indicates the name of the class which is HelloWorld. In Java, all code should be
placed inside a class declaration. We do this by using the class keyword.

In addition, the class uses an access specifier public, which indicates that
our class in accessible to other classes from other packages (packages are a
collection of classes). You will discover about the packages and access specifiers
later.

The next line which contains a curly brace { indicates the start of a block. In
this code, you placed the curly brace at the next line after the class declaration,
however, we can also place this next to the first line of our code. So, we could
actually write our code as:
public class HelloWorld
{
or
public class HelloWorld {

pg. 14
The next line indicates a Java comment. A comment is something used to
document a part of a code. It is not part of the program itself, but used for
documentation purposes.
It is good programming practice to add comments to your code.

/* My first java program */

A comment is indicated by the delimiters “/*” and “*/”. Anything within these delimiters
are ignored by the Java compiler, and are treated as comments.

The next line,

public static void main (String []args) {

or can also be written as,

public static void main (String []args)

indicates the name of one method in HelloWorld which is the main method. The main
method is the starting point of a Java program. All programs except Applets written in
Java start with the main method. Make sure to follow the exact signature.

The next line is also a Java comment,

//prints the string "Hello world" on screen

Now, you learned two ways of creating comments. The first one is by placing the
comment inside /* and */, and the other one is by writing // at the start of the comment.

The next line,

System.out.println("Hello, World!");

prints the text “Hello World!” on screen. The command System.out.println(), prints the
text enclosed by quotation on the screen.
The last two lines which contains the two curly braces is used to close the main method
and class respectively.

pg. 15
3.3 Java Comments
Comments are notes written to a code for documentation purposes. Those
text are not part of the program and does not affect the flow of the program.
Java supports three types of comments: C++-style single line comments,
Cstyle multiline comments and special Javadoc comments.
3.4 Java Statements and blocks
A statement is one or more lines of code terminated by a semicolon. An
example of a single statement is,

System.out.println("Hello, World!");

A block is one or more statements bounded by an opening and closing curly


braces that groups the statements as one unit. Block statements can be nested
indefinitely. Any amount of white space is allowed. An example of a block is,

public static void main (String []args) {


System.out.println("Hello");
System.out.println("World!");
}

Coding Guidelines:
1. In creating blocks, you can place the opening curly brace in line with the
statement or you can place the curly brace on the next line.
2. You should indent the next statements after the start of a block.

3.5 Java Identifiers


Identifiers are tokens that represent names of variables, methods, classes, etc.
Examples of identifiers are: Hello, main, System, out.
• Java identifiers are case-sensitive. This means that the identifier: Hello is
not the same as hello.
• Identifiers must begin with either a letter, an underscore “_”, or a dollar sign
“$”.
• Letters may be lower or upper case.
• Subsequent characters may use numbers 0 to 9.

pg. 16
• Identifiers cannot use Java keywords like class, public, void, etc. More about
Java keywords in the following lessons.
Coding Guidelines:
1. For names of classes, capitalize the first letter of the class name. For names of
methods and variables, the first letter of the word should start with a small
letter.

For example:

ThisIsAnExampleOfClassName
thisIsAnExampleOfMethodName

2. In case of multi-word identifiers, use capital letters to indicate the start of the
word except the first word.

For example:

charArray, fileNumber, ClassName. 3. Avoid using underscores

at the start of the identifier such as _read or _write.

3.6 Java Keywords


Keywords are predefined identifiers reserved by Java for a specific purpose. You
cannot use keywords as names for your variables, classes, methods …etc. Here is a
list of the Java Keywords.
You will discover all the meanings of these keywords and how they are used in your
Java programs as you go along the way.

Note: true, false, and null are not keywords but they are reserved words, so you
cannot use them as names in your programs either

pg. 17
3.7 Java Literals
Literals are tokens that do not change or are constant. This are the different types
of literals in Java:
3.7.1 Integer Literals
Integer literals come in different formats: decimal (base 10), hexadecimal
(base 16), and octal (base 8). In using integer literals in our program, we have to
follow some special notations.
For decimal numbers, we have no special notations. We just write a decimal
number as it is. For hexadecimal numbers, it should be proceeded by “0x” or “0X”.
For octals, they are proceeded by “0”.
For example, consider the number 12. Its decimal representation is 12, while
in hexadecimal, it is 0xC, and in octal, it is equivalent to 014.
Integer literals default to the data type int. An int is a signed 32-bit value. In
some cases, you may wish to force integer literal to the data type long by
appending the “l” or “L” character. A long is a signed 64-bit value.
3.7.2 Floating-Point Literals
Floating point literals represent decimals with fractional parts. An example is
3.1415. Floating point literals can be expressed in standard or scientific notations.
For example, 583.45 is in standard notation, while 5.8345e2 is in scientific
notation.
Floating point literals default to the data type double which is a 64-bit value.
To use a smaller precision (32-bit) float, just append the “f” or “F” character.
3.7.3 Boolean Literals
Boolean literals have only two values, true or false.
3.7.4 Character Literals
Character Literals represent single Unicode characters. A Unicode character is
a 16-bit character set that replaces the 8-bit ASCII character set. Unicode allows
the inclusion of symbols and special characters from other languages.
To use a character literal, enclose the character in single quote delimiters.
For example, the letter a, is represented as ‘a’.

pg. 18
To use special characters such as a newline character, a backslash is used
followed by the character code. For example, ‘\n’ for the newline character, ‘\r’ for
the carriage return, ‘\b’ for backspace.
3.7.5 String Literals
String literals represent multiple characters and are enclosed by double
quotes. An example of a string literal is, “Hello World”.
3.8 Primitive data types
The Java programming language defines eight primitive data types. The
following are, boolean (for logical), char (for textual), byte, short, int, long
(integral), double and float (floating point).
3.8.1 Logical – boolean
A boolean data type represents two states: true and false. An example is, boolean
result = true;

The example shown above, declares a variable named result as boolean type and
assigns it a value of true.
3.8.2 Textual – char
A character data type (char), represents a single Unicode character. It must have
its literal enclosed in single quotes (’ ’). For example,
‘a’ //The letter a
‘\t’ //A tab

To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \. For example,
'\'' //for single quotes
'\"' //for double quotes

Although, String is not a primitive data type (it is a Class), we will just introduce
String in this section. A String represents a data type that contains multiple
characters. It is not a primitive data type; it is a class. It has it’s literal enclosed
in double quotes (“”).
For example,
String message = “Hello world!”

3.8.3 Integral – byte, short, int & long


Integral data types in Java uses three forms – decimal, octal or hexadecimal.

pg. 19
Examples are, v
2 //The decimal value 2
077 //The leading 0 indicates an octal value
0xBACC //The leading 0x indicates a hexadecimal value Integral
types have int as default data type. You can define its long value by appending the
letter l or L. Integral data type have the following ranges:
Integer Length Name or Type Range
8 bits byte -27 to 27-1
16 bits short -215 to 215-1
32 bits int -231 to 231-1
64 bits long -263 to 263-1
Table 4: Integral types and their ranges

Coding Guidelines:
In defining a long value, a lowercase L is not recommended because it is hard to
distinguish from the digit 1.

3.8.4 Floating Point – float and double


Floating point types has double as default data type. Floating-point literal
includes either a decimal point or one of the following,
E or e // (add exponential value)
F or f //(float)
D or d //(double)

Examples are,
3.14 //A simple floating-point value (a double)
6.02E23 //A large floating-point value
2.718F //A simple float size value
123.4E+306D //A large double value with redundant D

In the example shown above, the 23 after the E in the second example is
implicitly positive. That example is equivalent to 6.02E+23. Floating-point data
types have the following ranges:
Float Length Name or Type Range
32 bits float -231 to 231-1
64 bits double -263 to 263-1
Table 5: Floating point types and their ranges

pg. 20
3.9 Variables
A variable is an item of data used to store state of objects.
A variable has a data type and a name. The data type indicates the type of
value that the variable can hold. The variable name must follow rules for
identifiers.

3.9.1 Declaring and Initializing Variables


To declare a variable is as follows,
<data type> <name> [=initial value];

Note: Values enclosed in <> are required values, while those values enclosed in []
are optional.

Here is a sample program that declares and initializes some variables,

public class VariableSamples


{ public static void main (String [] args) {
//declare a data type with variable name
// result and boolean data type boolean
result;

//declare a data type with variable name


// option and char data type char
option;
option = 'C’; //assign 'C' to option

//declare a data type with variable name


//grade, double data type and initialized
//to 0.0
double grade = 0.0;
}
}

pg. 21
Coding Guidelines:
1. It always good to initialize your variables as you declare them.
2. Use descriptive names for your variables. Like for example, if you want to have
a variable that contains a grade for a student, name it as, grade and not just
some random letters you choose.
3. Declare one variable per line of code. For example, the variable declarations,
double exam=0;
double quiz=10;
double grade = 0;

is preferred over the declaration,


double exam=0, quiz=10, grade=0;

3.9.2 Outputting Variable Data


In order to output the value of a certain variable, we can use the following
commands,
System.out.println()
System.out.print()

Here's a sample program, public


class OutputVariable
{ public static void main (String [] args)
{ int value = 10; char x; x = ‘A’;
System.out.println(value);
System.out.println(“The value of x= “+ x);
}
}

The program will output the following text on screen,


10
The value of x=A

3.9.3 System.out.println() vs System.out.print()


What is the difference between the commands System.out.println() and
System.out.print()? The first one appends a newline at the end of the data to
output, while the latter doesn't.
pg. 22
Consider the statements,
System.out.print("Hello ");
System.out.print("world!");

These statements will output the following on the screen,


Hello world!

Now consider the following statements,


System.out.println("Hello ");
System.out.println("world!");

These statements will output the following on the screen,


Hello world!

3.9.4 Reference Variables vs. Primitive Variables


We will now differentiate the two types of variables that Java programs have.
These are reference variables and primitive variables.
Primitive variables are variables with primitive data types. They store data
in the actual memory location of where the variable is.
Reference variables are variables that stores the address in the memory
location. It points to another memory location of where the actual data is. When
you declare a variable of a certain class, you are actually declaring a reference
variable to the object with that certain class.
For example, suppose we have two variables with data types int and String.
int num = 10;
String name = "Hello";

Suppose, the illustration shown below is the actual memory of your


computer, wherein you have the address of the memory cells, the variable name
and the data they hold.
Memory Variable
Data
Address Name
10
1001 num
:
:
Address (2000)
1563 name
:
: :
"Hello"

2000

pg. 23
As you can see, for the primitive variable num, the data is on the actual
location of where the variable is. For the reference variable name, the variable just
holds the address of where the actual data is.

3.10 Operators
In Java, there are different types of operators. There are arithmetic
operators, relational operators, logical operators and conditional operators. These
operators follow a certain kind of precedence so that the compiler will know which
operator to evaluate first in case multiple operators are used in one statement.
3.10.1 Arithmetic Operators
Here are the basic arithmetic operators that can be used in creating your
Java programs,

Operator Use Description

+ op1 + op2 Adds op1 and op2


* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divides op1 by op2

Computes the remainder of dividing


% op1 % op2
op1 by op2

- op1 - op2 Subtracts op2 from op1

Table 6: Floating point types and their ranges

public class ArithmeticDemo


{ public static void main (String [] args)
{
//a few numbers int i =
37; int j = 42;
double x = 27.475;
double y = 7.22;

pg. 24
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" x = " + x);
System.out.println(" y = " + y);
System.out.println("Adding..."); //adding numbers
System.out.println(" i + j = " + (i + j));
System.out.println(" x + y = " + (x + y));
System.out.println("Subtracting..."); //subtracting numbers
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));
System.out.println("Multiplying..."); //multiplying numbers
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
System.out.println("Dividing..."); //dividing numbers
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));

//computing the remainder resulting from dividing numbers


System.out.println("Computing the remainder...");
System.out.println(" i % j = " + (i % j));
System.out.println(" x % y = " + (x % y));
System.out.println("Mixing types..."); //mixing types
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x)); }
}
Note: When an integer and a floating-point number are used as operands to a single
arithmetic operation, the result is a floating point. The integer is implicitly converted to a
floating-point number before the operation takes place.
3.10.2 Increment and Decrement Operators
Aside from the basic arithmetic operators, Java also includes a unary increment
operator (++) and unary decrement operator (--). Increment and decrement
operators increase and decrease a value stored in a number variable by 1.
For example, the expression, count = count + 1; //increment the
value of count by 1

is equivalent to,
count++;
Operator Use Description

pg. 25
++ op++ Increments op by 1; evaluates to the value of op before it was
incremented
++ ++op Increments op by 1; evaluates to the value of op after it was incremented
-- op-- Decrements op by 1; evaluates to the value of op before it was
decremented
-- --op Decrements op by 1; evaluates to the value of op after it was decremented
Table 7: Increment and Decrement operators

The increment and decrement operators can be placed before or after an operand.
When used before an operand, it causes the variable to be incremented or
decremented by 1, and then the new value is used in the expression in which it
appears. For example,
int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14
When the increment and decrement operators are placed after the operand, the
old value of the variable will be used in the expression where it appears. For
example,
int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13

Coding Guideline:
Always keep expressions containing increment and decrement operators
simple and easy to understand.

3.10.3 Relational Operators


Relational operators compare two values and determines the relationship
between those values. The output of evaluation is the boolean values true or
false.
Operator Use Description
> op1 > op2 op 1 is greater than op2

>= op1 >= op2 op1 is greater than or equal to op2


< op1 < op2 op1 is less than op2

pg. 26
<= op1 <= op2 op1 is less than or equal to op2

== op1 == op2 op1 and op2 are equal


!= op1 != op2 op1 and op2 are not equal
Table 8: Relational Operators
public class RelationalDemo { public static
void main (String [] args) { int i = 37;
int j = 42; int k = 42;

System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" k = " + k);

System.out.println("Greater than..."); //greater than


System.out.println(" i > j = " + (i > j)); //false
System.out.println(" j > i = " + (j > i)); //true
System.out.println(" k > j = " + (k > j)); //false
System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j)); //false
System.out.println(" j >= i = " + (j >= i)); //true
System.out.println(" k >= j = " + (k >= j)); //true
System.out.println("Less than..."); //less than
System.out.println(" i < j = " + (i < j)); //true
System.out.println(" j < i = " + (j < i)); //false
System.out.println(" k < j = " + (k < j)); //false
System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j)); //true
System.out.println(" j <= i = " + (j <= i)); //false
System.out.println(" k <= j = " + (k <= j)); //true

System.out.println("Equal to..."); //equal to


System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true
System.out.println("Not equal to..."); //not equal to
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}

3.10.4 Logical Operators


Logical operators have one or two boolean operands that yield a boolean result.
The basic expression for a logical operation is,
x1 op x2

where x1, x2 can be boolean expressions, variables or constants, and op is

pg. 27
either && (AND), & (boolean AND), || (OR), | (boolean inclusive OR) or ^
(boolean exclusive OR) operator.
3.10.4.1 && (logical AND) and & (boolean logical AND)
Here is the truth table for && and &,
x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE
Table 9: Truth table for & and &&

The basic difference between && and & operators is that && supports
shortcircuit evaluations (or partial evaluations), while & doesn't. What does
this mean? Given an expression,
exp1 && exp2

&& will evaluate the expression exp1, and immediately return a false value is
exp1 is false. If exp1 is false, the operator never evaluates exp2 because the
result of the operator will be false regardless of the value of exp2. In contrast,
the & operator always evaluates both exp1 and exp2 before returning an
answer.

public class TestAND { public static void main


(String [] args){ int i = 0; int j = 10;
boolean test = false;

test = (i > 10) && (j++ > 9); //demonstrate &&


System.out.println(i);
System.out.println(j); System.out.println(test);
test = (i > 10) & (j++ > 9); //demonstrate &
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}
3.10.4.2 || (logical OR) and | (boolean logical inclusive OR)
Here is the truth table for || and |,
x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE

pg. 28
FALSE FALSE FALSE
Table 10: Truth table for | and ||

The basic difference between || and | operators is that || supports short-


circuit evaluations (or partial evaluations), while | doesn't. What does this
mean?

Given an expression,
exp1 || exp2

|| will evaluate the expression exp1, and immediately return a true value is
exp1 is true. If exp1 is true, the operator never evaluates exp2 because the
result of the operator will be true regardless of the value of exp2. In contrast,
the | operator always evaluates both exp1 and exp2 before returning an answer.

public class TestOR


{ public static void main (String [] args) {
int i = 0; int j = 10;
boolean test = false;

//demonstrate ||
test = (i < 10) || (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);

//demonstrate |
test = (i < 10) | (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}

3.10.4.3 ^ (boolean logical exclusive OR)


Here is the truth table for ^,
x1 x2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE

pg. 29
FALSE FALSE FALSE
Table 11: Truth table for ^

The result of an exclusive OR operation is TRUE, if and only if one operand is


true and the other is false. Note that both operands must always be evaluated in
order to calculate the result of an exclusive OR.
public class
TestXOR
{ public static void main (String [] args) {
boolean val1 = true;
boolean val2 = true;
System.out.println(val1 ^ val2);
val1 =
false; val2
= true;
System.out.println(val1 ^ val2);
val1 =
false; val2
= false;
System.out.println(val1 ^ val2);
val1 = true;
val2 = false;
System.out.println(val1 ^ val2); }
}
3.10.4.4 ! (logical NOT)
The logical NOT takes in one argument, wherein that argument can be an
expression, variable or constant. Here is the truth table for !,
x1 Result
TRUE FALSE
FALSE TRUE
Table 12: Truth table for !
public class TestNOT
{ public static void main (String [] args) {
boolean val1 = true; boolean
val2 = false;
System.out.println(!val1);
System.out.println(!val2);
}
}
3.10.5 Conditional Operator (?:)
The conditional operator ?: is a ternary operator. This means that it takes in
three arguments that together form a conditional expression. The structure of an
expression using a conditional operator is,

pg. 30
exp1?exp2:exp3

wherein exp1 is a boolean expression whose result must either be true or false. If
exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned. For
example,

public class ConditionalOperator{ public static


void main (String [] args) {

String status = ""; int


grade = 80;

//get status of the student status =


(grade >= 60)?"Passed":"Fail";

//print status
System.out.println(status);
}
}

Example 2,
class ConditionalOperator
{ public static void main (String [] args) {
int score = 0; char
answer = 'a';

score = (answer == 'a') ? 10 : 0;


System.out.println("Score = " + score); }
}

3.10.6 Operator Precedence


Operator precedence defines the compiler’s order of evaluation of operators so as
to come up with an unambiguous result.

pg. 31
Given a complicated expression,
6%2*5+4/2+88-10
you can re-write the expression and place some parenthesis base on operator
precedence,
((6%2) *5) +(4/2) +88-10;

Coding Guidelines
To avoid confusion in evaluating mathematical operations, keep your expressions
simple and use parenthesis.
3.11 Assessment
3.11.1 Declaring and printing variables
Given the table below, declare the following variables with the corresponding data
types and initialization values. Output to the screen the variable names together with
the values.
Variable Data Type Initial value
name
number integer 10
letter character a
result boolean true
str String hello

The following should be the expected screen output,

pg. 32
Number = 10
letter = a
result = true
str = hello
3.11.2 Getting the average of three numbers
Create a program that outputs the average of three numbers. Let the values of
the three numbers be, 10, 20 and 45. The expected screen output is,
number 1 = 10
number 2 = 20
number 3 = 45
Average is = 25
3.11.3 Output greatest value
Given three numbers, write a program that outputs the number with the greatest
value among the three. Use the conditional ?: operator that we have studied so
far (HINT: You will need to use two sets of ?: to solve this). For example, given
the numbers 10, 23 and 5, your program should output,
number 1 = 10 number
2 = 23
number 3 = 5
The highest number is = 23
3.11.4 Operator precedence
Given the following expressions, re-write them by writing some parenthesis based
on the sequence on how they will be evaluated.
1. a / b ^ c ^ d – e + f – g * h + i
2. 3 * 10 *2 / 15 – 2 + 4 ^ 2 ^ 2
3. r ^ s * t / u – v + w ^ x – y++

Unit IV – Getting Input from the Keyboard

4.1 Learning Objectives


Now that you've studied some basic concepts in Java and you've written
some simple programs, let's make our programs more interactive by getting some
input from the user. In this section, you’ll be learning about the two methods of
getting input, the first one is through the use of the BufferedReader class and the
other one involves a graphical user interface by using JOptionPane.

At the end of the lesson, you should be able to:

pg. 33
• Create an interactive Java program that gets input from the keyboard
• Use the BufferedReader class to get input from the keyboard using a console
• Use the JOptionPane class to get input from the keyboard using a graphical user
interface
4.2 Using BufferedReader to get input
In this section, you will use the BufferedReader class found in the java.io
package in order to get input from the keyboard.

Here are the steps to get input from the keyboard:


1. Add this at the top of your code:
import java.io. *;

2. Add this statement:


BufferedReader dataIn = new BufferedReader (
new InputStreamReader (System.in));

3. Declare a temporary String variable to get the input, and invoke


the readLine() method to get input from the keyboard. You have to type it
inside a try-
catch block.
try{
String temp = dataIn.readLine();
}
catch (IOException e) {
System.out.println(“Error in getting input”);
}
Here is the complete source code:
import java.io.BufferedReader; import
java.io.InputStreamReader; import
java.io.IOException;
public class
GetInputFromKeyboard
{ public static void main (String [] args) {

BufferedReader dataIn = new BufferedReader (new


InputStreamReader (System.in));

String name = "";

System.out.print("Please Enter Your Name:");


pg. 34
try{ name =
dataIn.readLine();
}catch(IOException e ){
System.out.println("Error!");
}
System.out.println("Hello " + name +"!"); }
}

Now let's try to explain each line of code: The statements,


import java.io.BufferedReader; import
java.io.InputStreamReader; import

java.io.IOException;

indicate that we want to use the classes BufferedReader, InputStreamReader and


IOException which is inside the java.io package. The Java Application
Programming Interface (API) contains hundreds of predefined classes that you can
use in your programs. These classes are organized into what you call packages.

Packages contain classes that have related purpose. Just like in our
example, the java.io package contains classes that allow programs to input and
output data.
The statements can also be rewritten as,
import java.io.*;

which will load all the classes found in the package, and then you can use those
classes inside your program.
• The next two statements,
public class GetInputFromKeyboard
{
public static void main( String[] args ){
you are already know in the previous lesson. This means you declare a class named
GetInputFromKeyboard and you declare the main method.

• In the statement,
BufferedReader dataIn = new BufferedReader(new
InputStreamReader(System.in));
you are declaring a variable named dataIn with the class type BufferedReader.
Don't worry about what the syntax means for now. You will discover more about
this later in the course.

pg. 35
• Now, we are declaring a String variable with the identifier name,
String name = "";

This is where you will store the input of the user. The variable name is initialized to
an empty String "". It is always good to initialize your variables as you declare
them.
• The next line just outputs a String on the screen asking for the user's name.
System.out.print("Please Enter Your Name:");

• Now, the following block defines a try-catch block, try{ name =


dataIn.readLine(); }catch(IOException e){
System.out.println("Error!");
}

• This assures that the possible exceptions that could occur in the statement
name = dataIn.readLine();

will be catched. You will discover more about exception handling in the latter part of
this course, but for now, just take note that you need to add this code in order to
use the readLine() method of BufferedReader to get input from the user.

The method call, dataIn.readLine(), gets input from the user and will return a
String value. This value will then be saved to our name variable, which we will use
in our final statement to greet the user,
System.out.println("Hello " + name + "!");
4.3 Using JOptionPane to get input
Another way to get input from the user is by using the JOptionPane class which
is found in the javax.swing package. JOptionPane makes it easy to pop up a
standard dialog box that prompts users for a value or informs them of something.

Given the following code,

import javax.swing.JOptionPane;

public class GetInputFromKeyboard


{ public static void main( String[] args ){
String name = "";
name = JoptionPane.showInputDialog("Please enter your name");
String msg = "Hello " + name + "!";

pg. 36
JOptionPane.showMessageDialog(null, msg);
}
}

This will output,

Figure 4.1: Getting Input Using JOptionPane

Figure 4.2: Input florence on the JOptionPane

Figure 4.3: Showing Message Using JOptionPane

pg. 37
The first statement,

import javax.swing.JOptionPane;

indicates that we want to import the class JOptionPane from the javax.swing
package.

We can also write this as,

import javax.swing.*;

The statement,

name = JOptionPane.showInputDialog("Please enter your


name");

creates a JOptionPane input dialog, which will display a dialog with a message, a
textfield and an OK button as shown in the figure. This returns a String which we
will save in the name variable.

Now we create the welcome message, which we will store in the msg variable,

String msg = "Hello " + name + "!";

The next line displays a dialog which contains a message and an OK button.

JOptionPane.showMessageDialog(null, msg);

4.4 Assessments
4.4.1 Last 3 words (BufferedReader version)
Using BufferedReader, ask for three words from the user and output those three
words on the screen. For example,

pg. 38
Enter word1:Goodbye
Enter word2:and
Enter word3:Hello

Goodbye and Hello

4.4.2 Last 3 words (JOptionPane version)

Figure 4.4: First Input

pg. 39
Figure 4.5: Second Input

Figure 4.6: Third Input

Figure 4.7: Show Message

Unit V – Control Structures

5.1 Learning Objectives


In the previous sections, you have given examples of sequential programs,
wherein statements are executed one after another in a fixed order. In this section,
you will learn about control structures, which will allow you to change the ordering
of how the statements in our programs are executed.

At the end of the lesson, you should be able to:


• Use decision control structures (if, else, switch) which allows selection of
specific sections of code to be executed
• Use repetition control structures (while, do-while, for) which allow
executing specific sections of code a number of times
• Use branching statements (break, continue, return) which allows redirection
of program flow

5.2 Decision Control Structures


Decision control structures are Java statements that allows us to select and
execute specific blocks of code while skipping other sections.

pg. 40
5.2.1 if statement
The if-statement specifies that a statement (or block of code) will be
executed if and only if a certain boolean statement is true.

The if-statement has the form,


if( boolean_expression ) statement;

or
if( boolean_expression ){
statement1; statement2;
. . .
}

where, boolean_expression is either a boolean expression or boolean variable.


For example, given the code snippet,
int grade = 68;

if( grade > 60 )


System.out.println("Congratulations!");

or
int grade = 68;

if( grade > 60 ){


System.out.println("Congratulations!");
System.out.println("You passed!");
}

Coding Guidelines:
1. The boolean_expression part of a statement should evaluate to a
boolean value. That means that the execution of the condition should
either result to a value of true or a false.
2. Indent the statements inside the if-block.For example,
if( boolean_expression ){

//statement1; //statement2;
}

pg. 41
5.2.2 if-else statement
The if-else statement is used when we want to execute a certain statement if
a condition is true, and a different statement if the condition is false.
The if-else statement has the form,
if( boolean_expression ) statement;
else statement;
or can also be written as,
if( boolean_expression )
{ statement1;
statement2;
. . .
}
else{ statement1;
statement2;
. . .
}

For example, given the code snippet,


int grade = 68;

if( grade > 60 )


System.out.println("Congratulations!"); else
System.out.println("Sorry you failed");
or
int grade = 68;

if( grade > 60 ){


System.out.println("Congratulations!");
System.out.println("You passed!");
} else{
System.out.println("Sorry you failed");
}

pg. 42
Coding Guidelines:

1. To avoid confusion, always place the statement or statements of an if


or if-else block inside brackets {}.
2. You can have nested if-else blocks. This means that you can have
other if-else blocks inside another if-else block. For example,
if( boolean_expression ){
if( boolean_expression ){
. . .
}
} else{
. . .
}

5.2.3 if-else-if statement


The statement in the else-clause of an if-else block can be another if-else
structures. This cascading of structures allows us to make more complex selections.

The if-else if statement has the form,


if( boolean_expression1 ) statement1;
else if( boolean_expression2 ) statement2;
else statement3;

Take note that you can have many else-if blocks after an if-statement. The
else-block is optional and can be omitted. In the example shown above,
• if boolean_expression1 is true, then the program executes statement1
and skips the other statements.
• If boolean_expression2 is true, then the program executes statement
2 and skips to the statements following statement3.

For example, given the code snippet,


int grade =
68;

pg. 43
if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
} else{
System.out.println("Sorry you failed");
}

5.2.4 Common Errors when Using the if-else statements


1. The condition inside the if-statement does not evaluate to a boolean value. For
example,
//WRONG int number =
0;
if( number ){
//some statements here
}
The variable number does not hold a Boolean value.
2. Using = instead of == for comparison. For example,
//WRONG int number =
0;
if( number = 0 ){
//some statements here
}
This should be written as,
//CORRECT int number
= 0;
if( number == 0 ){
//some statements here
}
3. Writing elseif instead of else if.

5.2.5 Example for if-else-else-if


public class Grade { public static void main(
String[] args ){ double grade = 92.0;

if( grade >= 90 ){


System.out.println( "Excellent!" );

pg. 44
}
else if( (grade < 90) && (grade >= 80)){
System.out.println("Good job!" );
}
else if( (grade < 80) && (grade >= 60)){
System.out.println("Study harder!" );
} else{
System.out.println("Sorry, you failed."); }
}
}

5.2.6 switch statement


Another way to indicate a branch is through the switch keyword. The switch
construct allows branching on multiple outcomes.

The switch statement has the form,


switch( switch_expression ){ case
case_selector1:
statement1; // statement2;
//block 1
. . . //
break; case
case_selector2:
statement1; // statement2;
//block 2
. . . //
break; . . .
default:
statement1; // statement2;
//block n
. . . // break;
}
where, switch_expression is an integer or character expression and,
case_selector1, case_selector2 and so on, are unique integer or character
constants.

When a switch is encountered, Java first evaluates the switch_expression,


and jumps to the case whose selector matches the value of the expression. The
program executes the statements in order from that point on until a break
statement is encountered, skipping then to the first statement after the end of the
switch structure.

pg. 45
If none of the cases are satisfied, the default block is executed. Take note
however, that the default part is optional. A switch statement can have no default
block.

NOTES:
• Unlike with the if statement, the multiple statements are executed in the
switch statement without needing the curly braces.
• When a case in a switch statement has been matched, all the statements
associated with that case are executed. Not only that, the statements
associated with the succeeding cases are also executed.
• To prevent the program from executing statements in the subsequent cases,
we use a break statement as our last statement.

Coding Guidelines:

1. Deciding whether to use an if statement or a switch statement is a judgment


call. You can decide which to use, based on readability and other factors.
2. An if statement can be used to make decisions based on ranges of values or
conditions, whereas a switch statement can make decisions based only on a
single integer or character value. Also, the value provided to each case
statement must be unique.

5.2.7 Example for switch


public class Grade { public static void main(
String[] args )
{ int grade = 92;
switch(grade){
case 100:
System.out.println( "Excellent!" );
break;
case 90:
System.out.println("Good job!" );
break;
case 80:

pg. 46
System.out.println("Study harder!" );
break;
default:
System.out.println("Sorry, you failed."); }
}
}
5.3 Repetition Control Structures
Repetition control structures are Java statements that will allow you to
execute specific blocks of code a number of times. There are three types of
repetition control structures, the while, do-while and for loops.

5.3.1 while loop


The while loop is a statement or block of statements that is repeated as long
as some condition is satisfied.

The while statement has the form,


while( boolean_expression ){
statement1;
statement2; . . .
}

The statements inside the while loop are executed as long as the
boolean_expression evaluates to true.

For example, given the code snippet,


int i = 4; while
( i > 0 ){
System.out.print(i); i--;
}

The sample code shown will print 4321 on the screen.

Take note that if the line containing the statement i--; is removed, this will
result to an infinite loop, or a loop that does not terminate.
Therefore, when using while loops or any kind of repetition control structures,
make sure that you add some statements that will allow your loop to terminate at
some point.

pg. 47
The following are other examples of while loops, Example
1:
int x = 0; while
(x<10)
{
System.out.println(x); x++;
}
Example 2:
//infinite loop while(true)
System.out.println(“hello”);
Example 3:
//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);

5.3.2 do-while loop


The do-while loop is similar to the while-loop. The statements inside a do-
while loop are executed several times as long as the condition is satisfied.

The main difference between a while and do-while loop is that, the
statements inside a do-while loop are executed at least once.

The do-while statement has the form,


do{ statement1;
statement2;
. . .
}while( boolean_expression );
The statements inside the do-while loop are first executed, and then the
condition in the boolean_expression part is evaluated. If this evaluates to true, the
statements inside the do-while loop are executed again.
Here are a few examples that uses the do-while loop:

pg. 48
Example 1:
int x = 0;
do {
System.out.println(x); x++;
}while (x<10);

This example will output 0123456789 on the screen.

Example 2:
//infinite loop do{
System.out.println(“hello”);
} while (true);

This example will result to an infinite loop, that prints hello on screen.

Example 3:
//one loop
// statement is executed once do
System.out.println(“hello”); while
(false);

This example will output hello on the screen.

Coding Guidelines:
1. Common programming mistakes when using the do-while loop is forgetting
to write the semi-colon after the while expression.
do{
...
}while(boolean_expression) //WRONG->forgot semicolon ;
2. Just like in while loops, make sure that your do-while loops will terminate at
some point.
5.3.3 for loop
The for loop, like the previous loops, allows execution of the same code a
number of times.

The for loop has the form,

pg. 49
for(InitializationExpression;LoopCondition;StepExpression){
statement1; statement2; . . .
}

where,
InitializationExpression - initializes the loop variable.
LoopCondition - compares the loop variable to some limit value.
StepExpression - updates the loop variable.

A simple example of the for loop is,


int i;
for( i = 0; i < 10; i++ ){ System.out.print(i);
}
In this example, the statement i=0, first initializes our variable. After that,
the condition expression i<10 is evaluated. If this evaluates to true, then the
statement inside the for loop is executed. Next, the expression i++ is executed,
and then the condition expression is again evaluated. This goes on and on, until the
condition expression evaluates to false.

This example, is equivalent to the while loop shown below,


int i = 0; while(
i < 10 ){
System.out.print(i); i++;
}

5.4 Branching Statements


Branching statements allows us to redirect the flow of program execution.
Java offers three branching statements: break, continue and return.

5.4.1 break statement


The break statement has two forms: unlabeled (we saw its unlabeled form in the
switch statement) and labeled.

pg. 50
5.4.1.1 unlabeled break statement
The unlabeled break terminates the enclosing switch statement, and flow of
control transfers to the statement immediately following the switch. You can
also use the unlabeled form of the break statement to terminate a for, while, or
dowhile loop.

For example,
String names[] = {"Beah", "Bianca", "Lance", "Belle", "Nico",
"Yza", "Gem", "Ethan"};

String searchName = "Yza"; boolean


foundName = false;
for( int i=0; i< names.length; i++ ){
if( names[i].equals( searchName )){
foundName = true; break;
}
}
if( foundName ){
System.out.println( searchName + " found!" );
}
else{
System.out.println( searchName + " not found." ); }

In this example, if the search string "Yza" is found, the for loop will stop and
flow of control transfers to the statement following the for loop.

5.4.1.2 labeled break statement

The labeled form of a break statement terminates an outer statement, which


is identified by the label specified in the break statement. The following program
searches for a value in a two-dimensional array. Two nested for loops traverse
the array. When the value is found, a labeled break terminates the statement
labeled search, which is the outer for loop.

int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

pg. 51
int searchNum = 5; boolean
foundNum = false;
searchLabel:
for( int i=0; i<numbers.length; i++ ){
for( int j=0; j<numbers[i].length; j++ ){
if( searchNum == numbers[i][j] ){
foundNum = true; break searchLabel;
}
}
}
if( foundNum ){
System.out.println( searchNum + " found!" );
}
else{
System.out.println( searchNum + " not found!" ); }

The break statement terminates the labeled statement; it does not transfer the
flow of control to the label. The flow of control transfers to the statement
immediately following the labeled (terminated) statement.

5.4.2 continue statement


The continue statement has two forms: unlabeled and labeled. You can use the
continue statement to skip the current iteration of a for, while or do-while loop.
5.4.2.1 unlabeled continue statement
The unlabeled form skips to the end of the innermost loop's body and evaluates
the boolean expression that controls the loop, basically skipping the
remainder of this iteration of the loop.

• The following example counts the number of "Beah"s in the array.


String names[] = {"Beah", "Bianca", "Lance", "Beah"}; int
count = 0;

for( int i=0; i<names.length; i++ ){ if(


!names[i].equals("Beah") ){ continue;
//skip next statement

pg. 52
} count+
+;
}
System.out.println("There are " + count + " Beahs in the list");

5.4.2.2 labeled continue statement


The labeled form of the continue statement skips the current iteration of an
outer loop marked with the given label.

outerLoop:
for( int i=0; i<5; i++ ){ for(
int j=0; j<5; j++ ){
System.out.println("Inside for(j) loop"); //message1
if( j == 2 ) continue outerLoop;
}
System.out.println("Inside for(i) loop"); //message2
}

In this example, message 2 never gets printed since we have the statement
continue outerloop which skips the iteration.
5.4.3 return statement

The return statement is used to exit from the current method. The flow of
control returns to the statement that follows the original method call. The return
statement has two forms: one that returns a value and one that doesn't.

To return a value, simply put the value (or an expression that calculates the value)
after the return keyword. For example,

return ++count;

or
return "Hello";

pg. 53
The data type of the value returned by return must match the type of the method's
declared return value. When a method is declared void, use the form of return that
doesn't return a value. For example,

return;

You will learn more about return statements later when you learn about methods.

5.5 Assessments
5.5.1 Grades
Get three exam grades from the user and compute the average of the grades.
Output the average of the three exams. Together with the average, also include a
smiley face in the output if the average is greater than or equal to 60, otherwise
output :-(. 1. Use BufferedReader to get input from the user, and System.out to
output the result.
2. Use JOptionPane to get input from the user and to output the result.

5.5.2 Number in words


Get a number as input from the user, and output the equivalent of the number in
words. The number inputted should range from 1-10. If the user inputs a number
that is not in the range, output, "Invalid number". 1. Use an if-else statement to
solve this problem
2. Use a switch statement to solve this problem

5.5.3 Hundred Times


Create a program that prints your name a hundred times. Do three versions of this
program using a while loop, a do-while loop and a for-loop.

5.5.4 Powers
Compute the power of a number given the base and exponent. Do three versions of
this program using a while loop, a do-while loop and a for-loop.

pg. 54
Unit VI – Java Arrays

6.1 Learning Objectives


In this section, you will be learning about Java Arrays. First, you are going to
learn what arrays are, and then you are going to learn on how to declare and use
them.

At the end of the lesson, you should be able to:


• Declare and create arrays
• Access array elements
• Determine the number of elements in an array
• Declare and create multidimensional arrays

6.2 Introduction to Arrays


In the previous sections, you learned on how to declare different variables
using the primitive data types. In declaring variables, you often use a unique
identifier or name and a datatype. In order to use the variable, you call it by its
identifier name.
For example, you have here three variables of type int with different
identifiers for each variable.
int number1;
int number2;
int number3;
number1 =
1; number2
= 2;
number3 =
3;

As you can see, it seems like a tedious task in order to just initialize and use
the variables especially if they are used for the same purpose. In Java and other
programming languages, there is one capability wherein we can use one variable to
store a list of data and manipulate them more efficiently. This type of variable is
called an array.

pg. 55
Figure 6.1: Example of an Integer Array

An array stores multiple data items of the same datatype, in a contiguous


block of memory, divided into a number of slots. Think of an array as a stretched
variable – a location that still has one identifier name, but can hold more than one
value.

6.3 Declaring Arrays


Arrays must be declared like all variables. When declaring an array, you list
the data type, followed by a set of square brackets [], followed by the identifier
name. For example,
int []ages;

or you can place the brackets after the identifier. For example,
int ages[];

After declaring, we must create the array and specify its length with a constructor
statement. This process in Java is called instantiation (the Java word for creates).
In order to instantiate an object, we need to use a constructor for this. You will
learn more about instantiating objects and constructors later. Take note, that the
size of an array cannot be changed once you've initialized it. For example,
//declaration int ages[];

//instantiate object ages = new int[100]; or, can also be


written as,
//declare and instantiate object int ages[] = new int[100];

In the example, the declaration tells the Java Compiler that the identifier ages will
be used as the name of an array containing integers, and to create or instantiate a new
array containing 100 elements.
Instead of using the new keyword to instantiate an array, you can also automatically
declare, construct and assign values at once.

pg. 56
Figure 6.2: Instantiating Arrays
Examples are,
//creates an array of boolean variables with ientifier
//results. This array contains 4 elements that are
//initialized to values {true, false, true, false}
boolean results[] ={ true, false, true, false };

//creates an array of 4 double variables initialized


//to the values {100, 90, 80, 75}; double
[]grades = {100, 90, 80, 75};

//creates an array of Strings with identifier days and


//initialized. This array contains 7 elements
String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};

6.4 Accessing an Array Element


To access an array element, or a part of the array, you use a number called an index
or a subscript.
An index number or subscript is assigned to each member of the array, allowing
the program and the programmer to access individual values when necessary. Index
numbers are always integers. They begin with zero and progress sequentially by
whole numbers to the end of the array. Take note that the elements inside your array is
from 0 to (sizeOfArray-1).
For example, given the array we declared a while ago, we have

pg. 57
//assigns 10 to the first element in the array ages[0]
= 10;

//prints the last element in the array


System.out.print(ages[99]);
Take note that once an array is declared and constructed, the stored value of each
member of the array will be initialized to zero for number data. However, reference data
types such as Strings are not initialized to blanks or an empty string “”. Therefore, you must
populate the String arrays explicitly.
The following is a sample code on how to print all the elements in the array. This
uses a for loop, so our code is shorter.
public class ArraySample{ public static void
main( String[] args ){ int[] ages = new
int[100]; for( int i=0; i<100; i++ ){
System.out.print( ages[i] );
}
}
}
Coding Guidelines:
1. It is usually better to initialize or instantiate the array right away after
you declare it.
For example, the declaration,
int []arr = new int[100];
is preferred over,
int []arr;
arr = new int[100];
2. The elements of an n-element array have indexes from 0 to n-1. Note
that there is no array element arr[n]! This will result in an array-index-out-of-
bounds exception.
3. You cannot resize an array.

6.5 Array length


In order to get the number of elements in an array, you can use the length
field of an array. The length field of an array returns the size of the array. It can be
used by writing,
arrayName.length
For example, given the previous example, you can re-write it as,

public class ArraySample{ public static void


main( String[] args ){
int[] ages = new int[100];

pg. 58
for( int i=0; i<ages.length; i++ ){
System.out.print( ages[i] );
}
}
}

Coding Guidelines:
1. When creating for loops to process the elements of an array, use the array
object's length field in the condition statement of the for loop. This will allow the loop
to adjust automatically for different-sized arrays.
2. Declare the sizes of arrays in a Java program using named constants to make
them easy to change. For example, final int ARRAY_SIZE = 1000;
//declare a constant . . .
int[] ages = new int[ARRAY_SIZE];

6.6 Multidimensional Arrays

Multidimensional arrays are implemented as arrays of arrays. Multidimensional


arrays are declared by appending the appropriate number of bracket pairs after the
array name. For example,

// integer array 512 x 128 elements int[][]


twoD = new int[512][128];

// character array 8 x 16 x 24 char[][][]


threeD = new char[8][16][24];

// String array 4 rows x 2 columns


String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"}, {
"fido", "black"}
};

pg. 59
To access an element in a multidimensional array is just the same as accessing the
elements in a one-dimensional array. For example, to access the first element in
the first row of the array dogs, we write,

System.out.print( dogs[0][0] );

This will print the String "terry" on the screen.

6.7 Assessment
6.7.1 Days if the Week
Create an array of Strings which are initialized to the 7 days of the week. For
Example,
String days[] = {“Monday”, “Tuesday”….};

Using a while-loop, print all the contents of the array. (do the same for do-while
and for- loop)

6.7.2 Greatest number


Using BufferedReader or JOptionPane, ask for 10 numbers from the user. Use an
array to store the values of these 10 numbers. Output on the screen the number
with the greatest value.

6.7.3 Addressbook Entries


Given the following multidimensional array that contains addressbook entries:

String entry = {{"Florence", "735-1234", "Manila"},


{"Joyce", "983-3333", "Quezon City"},
{"Becca", "456-3322", "Manila"}};

Print the following entries on screen in the following format:

Name : Florence
Tel. # : 735-1234

pg. 60
Address : Manila

Name : Joyce
Tel. # : 983-3333
Address : Quezon City

Name : Becca
Tel. # : 456-3322
Address : Manila

Unit VII – Basic Exception Handling


7.1 Learning Objectives

In this section, you are going to study a technique used in Java to handle
unusual conditions that interrupt the normal operation of the program. This
technique is called exception handling.

At the end of the lesson, the student should be able to:


• Define exceptions
• Handle exceptions using a simple try-catch-finally block

7.2 What are Exceptions?


An exception is an event that interrupts the normal processing flow of a
program. This event is usually some error of some sort. This causes our program to
terminate abnormally.

Some examples of exceptions that you might have encountered in our


previous exercises are: ArrayIndexOutOfBounds exceptions, which occurs if we
try to access a non-existent array element, or maybe a NumberFormatException,
which occurs when we try to pass as a parameter a non-number in the
Integer.parseInt method.

7.3 Handling Exceptions


To handle exceptions in Java, we use a try-catch-finally block. What we do in
our programs is that we place the statements that can possibly generate an
exception inside this block.

pg. 61
The general form of a try-catch-finally block is,
try{
//write the statements that can generate an
exception //in this block
} catch( <exceptionType1>
<varName1> ){
//write the action your program will do if an exception
//of a certain type occurs
}
. . . catch( <exceptionTypen>
<varNamen> ){
//write the action your program will do if an
//exception of a certain type occurs
} finally{
//add more cleanup code here
}
Exceptions thrown during execution of the try block can be caught and handled in a
catch block. The code in the finally block is always executed.

The following are the key aspects about the syntax of the try-catch-finally
construct:
• The block notation is mandatory.
• For each try block, there can be one or more catch blocks, but only one
finally block.
• The catch blocks and finally blocks must always appear in conjunction with
the try block, and in the above order.
• A try block must be followed by at least one catch block OR one finally
block, or both.
• Each catch block defines an exception handle. The header of the catch block
takes exactly one argument, which is the exception its block is willing to
handle. The exception must be of the Throwable class or one of its
subclasses.

pg. 62
Figure 7.1: Flow of events in a try-catch-finally block

Let's take for example: The following is an array declared with 2 elements. Then the
code tries to access the 3rd element of the array which throws an exception.
int a[] = new int[2];
System.out.println("Access element three :" + a[3]); // Error Here!

To prevent this from happening, we can place the code inside a try-catch block. The
finally block is just optional. For this example, we won't use the finally block.
public class ExcepTest { public static void
main(String args[]) { try { int a[] =
new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block"); }
}

This will produce the following result −


Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

pg. 63
7.4 Assessment
7.4.1 Catching Exceptions1 Given
the following code:
public class TestExceptions{ public static void
main( String[] args ){ for( int i=0;
true; i++ ){
System.out.println("args["+i+"]="+
args[i]); }
}
}

Compile and run the TestExceptions program. The output should look like this:

javac TestExceptions one two


three args[0]=one args[1]=two
args[2]=three
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 3 at
TestExceptions.main(1.java:4)

Modify the TestExceptions program to handle the exception. The output of the
program after catching the exception should look like this:

javac TestExceptions one two three args[0]=one


args[1]=two args[2]=three
Exception caught: java.lang.ArrayIndexOutOfBoundsException: 3 Quiting...

7.4.2 Catching Exceptions2


Chances are very good that some programs you've written before have
encountered exceptions. Since you didn't catch the exceptions, they simply halted
the execution of your code. Go back to those programs and implement exception
handling.
8 Appendix: Machine Problems
8.1 Machine Problem 1: Phone Book

pg. 64
Write a program that will create a phonebook, wherein you can add entries
in the phonebook, delete entries, view all entries and search for entries. In
viewing all entries, the user should have a choice, whether to view the entries in
alphabetical order or in increasing order of telephone numbers. In searching for
entries, the user should also have an option to search entries by name or by
telephone numbers. In searching by name, the user should also have an option if
he/she wants to search by first name or last name.

MAIN MENU
1 - Add phonebook entry
2 - Delete phonebook entry
3 - View all entries a - alphabetical order
b - increasing order of telephone numbers
4 - Search entries a - by name b - by telephone number
5 – Quit

The following will appear when one of the choices in the main menu is chosen.
Add phonebook entry Enter
Name:
Enter Telephone number:
(* if entry already exists, warn user about this)

View all entries


Displays all entries in alphabetical order
Displays all entries in increasing order of telephone #s

Search entries
Search phonebook entry by name
Search phonebook entry by telephone number

Quit close phonebook

8.2 Machine Problem 2: Minesweeper


This is a one player game of a simplified version of the popular computer game
minesweeper. First, the user is asked if he or she wants to play on a 5x5 grid or 10x10 grid.
You have two 2-dimensional arrays that contains information about your grid. An entry in
the array should either contain a 0 or 1. A 1 signifies that there is a bomb in that location,
and a 0 if none.
For example, given the array:
int bombList5by5[][]={{0, 0, 1, 0, 0},

pg. 65
{0, 0, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 1, 1},
{0, 1, 1, 0, 0}};
Given the bomb list, we have 6 bombs on our list. The bombs are located in (row,col)
cells, (0,2), (2,1), (3,3), (3,4), (4,1) and (4,2).

If the user chooses a cell that contains a bomb, the game ends and all the bombs are
displayed. If the user chooses a cell that does not contain a bomb, a number appears at that
location indicating the number of neighbors that contain bombs. The game should end when
all the cells that do not contain bombs have been marked (player wins) or when the user
steps on a bomb(player loses).

Here's a sample output of the game, given the bombList5by5.


Welcome to Minesweeper!
Choose size of grid (Press 1 for 5x5, Press 2 for 10x10): 1
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
Enter row and column of the cell you want to open[row col]: 1 1
[ ] [ ] [ ] [ ] [ ]
[ ] [2] [ ] [ ] [ ] [
] [ ] [] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
Enter row and column of the cell you want to open[row col]: 3 2
[ ] [ ] [ ] [ ] [ ]
[ ] [2 ] [ ] [] [ ]
[ ] [ ] [ ] [ ] [ ]
[ ] [ ] [4 ] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
Enter row and column of the cell you want to open[row col]: 0 2
[ ] [ ] [ ] [ ] [ ] [
] [2] [ ] [] [ ]
[ ] [X] [ ] [ ] [ ]
[ ] [ ] [4] [ ] [ ]
[ ] [ ] [ ] [ ] [ ]
Ooppps! You stepped on a bomb. Sorry, game over!
8.3 Machine Problem 3: Number Conversion
Create your own scientific calculator that will convert the inputted numbers
to the four number representations ( Decimal, Binary, Octal, Hexadecimal ). Your
program should output the following menu on screen.

MAIN MENU:

pg. 66
Please type the number of your choice:
1 – Binary to Decimal
2 – Decimal to Octal
3 – Octal to Hexadecimal
4 – Hexadecimal to Binary
5 – Quit

The following will appear when one of the choices in the main menu is chosen.
Choice 1:
Enter a binary number: 11000
11000 base 2 = 24 base 10
(goes back to main menu)
Choice
2:
Enter a Decimal number: 24
24 base 10 = 30 base 8
(goes back to main menu)
Choice
3:
Enter an Octal number: 30
30 base 8 = 18 base 16
(goes back to main menu)
Choice
4:
Enter a Hexadecimal number: 18
18 base 16 = 11000 base 2
Choice
1:
Enter a binary number: 110A
Invalid binary number!
Enter a binary number: 1 1
base 2 = 1 base 10
(goes back to main menu)

(user chooses 5) Goodbye!


You can be more creative with your user interface if you want to, as long as the
program outputs the correct conversion of numbers.
8.4 Rubrics
Trait Exceptional Acceptable Amateur Unsatisfactory
(4) (3) (2) (1)

pg. 67
Specifications The program The program works The program The program is
works and and produces the produces correct producing
meets all of the correct results and results but does incorrect results.
specifications. displays them not display them
correctly. It also correctly.
meets most of the
other specifications.

Readability The code is The code is fairly The code is The code is
exceptionally well easy to read. poorly organized
readable only by
organized and and very difficult
very easy to someone who to read
follow knows what it is
supposed to be
doing.

Reusability The code could be Most of the code Some parts of The code is not
reused as a whole the code could organized for
could
or each routine be reused in reusability.
could be reused. be reused in other other
programs. programs.

Delivery The program was The program was The code was The code was
delivered on time. delivered after a after 2 days of delivered
day of the due the due date. more than 2
date. days overdue

Efficiency The code is The code is fairly The code is brute The code is huge
efficient without force and and appears to
extremely efficient
sacrificing unnecessarily be patched
without sacrificing readability and long. together.
readability and understanding.
understanding.

9 References

1 Programming Language. From Wikipedia at


http://en.wikipedia.org/wiki/Programming_language

pg. 68
2 Programming Language. From Webopedia at
http://www.webopedia.com/TERM/p/programming_language.html
3 Programming Language. From Answers.com at
http://www.answers.com/topic/programming-language
4 High-Level Programming Language. From Wikipedia at
http://en.wikipedia.org/wiki/High-level_programming_language
5 Defining Flowchart Symbols. Available at http://www.patton-
patton.com/basic_flow_chart_symbols.htm
6 Integrated Development Environment. From Webopedia at
http://www.webopedia.com/TERM/I/integrated_development_environment.html
7 Variables and Expressions. Available at
http://www.geocities.com/SiliconValley/Park/3230/java/javl1002.html
8 Writing Abstract Classes and Methods. Available at
http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html
9 Gary B. Shelly, Thomas J. Cashman, Joy L. Starks. Java Programming Complete
Concepts and Techniques. Course Technology Thomson Learning. 2001.
nd
10 Stephen J. Chapman. Java for Engineers and Scientists 2 Edition. Pearson
Prentice Hall. 2004
th
11 Deitel & Deitel. Java How to Program 5 Edition.
12 Sun Java Programming Student Guide SL-275. Sun Microsystems. February 2001.
13 Does Java pass by reference or pass by value? Why can't you swap in Java?
Available at http://www.javaworld.com/javaworld/javaqa/2000-05/03qa-0526-
pass.html
14 Java Branching Statements. Available at
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/ branch.html.
15 Rubric
Uwf.edu. 2020. [online] Available at: https://uwf.edu/media/university-of-
westflorida/academic-affairs/departments/cutla/documents/Computer-Programming-
Grading-Rubric---California-State-University-Long-Beach.pdf.

pg. 69

You might also like