4 Java Workbook Contents
4 Java Workbook Contents
INTRODUCTION
Brief History of Java
With the popularity of the World Wide Web and the Internet, the creators of Java
realized that the programming language could be used to design transactional
web applications.
1. Programming Language
Java can generate all kinds of application that can be created using
conventional programming languages.
2. Development Environment
Java provides the developer tools such as a compiler, an
interpreter, a document generator, and a class file packaging tool to
name a few.
3. Application Environment
Java applications are general-purpose programs running on a
machine where the Java runtime environment (JRE) is installed.
4. Deployment Environment
JRE supplies a Software Development Kit (SDK) that contains a
complete set of class files for all types Java technology packages.
Most commercial web browsers supply a Java technology
interpreter and runtime environment.
Workbook
Logic and Programming Fundamentals 2
Features of Java
2. Garbage Collection
The garbage collection thread is responsible for deallocating
memory previously allocated by the programmer. In earlier
programming languages, freeing memory that was used is the
responsibility of the programmer.
3. Code Security
JRE runs the code compiled for a JVM and performs class loading,
code verification, and code execution.
o The Class Loader is responsible for loading all classes
needed for the Java Program
o The byte code verifier tests the format of the code fragments
and checks the code fragments for illegal code that can
violate access rights to objects.
o Lastly, code is executed.
First phase in creating a Java program is writing the program in a text editor and
store it with an extension filename of .java.
After creating and saving the Java program, compile the program by using the
Java compiler resulting in Java bytecodes with extension filename .class.
The .class file is then interpreted by the Java interpreter that converts the
bytecodes into a machine language of the computer being used.
Workbook
Logic and Programming Fundamentals 3
Editor Java
Compiler
File.java
Happens only
once
Java
Interpreter File.class
Happens every
time
Workbook
Logic and Programming Fundamentals 4
UNIT 1
We can write the codes in Java using any text editor by typing the following
lines:
/* My first Java Program */
The program shown in the example above is called a program source code.
The source code is made of letters, numbers, and other symbols available in
the ASCII format. Or in a more technical term, it is an aggregate of
characters.
After writing the source code, the next step to do is to COMPILE and RUN it
in order to see whether we have achieved our objective. If there are errors
reported by the compiler (also known as syntax errors), then there is a need
to debug (fix) the source code before it is recompiled and tested again.
Hello World!
_
Paths for the Java compiler and Java classes must be set first before
compiling and executing a Java program from the command line.
Workbook
Logic and Programming Fundamentals 5
Step 2: Type cmd on the Run window and click Ok. The command
prompt window should appear.
Step 3: Set the path for the Java Development Kit (JDK) to be able to
use the functions needed to compile and execute Java
programs by typing set path=%path%;c:\Program
Files\jdk1.6.0\bin on the command line.
Note: The Java and class paths for Ubuntu Linux is already set and no
further modification to the paths is necessary.
Workbook
Logic and Programming Fundamentals 6
A Java source code can be encoded in any text editor (notepad for MS
Windows and gEdit for Ubuntu Linux among others). Below are simple
steps on how to encode source code in a text editor.
Step 3: Save the file as Hello.java (note: the class name should be
the same as the file name when saving Java source code).
Workbook
Logic and Programming Fundamentals 7
After encoding the source code and saving it to its proper filename, it is
now ready for compilation (generation of the bytecodes) and execution
(running the program to view the output).
1.4. Errors
Workbook
Logic and Programming Fundamentals 8
Workbook
Logic and Programming Fundamentals 9
or
/* My
First
Java
Program */
or
public class Hello indicates the name of the class which is Hello.
All codes should be written inside the class declaration. A class
declaration is done by using the keyword class preceded by an access
modifier that indicates the accessibility of the class to other classes. On
this example, the access modifier public was used indicating that the
class is accessible to other classes from other packages.
} The first close curly brace indicates the end of the main method.
} The last close curly brace indicates the end of the Hello class.
Workbook
Logic and Programming Fundamentals 10
Workbook
Logic and Programming Fundamentals 11
2. For method and variable names, the first letter of the word
should start with a small letter.
Example: ThisIsAnExampleOfClassName
thisIsAnExampleOfMethodName
thisIsAnExampleOfVariableName
Example: charArray
fileNumber
a
A
age
num1
xyz
final_grade
employee33
id_Number
firstName
sum
aReA5b3h1
Workbook
Logic and Programming Fundamentals 12
Java Keywords
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Literals and constants are tokens whose values do not change. In Java,
there are 5 kinds of literals.
Example:
12 (decimal)
0xC (hexadecimal)
014 (octal)
Example:
3.1416
54.567
5.8234e2
10.2000e4
Workbook
Logic and Programming Fundamentals 13
Example:
‘a’ Letter a
‘Z’ Letter Z
‘\n’ New line character
‘\b’ Carriage return character
Example:
“Hello World”
“Java Programming”
A boolean data type stores only one of two values, either “true”
or “false”.
Workbook
Logic and Programming Fundamentals 14
Example:
boolean state = true;
boolean value;
Example:
char letter = ‘A’;
char choice;
Example:
byte no = 10;
int number = 500;
short x;
long z;
Integer Name
Length or Range Value
Type
8 bits Byte -27 to 27-1 -127 to 126
16 bits Short -215 to 215-1 -32,768 to 32,767
-2,147,483,648 to
32 bits Int -231 to 231-1
2,147,483,647
-9,223,372,036,854,775,808
64 bits Long -263 to 263-1
to 9,223,372,036,854,775,807
Workbook
Logic and Programming Fundamentals 15
Example:
float pi = 3.14.16f;
double decimal = 123456.73e10D;
Integer Name or
Range Value
Length Type
32 bits Float -231 to 231-1 3.4E-38 to 3.4E+38
64 bits Double -263 to 263-1 1.7E-308 to 1.7E+308
Example:
Variables are entities where data can be stored into it. Values stored in
the variable can be changed anytime. It is an abstraction of the computer
memory cell or collection of cells
Workbook
Logic and Programming Fundamentals 16
3. Value – the contents of the memory cell or cells associated with it.
4. Data Type - determines the range of values the variable can have
and set of operations that are defined for values of this type.
char letter;
letter = ‘A’; // assign A to letter
Sample program:
System.out.println(number);
System.out.println(“The letter is = ” + letter);
}
}
100
The letter is = A
Workbook
Logic and Programming Fundamentals 18
. . . . . .
. . . . . .
. . . . . .
. . . . . .
Workbook
Logic and Programming Fundamentals 19
3. Operators
The operator used in assignment operation is the equal symbol (=). This
is use to store or assign a value from the right-hand side (RHS) of an
expression to the left-hand side (LHS).
Example:
LHS = RHS
Example:
age = 5; /* age GETS THE VALUE OF 5 */
x = x + 1; /* x GETS THE VELUE OF x + 1 */
Workbook
Logic and Programming Fundamentals 20
Example:
X = 5;
Y = X; Z = Y;
Example:
int i = 65;
double d = 14.50987;
char c = ‘B’;
Workbook
Logic and Programming Fundamentals 21
+ addition
- subtraction
* multiplication
/ division
% modulo (yields the remainder)
The +, -, *, / can be used for operands of type int, float, and double
data types. The % operator can be used only with integer operands. All
of these operators are called binary operators because they require two
operands.
System.out.println(“a = ” + a);
System.out.println(“b = ” + b);
System.out.println(“c = ” + c);
System.out.println(“d = ” + d);
System.out.println(“e = ” + e);
}
}
The / operator when used with operand whose data types are of integer
values will result to integer division which truncates or discards any
fractional part. If the fractional part is needed, then at least one of the
operand should be float or double data type.
Workbook
Logic and Programming Fundamentals 22
Operator Associativity
*,/, % Left to Right
+, - Left to Right
Example:
X = 3 + 6 * 2 – 5 + 10 / 2 * 8 /2 – 3
X = 3 + 12 – 5 + 10 / 2 * 8 /2 – 3
X = 3 + 12 – 5 + 5 * 8 /2 – 3
X = 3 + 12 – 5 + 40/2 – 3
X = 3 + 12 – 5 +20 – 3
X = 15 – 5 +20 – 3
X = 10 + 20 – 3
X = 30 – 3
X = 27
Example:
Workbook
Logic and Programming Fundamentals 23
Example:
Usage Description
var++ Increments var by1; evaluates to the
value of var prior to incrementing
++var Increments var by 1; evaluates to the
value of var after it was incremented
var-- Decrements var by1; evaluates to the
value of var prior to decrementing
--var decrements var by 1; evaluates to the
value of var after it was decremented
Example:
int i = 10;
int j = 3;
int k = 0;
k = ++j + i; //expression is k = 4 + 10
Example:
int i = 10;
int j = 3;
int k = 0;
k = j++ + i; //expression is k = 3 + 10
Workbook
Logic and Programming Fundamentals 24
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
It is important to remember that the test for equality uses two equal
signs. Forgetting one of the equal sign is a very common logical (not
syntactical) error which can be very difficult to find (debug) in a fairly
large program.
Example:
x = 8
y = 13
a = (x == y) result is False
b = (x != y) result is True
Workbook
Logic and Programming Fundamentals 25
x = 8;
y = 13;
a = (x == y);
b = (x != y);
c = (x > y);
d = (x < y);
e = (x >= y);
f = (x <= y);
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
System.out.println(f);
}
}
The logical operators are used to test multiple conditions and are
normally used in conjunction with relational operators. Logical operators
available in Java are the following:
! Logical NOT
&& Logical AND
& boolean Logical AND
|| Logical OR
| boolean Logical Inclusive OR
^ boolean Logical Exclusive OR
Workbook
Logic and Programming Fundamentals 26
The general idea behind the AND operation is that all expressions
evaluated should be true in order to conclude that the statement
is true; otherwise, the statement will be false.
The basic difference between && and & operators is that &&
supports short-circuit evaluations (partial evaluation). If && will
evaluate expr1 as false; the operator will not anymore evaluate
expr2 because the result will be false regardless of the value
of expr2. In contrast, the & operator evaluates both expressions
before returning the result.
Example:
//&& operator
result = (i>10) && (j>9);
System.out.println(i);
System.out.println(j);
System.out.println(result);
//& operator
result = (i>10) & (j>9);
System.out.println(i);
System.out.println(j);
System.out.println(result);
}
}
Workbook
Logic and Programming Fundamentals 27
0
10
false
0
10
false
The general idea behind the OR operation is that at least one (1)
expression evaluated should be true in order to conclude that
the statement is true; otherwise, the statement will be false.
Example:
//|| operator
result = (i<10) || (j<9);
System.out.println(i);
System.out.println(j);
System.out.println(result);
Workbook
Logic and Programming Fundamentals 28
//| operator
result = (i<10) | (j<9);
System.out.println(i);
System.out.println(j);
System.out.println(result);
}
}
Example:
val1 = false;
System.out.println(val1 ^ val2);
val2 = false;
System.out.println(val1 ^ val2);
Workbook
Logic and Programming Fundamentals 29
val1 = true;
System.out.println(val1 ^ val2);
}
}
false
true
false
true
expr Result
TRUE FALSE
FALSE TRUE
Example:
false
true
Workbook
Logic and Programming Fundamentals 30
The general idea in using the operator is that when expr1 is true,
value of expr2 is returned, otherwise, expr3 is returned.
Example:
String status;
int grade = 80;
Pass
Workbook
Logic and Programming Fundamentals 31
3. Declare a temporary String variable to hold the input value then invoke
the readLine() method to get the input from the keyboard. The
readLine() method must be type inside a try-catch block.
try{
String input = dataIn.readLine();
}catch(IOException e){
System.out.println(“Error in getting input”);
}
Workbook
Logic and Programming Fundamentals 32
Example:
import java.io.*;
String text;
try{
text=dataIn.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
To better understand the sample code written, let us explain the statements
per line.
The statement import java.io.* indicate that we want to use all the
classes found inside java.io package like BufferedReader,
InputStreamReader, and IOException in the program. Packages
contain classes that have related purposes.
The statements,
Workbook
Logic and Programming Fundamentals 33
try{
text=dataIn.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
assures that the possible exceptions that could occur in the statement
text=dataIn.readLine(); will be catched. Note that when using the
readLine() method, it should be inside a try-catch block
The statement, text=data.readLine(); gets input from the user and will
return a String value to be stored to the text variable.
The user input, whose value is stored on variable text, will be displayed in
place of the text on the statement System.out.println(“Hello “ +
text + “!”);.
When user wants to input values other than that of a String type, the
user input must be parsed (converted) first to be used for its intended
purpose.
Workbook
Logic and Programming Fundamentals 34
Example:
try{
string=dataIn.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
int number=Integer.parseInt(string);
Example:
try{
string=dataIn.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
double number=Double.parseDouble(string);
Workbook
Logic and Programming Fundamentals 35
Learning Objective:
INSTRUCTIONS:
HANDS ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Create a folder under drive C: and name it myJavaProgs.
3. Upon successful log-in, go to the command prompt and set the path and
classpath.
Workbook
Logic and Programming Fundamentals 36
3.1. After setting the path (when using Ubuntu Linux, there is no need
for set path command), type echo %path%.
What would be written on the command prompt window?
_____________________________________________________
_____________________________________________________
_____________________________________________________
3.2. After setting the classpath, type echo %classpath%.
What would be written on the command prompt window?
_____________________________________________________
_____________________________________________________
_____________________________________________________
Workbook
Logic and Programming Fundamentals 37
10. Modify your program by deleting the statement in the main( ) method block
replacing it with these statements:
System.out.println(“My”);
System.out.println(“First”);
System.out.println(“Java”);
System.out.println(“Program”);
System.out.println(“!”);
System.out.print(“My”);
System.out.print(“First”);
System.out.print(“Java”);
System.out.print(“Program”);
System.out.print(“!”);
12. Modify the program by deleting the statements by copying the code written
below exactly as it is:
Workbook
Logic and Programming Fundamentals 38
13.2. Correct the error; Save and Compile the program again.
What would be displayed on the screen?
Workbook
Logic and Programming Fundamentals 39
13.4. Continue debugging the program until such time that there is no
more error after compilation.
Copy the corrected code here:
Workbook
Logic and Programming Fundamentals 40
Learning Objective:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open the command prompt and set the path and classpath.
3. Change your working directory to where you store your files.
4. Write your next Java program:
4.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 41
6. Modify the main() block and insert these statements before the
System.out.println() statements.
i = c;
d = c;
8. Modify the main( ) block by deleting what you inserted in number 6 and
inserting this statement in its place.
b=i;
Workbook
Logic and Programming Fundamentals 42
String s = ‘S’;
14. Modify the program so that it would display the following as the output.
Student Information
Lastname: <Your Lastname>
Firstname: <Your Firstname>
Middle Initial: <Your Middle Initial>
Age: <Your Age>
Course: <Your Course>
Year: <Your Year>
Note that the data regarding Lastname, Firstname, Middle Initial, Age,
Course and Year should be placed in a variable declared with the proper
data type.
Workbook
Logic and Programming Fundamentals 43
Workbook
Logic and Programming Fundamentals 44
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open the command prompt and set the path and classpath.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 45
Workbook
Logic and Programming Fundamentals 46
4.2. Notice that the result of the division operation it is not displaying the
actual quotient of the two (2) operands. Modify the program in order
for it to output the correct quotient of the two (2) operands.
4.3. Modify the program again and this time use only one (1) variable to
store the results of each of the arithmetic operations to be used
inside the System.out.println() statement.
Write your code on the box provided:
Workbook
Logic and Programming Fundamentals 47
5. Given the following code segment, simulate the order of how the operation is
performed based on the precedence of the operators.
double op1 = 5;
double op2 = 7;
double op3 = 3;
double op4 = 20;
double op5 = 16;
double op6 = 2;
double result = 0;
6. Basing it on the code fragment written above, what value would be stored in
the variable result if the expression is grouped as follows:
Workbook
Logic and Programming Fundamentals 48
Workbook
Logic and Programming Fundamentals 49
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 50
boolean a, b, c, d, e, f;
int x, y;
x = 8;
y = 13;
a = (x == y);
b = (x != y);
c = (x > y);
d = (x < y);
e = (x >= y);
f = (x <= y);
System.out.println(“a = ” + a);
System.out.println(“b = ” + b);
System.out.println(“c = ” + c);
System.out.println(“d = ” + d);
System.out.println(“e = ” + e);
System.out.println(“f = ” + f);
}
}
3.2. Save your program as RelationalOperators.java then compile
your program until no errors and warnings are reported.
3.3. Execute your program.
3.4. Write what will be displayed on the screen.
Workbook
Logic and Programming Fundamentals 51
3.5. Assuming that the values for x and y were changed, interpret the
value that would be generated whether it is TRUE or FALSE
x = 27;
y = 15;
x = 17;
y = 20;
Workbook
Logic and Programming Fundamentals 52
5.1. Save, Compile and Execute and write the output on the box provided
below.
5.2. List all relational operators that were used in the program and
describe the function of each briefly.
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 54
}
}
Workbook
Logic and Programming Fundamentals 55
Workbook
Logic and Programming Fundamentals 56
8. Modify the program and replace all && with & and all || with |. Save,
Compile and Execute the program. Write the output on the box provided.
x = 5;
y = 10;
z = 10%5;
Workbook
Logic and Programming Fundamentals 57
10. Modify the program by deleting the statements written under the main()
block and replacing it with the statements below.
int x, y;
String eval;
x = 10;
y = x%x;
10.1. Save, Compile and Execute the program. Write the output here:
Workbook
Logic and Programming Fundamentals 58
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 59
import java.io.*;
System.out.println(“Hello “ + name);
}
}
Workbook
Logic and Programming Fundamentals 60
4.3. Save and Compile your program until such time that there is no more
error.
4.4. Execute the program and write the output on the box provided below.
Workbook
Logic and Programming Fundamentals 61
5. Create another program by copying the code below in your text editor.
Workbook
Logic and Programming Fundamentals 62
6. Write a complete Java program that will ask the user to input two (2)
numbers and perform the five (5) basic arithmetic operations on these
numbers. Save your program as PerformArtithmetic.Java
Sum = 8
Difference = 2
Product = 15
Quotient = 1.0
Remainder = 2
Write your code here:
Workbook
Logic and Programming Fundamentals 63
UNIT 2
Control Structures
1. Control Flows
a = 1; // First Statement
b = 2; // Second Statement
c = a + b; // Third Statement
In the above example, the order by which execution occurs will be from the
first statement, followed by the second statement, and finally the third
statement.
Workbook
Logic and Programming Fundamentals 64
3.1 if Statement
if(boolean expression)
statement;
or
if(boolean expression){
statement1;
statement2;
. . .
statementN;
}
Workbook
Logic and Programming Fundamentals 65
The modified program above uses two (2) if() blocks, one to evaluate
whether an input number is greater than or equal to zero hence a positive
number, and one to evaluate whether an input number is lesser than zero
which is a negative number. The program is not the best implementation
of an if() statement because if you will trace it, both conditions are
tested. Meaning, the program will test for the second condition still, even
though the first condition has already been met. But first let us try to trace
and simulate the program.
Simulation:
Input a number = 5
n = 5 is POSITIVE
_
Analysis:
When the user inputs 5, the value is then stored in the variable in prior to
conversion to an integer value to be stored in the variable num. The
program performs the first conditional statement if(num>=0). Since it
Workbook
Logic and Programming Fundamentals 66
Example: Write a program that will accept a number representing the day
of the week. Thereafter, the program will display the equivalent day.
if(day == 1){
System.out.println(“That day is a Monday!”);
System.out.println(“Have a nice day.”);}
if(day == 2){
System.out.println(“That day is a Tuesday!”);
System.out.println(“Have a nice day.”);}
if(day == 3){
System.out.println(“That day is a Wednesday!”);
System.out.println(“Have a nice day.”);}
if(day == 4){
System.out.println(“That day is a Thursday!”);
System.out.println(“Have a nice day.”);}
if(day == 5){
System.out.println(“That day is a Friday!”);
System.out.println(“Have a nice day.”);}
if(day == 6){
System.out.println(“That day is a Saturday!”);
System.out.println(“Have a nice day.”);}
if(day == 7){
System.out.println(“That day is a Sunday!”);
System.out.println(“Have a nice day.”);}
}
}
Workbook
Logic and Programming Fundamentals 67
Analysis:
The day program is just one possible solution, and it is not really a good
solution like the number program! If you’ll notice, the statement
System.out.println(“Have a nice day.”) is common to all if-
statement and it is repeated seven times! This common instruction can
actually be factored out. A better solution is given below (but not yet the
best!).
if(day == 1)
System.out.println(“That day is a Monday!”);
if(day == 2)
System.out.println(“That day is a Tuesday!”);
if(day == 3)
System.out.println(“That day is a Wednesday!”);
if(day == 4)
System.out.println(“That day is a Thursday!”);
if(day == 5)
System.out.println(“That day is a Friday!”);
if(day == 6){
System.out.println(“That day is a Saturday!”);
if(day == 7){
System.out.println(“That day is a Sunday!”);
Note that this program is better than the previous one. One of the
desirable qualities that an aspiring programmer should have is the ability
to factor out common instructions to reduce the perceived length and
complexity of a program.
Workbook
Logic and Programming Fundamentals 68
However, please note that this is still not the best solution to the problem.
Why? Assume that day is equivalent to a value of 1. If that is the case,
then the first if condition will be evaluated as true and the program will
output “That day is a Monday!”. So far there’s no problem, however,
please note that after executing the System.out.println(), the
program will still execute the remaining six if statement. Logic tells us that
we need not do them. As much as possible, we don’t want the program to
execute unnecessary instructions since it will be a waste of computation
time. There must be a much better solution to the problem.
Example:
In temperate countries like Japan, there are four seasons. April to June is
spring, July to September is summer, October to December is autumn and
January to March is winter. We wish to write a program that allows the
user to input month in its numeric equivalent (i.e., January is 1, February
is to 2 and so on…). The output of the program is the season associated
with that month.
// Season program using if-statement
import java.io.*;
public class Season{
public static void main(String[] args){
int month;
String in;
BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
System.out.print(“Input a Number from 1-12: “);
try{
in=input.readLine();
}catch(IOException e){
System.out.println(“Error”);
}
month = Integer.parseInt(in);
if(month == 1)
System.out.println(“It’s winter.”);
if(month == 2)
System.out.println(“It’s winter.”);
if(month == 3)
System.out.println(“It’s winter.”);
if(month == 4)
System.out.println(“It’s spring.”);
if(month == 5)
System.out.println(“It’s spring.”);
if(month == 6)
System.out.println(“It’s spring.”);
if(month == 7)
System.out.println(“It’s summer.”);
Workbook
Logic and Programming Fundamentals 69
if(month == 8)
System.out.println(“It’s summer.”);
if(month == 9)
System.out.println(“It’s summer.”);
if(month == 10)
System.out.println(“It’s autumn.”);
if(month == 11)
System.out.println(“It’s autumn.”);
if(month == 12)
System.out.println(“It’s autumn.”);
}
}
Note: The program above will give the required result, however, it is not
really the best possible solution to the problem.
1. Using Logical OR
month = Integer.parseInt(in);
Workbook
Logic and Programming Fundamentals 70
month = Integer.parseInt(in);
}
}
Workbook
Logic and Programming Fundamentals 71
if(<condition>)
{
statement1;
statement2;
. . .
statementN;
}
else
{
statement1;
statement2;
. . .
statementN;
}
num = Integer.parseInt(in);
if(num>=0)
System.out.println(“Number is POSITIVE”);
else
System.out.println(“Number is NEGATIVE”);
}
}
Workbook
Logic and Programming Fundamentals 72
Example:
Workbook
Logic and Programming Fundamentals 73
is billed as a 3 minute call). The rate applied depends on the day the call
was made and on the time the call was started (not when it ended).
Based on the information entered, the program should print the bill
corresponding to the call.
// TNP program using nested if/if-else
import java.io.*;
public class TNPProgram{
public static void main(String[] args){
double charge, rate;
int day=0, sTime=0, duration=0;
String in;
BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
try{
/* input the day, start time and duration
of the call */
System.out.print(“Day:“);
in=input.readLine();
day = Integer.parseInt(in);
System.out.print(“Start Time:“);
in=input.readLine();
sTime = Integer.parseInt(in);
System.out.print(“Duration of Call:“);
in=input.readLine();
duration = Integer.parseInt(in);
}catch(IOException e){
System.out.println(“Error”);
}
Example:
Write a program that will determine the income of an employee. An
employee is either a part-time employee or a full-time employee. A part-
time employee’s gross income is computed as the product or his/her
hourly rate and the number of hours worked. The gross income of a full-
time employee is computed as regular pay plus overtime pay. The
overtime pay is computed as overtime rate multiplied by the number of
overtime hours. The overtime pay should be computed if and only if the
overtime hours rendered is not zero.
// Salary Program using nested if/if-else */
import java.io.*;
public class SalaryProgram{
public static void main(String[] args){
int eType=0;
double gIncome=0, hRate=0, hWorked=0;
double rPay=0, otHours=0, otRate=0, otPay=0;
int day=0, sTime=0, duration=0;
String in;
BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
try{
// input employee type
System.out.print(“Employee is [1]Part-time
[2] Full-time“);
in=input.readLine();
eType = Integer.parseInt(in);
}catch(IOException e){
System.out.println(“Error”);
}
Workbook
Logic and Programming Fundamentals 75
else{ // employee_type == 2
try{
/* input regular pay and overtime hours
and overtime rate */
System.out.print(“Input regular pay: ”);
in=input.readLine();
rPay = Double.parseDouble(in);
System.out.print(“Input number of
overtime hours: “);
in=input.readLine();
otHours = Double.parseDouble(in);
System.out.print(“Input overtime rate”);
in=input.readLine();
otRate = Double.parseDouble(in);
}catch(IOException e){
System.out.println(“Error”);
}
Workbook
Logic and Programming Fundamentals 76
if(day == 1)
System.out.println(“That day is a Monday!”);
else if(day == 2)
System.out.println(“That day is a Tuesday!”);
else if(day == 3)
System.out.println(“That day is a Wednesday!”);
else if(day == 4)
System.out.println(“That day is a Thursday!”);
else if(day == 5)
System.out.println(“That day is a Friday!”);
else if(day == 6)
System.out.println(“That day is a Saturday!”);
else if(day == 7)
System.out.println(“That day is a Sunday!”);
NOTE: What will happen if the user entered 1 as the value of day? The
program will print “That day is a Monday!” and following it below is
the text “Have a nice day.”. It will not test the other condition unlike in
the simple if solution presented before. Thus, there are no unnecessary
computations.
Workbook
Logic and Programming Fundamentals 77
import java.io.*;
public class SeasonProgram{
public static void main(String[] args){
String in = “ “;
int month = 0;
BufferedReader input = new BufferedReader(new
InputStreamReader(System.in));
System.out.print(“Input month: ”);
try{
in = input.ReadLine();
month = Integer.parseInt(in);
}catch(IOException e){
System.out.println(“Error!”);
}
if(month <= 3)
System.out.println(“It’s winter.”);
Workbook
Logic and Programming Fundamentals 78
Syntax:
switch(<expression>)
{
case <value1>: <statement1.1>;
<statement1.2>;
<statement1.N>;
[break];
[default : <statement> ];
}
Note:
Workbook
Logic and Programming Fundamentals 79
switch(day)
{
case 1: System.out.println(“That day is a Monday!”);
break;
case 2: System.out.println(“That day is a Tuesday!”);
break;
case 3: System.out.println(“That day is a Wednesday!”);
break;
case 4: System.out.println(“That day is a Thursday!”);
break;
case 5: System.out.println(“That day is a Friday!”);
break;
case 6: System.out.println(“That day is a Saturday!”);
break;
case 7: System.out.println(“That day is a Sunday!”);
break
default: System.out.println(“Invalid input try again”);
}
System.out.println(“Have a nice day.”);
}
}
Workbook
Logic and Programming Fundamentals 80
switch(month){
case 1: System.out.println(“It is winter.”);
break;
case 2: System.out.println(“It is winter.”);
break;
case 3: System.out.println(“It is winter.”);
break;
case 4: System.out.println(“It is spring.”);
break;
case 5: System.out.println(“It is spring.”);
break;
case 6: System.out.println(“It is spring.”);
break;
case 7: System.out.println(“It is summer.”);
break;
case 8: System.out.println(“It is summer.”);
break;
case 9: System.out.println(“It is summer.”);
break;
case 10: System.out.println(“It is autumn.”);
break;
case 11: System.out.println(“It is autumn.”);
break;
case 12: System.out.println(“It is autumn.”);
break;
}
}
}
NOTE: This program will run but it is not the best implementation.
It is possible to have several cases respond to the same statement. A
better way of implementing the previous program is shown below:
Workbook
Logic and Programming Fundamentals 81
switch(month){
case 1:
case 2:
case 3: System.out.println(“It is winter.”);
break;
case 4:
case 5:
case 6: System.out.println(“It is spring.”);
break;
case 7:
case 8:
case 9: System.out.println(“It is summer.”);
break;
case 10:
case 11:
case 12: System.out.println(“It is autumn.”);
break;
}
}
}
Workbook
Logic and Programming Fundamentals 82
Initialization: counter = 1
Condition: While counter <= 50
Body of the loop: Print “HELLO”
Change of state: counter = counter + 1
There are three available loop control structures in Java. These are:
1. while Loop
2. for Loop
3. do-while Loop
<initialization>
while(<condition>)
{
<statement1>;
. . .
<statementN>;
<change of state>;
}
Workbook
Logic and Programming Fundamentals 83
System.out.println(“HELLO”); // Body
counter = counter + 1; // Change of State
}
}
}
The program above can be modified easily to print the word “HELLO” any
number of times. It is simply a matter of changing the value inside the
condition.
Example: Program that will compute the sum of all numbers that are
divisible by 5 from 0 to 100.
Workbook
Logic and Programming Fundamentals 84
Variable used for the change of state are not limited to integers only and
need not always be incremental. Consider the following example:
// Step down using while loop
public class StepDown{
public static void main(String[] args){
double n = 10;
while(n >= 1){
System.out.println(n);
n = n – 0.5;
}
}
}
Try simulating the output of the step down program written above.
Workbook
Logic and Programming Fundamentals 85
The for-loop is actually a “more compact” form of the while loop. The
loop is executed as follows:
1. Perform the initialization
2. Check the condition
3. If the condition results to a TRUE value, the statement/s inside the for-
loop (body) will be executed. Else proceed to #6
4. Change of state
5. Goes back to #2.
6. Exit the loop and the statement after the end of the for-loop will be
executed.
Note that the initialization, condition, and the change of state are only
found in one line. The body of the for-loop like the while-loop is enclosed
in a pair of curly braces. If there is only one statement representing the
body of the loop, then the pair of curly brackets can be optional.
Workbook
Logic and Programming Fundamentals 86
Input a number: 10
The Fibonacci series of 10 is:
0 1 1 2 3 5 8 13 21 34 55 _
Workbook
Logic and Programming Fundamentals 87
<initialization>;
do{
<statement1>;
. . .
<statementN>;
<change of state>;
}while(<condition>);
Workbook
Logic and Programming Fundamentals 88
Loops are not confined on processing numeric data, the program will
depend on the problem that is being solved. Let us consider the
problem below.
// Interactive program using loops
import java.io.*;
public class InteractiveProgram{
public static void main(String[] args){
int a, b = 0, sum;
char again;
String input = “ “;
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
do{
sum = 0;
for(a = 0; a < 10; a++){
System.out.println(“Input number “ + a + “ of 9: ”);
try{
input = in.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
b = Integer.parseInt(input);
sum = sum + b;
}
System.out.println(“The sum = ” + sum);
System.out.println(“Do you want to try again? (Y/N)”);
try{
input = in.readLine();
}catch(IOException e){}
again = input.charAt(0);
}while(again == ‘Y’ || again == ‘y’);
System.out.println(“Have a nice day!”);
}
}
Workbook
Logic and Programming Fundamentals 89
4.5. Counters
Example: Write a program that will ask the user to input 10 integers. The
program should output how many of the data are positive. Assume that zero is a
positive integer.
// Counter program
import java.io.*;
public class CounterProgram
public static void main(String[] args){
int i=0, num, ctr_positive;
String input = “ “;
ctr_positive = 0;
Exercise:
1. Modify the previous program such that it will also count and print the
number of negative integers that were inputted by the user.
2. Create a new program that will ask the user to input n integer values
then print the number of ODD and EVEN numbers.
3. Create a program the will display all numbers that are divisible by 5
and count how many of them are there in the range of a signed integer
data type.
Workbook
Logic and Programming Fundamentals 90
4.6. Accumulators
Example: Write a program that will ask the user to input n integers. The program
should output the sum of all the input data.
// Accumulator Sample
import java.io.*;
public class AccumulatorSample{
public static void main(String[] args){
int n, i, num, sum;
String input = “ “;
sum = 0;
Workbook
Logic and Programming Fundamentals 91
Exercises:
1. Modify the previous program such that it will compute and output the
sum of positive numbers and the sum of negative numbers.
2. Create a new program that will ask the user to input how many
students are there in a class. Thereafter, the user will be asked to input
the final grade for each student. The program should determine the
average of all the grades of the student in that class. How many of
them passed, and how many of them failed.
Assume that the passing grades are from 75 to 99, and failing grades
are from 70 to 74.
Workbook
Logic and Programming Fundamentals 92
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program.
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 93
import java.io.*;
public class PosNeg{
public static void main(String[] args){
int number;
String input = “ “;
System.out.println(“Input a Number: “ );
try{
input = in.readLine();
}catch(IOException e){
System.out,println(“Error!”);
}
number = Integer.parseInt(input);
if(number < 0)
{
System.out.println(“The number “ + number + “ is
NEGATIVE”);
}
if(number >= 0)
{
System.out.println(“The number “ + number + “ is
POSITIVE”);
}
}
}
Workbook
Logic and Programming Fundamentals 94
Workbook
Logic and Programming Fundamentals 95
4.2. Save then compile your program until no errors and warnings are
reported.
4.3. Run your program.
4.4. Simulate and write what will be displayed on the screen.
5. Rewrite your PosNeg.java source code using only one if statement and
an else statement. Save it as PosNeg2.java
Workbook
Logic and Programming Fundamentals 96
5.2. Save then compile your program until no errors and warnings are
reported.
5.3. Run your program.
5.4. Write what will be displayed on the screen after a complete
simulation of your program.
Workbook
Logic and Programming Fundamentals 97
6.2. Save then compile your program until no errors and warnings are
reported.
6.3. Run your program.
6.4. Write what will be displayed on the screen after a complete
simulation of your program.
int age;
String input = “ “;
try{
input = in.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
age = Integer.parseInt(input);
Workbook
Logic and Programming Fundamentals 98
7.2. Save your program as Age.java then compile your program until
no errors and warnings are reported.
7.3. Run your program.
7.4. Write what will be displayed on the screen for the following input.
Input age : 101
Input age : 95
Input age : 50
Input age : 45
Input age : 13
Input age : 10
Input age : 3
Input age : -2
Workbook
Logic and Programming Fundamentals 99
7.5. Based from the results of your simulation, write down what you
have observed.
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
8.2. Simulate using the same test inputs. Write what will be displayed
on the screen:
Input age : 101
Input age : 95
Input age : 50
Input age : 45
Input age : 13
Workbook
Logic and Programming Fundamentals 100
Input age : 10
Input age : 3
Input age : -2
8.3. Based from the results of your simulation, write down what you
have observed.
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
8.4. Is there any difference between a nested if and cascading if-else
statements? If so, differentiate it.
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
_____________________________________________________
9.1. You were hired by PAGCOR as part of the programming team in-
charge of automating its BINGO game. Your task is to write a
program that will accept an integer number whose value is from 1
to 75. Thereafter, your program should determine and print the
letter that corresponds to that number. That is, numbers 1 to 15
corresponds to the letter ‘B’, 16 to 30 corresponds to the letter ‘I’,
31 to 45 corresponds to the letter ‘N’, 46 to 60 corresponds to the
letter ‘G’ and 61 to 75 corresponds to the letter ‘O’.
Workbook
Logic and Programming Fundamentals 101
Workbook
Logic and Programming Fundamentals 102
9.3. Save then compile your program until no errors and warnings are
reported.
9.4. Run your program.
9.5. Write what will be displayed on the screen during your simulation or
test run.
Workbook
Logic and Programming Fundamentals 103
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 104
import java.io.*;
public class Days{
public static void main(String[] args){
int day;
String input = “ “;
try{
input = in.readLine();
}catch(IOException e){
System.out.println(“Error!”);
}
day = Integer.parseInt(input);
switch(day){
case 1 : System.out.println(“The day is a Monday!”);
break;
case 2: System.out.println(“The day is a Tuesday!”);
break;
case 3: System.out.println(“The day is a Wednesday!”);
break;
case 4: System.out.println(“That day is a Thursday!”);
break;
case 5: System.out.println(“The day is a Friday!”);
break;
case 6: System.out.println(“The day is a Saturday!”);
break;
case 7: System.out.println(“The day is a Sunday!”);
break;
}
System.out.println(“Have a nice day.”);
}
}
3.2. Save your program as Days.java then compile your program until
no errors and warnings are reported.
3.3. Run your program.
Workbook
Logic and Programming Fundamentals 105
4.2. Save, compile, then run your Days.java program and input a
value for day that is not from 1 to 7. What will be displayed on the
screen?
4.3. Now remove the break statement in case 2. Then compile and run
your program. Input a value for day equal to 2. Write what will be
displayed on the screen.
Workbook
Logic and Programming Fundamentals 106
4.4. Reinsert the break statement in case 2. Now try moving the
following codes:
4.5. Compile, run your program. Try inputting a value that is not from 1
to 7.
Workbook
Logic and Programming Fundamentals 107
Workbook
Logic and Programming Fundamentals 108
Workbook
Logic and Programming Fundamentals 109
Name: _________________________________________________________
Subject Code & Schedule: _______________________________________
Course and Year: _______________________________________________
TITLE: Loops
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 110
import java.io.*;
public class Sum1{
public static void main(String[] args){
int start = 0, end = 0, sum;
String input = “ “;
try{
System.out.print(“Input starting number: “);
input = in.readLine();
start = Integer.parseInt(input);
if(start%2 == 0)
{
start = start + 1;
}
sum = 0;
while(start <= end)
{
sum = sum + start;
start = start + 2;
}
System.out.println(“Sum = ” + sum);
}
}
Workbook
Logic and Programming Fundamentals 111
3.2. Save the program as Sum1.java then compile your program until
no errors and warnings are reported.
3.3. Run your program.
3.4. Simulate and write what will be displayed on the screen.
4. Now let’s try another implementation. Copy the source code below and
save it as Sum2.java
/* Programmed by: <write your name here>
Program title: Sum2.java
Program Date: <write the date today here> */
import java.io.*;
public class Sum2{
public static void main(String[] args){
int start = 0, end = 0, sum;
String input = “ “;
Workbook
Logic and Programming Fundamentals 112
4.1. Simulate and write what will be displayed on the screen. Try using
the same input values in your Sum1.java
5. Let us try another implementation. Copy the source code and save it as
Sum3.C
/* Programmed by: <write your name here>
Program title: Sum3.java
Program Date: <write the date today here> */
import java.io.*;
public class Sum3{
public static void main(String[] args){
int start = 0, end = 0, sum;
String input = “ “;
System.out.println(“Sum = ” + sum);
}
}
Workbook
Logic and Programming Fundamentals 113
5.1. Simulate and write what will be displayed on the screen. Try using
the same input values in your Sum1.java and Sum2.java
6. After your simulation for the three programs, what do you think is the main
objective of these programs?
___________________________________________________________
___________________________________________________________
___________________________________________________________
___________________________________________________________
___________________________________________________________
___________________________________________________________
___________________________________________________________
Workbook
Logic and Programming Fundamentals 114
10. Create a complete Java program that shall allow the user to accept three
integer values representing the START, END, and STEP respectively. The
START should always be lesser than the END value, and the STEP is
always greater than zero. The program shall print vertically the values
starting from the START to the last value which can be equal to or lesser
than the END incremented by the STEP value.
1
3
5
7
9
-10
-5
0
5
10
15
20
10.1. Your program should automatically detect any errors in the initial
input.
10.2. Your program should have an additional feature that asks the user
whether the user wants TO TRY AGAIN. The Program will not
terminate until the user inputs any character other than ‘Y’ or ‘y’.
10.3. Implement the program using all looping constructs identified
earlier.
Workbook
Logic and Programming Fundamentals 115
Workbook
Logic and Programming Fundamentals 116
Workbook
Logic and Programming Fundamentals 117
Workbook
Logic and Programming Fundamentals 118
Name: _________________________________________________________
Subject Code & Schedule: _______________________________________
Course and Year: _______________________________________________
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 119
import java.io.*;
public class Count{
public static void main(String[] args){
int i, n, ctr;
String input = “ “;
ctr = 0;
n = Integer.parseInt(input);
if(n >=0){
ctr = ctr + 1;
}
}
System.out.println(“The total value for counter is ” + ctr);
}
}
Workbook
Logic and Programming Fundamentals 120
4.2. Save then compile your program until no errors and warnings are
reported.
Workbook
Logic and Programming Fundamentals 121
Workbook
Logic and Programming Fundamentals 122
5. Write your next program by copying the source code shown below to your
text editor.
5.1. Create a new program and save it as Accum.java
/* Programmed by: <write your name here>
Program title: Accum.java
Program Date: <write the date today here> */
n = Integer.parseInt(input);
sum = sum + n;
}
System.out.println(“The sum of the integers is ” + sum);
}
}
5.2. Save then compile your program until no errors and warnings are
reported.
5.3. Run your program.
5.4. Simulate and write what will be displayed on the screen.
Workbook
Logic and Programming Fundamentals 123
6.2. Save then compile your program until no errors and warnings are
reported.
Workbook
Logic and Programming Fundamentals 124
Workbook
Logic and Programming Fundamentals 125
UNIT 3
1. Java Arrays
An array stores multiple data items of the same type, in a contiguous block of
memory, divided into a number of slots. Furthermore, array is a capability of
programming languages wherein one variable can store a list of data and
manipulate these data more efficiently.
In simple words:
An array is a group of elements with the same data type (homogeneous).
An array is characterized by its name, dimension, size, and element data
type.
An array has a dimension:
o If dimension is 1, we say that the array is a one-dimensional; Also
known as a list.
o If dimension is 2, we say that the array is a two-dimensional; Also
known as a table.
o Array having more than one dimension is also known as multi-
dimensional array.
In our course, we will just discuss one and two dimensional arrays. But in the
Java language, you can have more than two dimensions for an array.
<data_type> <array_name>[];
or
<data_type>[] <array_name>;
After declaring, you must create the array and specify its length using a
constructor. The process of using a constructor to create an array is
called instantiation.
Sample Declaration:
//declaration
int number[];
//instantiation
number = new int[10];
Workbook
Logic and Programming Fundamentals 126
The declaration tells the Java Compiler that the identifier number will be
used as the name of the array containing integers and creates or
instantiate a new array containing 10 elements.
Examples:
char name[] = new char[35];
int grades[] = new int[50];
float area[] = new float[5];
double data[] = new double[10];
Note: array elements not explicitly initialized will have garbage values.
<array_name>[<index>]
scores[0] = 7
scores[1] = 3
scores[2] = 8
scores[3] = 4
scores[4] = 6
scores[5] = 3
scores[6] = 6
scores[7] = 9
scores[8] = 7
scores[9] = 5
Workbook
Logic and Programming Fundamentals 127
index 0 1 2 3 4 5 6 7 8 9
scores: 7 3 8 4 6 3 6 9 7 5
values
Workbook
Logic and Programming Fundamentals 128
Workbook
Logic and Programming Fundamentals 129
<data_type> <array_name>[<rowsize>][<colsize>];
Or
<data_type>[<rowsize>][<colsize>] <array_name>;
Sample Declaration:
//declaration
int number[][];
//instantiation
number = new int[5][10];
Example:
Workbook
Logic and Programming Fundamentals 130
[0][3]
[1][0]
[1][1]
Row 1
[1][2]
[1][3]
[2][0]
[2][1] Row 2
[2][2]
[2][3]
<array_name>[<row_index>][<column_index>]
Workbook
Logic and Programming Fundamentals 131
Row 0 2 4 5 7
Row 1 1 6 9 3
Row 2 4 6 2 8
Workbook
Logic and Programming Fundamentals 132
//Table 3 x 4 program
public class Table3x4{
public static void main(String[] args){
int table[][] = new int[3][4];
int i, j;
table[0][0] = 2;
table[0][1] = 4;
table[0][2] = 5;
table[0][3] = 7;
table[1][0] = 1;
table[1][1] = 6;
table[1][2] = 9;
table[1][3] = 3;
table[2][0] = 4;
table[2][1] = 6;
table[2][2] = 2;
table[2][3] = 8;
// print table in matrix format
for(i = 0; i < 3; i++){
for(j = 0; j < 4; j++){
System.out.print(“ “ + table[i][j]);
}
System.out.println();
}
}
} Exercise:
Using the same table, create a program that will initialize the table to zero
and ask the user to input values. Thereafter, the program will print the
inputted values in matrix form. The program should also display the sum
of all the values inputted.
Workbook
Logic and Programming Fundamentals 133
Workbook
Logic and Programming Fundamentals 134
Exercises:
Write a program that will create a 2-dimensional array with a row size = 10
and a column size = 10 also. Or simply a 10 x 10 table, thereafter the
program should:
arrayName.length
Workbook
Logic and Programming Fundamentals 135
2. Java Methods
To know more of what a method is, let us first consider the following scenario.
Let us assume that you were a programmer and you were asked to write a
program that will be used to handle Automated Teller Machine transactions.
Such transactions includes: (1) balance inquiry, (2) deposit and (3) withdraw.
Aside from these, the user should be presented a menu showing there
transaction as possible options. For a non-trivial program like these, it is
advise to write the codes under one method which the main()method.
It is better to subdivide the programs into smaller portions – which we call
methods. Each method should be able to solve part of the bigger problem. In
the scenario above, one method will handle the generation of the menu,
another method will be in-charge of handling the balance inquiry, another
method will be used for deposit transaction, and a method that will handle
withdrawal transactions. Notice that each method does a specified job of
other methods.
In a more concrete term, a method is basically a program by itself – it has
inputs, output, and will perform some kind of processing steps.
Characteristics of Methods
Workbook
Logic and Programming Fundamentals 136
Where,
access_modifier can either be public, private, protected (if
no access is present, the default modifier is in effect).
static is a keyword used to indicate that the method is a
static method
return_type can be the different data types.
method_name is any name given by the programmer to
identify the method.
parameters are arguments that is passed from one-method
to another (optional if no arguments are to be passed).
ClassName.staticMethodName(params);
Or
staticMethodName(params);
Sample Program: Program that print the text “Hello World!” where “Hello”
is to be printed by one method and “World!” is to be printed by another
method.
//Declaring and Calling Methods
public class UsingMethods{
public static void printHello(){
System.out.print(“Hello “);
}
public static void printWorld(){
System.out.println(“World!”);
}
public static void main(String[] args){
printHello();//same as UsingMethods.printHello
printWorld();//same as UsingMethods.printWorld
}
}
Workbook
Logic and Programming Fundamentals 137
Exercise: What will happen if we write the hello() function after the
main() function? Will the program behave as what is expected? If not,
how will you remedy the situation where functions are written after the
main() method?
Workbook
Logic and Programming Fundamentals 139
2.3.1. Pass-by-value
When pass-by-value occurs, the method makes a copy of the
value of the variable passed to the method.
//Pass by value
public class PassByValue{
//Method with parameter
public static void methodWithParam(int j){
//print value of j
System.out.println(“Value of j = “ + j);
}
public static void main(String[] args){ Pass i as a parameter
int i; which is copied to j
Return to the
caller
i = 50;
and perform the
statement after //call methodWithParam passing value of i
the method call methodWithParam(i);
//print value of i
System.out.println(i);
}
}
Value of j = 50;
Value of i = 50;
Value of j = 100;
Value of i = 50;
Note: The method cannot modify the original value of the variable
being passed. By default, all primitive data types when passed to a
method are pass-by-value.
Workbook
Logic and Programming Fundamentals 140
//Pass by value
public class PassByValue{
//Method with parameter
public static void methodWithParam(int j, int k){
//print value of j
System.out.println(“Value of j = “ + j);
System.out.println(“Value ok k = “ + k);
}
public static void main(String[] args){
int i;
i = 50;
Value of j = 50
Value of k = 50
Value of i = 50
2.3.2. Pass-by-reference
Workbook
Logic and Programming Fundamentals 141
10
20
30
60
70
80
Workbook
Logic and Programming Fundamentals 142
a = 22;
b = 14;
/*call method computeSum passing values of variables
A and b as parameters*/
System.out.println(“Sum = ” + computeSum(a, b));
}
}
Sum = 21
Sum = 300
Sum = 36
Workbook
Logic and Programming Fundamentals 143
Exercise:
if (n > = 0)
result = 1;
else
result = 0;
return result;
}
// Another implementation
Workbook
Logic and Programming Fundamentals 144
1. If the method will not return anything, use void as the return type.
2. If the method will return a value, the appropriate data type should be
specified.
3. If the method will return a value, don’t forget to use the return
statement inside the method.
4. The data type of the value that appears after the return statement must
be compatible with the return data type.
5. You can use any name for the method as long as you follow the
naming convention and do not use Java keywords as method names.
6. A method may have zero, one or more parameters.
7. If the method does not have any parameter, leave the area in between
the parentheses blank.
8. If the method has parameters, specify their data types and names.
9. Parameters should be separated by comma.
10. The name of the parameters does not matter. Always remember that
the number of parameters, their respective data types, and their
sequence are the things that actually matter!
11. When calling a method, constants, expressions and variables maybe
used as actual parameters.
12. A method can return at the most only one value at any given point in
time.
3. Scope of Variable
The scope determines where in the program the variable is accessible. The
scope also determines the lifetime or how long the variable can exist in
memory. The placement of the variable, or where the variable is declared,
determines the scope for that variable.
For example:
Workbook
Logic and Programming Fundamentals 145
Workbook
Logic and Programming Fundamentals 146
Name: _________________________________________________________
Subject Code & Schedule: _______________________________________
Course and Year: _______________________________________________
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 147
import java.io.*;
public class List{
public static void main(String[] args){
int list[] = new int[10];
int i, num = 0;
String input = “ “;
3.2. Save the program as List.java then compile your program until
no errors and warnings are reported.
3.3. Run your program.
3.4. Simulate and write what will be displayed on the screen.
Workbook
Logic and Programming Fundamentals 148
Example output:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Workbook
Logic and Programming Fundamentals 149
Workbook
Logic and Programming Fundamentals 150
4.2. Save then compile your program until no errors and warnings are
reported.
4.3. Run your program.
4.4. Simulate and write what will be displayed on the screen.
Example output:
List1 : 1 3 2 5 7 8 5 6 9 4
List2 : 2 1 4 3 2 1 4 2 0 2
List3 : 3 4 6 8 9 9 9 8 9 6
Workbook
Logic and Programming Fundamentals 151
6.1. Save then compile your program until no errors and warnings are
reported.
6.2. Run your program.
6.3. Simulate and write what will be displayed on the screen.
Workbook
Logic and Programming Fundamentals 152
7.2. Save then compile your program until no errors and warnings are
reported.
Workbook
Logic and Programming Fundamentals 153
Workbook
Logic and Programming Fundamentals 154
Name: _________________________________________________________
Subject Code & Schedule: _______________________________________
Course and Year: _______________________________________________
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 155
import java.io.*;
public class Table{
public static void main(String[] args){
int table[][] = new int[3][3];
int i, j, num = 0;
String input = “ “;
3.2. Save the program as Table.java then compile your program until
no errors and warnings are reported.
3.3. Run your program.
Workbook
Logic and Programming Fundamentals 156
Workbook
Logic and Programming Fundamentals 157
Workbook
Logic and Programming Fundamentals 158
4.2. Save then compile your program until no errors and warnings are
reported.
4.3. Run your program.
4.4. Simulate and write what will be displayed on the screen
Workbook
Logic and Programming Fundamentals 159
Workbook
Logic and Programming Fundamentals 160
6.1. Save then compile your program until no errors and warnings are
reported.
6.2. Run your program.
6.3. Simulate and write what will be displayed on the screen.
Workbook
Logic and Programming Fundamentals 161
Workbook
Logic and Programming Fundamentals 162
Example Output 1:
Input size of Magic Square: 3
Output:
8 1 6
3 5 7
4 9 2
Note that if you add all the rows it will be equal to 15. If you add all the
columns it is still equal to 15. And if you add numbers diagonally, it is still
equal to 15. That is why it is called the MAGIC SQUARE!
Example Output 2:
Input size of Magic Square: 5
Output:
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
HINT: There is a pattern in making a magic square. The pattern is also called
an algorithm. Find the algorithm and transform it into a Java code and you
can create any magic square with an ODD value for the size of its row and
column!
Workbook
Logic and Programming Fundamentals 163
7.2. Save then compile your program until no errors and warnings are
reported.
7.3. Run your program.
Workbook
Logic and Programming Fundamentals 164
Workbook
Logic and Programming Fundamentals 165
Name: _________________________________________________________
Subject Code & Schedule: _______________________________________
Course and Year: _______________________________________________
LEARNING OBJECTIVES:
INSTRUCTIONS:
HANDS-ON:
1. Log-on using your own individual account. Use your own username and
password.
2. Open your text editor.
3. Write your next Java program:
3.1. Write your next program by copying the source code shown below
to your text editor.
Workbook
Logic and Programming Fundamentals 166
Workbook
Logic and Programming Fundamentals 167
HINT: To call a method, indicate the name of the method preceded by the ()
symbol. User-define methods are methods you created , while pre-defined
functions are functions already inherent to the compiler.
Workbook
Logic and Programming Fundamentals 168
Workbook
Logic and Programming Fundamentals 169
int a;
int b;
twoParams(10, 20);
twoparams(x + 2, y * 10);
a = -2;
b = 22;
twoParams(a, b);
}
}
5.2. Save then compile your program until no errors and warnings are
reported.
5.3. Run your program.
5.4. Simulate and write what will be displayed on the screen.
Workbook
Logic and Programming Fundamentals 170
//Return value
a = 25;
b = 75;
}
}
Workbook
Logic and Programming Fundamentals 171
Workbook
Logic and Programming Fundamentals 172
REFERENCES
A. Books
Deitel, P.J., Deitel, H.M. (2007), Java: How to Program, 7th Edition,
Prentice Hall.
Bates, B., Sierra, K. (2005), Head First Java, 2nd Edition, O’ Reilly.
B. Websites
Workbook