CBLM-Computer Programming
CBLM-Computer Programming
Chapter I
INTRODUCTION TO COMPUTER PROGRAMMING
“Computers do what we tell them to do, NOT what we want them to do.”
Computer Programming involves writing instructions and giving them to the computer to
complete a task.
Who is a Programmer?
A programmer is a person who writes the required computer programs.
Programmers translate the expected tasks given in human understandable form into
machine understandable form by using compilers and interpreters.
Execution of a Program
Using Compiler
Source Compiler Object Code Execute
Code Program
Using Interpreter
Source Compiler Object Code Interpreter Execute
Code Program
Programming Process
Real Solution in an
Verify and Test Life
Algorithm Form
Problem
Difficult way
Solution as a
Computer Program
1. Problem definition
What must the program do?
What outputs are required and in what form?
What inputs are available and in what form?
Example: Find a maximum of two numbers
o Input two numbers, compare them and print the maximum value
o Inputs and outputs are decimal numbers
o Inputs are entered from the keyboard
o Result is shown on the monitor
3. Program Coding means expressing the algorithm developed for solving a problem, in a
programming language
Example of source code
Program Compilation
translation of a program written in a high-level programming language into
machine language instructions
step converts a source program into an intermediate form, called object code
Linking step is necessary to combine this object code with other code to produce an
executable program
The advantage of this two-step approach:
Source of the large program may be split into more than one file
These files are worked on and compiled separately
Object code may be stored in libraries and used for many programs
Then they will be combined into one executable code
Types of Errors
1. Syntax Errors: Violation of syntactic rules in a Programming Language generates syntax
errors.
o Effect? Interpreter or Compiler finds it in Syntax Check Phase.
2. Semantic Errors: Doing logical mistakes causes semantic errors in Source code.
o Effect? Interpreters and Compilers cannot notice them, but on execution, they
causes unexpected results.
3. Run-time Errors: Occur on program execution. Mostly caused by invalid data entry or
tries to use not existing resources.
o Effect? It occurs on run time and may crash the program execution
b. Assembly Language
Code is assembled to make Machine Language (consisting only of 1’s and 0’s)
which is the real language of the CPU
Assembly language is a low-level interface to CPU functions
Writing programs can be very time-consuming, as you have to directly
manipulate CPU registers and use complicated interfaces to I/O devices
Example of code:
Mov ax, 1
Mov bx, 2
Add ax, bx
b. Object-oriented
Most object-oriented languages are high-level languages.
The focus of OOP languages is not on structure, but on modeling data.
Programmers code using “blueprints” of data models called classes.
Examples of OOP languages include C++, Visual Basic.NET and Java.
What is SDLC?
2. Analysis Phase
requires the analyst to thoroughly study the current procedures or system used to
execute tasks in an organization
the main goal in this phase is to identify the requirements for a new system or simply
change several aspects in the current working system
“This phase studies the current system and produces proposed alternatives or
replacements”
3. Design Phase
during this phase, the developer of the system translates the result of the previous
phase into actual design or specifications of the system
development of the system involves covering the input and output screens to reports,
databases, and computer process
4. Implementation
a. Coding – creation of the actual program
b. Testing – both programmer and analyst submits the system to various “quality
testing” to discover if there are any bugs within the system
c. Installation – after coding and testing is done, the actual system must be installed
and slowly or completely replaces the old system
5. Maintenance Phase
used to make necessary patches to remove found errors
where the system is systematically repaired and improved based on errors or
possible new requirements found
Algorithm
A step-by-step problem-solving procedure, especially an established, recursive
computational procedure for solving a problem in a finite number of steps.
Finite sequence of steps for solving a logical or mathematical problem.
A specific set of well-defined, simple mathematical and logical procedures that can be
followed to solve a problem in a finite number of steps.
Example:
1) Baking of chocolate cake
2) Computing for average grade
3) Going from one location to another
Characteristics of an Algorithm
1. Specify each step or instruction exactly.
There must be no ambiguity.
The instructions must be clear.
2. There must be a finite number of steps.
The algorithm must terminate.
There must be a stopping point.
3. There must be an output.
The algorithm must produce the correct result.
Flowchart
A chart that contains symbols referring to computer operations, describing how the
program performs.
A graphic map of the path of control or data through the operations in a program or an
information-handling system.
Symbols such as squares, diamonds, and ovals represent various operations.
These symbols are connected by lines and arrows to indicate the flow of data or control
from one point to another.
The plan or “blueprint” of a program
Flowcharting Symbols
1. Flowlines
are indicated by straight lines with optional arrows to show the direction of data flow
the arrowhead is necessary when the flow direction might be in doubt
are used to connect blocks by exiting from one and entering another
2. Terminal Box
flattened ellipses indicate the start and the end of a module
an ellipse uses the name of the module at the start
the end is indicated by the word end or stop for the top or Control Module
a start has no flowlines entering it and only one exiting it; an end or exit has one
flowline entering it but none exiting it
start stop
3. Initialization box
is used for declaring / initializing variables needed to solve a certain process.
Take note: You can only use variables that are placed inside the Initialization
box.
Declaration
binding of an identifier to the information that relates to it
stating a variable name to be used
initialization -to set (a starting value of a variable)
to prepare (a computer or a printer) for use; boot
to format (a storage medium, such as a disk)
int age = 17
double grade = 78.60
Variable
A symbol representing such a quantity. For example, in the expression a2 + b2 = c2.
a, b, and c are variables which may represent any value.
Naming Convention
a. Do not use reserved words as your variable names.
b. Name your variables close to its functionality.
c. Always start with a letter.
d. Avoid spaces or special characters
e. Case sensitivity must be observe
f. Variable name consistency
4. Process box
the rectangle indicates a processing block, for such things as calculations, opening
and closing files, and so forth
a processing block has one entrance and one exit
5. Input/Output box
the parallelogram indicates input to and output from the computer memory
an I/O block has one entrance and only one exit
enter display
num1 sum
6. Decision box
the diamond indicates a decision
it has one entrance and two and only two exits from the block
one exit is the action when the resultant is TRUE and the other exit is the action
when resultant is FALSE
num1> num2
7. Connectors
the connector block is used as a connection between two sections of a flowchart that
is not adjacent or closely located to each other
Note: These connectors should be used as little as possible. They should be used to
enhance readability. Overuse decreases readability and produces a cluttered effect.
on-page off-page
connector connector
Examples
1. Create a flowchart that allows the user to input two numbers and get their sum.
2. Create a flowchart having a variable that is initialized to your current age. Your flowchart
should be able to show your age 5 years from now.
3. Create a flowchart that computes for the circumference of a circle. Assume that the
value for radius is 7.23. Your flowchart should be able to show the value of the
circumference.
Additional facts: The pi value is 3.1416 which is constant and should never be changed.
You can compute the circumference by using this formula 2piR.
4. Draw a flowchart that will let the user enter a character to determine the user’s gender
(Male or Female). Display “Male” if the user enters the value of ‘M’ and “Female” for the
value of ‘F’. (Assume all inputs are correct)
5. Create a flowchart that will determine if a certain grade is either “PASSED” or “FAILED”.
6. Draw a flowchart that will let the user enter a number, increase the value of the number
by 5 if it is greater than 10 and display the result, otherwise do nothing.
Exercises
1. Create a flowchart having 3 variables. Two of the variables is used to initialize the Birth
Year and the Current Year. The third variable is used to compute for the current age.
Your flowchart should display the age value.
2. Create a flowchart that will compute for the Average score of a student based on three
quizzes. The quizzes are entered by the user, the value may range from 0 to 100.
However, the Average may have a value having decimal places.
Ex:
Q1: 98
Q2: 79
Q3: 88
Ave is 83.33
4. Draw a flowchart that will let the user enter a number, increase the value of the number
by 5 if it is greater than 10 and display the result, otherwise multiply the value by 5 and
display the result.
5. Draw a flowchart for a college’s admissions office. Create variables to store a student’s
numeric high school grade point average and an admission test score. Print the
message “Accept” if the student has a grade point average of 3.0 or above and an
admission test score of at least 60. If the student does not meet either of the qualification
criteria, print “Reject”.
6. Let the user enter a number from 1 – 3. If 1 is entered print “Hello”, if 2 is entered print
“Hi”, and if 3 is entered then print “Bye”.Otherwise, print “Invalid Number”
7. Draw a flowchart that will print the student’s letter grade given the following :
8. Create a flowchart that will allow the user to access his cellphone by entering the correct
PIN. If in three (3) attempts the entered PIN is wrong the flowchart will terminate,
otherwise will access the cellphone.
Chapter II
JAVA PROGRAMMING
I. Introduction to Java
Java Background
A programming language
As a programming language, Java can create all kinds of applications that you could
create using any conventional programming language.
A development environment
As 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 so on.
An application environment
Java technology applications are typically general-purpose programs that run on any
machine where the Java runtime environment (JRE) is installed.
A deployment environment
There are two main deployment environments: First, the JRE supplied by the 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.
A bytecode is a special machine language that can be understood by the Java Virtual
Machine (JVM). The bytecode is independent of any particular computer hardware, so
any computer with a Java interpreter can execute the compiled Java program, no matter
what type of computer the program was compiled on.
Garbage Collection
Many programming languages allows a programmer to allocate memory during runtime.
However, after using that allocated memory, there should be a way to deallocate that
memory block in order for other programs to use it again. In C, C++ and other languages
the programmer is responsible for this. This can be difficult at times since there can be
instances wherein the programmers forget to deallocate memory and therefor result to
what we call memory leaks.
In Java, the programmer is freed from the burden of having to deallocate that memory
themselves by having what we call the garbage collection thread. The garbage
collection thread is responsible for freeing any memory that can be freed. This happens
automatically during the lifetime of the Java program.
The following figure describes the process of compiling and executing a Java program.
The first step in creating a Java program is by writing your programs in a text editor.
Examples of text editors you can use are notepad, vi, emacs, etc. This file is stored in a
disk file with the extension .java.
After creating and saving your Java program, compile the program by using the Java
Compiler. The output of this process is a file of Java bytecodes with the file extension
.class.
The .class file is then interpreted by the Java interpreter that converts the bytecodes into
the machine language of the particular computer you are using.
Activity 1
Indicates the name of the class which is Hello. 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). We will be covering
packages and access specifiers later.
The next line which contains a curly brace { indicates the start of a block. In this code,
we 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:
The next three lines 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.
Now, we 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.
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.
Coding Guidelines:
1. Your Java programs should always end with the .java extension.
2. Filenames should match the name of your public class. So for example, if the name of
your public class is Hello, you should save it in a file called Hello.java.
3. You should write comments in your code explaining what a certain class does, or what a
certain method do.
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, C-style
multiline comments and special javadoc comments.
1. C++-Style Comments
C++ Style comments starts with //. All the text after // are treated as comments. For
example,
// This is a C++ style or single line comments
2. C-Style Comments
C-style comments or also called multiline comments starts with a /* and ends with a */.
All text in between the two delimeters are treated as comments. Unlike C++ style
comments, it can span multiple lines. For example,
/* this is an example of a
C style or multiline comments */
/**
This is an example of special java doc comments used for \n
generating an html documentation. It uses tags like:
@author Florence Balagtas
@version 1.2
*/
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,
Coding Guidelines:
1. In creating blocks, you can place the opening curly brace in line with the statement, like
for example,
or you can place the curly brace on the next line, like,
2. You should indent the next statements after the start of a block,for example,
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.
Identifiers cannot use Java keywords like class, public, void, etc. We will discuss more
about Java keywords later.
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.
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.
We will try to discuss all the meanings of these keywords and how they are used in our Java
programs as we 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
Java Literals
Literals are tokens that do not change or are constant. The different types of literals in
Java are: Integer Literals, Floating-Point Literals, Boolean Literals, Character Literals
and String Literals.
a. Integer Literals
o 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.
o For decimal numbers, we have no special notations. We just write a decimal
number as it is. For hexadecimal numbers, it should be preceeded by “0x” or
“0X”. For octals, they are preceeded by “0”.
o For example, consider the number 12. It's decimal representation is 12, while in
hexadecimal, it is 0xC, and in octal, it is equivalent to 014.
o 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. We will cover more on
data types later.
b. Floating-Point Literals
o 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.
o 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.
c. Boolean Literals
o Boolean literals have only two values, true or false.
d. Character Literals
o 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.
o To use a character literal, enclose the character in single quote delimiters. For
example, the letter a, is represented as ‘a’.
o 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.
e. String Literals
o String literals represent multiple characters and are enclosed by double quotes.
An example of a string literal is, “Hello World”.
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).
a. Logical - boolean
o A boolean data type represents two states: true and false. An example is,
o The example shown above, declares a variable named result as boolean type
and assigns it a value of true.
b. Textual – char
o A character data type (char), represents a single Unicode character. It must have
its literal enclosed in single quotes(’ ’). For example,
o To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \. For example,
o 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,
o Integral types has 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:
Coding Guidelines:
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
o 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:
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.
Activity 2
Coding Guidelines:
Activity 3
System.out.println( value );
System.out.println( “The value of x=” + x );
}
}
10
The value of x=A
System.out.print("Hello ");
System.out.print("world!");
Hello world!
System.out.println("Hello ");
System.out.println("world!");
Hello
world!
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.
a. Arithmetic operators
o Here are the basic arithmetic operators that can be used in creating your Java
programs,
Activity 4
//subtracting numbers
System.out.println("Subtracting...");
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));
//multiplying numbers
System.out.println("Multiplying...");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing...");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));
//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x));
}
}
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i/j=0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58
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.
is equivalent to,
count++;
int i = 10,
int j = 3;
int k = 0;
o 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;
Coding Guideline:
Always keep expressions containing increment and decrement operators simple and
easy to understand.
c. Relational operators
Activity 5
//greater than
System.out.println("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
//less than
System.out.println("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
//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true
//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j = false
j > i = true
k > j = false
Greater than or equal to...
i >= j = false
j >= i = true
k >= j = true
Less than...
i < j = true
j < i = false
k < j = false
Less than or equal to...
i <= j = true
j <= i = false
k <= j = true
Equal to...
i == j = false
k == j = true
Not equal to...
i != j = true
k != j = false
d. Logical operators
o Logical operators have one or two boolean operands that yield a boolean result.
There are six logical operators: && (logical AND), & (boolean logical AND), ||
(logical OR), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR),
and ! (logical NOT).
x1 op x2
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 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.
Here's a sample source code that uses logical and boolean AND,
Activity 6
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);
}
}
0
10
false
0
11
false
Note, that the j++ on the line containing the && operator is not evaluated since
the first expression (i>10) is already equal to false.
x1 x2 Result
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Table 8: 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.
Here's a sample source code that uses logical and boolean OR,
Activity 7
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);
}
}
0
10
true
0
11
true
Note, that the j++ on the line containing the || operator is not evaluated since the
first expression (i<10) is already equal to true.
x1 x2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
Table 9: Truth table for ^
Here's a sample source code that uses the logical exclusive OR operator,
Activity 8
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);
}
}
false
true
false
true
! (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 10: Truth table for !
Here's a sample source code that uses the logical NOT operator,
Activity 9
false
true
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.
Activity 10
//print status
System.out.println( status );
}
}
Passed
Activity 11
class ConditionalOperator
{
public static void main( String[] args ){
int score = 0;
char answer = 'a';
Score = 10
Exercise A
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
import java.io.*;
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”);
}
Activity 12
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
The statements,
import java.io.BufferedReader;
import java.io.InputStreamReader;
import 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 we can use those classes
inside our program.
were already discussed in the previous lesson. This means we declare a class named
GetInputFromKeyboard and we declare the main method.
In the statement,
we are declaring a variable named dataIn with the class type BufferedReader. Don't
worry about what the syntax means for now. We will cover more about this later in the
course.
This is where we 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.
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. We will cover 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.
name = dataIn.readLine();
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,
Activity 13
import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name = "";
name = JoptionPane.showInputDialog("Please enter your name");
JOptionPane.showMessageDialog(null, msg);
}
}
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);
Activity 14
Using BufferedReader create a program that accept a certain firstName,
middleName, lastName and will display its fullName.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class BufferFullName{
public static void main( String[] args ){
BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) );
String fName = " ";
String mName = " ";
String lName = " ";
String fullName = " ";
try{
System.out.print("Enter your first name: ");
fName = dataIn.readLine();
System.out.print("Enter your middle name: ");
mName = dataIn.readLine();
System.out.print("Enter your last name: ");
lName = dataIn.readLine();
}catch(IOException e ){
System.out.println("Error!");
}
fullName = fName + " " + mName + " " + lName;
System.out.println("Your full name is " + fullName + "!");
}
}
Activity 15
Using JOptionPane create a program that accept a certain firstName, middleName,
lastName and will display its fullName.
import javax.swing.JOptionPane;
public class JOptionDemo {
public static void main(String[] args) {
String fName = " ";
String mName = " ";
String lName = " ";
String fullName = " ";
Exercise B
For example,
Enter word1:Goodbye
Enter word2:and
Enter word3:Hello
For example,
a. if statement
o The if-statement specifies that a statement (or block of code) will be executed if
and only if a certain boolean statement is true.
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
...
}
or
Activity 16
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;
}
b. if-else statement
o 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.
if( boolean_expression )
statement;
else
statement;
if( boolean_expression ){
statement1;
statement2;
...
}
else{
statement1;
statement2;
...
}
Activity 17
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{ . . .
}
c. if-else-if statement
o 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.
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.
The condition inside the if-statement does not evaluate to a boolean value. For example,
//WRONG
int number = 0;
if( number ){
//some statements here
}
//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
Activity 18
d. switch statement
o Another way to indicate a branch is through the switch keyword. The switch
construct allows branching on multiple outcomes.
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;
}
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.
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:
1. Unlike with the if statement, the multiple statements are executed in the switch
statement without needing the curly braces.
2. 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.
3. To prevent the program from executing statements in the subsequent cases, we use a
break statement as our last statement.
Coding Guidelines:
Activity 19
switch(grade){
case 100:
System.out.println( "Excellent!" );
break;
case 90:
System.out.println("Good job!" );
break;
case 80:
System.out.println("Study harder!" );
break;
default:
System.out.println("Sorry, you failed.");
}
}
}
a. while loop
o The while loop is a statement or block of statements that is repeated as long as
some condition is satisfied.
while( boolean_expression ){
statement1;
statement2;
...
}
The statements inside the while loop are executed as long as the boolean_expression
evaluates to true.
Activity 20
int i = 5;
while ( i >= 1 ){
System.out.print(i);
i--;
}
}
}
The sample code shown will print 54321 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.
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”);
b. do-while loop
o 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.
o The main difference between a while and do-while loop is that, the statements
inside a do-while loop are executed at least once.
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.
Activity 21
//infinite loop
do{
System.out.println(“hello”);
} while (true);
This example will result to an infinite loop, that prints hello on screen.
//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.
c. for loop
o The for loop, like the previous loops, allows execution of the same code a
number of times.
where,
InitializationExpression -initializes the loop variable.
LoopCondition - compares the loop variable to some limit value.
StepExpression - updates the loop variable.
Activity 22
o In this example, the statement i=1, 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.
4. Branching Statements
Branching statements allows us to redirect the flow of program execution. Java offers
three branching statements: break, continue and return.
a. break statement
o The break statement has two forms: unlabeled (we saw its unlabeled form in the
switch statement) and labeled.
For example,
Activity 23
if( foundName ){
System.out.println( searchName + " found!" );
}else{
System.out.println( searchName + " not found." );
}
}
}
o 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.
Activity 24
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!" );
}
}
}
o 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.
b. continue statement
o 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.
o In this example, message 2 never gets printed since we have the statement
continue outerloop which skips the iteration.
c. return statement
o 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.
o 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";
o 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;
Activity 27
Create a java program using BufferedReader that can compute the total quizzes
assuming that the inputted number specifies the user Input.
import java.io.*;
public class Quizzes {
public static void main(String[] args) throws IOException {
BufferReader dataIn = new Bufferedreader(new InputStreamReader(System.in));
System.out.print("how many quizzes do you want to compute?");
int x = Integer.parseInt(dataIn.readLine());
int y = 0;
Integer[] grades = new Integer[x];
int z=1;
int total=0;
for (y=0;y<=x-1;y++) {
System.out.print("Quiz " +z +" " +":");
grades[y]= Integer.parseInt(dataIn.readLine());
total = total + grades[y];
z++;
}
double ave = total/x;
System.out.print("average is"+" " +ave);
}
}
Activity 28
Create a simple Log-in program using BufferedReader specify the Username and
Password will determine that you are log-on to the System.
import java.io.*;
public class Login{
String user = “”, pass = “”;
public static void main(String[] args)throws IOException{
BufferReader dataIn = new Bufferedreader(new InputStreamReader(System.in));
System.out.print("Usename: ");
user= dataIn.reaLine();
System.out.print("Password: ");
pass= dataIn.reaLine();
Activity 29
Write a java program that calculate the product of the odd integers from 1 to 20
Activity 30
Using Switch create a simple POS program that could sell five products with their
respective prices.
import java.io.*;
public class ProducSwitch {
double total;
System.out.println("Choices of Product!");
System.out.println(" [1] 16GB Flash Drive");
System.out.println(" [2] 500GB Hard Disk");
System.out.println(" [3] 3 in 1 Printer");
System.out.println(" [4] External DVD Writer");
System.out.println(" [5] USB Keyboard");
System.out.print(" Choose Product: ");
hold=Integer.parseInt(in.readLine());
switch(hold){
case 1:
System.out.print("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product1*value;
System.out.println("16GB Flash Drive:");
System.out.println("Unit Price: "+ product1);
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"Php \n");
break;
case 2:
System.out.print("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product2*value;
System.out.println("500GB Hard Disk:");
System.out.println("Unit Price: "+ product2);
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"Php \n");
break;
case 3:
System.out.print("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product3*value;
System.out.println("3 in 1 Printer:");
System.out.println("Unit Price: "+ product3);
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"Php \n");
break;
case 4:
System.out.print("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product4*value;
System.out.println("External DVD Writer:");
System.out.println("Unit Price: "+ product4);
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"Php \n");
break;
case 5:
System.out.print("Quantity you want?: ");
value = Integer.parseInt(in.readLine());
total=product5*value;
System.out.println("USB Keyboard:");
System.out.println("Unit Price: "+ product5);
System.out.println("Quantity sold: "+value);
System.out.print("Amount to be paid: "+total+"Php \n");
break;
}
}
Exercise C
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 :-(.
a. Use BufferedReader to get input from the user, and System.out to output the
result.
b. Use JOptionPane to get input from the user and to output the result.
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".
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.
V. JAVA ARRAYS
1. Introduction to arrays
In the previous sections, we have discussed on how to declare different variables using
the primitive data types. In declaring variables, we often use a unique identifier or name
and a datatype. In order to use the variable, we call it by its identifier name.
For example, we 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.
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.
2. 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. We will cover 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];
Examples are,
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).
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.
Activity 31
Coding Guidelines:
a. 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];
b. 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.
c. You cannot resize an array.
4. 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
Activity 32
Coding Guidelines:
a. 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.
b. 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];
5. 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,
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];
System.out.print( dogs[0][0] );
Exercise D
Using a while-loop, print all the contents of the array. (do the same for do-while and
for-loop)
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.
Name : Florence
Tel. # : 735-1234
Address : Metro Manila
Name : Joyce
Tel. # : 983-3333
Address : Quezon City
Name : Becca
Tel. # : 456-3322
Address : Laguna
4. Number Sorting
Input five integers then sort them from highest to lowest:
Enter Five Integers
10
25
35
2
15
Sorted from highest to lowest
35
25
15
10
2
For example, a car object has the properties, type of transmission, manufacturer and
color. Its behaviors are turning, braking and accelerating. Similarly, we can define
different properties and behavior of a lion. Please refer to the table below for the
examples.
With these descriptions, the objects in the physical world can easily be modeled as
software objects using the properties as data and the behaviors as methods. These
data and methods could even be used in programming games or interactive software to
simulate the real-world objects! An example would be a car software object in a racing
game or a lion software object in an educational interactive software zoo for kids.
To differentiate between classes and objects, let us discuss an example. What we have
here is a Car Class which can be used to define several Car Objects. In the table shown
below, Car A and Car B are objects of the Car class. The class has fields plate number,
color, manufacturer, and current speed which are filled-up with corresponding values in
objects Car A and Car B. The Car has also some methods Accelerate, Turn and Brake.
When instantiated, each object gets a fresh set of state variables. However, the method
implementations are shared among objects of the same class.
Classes provide the benefit of reusability. Software programmers can use a class over
and over again to create many objects.
Encapsulation
Encapsulation is the method of hiding certain elements of the implementation of a
certain class. By placing a boundary around the properties and methods of our objects,
we can prevent our programs from having side effects wherein programs have their
variables changed in unexpected ways.
We can prevent access to our object's data by declaring them declaring them in a certain
way such that we can control access to them. We will learn more about how Java
implements encapsulation as we discuss more about classes.
To clearly describe class variables, let's go back to our Car class example. Suppose that
our Car class has one class variable called Count. If we change the value of Count to 2,
all of the objects of the Car class will have the value 2 for their Count variable.
Class Instantiation
To create an object or an instance of a class, we use the new operator. For example, if
you want to create an instance of the class String, we write the following code,
The new operator allocates a memory for that object and returns a reference of that
memory location to you. When you create an object, you actually invoke the class'
constructor. The constructor is a method where you place all the initializations, it has
the same name as the class.
Methods
A method is a separate piece of code that can be called by a main program or any other
method to perform some specific function.
Now, why do we need to create methods? Why don't we just place all the code inside
one big method? The heart of effective problem solving is in problem decomposition. We
can do this in Java by creating methods to solve a specific part of the problem. Taking a
problem and breaking it into small, manageable pieces is critical to writing large
programs.
Pass-by-value
When a pass-by-value occurs, the method makes a copy of the value of the variable
passed to the method. The method cannot accidentally modify the original argument
even if it modifies the parameters during calculations.
For example,
Activity 33
In the given example, we called the method test and passed the value of i as parameter.
The value of i is copied to the variable of the method j. Since j is the variable changed in
the test method, it will not affect the variable value if i in main since it is a different copy
of the variable.
By default, all primitive data types when passed to a method are pass-by-value.
Pass-by-reference
When a pass-by-reference occurs, the reference to an object is passed to the calling
method. This means that, the method makes a copy of the reference of the variable
passed to the method. However, unlike in pass-by-value, the method can modify the
actual object that the reference is pointing to, since, although different references are
used in the methods, the location of the data they are pointing to is the same.
For example,
Activity 34
class TestPassByReference
{
public static void main( String[] args ){
//create an array of integers
int []ages = {10, 11, 12};
Coding Guidelines:
where
<modifier> is an access modifier, which may be combined with other types of modifier.
Coding Guidelines:
Remember that for a top-level class, the only valid access modifiers are public and
package (i.e., if no access modifier prefixes the class keyword).
In this section, we will be creating a class that will contain a student record. Since we've
already identified the purpose of our class, we can now name it. An appropriate name for
our class would be StudentRecord.
where,
public - means that our class is accessible to other classes outside the
package
class - this is the keyword used to create a class in Java
StudentRecord - a unique identifier that describes our class
Coding Guidelines:
a. Think of an appropriate name for your class. Don't just call your class XYZ or any
random names you can think of.
b. Class names should start with a CAPITAL letter.
c. The filename of your class should have the SAME NAME as your public class name.
Declaring Attributes
To declare a certain attribute for our class, we write,
Now, let us write down the list of attributes that a student record can contain. For each
information, also list what data types would be appropriate to use. For example, you
don't want to have a data type int for a student's name, or a String for a student's grade.
The following are some sample information we want to add to the student record.
name - String
address - String
age - int
math grade - double
english grade - double
science grade - double
average grade - double
You can add more information if you want to, it's all really up to you. But for this
example, we will be using these information.
Instance Variables
Now that we have a list of all the attributes we want to add to our class, let us now add
them to our code. Since we want these attributes to be unique for each object (or for
each student), we should declare them as instance variables.
For example,
public class StudentRecord
{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
//we'll add more code here later
}
where,
private here means that the variables are only accessible within the class. Other objects
cannot access these variables directly. We will cover more about accessibility later.
Coding Guidelines:
a. Declare all your instance variables on the top of the class declaration.
b. Declare one variable for each line.
c. Instance variables, like any other variables should start with a SMALL letter.
d. Use an appropriate data type for each variable you declare.
e. Declare instance variables as private so that only class methods can access them
directly.
f.
Class Variables or Static Variables
Aside from instance variables, we can also declare class variables or variables that
belong to the class as a whole. The value of these variables are the same for all the
objects of the same class. Now suppose, we want to know the total number of student
records we have for the whole class, we can declare one static variable that will hold this
value. Let us call this as studentCount.
Declaring Methods
Before we discuss what methods we want our class to have, let us first take a look at the
general syntax for declaring methods.
where,
Accessor methods
In order to implement encapsulation, that is, we don't want any objects to just access our
data anytime, we declare the fields or attributes of our classes as private. However,
there are times wherein we want other objects to access private data. In order to do this,
we create accessor methods.
Accessor methods are used to read values from class variables (instance/static). An
accessor method usually starts with a get<NameOfInstanceVariable>. It also returns a
value.
For our example, we want an accessor method that can read the name, address, english
grade, math grade and science grade of the student.
The statement,
return name;
in our program signifies that it will return the value of the instance variable name to the
calling method. Take note that the return type of the method should have the same data
type as the data in the return statement. You usually encounter the following error if the
two does not have the same data type,
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
}
The getAverage method computes the average of the 3 grades and returns the result.
Mutator Methods
Now, what if we want other objects to alter our data? What we do is we provide methods
that can write or change values of our class variables (instance/static). We call these
methods, mutator methods. A mutator method is usuallyu written as
set<NameOfInstanceVariable>.
where,
public - means that the method can be called from objects outside the class
void - imeans that the method does not return any value
setName - the name of the method
(String temp) - parameter that will be used inside our method
The statement,
name = temp;
assigns the value of temp to name and thus changes the data inside the instance
variable name.
Take note that mutator methods don't return values. However, it contains some program
argument or arguments that will be used inside the method.
if( num == 1 ){
return "one"; //return a constant
}
else if( num == 2){
return "two"; //return a constant
}
//return a variable
return defaultNum;
}
Static methods
For the static variable studentCount, we can create a static method to access its value.
where,
public - means that the method can be called from objects outside the class
static - means that the method is static and should be called by
typing,[ClassName].[methodName]. For example, in this case, we
call the method StudentRecord.getStudentCount()
int - is the return type of the method. This means that the method
should return a value of type int
getStudentCount - the name of the method
() - this means that our method does not have any parameters
For now, getStudentCount will always return the value zero since we haven't done
anything yet in our program in order to set its value. We will try to change the value of
studentCount later on when we discuss constructors.
Coding Guidelines:
a. Method names should start with a SMALL letter.
b. Method names should be verbs
c. Always provide documentation before the declaration of the method. You can use
javadocs style for this.
Activity 35
public class StudentRecord {
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
/**
* Returns the name of the student
*/
public String getName(){
return name;
}
/**
* Changes the name of the student
*/
public void setName( String temp ){
name = temp;
}
/**
* Computes the average of the english, math and science
* grades
*/
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
/**
* returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}
}
Activity 36
System.out.println("Count="+StudentRecord.getStudentCount());
}
}
The output of this program is,
Anna
Student Count = 0
Exercise E
1. Arithmetic Operations
Create a program that performs arithmetic operations with these respective methods
(Addition, Subtraction, Multiplication, and Division).
First Number: 20
Second Number: 5
Sum: 25
Difference: 15
Product: 100
Quotient: 4
2. ATM Program
Create a simple ATM Program that could performs Balance Inquiry, Deposit and
Withdraw.
Student
Full Name: Juan Dela Cruz
Address: Casili, Mallig, Isabela
Age: 18
Course: BSIT
Year: 1
Name: __________________________ Course & Year: __________ Day & Time: __________
JAVA Activities
Act No. ClassName Remarks Act No. ClassName Remarks
Act 1 Act 19
Act 2 Act 20
Act 3 Act 21
Act 4 Act 22
Act 5 Act 23
Act 6 Act 24
Act 7 Act 25
Act 8 Act 26
Act 9 Act 27
Act 10 Act 28
Act 11 Act 29
Act 12 Act 30
Act 13 Act 31
Act 14 Act 32
Act 15 Act 33
Act 16 Act 34
Act 17 Act 35
Act 18 Act 36
JAVA Exercises
Exercise A Exercise D
Exer No. ClassName Remarks Exer No. ClassName Remarks
Exer 1 Exer 1
Exer 2 Exer 2
Exer 3 Exer 3
Exercise B Exer 4
Exer No. ClassName Remarks Exercise E
Exer 1 Exer No. ClassName Remarks
Exer 2 Exer 1
Exercise C Exer 2
Exer No. ClassName Remarks Exer 3
Exer 1
Exer 2
Exer 3
Exer 4
REFERENCES
Books
1. Hoffer, Modern Systems Analysis & Design 2nd Ed
2. Parson et al, Computer Concepts 5th Ed
3. Joyce Farrell, “Program Logic Formulation”, 2009
4. Introduction to Java Programming, Sixth Edition, 2005
5. Malik, D.S., Java Programming, 2008
6. Drozdek, Adam, Java: Data Structure & Algorithm
Websites
1. http://bufferedreaderprogram.blogspot.com/
2. https://docs.oracle.com/javase/tutorial/
3. https://jedi.java.net/
4. http://www.tutorialspoint.com/java/