Fundamentals of Programming
Fundamentals of Programming
Fundamentals of Programming
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.”
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.
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.
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
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
pg. 10
Unit II – Introduction to Java
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.
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:
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!");
}
}
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.
A comment is indicated by the delimiters “/*” and “*/”. Anything within these delimiters
are ignored by the Java compiler, and are treated as comments.
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.
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.
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!");
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.
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:
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!”
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.
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.
Note: Values enclosed in <> are required values, while those values enclosed in []
are optional.
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;
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,
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));
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.
pg. 26
<= op1 <= op2 op1 is less than or equal to op2
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" k = " + k);
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.
pg. 28
FALSE FALSE FALSE
Table 10: Truth table for | and ||
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.
//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);
}
}
pg. 29
FALSE FALSE FALSE
Table 11: Truth table for ^
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,
//print status
System.out.println(status);
}
}
Example 2,
class ConditionalOperator
{ public static void main (String [] args) {
int score = 0; char
answer = 'a';
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
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++
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.
java.io.IOException;
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:");
• 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.
import javax.swing.JOptionPane;
pg. 36
JOptionPane.showMessageDialog(null, msg);
}
}
pg. 37
The first statement,
import javax.swing.JOptionPane;
indicates that we want to import the class JOptionPane from the javax.swing
package.
import javax.swing.*;
The statement,
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,
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
pg. 39
Figure 4.5: Second Input
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.
or
if( boolean_expression ){
statement1; statement2;
. . .
}
or
int grade = 68;
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;
. . .
}
pg. 42
Coding Guidelines:
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.
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");
}
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."); }
}
}
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:
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.
The statements inside the while loop are executed as long as the
boolean_expression evaluates to true.
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”);
The main difference between a while and do-while loop is that, the
statements inside a do-while loop are executed at least once.
pg. 48
Example 1:
int x = 0;
do {
System.out.println(x); x++;
}while (x<10);
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);
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.
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.
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"};
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.
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.
pg. 52
} count+
+;
}
System.out.println("There are " + count + " Beahs in the list");
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.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
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
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[];
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 };
pg. 57
//assigns 10 to the first element in the array ages[0]
= 10;
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];
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] );
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)
Name : Florence
Tel. # : 735-1234
pg. 60
Address : Manila
Name : Joyce
Tel. # : 983-3333
Address : Quezon City
Name : Becca
Tel. # : 456-3322
Address : Manila
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.
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"); }
}
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:
Modify the TestExceptions program to handle the exception. The output of the
program after catching the exception should look like this:
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)
Search entries
Search phonebook entry by name
Search phonebook entry by telephone number
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).
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)
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
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