0% found this document useful (0 votes)
90 views

Comprog Fundamentals Oblcbl Module 2nd 2022 2023 Java

This document provides an overview of the Java programming language. It discusses Java's history and design goals of being simple, secure, distributed, object-oriented, robust, portable, interpreted, and multithreaded. It also describes the Java Virtual Machine (JVM), Java programming environment, how Java programs are written using classes and methods, and fundamental concepts like compiling and executing Java code. Installation steps are provided for popular Java integrated development environments (IDEs) like Eclipse and NetBeans.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Comprog Fundamentals Oblcbl Module 2nd 2022 2023 Java

This document provides an overview of the Java programming language. It discusses Java's history and design goals of being simple, secure, distributed, object-oriented, robust, portable, interpreted, and multithreaded. It also describes the Java Virtual Machine (JVM), Java programming environment, how Java programs are written using classes and methods, and fundamental concepts like compiling and executing Java code. Installation steps are provided for popular Java integrated development environments (IDEs) like Eclipse and NetBeans.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

MODULE IN

Computer Fundamentals and


Programming(Lab)

COMPROG

Computer Science & Computer Applications Department

SCHOOL OF ACCOUNTANCY, MANAGEMENT, COMPUTING


AND INFORMATION STUDIES
1
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 4: Java Fundamentals

Programming Language

● a standardized communication technique for expressing instructions to a


computer. Like human languages, each language has its own syntax and
grammar
● enables a programmer to precisely specify what data a computer will act upon,
how these data will be stored/transmitted, and precisely what actions to take
under various circumstances
● set of rules, symbols, and special words used to construct programs or instructions
that are translated into machine language that can be understood by
computers
● include Java, Python, C, C++, C#, Objective-C, Visual Basic, Pascal, Delphi,
FORTRAN, and COBOL

About Java

A Brief History
● developed in early 1990s by James Gosling et. al. as the programming language
component of the Green Project at Sun Microsystems
● originally named Oak and intended for programming networked “smart”
consumer electronics
● launched in 1995 as a “programming language for the Internet”; quickly gained
popularity with the success of the World Wide Web
● currently used by around 5 million software developers and powers more than
2.5 billion devices worldwide, from computers to mobile phones
● Design Goals
o simple: derived from C/C++, but easier to learn
o secure: built-in support for compile-time and run-time security
o distributed: built to run over networks
o object-oriented: built with OO features from the start
o robust: featured memory management, exception handling, etc.
o portable: “write once, run anywhere''
o interpreted: “bytecodes” executed by the Java Virtual Machine
o multithreaded, dynamic, high-performance, architecture-neutral
o Bytecodes are the machine language understood by the Java virtual
machine

Java Platform

● Java Virtual Machine or JVM: a virtual machine, usually implemented as a


program, which interprets the bytecodes produced by the Java compiler; the
JVM converts the bytecodes instructions to equivalent machine language code
of the underlying hardware; compiled Java programs can be executed on any
device that has a JVM

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Java Programming Environment

● Java programming language specification


o Syntax of Java programs
o Defines different constructs and their semantics
● Java byte code: Intermediate representation for Java programs
● Java compiler: Transform Java programs into Java byte code
● Java interpreter: Read programs written in Java byte code and execute them
● Java virtual machine: Runtime system that provides various services to running
programs
● Java programming environment: Set of libraries that provide services such as
GUI, data structures, etc.
● Java enabled browsers: Browsers that include a JVM + ability to load programs
from remote hosts

How are Java Programs Written?


/* This program displays the message "Hello, World!" on the standard output device (usually
the screen). This code must be saved in a file named HelloWorld.java...
*/
// this is the declaration of the HelloWorld class...
public class HelloWorld {
// the main method defines the "starting point" of the execution
// of this program...
public static void main(String[] args) {
// this statement displays the program’s output...
System.out.println("Hello, World!");
} // end of method main...
} // end of class HelloWorld...

The following are video tutorials of some of the programming editors or Integrated
Development Environment (IDE) that can assist you in writing java programs. Follow the
steps in the installation of any of the following IDEs.
● Module 4: How to Install JDK and JCREATOR LE.mp4
● Module 4: How to Install Eclipse IDE w Java JDK 13 on Windows 10.mp4
● Module 4: How to Install NetBeans 11 IDE And Java JDK SE 14 on Windows 10 8
7.mp4

You may also choose to use some online java compilers enumerated below:
● https://replit.com/languages/java10
● https://www.jdoodle.com/online-java-compiler/
● https://www.onlinegdb.com/online_java_compiler
● https://www.w3schools.com/java/java_compiler.asp
● https://compiler.javatpoint.com/opr/online-java-compiler.jsp
● https://www.jgrasp.org/

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Fundamental Concepts

● Java programs are made up of one or more classes.


● A Java class is defined through a class declaration, which, aside from assigning a
name for the class, also serves to define the structure and behavior associated
with the class.
● By convention, Java class names start with an uppercase letter. Java programs
are case-sensitive.
● A Java source code file usually contains one class declaration, but two or more
classes can be declared in one source code file. The file is named after the class
it declares, and uses a .java filename extension.
● For a class to be executable, it must be declared public, and must provide a
public static method called main, with an array argument of type String.
● If a file contains more than one class declaration, only one of the classes can be
declared public, and the file must be named after the sole public class.
● The Java compiler (javac) is used to compile a Java source code file into a class
file in bytecode format. The resulting class file has the same name as the source
code file, but with a .class filename extension.
● The Java Virtual Machine (java) is used to execute the class file.

Java Comments

● Comments are notes written to a code for documentation purposes. Those texts
are not part of the program and do not affect the flow of the program.
Two types of comment
o Single Line Comment
Example:
//This is an example of a single line comment
o Multi-line Comment
Example:
/* This is an example of a
multiline comment enclosed by two delimiters
that starts with a /* and ends with a */
*/

Java Statements, Blocks and Expressions

● A statement is any complete sentence that causes some action to occur. A


valid Java statement must end with a semicolon.
Examples:
System.out.println(“Hello world”);
int k; int j = 10;
double d1, d2, k, squareRootTwo;
k = a + b – 10;
boolean p = ( a >= b );
squareRootTwo = Math.sqrt(2);

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● 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.
Example:
public static void main (String[] args)
{
System.out.println(“Hello”) ;
System.out.println(“World”) ;
}
● An expression is a value, a variable, a method, or one of their combinations that
can be evaluated to a value.
Examples:
int cadence = 0;
anArray[0] = 100;
8 >= x;
p || q ;
System.out.println("Element 1 at index 0: " + anArray[0]);
double squareRootTwo = Math.sqrt(2)

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.

Coding Standards

● There are certain rules for the naming of Java identifiers. Valid Java identifier
must be consistent with the following rules.
o An identifier cannot be a Java reserve word.
o An identifier must begin with an alphabetic letter, underscore (_), or a dollar
sign ($).
o If there are any characters subsequent to the first one, those characters must
be alphabetic letters, digits, underscores (_), or dollar signs ($).
o Whitespace cannot be used in a valid identifier.
o An identifier must not be longer than 65,535 characters.
● Also, there are certain styles that programmers widely used in naming variables,
classes and methods in Java. Here are some of them.
o Use lowercase letter for the first character of variables’ and methods’ names.
o Use pascal case for the class names (ex: LastnameResistor)
o Use camel case for the methods and variables (ex: subtractFunction,
radius1Ellipse)
o Compound words or short phrases are fine, but use uppercase letter for the
first character of the words subsequent to the first. Do not use underscore to
separate words.

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
o Use uppercase letter for all characters in a constant. Use underscore to
separate words.
o Apart from the mentioned cases, always use lowercase letter.
o Use verbs for methods’ names.
● Here are some examples for good Java identifiers.
o Variables: height, speed, filename, tempInCelcius, incomingMsg, textToShow.
o Constant: SOUND_SPEED, KM_PER_MILE, BLOCK_SIZE.
o Class names: Account, DictionaryItem, FileUtility, Article.
o Method names: locate, sortItem, findMinValue, checkForError.
 Based on Oracle Coding standard, there should be four spaces before
indentation.
● Not following these styles does not mean breaking the rules, but it is always good
to be in style!

Java Keywords

● Keywords are predefined identifiers reserved by java for specific purposes. You
cannot use keywords as names of variables, classes, methods, etc.

abstract default goto


assert do if package synchronized
boolean double implements private this
break else import protected throw
byte enum instanceof public throws
case extends int return transient
catch false interface short true
char final long static try
class finally native strictfp void
const float new super volatile
continue for null switch while

Primitive Data Types in Java

● four of them represent integers: byte, short, int, long


● two of them represent floating point numbers: float, double
● one of them represents characters: char
● and one of them represents boolean values: boolean

Numeric Primitive Data

● The difference between the various numeric primitive types is their size, and
therefore the values they can store:
Size Range of values that can be stored
Type
byte 1 byte −128 to 127
Integer short 2 bytes −32768 to 32767
int 4 bytes −2,147,483,648 to 2,147,483,647

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
long 8 bytes −9,223,372,036,854,775,808 to
9,223,372,036,854,755,807
Floating float 4 bytes −3.4e−038 to 3.4e+038
Point double 8 bytes −1.7e−308 to 1.7e+038

Boolean Primitive Data

● a boolean value represents a true or false condition


● the reserved words true and false are the only valid values for a boolean type
Example:
boolean done = false;
● boolean variable can represent any two states such as a light bulb being on or
off
Example:
boolean isOn = true;

Characters

● a char variable stores a single character


● character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n'
Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
● A character set is an ordered list of characters, with each character
corresponding to a unique number
● A char variable in Java can store any character from the Unicode character set
● The Unicode character set uses sixteen bits per character, allowing for 65,536
unique characters
● It is an international character set, containing symbols and characters from
many world languages
● The ASCII character set is older and smaller than Unicode, but is still quite popular
(in C programs)
● The ASCII characters are a subset of the Unicode character set, including:
Uppercase letters A, B, C, …
Lowercase letters a, b, c, …
Punctuation period, semi-colon, comma, …
Digits 0, 1, 2, …
Special symbols &, |, \, …
Control characters carriage return, tab, …

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Character Strings

● A string of characters can be represented as a string literal by putting double


quotes around the text:
Examples:
"This is a string literal."
"123 Main Street"
"X"
● Note the distinction between a primitive character ‘X’, which holds only one
character, and a String object, which can hold a sequence of one or more
characters
● Every character string is an object in Java, defined by the String class
Separators

are symbols that indicate the division and arrangement of groups of code. The

structure and function of code is generally defined by the separators. The
separators used in Java are as follows:
o parentheses ( )
- Used to define precedence in expressions, to enclose parameters in
method definitions, and enclosing cast types
o braces { }
- Used to define a block of code and to hold the values of arrays.
o brackets [ ]
- Used to declare array types.
o semicolon ;
- Used to separate statements.
o comma ,
- Used to separate identifiers in a variable declaration and in
the for statement.
o period .
- Used to separate package names from classes and subclasses and to
separate a variable or a method from a reference variable.
Variables

● a variable is a name for a location in memory


● a variable must be declared by specifying the variable's name and the type of
information that it will hold.
Example:

data type variable name

int total;

● multiple variables can be created in one

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Examples:
int count, temp, result;
double pi, average;
char cc, mm, tk;

Variable Initialization
● assigning a value to a variable for the first time
● a variable can be given an initial value in the declaration with an equal sign
Example:
int sum = 0;
int base = 32, max = 149;
● when a variable is referenced in a program, its current value is used
example:
int keys = 88;
System.out.println(“A piano has ”+ keys + “ keys”);
● prints as:
A piano has 88 keys

Assignment Statement
● an assignment statement changes the value of a variable
● the equals sign is also the assignment operator
Example:

● the expression on the right is evaluated and the result is stored as the value of the
variable on the left
● the value previously stored in total is overwritten
● you can only assign a value to a variable that is consistent with the variable's
declared type

Constants
● a constant is an identifier that is similar to a variable except that it holds the same
value during its entire existence
● as the name implies, it is constant, not variable
● in Java, we use the reserved word final in the declaration of a constant
example:
final int MIN_HEIGHT = 69;
● any subsequent assignment statement with MIN_HEIGHT on the left of the =
operator will be flagged as an error
Constants are useful for three important reasons
o first, they give meaning to otherwise unclear literal values
 for example, NUM_STATES means more than the literal 50
o second, they facilitate program maintenance
 if a constant is used in multiple places and you need to change its
value later, its value needs to be updated in only one place
o third, they formally show that a value should not change, avoiding
inadvertent errors by other programmers

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
The println Method
● the System.out object represents a destination (the monitor screen) to which we
can send output
System.out.println ("Whatever you are, be a good one.");

Object Information provided to the method


Method
(Parameters)
name

The print Method

● the System.out object provides another method


● the print method is similar to the println method, except that it does not start the
next line
● therefore any parameter passed in a call to the print method will appear on the
same line
System.out.print (“Three… ”);
System.out.print (“Two… ”);
prints as: Three… Two…

String Concatenation

● the string concatenation operator (+) is used to append one string to the end of
another
"Peanut butter " + "and jelly"
● it can also be used to append a number to a string
● a string literal cannot be broken across two lines in a program so we must use
concatenation
System.out.println(“The following facts are for your ” + “extracurricular edification”);
● the + operator is also used for arithmetic addition
● the function that it performs depends on the type of the information on which it
operates
● if both operands are strings, or if one is a string and one is a number, it performs
string concatenation
● if both operands are numeric, it adds them
● the + operator is evaluated left to right, but parentheses can be used to force
the order
System.out.println(“24 and 45 concatenated: ” + 24 + 45);
prints as: 24 and 45 concatenated: 2445
● the + operator is evaluated left to right, but parentheses can be used to force
the order
System.out.println(“24 and 45 added: ” + (24 + 45));
Then concatenation Addition is
is done done first
prints as: 24 and 45 added: 69

10

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Escape Sequences

● What if we want to include the quote character itself?


● The following line would confuse the compiler because it would interpret the two
pairs of quotes as two strings and the text between the strings as a syntax error:
System.out.println ("I said "Hello" to you.");

● An escape sequence is a series of characters that represents a special character

● Escape sequences begin with a backslash character (\)


System.out.println ("I said \"Hello\" to you.");

● Some Java Escape Sequences

Escape Sequence Description


\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.

● Example
System.out.println(“Roses are red,\n\tViolets are blue”);

Prints as:
Roses are red,
Violets are blue

● To put a specified Unicode character into a string using its code value, use the
escape sequence: \uhhhh where hhhh are the hexadecimal digits for the
Unicode value
Example: Create a string with a temperature value and the degree symbol:
double temp = 98.6;
System.out.println(“Body temperature is ” + temp + “ \u00b0F.”);

Prints as:
Body temperature is 98.6 ºF.

11

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 5: Java Operators, Flowcharting Symbols and Sample Programs

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 of the operator to
evaluate first in case multiple operators are used in one statement.

Arithmetic Operators

Operator Operation Example


2+4 =6
+ Addition 2 + 2.4 = 4.4
5.2 + 7.3 = 13.5
45 – 90 = - 45
- Subtraction 2.9 – 2.5 = 0.399999999
2.9 – 2 = 0.8999999999
2 * 7 = 14
* Multiplication 2.9 * 2 = 5 .8
2.9 * 2.1 = 6.09
2/7=0
/ Division 2.9 / 2 = 1.45
2.1 /2.9 = 0.7241379310
2%7=2
% Modulus (Remainder) 2.9 % 2 = 0.8999999999
2.9 % 2.1 = 0.799999998

Note:
When evaluating the mod operator with negative integer operands, the answer
always takes the sign of the dividend.

Illustration:
-34 % 5 = -4
34 %-5 = 4
-34 %-5 = -4
34 % 5 = 4

Increment/Decrement Operators
● Aside from basic arithmetic operators, Java also includes a unary increment
operator and unary decrement operator.
o Increment Operator (++)
- increases the value of a variable by 1
Example:
int count = 3;
count = count + 1;

12

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
// the above statement may be written as the one
//shown below.
count++;

o Decrement Operator (--)


- decreases the value of a variable by 1
Example:
int count = 3;
count = count - 1;
// the above statement may be written as the one
//shown below.
count--;

Relational Operators
● Relational operators compare two values and determine the relationship
between those values.
● The outputs of evaluation are the boolean values true or false.
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to

Logical Operators
● Logical operators have Boolean operands that yield a Boolean result.
Operator Description Illustration
True && True = True
Logical AND
True && False = False
&& ● Returns True if all of its boolean
False && True = False
operands are True, False if otherwise.
False && False = False
Logical OR True||True = True
● Returns True if at least one of its True||False = True
||
Boolean operands are True, otherwise False||True = True
False False||False = False
Logical NOT !True = False
!
● Reverses the value of its operand. !False = True

Java Operator Precedence Table


Precedence Operator Type Associativity
() Parentheses
15 [] Array subscript Left to Right
· Member selection

13

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
*Larger number means higher precedence.
For more information on operator precedence, watch Module 5 Operator Precedence.

14

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Creating a Java Program

Simple Calculation

● Numeric values can be used in calculation using arithmetic operators, such as


add (+), subtract (-), multiply (*), divide (/), and modulo (%). An assignment
operator (=) is used to assign the result obtained from the calculation to a
variable. Parentheses are used to define the order of the calculation.
● The following program computes and prints out the average of the integers from
1 to 10.

● In the above example, the statement in line 5 declares two variables that are
used to store floating point numbers. In line 6, the values from 1.0 to 10.0 are
summed together using the + operator and the resulting value is assigned to
sum. In line 7, the value of sum is divided by 10 which to obtain their average.
The statement in line 8 just prints the result on screen.

The Program Development Life Cycle

- Programmers do not sit down and start writing code right away when trying to make
a computer program. Instead, they follow an organized plan or methodology that
breaks the process into a series of tasks.
Here are the basic steps in trying to solve a problem on the computer:
In order to understand the basic steps in solving a problem on a computer, let us
define a single problem that we will solve step-by-step as we discuss the problem
solving methodologies in detail.

1. Problem Definition
● A programmer is usually given a task in the form of a problem. Before a program
can be designed to solve a particular problem, the problem must be well and
clearly defined first in terms of its input and output requirements.
● A clearly defined problem is already half the solution. Computer programming
requires us to define the problem first before we even try to create a solution.
Let us now define our example problem:
“Create a program that will determine the number of times a name
occurs in a list.”
2. Problem Analysis
● After the problem has been adequately defined, the simplest and yet the most
efficient and effective approach to solve the problem must be formulated.

15

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Usually, this step involves breaking up the problem into smaller and simpler sub-

problems.
3. Algorithm Design and Representation (flowchart)
● Once our problem is clearly defined, we can set to finding a solution. In
computer programming, it is normally required to express our solution in a step-
by-step manner.
● An Algorithm is a clear and unambiguous specification of the steps needed to
solve a problem. It may be expressed in either Human Language (English,
Tagalog), through a graphical representation like flowchart.
● Now given that the problem is defined, how do we express our general solution
in such a way that it is simple yet understandable?
Example Problem:
Determine the number of times a name occurs in a list.
Input Program:
list of names, name to look for
Output Program:
the number of times the name occurs in a list

16

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowcharting Symbols and Their Meanings

Symbol Name Meaning


Process Represents the process of executing a defined operation or
Symbol groups of operations that results in a change in value, form,
or location of information. Also functions as the default
symbol when no other symbol is available.
Input/Output Represents as an input/output function, which makes data
Symbol available for processing (input) or displaying (output) of
processed information.
Flowline Represents the sequence of available information and
Symbol executable operations. The lines connect other symbols, and
the arrowheads are mandatory only for right-to-left and
bottom-to-top flow.
Decision Represents a decision that determines which of a number of
Symbol alternative paths is to be followed.

Terminal Represents the beginning and the end, or a point of


Symbol interruption or delay in program.

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

4. Coding and Debugging

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

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

● Two Types of Program Errors

● Compile-Time Error

- Occur if there is a syntax error in the code. The compiler will detect the
error and the program won’t even compile. At this point, the programmer
is unable to form an executable that a user can run until errors are fixed.
Forgetting a semi-colon at the end of a statement or misspelling a certain
command, for example, is a compile-time error.

17

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Runtime Error

- Compilers aren’t perfect and so can’t catch all errors at compile time. This
is especially true for logic errors such as infinite loops. This type of error is
called runtime error. For example, the actual syntax of the code looks
okay. But when you follow the code’s logic, the same piece of code
keeps executing over and over again infinitely so that it loops.

Representing Algorithms Using Flowcharts

● To create a computer program that works, one need not only the knowledge
about the rules and syntaxes of a programming language but also a procedure
or a process that is used to accomplish the objectives of that program. Such a
procedure is called an algorithm. Usually, before creating a computer program,
an algorithm is developed based on the objective of the program before the
source code is written. An algorithm could be as simple as a single command.
More often than not, they are more complex.

● Representing an algorithm using diagrams is useful both in designing an


algorithm for a complicate task and for expressing the algorithm to other people.
More than one way of creating such diagrams have been created and
standardized. One of the simplest ways is to use a flowchart. Although
representing an algorithm using a flowchart might not be an ideal way for some
situations, it is the most intuitive and should be sufficient for beginners of
computer programming.

● A flowchart needs a starting point of the program it represents and one or more
terminations. Steps or commands involved in the program are represented using
rectangles containing textual descriptions of the corresponding steps or
commands. These steps as well as the starting and terminating points are
connected together with line segments in which arrows are used for determining
the order of these steps. Shapes are typically placed from the top of the chart to
the bottom according to their orders. The starting and terminating points are
represented using oval shapes. Different shapes apart from the two shapes
already mentioned are defined so that they imply some specific meanings. The
following flowchart shows an algorithm of a computer program that prints out
the average of the integers from 1 to 10.

You can learn further about flowcharts by watching the Module 5 Flow Charting video.

18

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 6: Getting Program Input and Sequence Problems

Start

double ave,
Starting Point sum

sum = 1.0 + 2.0 + …+ 10.0 Process / Action

ave = sum / 10

Display / Output

Termination ave

End

● Java provides different ways to get input from the user, the BufferedReader
Class, the Console Class and the Scanner Class. The Scanner Class is presumably
the most favoured technique to take input. The primary reason for the Scanner
class is to parse primitive composes and strings utilizing general expressions, in
any case, it can utilize to peruse contribution from the client in the order line. In
order to use the object of Scanner, the programmer need to
import java.util.Scanner package.
● //this line will import the Scanner Class
import java.util.Scanner;
● //create an object of the Scanner
Scanner kbd = new Scanner(System.in);
● //take input from the user
int num = kbd.nextInt();

Example: A java program that allows the user to input two numbers. The program
calculates the sum and displays it.

19

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
//import the Scanner Class
import java.util.Scanner;
public class sumOfTwoNumbers {

public static void main(String[] args) {


//set up the program to be ready to get keyboard
// input by creating the scanner object
Scanner kbd = new Scanner(System.in);

//output a prompt message


System.out.print("Enter a number: ");

//read user input and store the input in variable num1


int num1 = kbd.nextInt();

//output a prompt message


System.out.print("Enter another number: ");

//read user input and store the input in variable num2


int num2 = kbd.nextInt();

//formula to add the two numbers


int sum = num1+num2;

//display the sum


System.out.println("The sum is "+sum);
}
}

For additional information about the Scanner class: watch


Module 6: Read Integers and Doubles from Keyboard with Scanner.mp4

Some commonly used Math class methods:


Math.PI
The double value that is closer than any other to pi (i.e 3.14159), the ratio of the
circumference of a circle to its diameter.
Math.pow(double a, double b)
Returns (ab) the value of the first argument raised to the power of the second argument.
Math. sqrt(double a)
Returns the correctly rounded positive square root of a double value (the positive square
root of a).

For additional information about the Math class: watch


Module 6 - Powers and Square Roots (Math Functions)

20

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Problems for Program Development: Solve the following Sequence Programs

1. Filename: PipeProblem_FamilyName
Create a flowchart and a java program
that will input the outside and the
inside diameter (outDia, inDia) of a
pipe. Calculate and print the thickness
(T) of the wall of the pipe.
Formula:

2. Filename: TemperatureProblem_FamilyName
Create a java program that will read a
temperature in degrees Fahrenheit (F),
output in degrees Centigrade (C).
Formula to convert degrees Centigrade to
degrees Celcius:

3. Filename: AngleToRadianProblem_FamilyName
Create a flowchart and a java program
that will read an angle expressed in
degrees (deg), minutes (min) and seconds
(sec), output in radians (rad).
Formula:

21

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
4. Filename: PowerLossProblem_FamilyName
Create a java program that will read a
current (I_AMP) flowing through a cable
and the resistance (R_OHM) of the cable,
compute and output the power loss
(P_WATT) through the cable.
Formula:
Sample Output:

5. Filename: ChangeProblem_FamilyName
Create a flowchart and a java program that
will input the amount of purchase which is
less than P100.00. The program will
calculate the change of P100.00 given by
the customer with the following breakdown:
P 50.00 - _______________;
P 20.00 - _______________;
P 10.00 - _______________;
P 5.00 - _______________;
P 1.00 - _______________;
Note: Purchases are all in pesos. No
centavos.
Formula Hint: Apply the concept of
modulus operator

6. Filename: TriangleProblem_FamilyName
If a, b and c represent the three sides of a triangle, then the area of the triangle is:
where:
Also the radius of the largest inscribed circle is given by:
and the radius of the smallest circumscribed circle is:

Inscribed Circle Circumscribed Circle

22

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Create a java program that will input the three sides of a triangle. Calculate and output
the area of the triangle, the area of the largest inscribed circle, and the area of the smallest
circumscribed circle given a value for a, b and c.

Sample Output:

23

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 7: Java Control Structures: Decision Control Structure

● A programming language uses control statements to cause the flow of


execution to advance and branch based on changes to the state of a program.
Java’s program control statements can be put into the following categories:
selection, iteration, and jump. Selection statements allow your program to
choose different paths of execution based upon the outcome of an expression
or the state of a variable. Iteration statements enable program execution to
repeat one or more statements (that is, iteration statements form loops). Jump
statements allow your program to execute in a nonlinear fashion. All of Java’s
control statements are examined here.

Java’s Selection Statements


● Java supports two selection statements: if and switch. These statements allow
you to control the flow of your program’s execution based upon conditions
known only during run time. You will be pleasantly surprised by the power and
flexibility contained in these two statements.

If Statement
● The if statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if
statement:

if (condition) { Flowchart View of if-else


if (condition)
statement1;
or statement2;
statement1;

else true conditio
false
statementN; n

}
statement2;
else { if true statements if false statements
statement1;
statement2;

statementN;
}

● Here, each statement may be a single statement or a compound statement


enclosed in curly braces (that is, a block). The condition is any expression that
returns a boolean value. The else clause is optional.
● The if works like this: If the condition is true, then statement1 is executed.
Otherwise, statement2 (if it exists) is executed. In no case will both statements be
executed. For example, consider the following:
int a, b;
if(a < b) Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In
a = 0; no case are they both set to zero. Most often, the expression used to control
else the if will involve the relational operators.
b = 0;

24

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Nested ifs
● A nested if is an if statement that is the target of another if or else. Nested ifs are
very common in programming. When you nest ifs, the main thing to remember is
that an else statement always refers to the nearest if statement that is within the
same block as the else and that is not already associated with an else. Here is
an example:
if(i == 10) {
if(j < 20)
a = b;
if(k > 100)
c = d;
else
a = c;
}else
a = d; // this else refers to the if(i == 10)

● As the comments indicate, the final else is not associated with if(j<20) because it
is not in the same block (even though it is the nearest if without an else). Rather,
the final else is associated /* Demonstrate if-else-if statements. The program below
with if(i==10). The inner else will determine which season is the 4th month (April) */
refers to if(k>100) because it is public class SeasonProblem {
the closest if within the same public static void main(String args[]) {
block. int month = 4; // April
String season;
The if-else-if Ladder if(month == 12 || month == 1 || month == 2)
● A common programming season = "Winter";
construct that is based upon a else
sequence of nested ifs is the if(month == 3 || month == 4 || month == 5)
season = "Spring";
if-else-if ladder. It looks like this:
else
if(condition)
if(month == 6 || month == 7 || month == 8)
statement; season = "Summer";
else else
if(condition) if(month == 9 || month == 10 || month == 11)
statement; season = "Autumn";
else else
if(condition) season = "Bogus Month";
statement; System.out.println("April is in the " + season + ".");
... }
else }
statement;
● The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions is true,
then the final else statement will be executed. The final else acts as a default
condition; that is, if all other conditional tests fail, then the last else statement is
performed. If there is no final else and all other conditions are false, then no

25

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
action will take place. Here is a program that uses an if-else-if ladder to
determine which season a particular month is in.
Flowchart of the if-else-if problem

Here is the output produced by the program:

For additional information about java’s selection statements: watch the following
videos
● Module 7: If Statement.mp4
● Module 7: If-else Statement.mp4
● Module 7: The If-Else-If Ladder.mp4
● Module 7: Nested IF Statements.mp4

Problems for Program Development: Solve using Decision Control Structure (if)

1. ThreeNumbersProblem_FamilyName
Create a flowchart and a java program that reads three distinct numbers (X,Y,Z). Determine
and output the following:
a) highest number (HN)
b) middle number (MN)
c) smallest number (SN)
d) the numbers in ascending order
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):

Enter x: 4 Enter x: 1 Enter x: 6


Enter y: 2 Enter y: 8 Enter y: 2
Enter z: 9 Enter z: 5 Enter z: 4
The Highest Number is 9 The Highest Number is 8 The Highest Number is 6
The Median Number is 4 The Median Number is 5 The Median Number is 2
The Lowest Number is 2 The Lowest Number is 1 The Lowest Number is 4
Ascending Order: 2 4 9 Ascending Order: 1 5 8 Ascending Order: 2 4 6
26

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
2. YearProblem_FamilyName
A leap year is a year divisible by 4 unless it is a century year, in which case it must be
divisible by 100. Create a java program that reads a year and output a message whether the
year is a leap year, century year or ordinary year.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):

Enter a year: 2012 Enter a year: 2018 Enter a year: 2100


It is a leap year. It is an ordinary year. It is a century year.

3. GradeProblem_FamilyName
A professor displays remarks for numeric grades in the following way:
Grade Remarks
93 – 99 Excellent
87 – 92 Very Good
80 – 86 Good
70 – 79 Fair
65 - 69 Poor
Using if, create a flowchart and a java program that reads a numeric grade and output the
equivalent remarks.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):

Enter a grade: 97 Enter a grade: 79 Enter a grade: 102


Excellent. Fair. Invalid Input.

4. ParkingFeeProblem_FamilyName
Parking charge per hour at SMBC underground parking is as follows:
P 35.00 - minimum charge for 4 hours parking or less,
P 15.00/hr. - additional charge in excess of 4 hours parking,
P 250.00 - maximum charge.
Create a java program that reads the number of hours a vehicle was parked. Calculate and
output the parking charge.
(Note: Inputs should be integers only)
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):

Enter number of hours: 3 Enter number of hours: 6 Enter number of hours: 23


Parking Fee: P 35 Parking Fee: P 65 Parking Fee: P 250

27

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
5. ElectricBillProblem_FamilyName
The ABC Electric Company bases its electricity charges on two rates. Customers are charged
P30.12 per kilowatt-hour (KWH) for the first 400 KWH used in a month, and P25.23 for all
KWH used thereafter. Create a flowchart and a java program that reads an electric
consumption and output the amount to be charged to the customer.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):

Enter electric consumption: 331 Enter electric consumption: 403


Electric bill is P9969.72 Electric bill is P12123.69

Switch

● The switch statement is Java’s multiway branch statement. It provides an easy


way to dispatch execution to different parts of your code based on the value of
an expression. As such, it often provides a better alternative than a large series of
if-else-if statements. Here is the general form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

● The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the
expression. (An enumeration value can also be used to control a switch
statement. Each case value must be a unique literal (that is, it must be a
constant, not a variable). Duplicate case values are not allowed.
● The switch statement works like this: The value of the expression is compared with
each of the literal values in the case statements. If a match is found, the code
sequence following that case statement is executed. If none of the constants
matches the value of the expression, then the default statement is executed.
However, the default statement is optional. If no case matches and no default is
present, then no further action is taken.
● The break statement is used inside the switch to terminate a statement
sequence. When a break statement is encountered, execution branches to the

28

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
first line of code that follows the entire switch statement. This has the effect of
“jumping out” of the switch.
● The break statement is optional. If you omit the break, execution will continue on
into the next case. It is sometimes desirable to have multiple cases without break
statements between them.
● The following are java programs that uses a switch statement:

/*Switch Example2. The program determines the


//Switch Example1 number of days in a month considering the leap year. */
// An improved version of the season program. public class MonthEnd {
public class SeasonProblemUsingSwitch { public static void main(String[] args) {
public static void main(String args[]) { int month = 2;
int month = 4; int year = 2000;
String season; int numDays = 0;
switch (month) { switch (month) {
case 12: case 1:
case 1: case 3:
case 2: case 5:
season = "Winter"; case 7:
break; case 8:
case 3: case 10:
case 4: case 12: numDays = 31;
case 5: break;
season = "Spring"; case 4:
break; case 6:
case 6: case 9:
case 7: case 11: numDays = 30;
case 8: break;
season = "Summer"; case 2:
break; if ( ((year % 4 == 0) && !(year % 100 == 0))
case 9: || (year % 400 == 0) )
case 10: numDays = 29;
case 11: else
season = "Autumn"; numDays = 28;
break; break;
default: default:
season = "Bogus Month"; System.out.println("Invalid month.");
} break;
System.out.println("April is in the " + season + "."); }
} System.out.println("Number of Days = " + numDays);
} }
}

For additional information about the switch statement: watch


Module 7: The Switch Statement.mp4

Problems for Program Development: Solve using the Switch Statement

1. GradeProblemUsingSwitch_FamilyName
A professor converts numeric grades to letter grades in the following way:
Grade Letter Grade
93 – 99 A
87 – 92 B

29

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
80 – 86 C
70 – 79 D
65 - 69 E
Using switch, create a java program that reads a numeric grade and output the equivalent
letter grade. There should be an error message if the grade entered is invalid.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):

Enter a grade: 97 Enter a grade: 79 Enter a grade: 102


Letter Grade: A Letter Grade: D Invalid Input.

2. CommodityCodeProblemUsingSwitch_FamilyName
A certain store has the following scheme:
Commodity Code:
1 - commodities are discounted by 15%
2 - commodities are taxed by 12%
3 - commodities are charged as priced
Using switch, create a program that reads a commodity code, quantity of the commodities
bought and the unit price and output the amount to be paid by the customer.
Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are calculated
and outputted by the program):
Enter commodity code: 1
Enter commodity code: 6 Enter quantity of commodity: 2
Invalid Code Enter unit price: 53.25
Amount to be paid is P90.53
Enter commodity code: 2
Enter quantity of commodity: 2 Enter commodity code: 3
Enter unit price: 53.25 Enter quantity of commodity: 4
Amount to be paid is P119.28 Enter unit price: 53.25
Amount to be paid is P213

Module 8: Java Control Structures: Iteration Control Structure

● Java’s iteration statements are for, while, and do-while. These statements create
what we commonly call loops. As you probably know, a loop repeatedly
executes the same set of instructions until a termination condition is met.

For Loop
● The for loop operates as follows. When the loop first starts, the initialization portion
of the loop is executed. Generally, this is an expression that sets the value of the
loop control variable, which acts as a counter that controls the loop. It is
important to understand that the initialization expression is only executed once.

30

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Next, condition is evaluated. This must be a Boolean expression. It usually tests
the loop control variable against a target value. If this expression is true, then the
body of the loop is executed. If it is false, the loop terminates.
● Next, the iteration portion of the loop is executed. This is usually an expression
that increments or decrements the loop control variable. The loop then iterates,
first evaluating the conditional expression, then executing the body of the loop,
and then executing the iteration expression with each pass. This process repeats
until the controlling expression is false.
Sample Program

public class ForExample{


public static void main(String args[]){
//for loop example
for(int i=1;i<=10;i++){
System.out.println(“Number ” +i);
}
}
}

A java program using for loop that displays the numbers from 1 to 10;

For Loop Flowchart Diagram

For additional information about the for loop: watch Module 8: The FOR Loop.mp4

initialization

for(initialization; condition; iteration)


{
//for loop body/statements;
}
condition?
false

true

statement/s;

More For Loop Examples

FileName: Series3Problem_FamilyName

31

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Create a java program that will output the numbers 1 4 7 ... between 1 and 150.

Depicted below is a sample output when the program is executed:

//no need to import the Scanner Class since there in no input in this program
public class Series3_CABS {
public static void main(String[] args) {
//initial value of x = 1
//this loop is terminated when the value of x is greater than 150
//value of the counter increases by 3
for(int x = 1; x<=150; x=x+3){
//output the value of x while x<=150
System.out.print(x+" ");
}
}
}

Flowchart Diagram of Series3 using For Loop

Start

x=1

False True
x<=150

Print x
End

x=x+3

32

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
FileName: FactorialProblem_FamilyName

Create a java program that reads a number and calculate and output its
factorial.

Depicted below are sample outputs when the program is executed (the items in bold
characters are inputted by the user, while the items in bold italic characters are
calculated and outputted by the program):
Input a number: 8 Input a number: 4
The factorial of 8 is 40320 The factorial of 4 is 24

Input a number: 10 Input a number: 5


The factorial of 10 is 3628800 The factorial of 5 is 120

//the type of loop used here is for


//research on the definition of Factorial
import java.util.Scanner;
public class FactorialProblem_FamilyName {
public static void main(String[] args) {
Scanner ram = new Scanner(System.in);
//input a number(num) an determine its factorial
System.out.print("Input a number: ");
int num = ram.nextInt();
//initial value of F is 1
int F = 1;
//initial value of the counter x is 1
//when x is greater than the value of num
//then the loop is terminated
for(int x = 1; x<=num; x++){
//formula to determine the factorial as the value of x increases
F = F*x;
}
//the following statement will be executed once the loop is terminated
System.out.println("The factorial of "+num+" is "+F);

}
}

33

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowchart Diagram for Factorial Using For Loop

Start

num

x=1
F=1

False

x<=num
True

F=F*x
Print num, F

x++
End

While Loop
● The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop/statements
}

34

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition becomes
false, control passes to the next line of code immediately following the loop. The
curly braces are unnecessary if only a single statement is being repeated.
Sample Program:

public class WhileLoopExample


{
public static void main(String args[])
{
int num = 0;
System.out.println("Let's count to 10!");
while(num < 10)
{
num = num + 1;
System.out.println("Number: " + num);
}
System.out.println("We have counted to 10! Hurray! ");
}
}

While Loop Flowchart Diagram

initialization
while (condition)
{
//while loop body/statements;
}

condition?
False

True

Statement/s;

For additional information about the while loop: watch Module 8: The While Loop.mp4

More While Loop Examples

Filename: Series2Problem_FamilyName

35

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Output the set of numbers in the series 1 2 4 7 11 16 … until 211 is reached.
Depicted below is a sample output when the program is executed:

//type of loop used is WHILE


public class Series2_CABS {
public static void main(String[] args) {
//initialize the value of x
int x = 1;
//initialize the value of the counter n
int n = 1;
//this is the termination test
//the loop is terminated when the value of x is greater than 211
while(x<=211){
//the following block of statements are executed while the termination test is true
//display the value of x
System.out.print(x+" ");
//formula to display the series
//the previous value of x is added to the increasing value of n
x = x+n;
//increment the counter
n++;

}
}
}
Flowchart Diagram of Series2 using While Loop

36

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Filename: SphereProblem_FamilyName

Create a java program that will calculate and output the volume and area of spheres using the
formula:
V = (4PiR3)/3 A = 4PiR2
where R is the radius of the sphere is from 1 to 20.
Depicted below is a sample output when the program is executed:

//no need to import the Scanner Class since no input is required


public class Sphere {
public static void main(String[] args) {
System.out.print("Radius Area Volume");
//declare the value of pi as constant
final double PI = 3.1416;
//initialize the value of radius (r)
int r = 1;
//this is the termination test/condition. the body of the loop is executed while r<=20
//at r = 21, the loop is terminated
while(r<=20){
//formula to compute the area
double a = 4*PI*Math.pow(r,2);
//formula to compute the volume
double v = 4*PI*Math.pow(r,3)/3.0;
//display the radius (r), area (a) and volume (v)
System.out.printf("\n%2d \t%10.4f\t%10.4f",r,a,v);
//increment r
r++;
}
}}

37

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowchart Diagram for Sphere Using While Loop

Start

r=1
pi = 3.1416

False True
r<=20

a = 4*pi*r2
v = 4*pi*r3/3.0
End

Print r,v,a

r++

Do-while Loop
● If the conditional expression controlling a while loop is initially false, then the
body of the loop will not be executed at all. However, sometimes it is desirable to
execute the body of a loop at least once, even if the conditional expression is
false to begin with. In other words, there are times when you would like to test
the termination expression at the end of the loop rather than at the beginning.
Fortunately, Java supplies a loop that does just that: the do-while. The do-while
loop always executes its body at least once, because its conditional expression is
at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);

38

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Java’s loops, condition must be a
Boolean expression.

Do-while Loop Flowchart Diagram

initialization
do
{
statement block; statement block;
}
while (condition);

true

condition?

false

For additional information about do-while loop: watch

 Module 8: The Do-While Loop.mp4

 Module 8: Java printf Method - Displaying data using System.out.printf.mp4

 Module 8: Print Formatting printf() Conversion Type Characters (Java).mp4

39

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Sample Program

import java.util.Scanner;
public class DoWhileMenuSelection {
public static void main(String[] args) {
// Using a do-while to process a menu selection
Scanner ram = new Scanner(System.in);
int choice;
do {
System.out.println("Help on. Please choose a number:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.print("Choose a number: ");
choice = ram.nextInt();
} while( choice < 1 || choice > 5);
switch(choice) {
case 1:
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case 2:
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence"); In the program, the do-
System.out.println(" break;"); while loop is used to
System.out.println(" // ..."); verify that the user has
System.out.println("}"); entered a valid choice.
break;
case 3: If not, then the user is
System.out.println("The while:\n"); prompted to enter
System.out.println("while(condition) another. Since the menu
statement;"); must be displayed at
break; least once, the do-while
case 4:
System.out.println("The do-while:\n"); is the perfect loop to
System.out.println("do {"); accomplish this.
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case 5:
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
} }}

40

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
More Do While Loop Examples

Filename: ObjectProblem_FamilyName
An object falling from rest in a vacuum falls 16 feet on the first second, 48 feet on
the 2nd second, 80 feet on the third second, 112 feet the 4th second and so on.
Create a java program that will output the distance traveled by the object after
15 seconds.
Depicted below is a sample output when the program is executed:

//no need to import the Scanner class since there is no input


public class Object_CABS {
public static void main(String[] args) {
//s - second, d - distance
//@s = 1 initial distance is 16
int s = 1, d = 16;
do{
//remove the (//)comment if you want to check the distance travelled every after a second
//System.out.printf("\n@%2d, the distance travelled is %3d",s,d);
//formula to solve for the distance since it increases 32ft every second
d = d+32;
//increment s by 1 (last value of s before the loop terminates is 15)
s++;
}
//the loop terminates when s = 15 or more
while(s<15);
//display the total distance travelled which is the latest value of d at s second
System.out.printf("@%2d seconds, the distance travelled is %3d",s,d);
}
}
Flowchart Diagram for Object Using Do While

41

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Filename: BounceProblem_Familyname
A ball is dropped from an initial height of 50 feet. If the ball bounces 2/3 of the
previous height, make a program that will calculate and print the total distance
traveled by the ball after the 10th bounce.
Depicted below is a sample output when the program is executed:

//no need the import the Scanner Class since there is no input
public class Bounce_CABANILLA {
public static void main(String[] args) {
//in order to better understand this program, please try to solve is manually
double d = 50, dist = 50.0;
int b = 1;
do{
//the ball bounces 2/3 of the previous height
d = (2.0/3.0)*d;
//if the ball will bounce it goes up and down so distance travelled is doubled
dist = dist + 2*d;
//counter/number of bounce
b++;
}
//the loop is terminated after the 10th bounce
while(b<=10);
//the 1/2 of the distance on the 10th bounce is subtracted
dist = dist-d;
//output the total distance travelled
System.out.println("@ b = "+(b-1)+ "the distance travelled by the ball is "+dist);
}
}

42

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Flowchart Diagram for Bounce using DoWhile

Start

d = 50
dist = 50
b=1

d = (2.0/3.0)*d
dist = dist + 2*d
b=b+1

False b<=10 True

dist = dist - d

Print b,dist

End

Java For Loop vs While Loop vs Do While Loop

Comparison for loop while loop do-while loop


The Java for loop is a The Java while loop is The Java do while
control flow statement that a control flow loop is a control flow
iterates a part of the statement that executes statement that
programs multiple times. a part of the program executes a part of the
Introduction repeatedly on the basis program at least once
of given boolean and the further
condition. execution depends
upon the given
boolean condition.

43

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
If the number of iterations is If the number of If the number of
fixed, it is recommended to iterations is not fixed, iterations is not fixed
use a for loop. it is recommended to and you must have to
When to use use a while loop. execute the loop at
least once, it is
recommended to use
the do-while loop.
for(init;condition;increment) while(condition){ do{
{ //code to be executed //code to be executed
Syntax
// code to be executed } }while(condition);
}
//for loop //while loop //do-while loop
for(int i=1;i<=10;i++){ int i=1; int i=1;
System.out.println(i); while(i<=10){ do{
Example
} System.out.println(i); System.out.println(i);
i++; i++;
} }while(i<=10);
while(true){ do{
Syntax for for(;;){ //code to be executed //code to be executed
infinite loop //code to be executed } }while(true);
}

Problems for Program Development: Repetition Control Structure (while, do-while, for)

1. FileName: ReverseProblem_FamilyName (Use While Loop)


Create a flowchart and a java program that reads a number (NUM) and determine its reverse
by using operators div and mod. If the last digit is zero, replace it with a one(1) before
reversing the number. Output also the sum of all the digits.
Depicted below are sample outputs when the program is executed:

Input a number: 1034 Input a number: 241620


The reversed order is 4301 The reversed order is 126142
The sum is 8 The sum is 16

2. FileName: EquationProblem_FamilyName (Use While Loop)


Using the equation Y=2+4X-X^2, create a java program that will
compute and output values of Y for values of X from 1 to 20, and in
increment of 1.
The figure shown is a sample output when the program is executed:

44

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
3. FileName: Series1Problem_FamilyName (Use Do While Loop)
The value of S is computed from the formula:
S = 1/1 + 1/2 + 1/3 + 1/4 + 1/5 + … + 1/N
Create a flowchart and a java program that will output the number of terms required and
the value of S before S exceeds 3.1.
Example:
1st term: S = 1;
2nd term: S = 1 + 1/2 = 1.5;
3rd term: S = 1 + 1/2 + 1/3 = 1.8333;
4th term: S = 1 + 1/2 + 1/3 + 1/4 = 2.08333;
5th term: S = 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.2833;
...
nth term: S = ?
Depicted below is a sample output when the program is executed:

4. FileName: FibonacciSeries_FamilyName (Use Do While Loop)


The Fibonacci Sequence is a peculiar series of numbers named after Italian
mathematician, known as Fibonacci. Starting with 0 and 1, each new number in the
Fibonacci Series is simply the sum of the two before it. Create a java program that will
display the first 13 fibonacci numbers.
Depicted below is a sample output when the program is executed:

5. FileName: PrimeOrComposite_FamilyName (Use for Loop)


Create a flowchart and a java program that reads an integer, determine and output a
message if the integer is prime or composite.

45

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Definition:
▪ Composite number is a positive integer that can have more than 2 factors.
Ex : 4,6,8,9 are the example of composite numbers.
▪ A prime number is a whole number greater than 1 whose only factors are 1 and
itself. A factor is a whole number that can be divided evenly into another
number. The first few prime numbers are 2, 3, 5, 7, 11, 13, and 17. The number 1
is neither prime nor composite.
Depicted below are sample outputs when the program is executed:

46

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 9: Java Arrays

Arrays
● An array is a collection of objects (consists of a collection of data) that holds a
fixed number of values of the same data type.
● Arrays of any type can be created and may have one or more dimensions. A
specific element in an array is accessed by its numerical index.

One-Dimensional Array
● A one-dimensional array is, essentially, a list of like-typed variables. To create an
array, you first must create an array variable of the desired type. The general
form of a one-dimensional array declaration is
type var-name[ ]; or type[]var-name;
● Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for the
array determines what type of data the array will hold. For example, the
following declares an array named month_days with the type “array of int”:
int month_days[]; or int [] month_days;
● Although this declaration establishes the fact that month_days is an array
variable, no array actually exists. In fact, the value of month_days is set to null,
which represents an array with no value. To link month_days with an actual,
physical array of integers, you must allocate one using new and assign it to
month_days. new is a special operator that allocates memory. You will look more
closely at new later, but you need to use it now to allocate memory for arrays.
The general form of new as it applies to one-dimensional arrays appears as
follows:
array-var = new type[size];
● Here, type specifies the type of data being allocated, size specifies the number
of elements in the array, and array-var is the array variable that is linked to the
array. That is, to use new to allocate an array, you must specify the type and
number of elements to allocate. The elements in the array allocated by new will
automatically be initialized to zero. The following example allocates a 12-
element array of integers and links them to month_days.
month_days = new int[12];
● After this statement executes, month_days will refer to an array of 12 integers.
Further, all elements in the array will be initialized to zero.

47

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Let’s review: Obtaining an array is a two-step process. First, you must declare a
variable of the desired array type. Second, you must allocate the memory that
will hold the array, using new, and assign it to the array variable. Thus, in Java all
arrays are dynamically allocated. Once you have allocated an array, you can
access a specific element in the array by specifying its index within square
brackets. All array indexes start at zero. For example, this statement assigns the
value 28 to the second element of month_days.
month_days[1] = 28;
● The next line displays the value stored at index 3.
System.out.println(month_days[3]);
● Putting together all the pieces, here is a program that creates an array of the
number of days in each month.
// Demonstrate a one-dimensional array.
public class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}}
● Arrays can be initialized when they are declared. The process is much the same
as that used to initialize the simple types. An array initializer is a list of comma-
separated expressions surrounded by curly braces. The commas separate the
values of the array elements. The array will automatically be created large
enough to hold the number of elements you specify in the array initializer. There is
no need to use new. For example, to store the number of days in each month,
the following code creates an initialized array of integers:
// An improved version of the previous program.
public class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

48

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
More examples of One Dimensional Array
1. A java program that determines and displays the average array of values.
public class Average {
public static void main(String args[]) {
double arrayKo[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double sum = 0, ave;
int i;
for(i=0; i<5; i++)
{
sum = sum + arrayKo[i];
}
ave = sum/5.0;
System.out.println("Average is " + ave);
}
}

2. A java program that allows the user to manually input the array size and elements in the
memory then displays its elements.
import java.util.Scanner;
public class JavaArrays {
public static void main(String[] args) {
Scanner ram = new Scanner(System.in);
System.out.print("Enter the array elements: ");
int size = ram.nextInt();
//declaring the 1-Dimensional Array
int arrayKo[]= new int[size];
int i;
//accessing the indices in the array
//then allocating the elements manually
for(i=0; i<size; i++)
{
System.out.print("The element at index "+i+" is ");
arrayKo[i] = ram.nextInt();
}
System.out.print("The array elements: ");
//access each of the indices in the array then display the array elements
for(i=0; i<5; i++)
{
System.out.print(arrayKo[i] + " ");
}
}
}

For additional information about one-dimensional arrays: watch

49

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 9: Declaring Arrays & Accessing Elements.mp4
For additional information about one-dimensional arrays and the for loop: watch
Module 9: Using a Loop to Access an Array.mp4

Problems and Exercises for Program Development: One-Dimensional Array


1. Create a java program that stores all elements of a 1-dimensional array of numbers at random
in the memory. Output the following:
a) Sum of the list
b) Average of the list
c) The biggest element
d) The smallest element
e) The median
Depicted below is a sample output when the program is executed:

2. Create a java program that would perform the following routines:


1) Input N digits as the elements of a 1-dimensional array.
2) Print the original array.
And the sorted elements in:
3) Ascending order
4) Descending order.
Output the original array and the sorted lists.

Depicted below is a sample output when the program is executed:


3. Create a flowchart and a java program that inputs N digits as the elements of a 1-dimensional
array. Accept a digit and search it in the array. Output the subscript of the element.
Depicted below is a sample output when the program is executed:

50

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Multidimensional Arrays

● In Java, multidimensional arrays are actually array of arrays. These, as you might
expect, look and act like regular multidimensional arrays. However, as you will
see, there are a couple of subtle differences. To declare a multidimensional
array variable, specify each additional index using another set of square
brackets. For example, the following declares a two-dimensional array variable
called twoD.
int twoD[][] = new int[4][5];
● The above code allocates a 4 by 5 array and
assigns it to twoD. Internally this matrix is
implemented as an array of arrays of int.
● When you allocate memory for a multidimensional
array, you need only specify the memory for the
first (leftmost) dimension. You can allocate the
remaining dimensions separately. The figure shown
is a conceptual view of a 4 by 5, two-dimensional
array.
● The following program randomly assign numbers as elements in the array from
left to right, top to bottom, and then displays these values:
// Demonstrate a two-dimensional array using the Random Class.
//import the Random Class
import java.util.Random;
public class TwoDArray {
public static void main(String[] args) {
//set up the program to be ready to accept
//a random input
Random rand = new Random();
//declaring the 2-Dimensional Array (4x5)
int twoD[][]= new int[4][5];
int i, j, k = 0;
System.out.println("The array elements: ");
//allocating the elements of a 4 by 5 array using the random class
for(i=0; i<4; i++){
for(j=0; j<5; j++){
//random number from 0 to 9 will be store at index twoD[i][j]
twoD[i][j] = rand.nextInt(10);
}
}
//access each of the indices in the array then display the array elements
for(i=0; i<4; i++) {
for(j=0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}

51

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
}

For additional information about multidimensional arrays: watch


Module 9: Two Dimensional Arrays.mp4

Problems for Program Development: Two-Dimensional Array

1. Create a java program that generates elements (randomly from 0 – 9) of a 2-dimensional


array (5x5) using the Random Class then perform the following:
1) Output the array elements
2) Output the sum of each row.
3) Output the sum of each column.
4) Output the sum of all the elements.

Depicted below is a sample output when the program is executed:

Graded Activity #7.1 (M9.1)

Part 1: One-Dimensional Array

Instruction:

There are two lists of numbers. Create a resultant list whose elements are the product of
the elements of the two lists.

Example: List A List B List C


21 30 630
50 10 500
…. …. ….

Write a Java program using a one-dimensional array that accepts as input an integer
value asking for the number of elements for each list. This will be used to generate
random numbers (5 to 69) for the one-dimensional arrays (List A and List B). The program

52

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
will compute for the product and store it in another array (List C). Display the result
similar to the Example above.

Sample Input/Output:

Depicted below are sample outputs when the program is executed (the items in bold
characters are input from the user, while the items in bold italic are generated,
calculated and printed by the program):

Input the number of elements: 3


List A List B List C
21 30 630
50 10 500
25 10 250

Input the number of elements: 5


List A List B List C
31 13 403
21 30 630
50 10 500
60 41 2460
25 10 250

Required: The .java file (FamilyName_List.java) containing the code and 2 image files
(Sample1 and Sample2) containing different sample input/output of the program.

Module 10: Java Methods

● A Java method is a collection of statements that are grouped together to


perform an operation. When you call the System.out.println method, for
example, the system actually executes several statements in order to display a
message on the console.

Creating Methods
● Considering the following example to explain the syntax of a method:
public static int methodName(int a, int b) {
// body
}
● Here,
public static: modifier.
int: return type
methodName: name of the method
a, b: formal parameters
int a, int b: list of parameters

53

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Method definition consists of a method header and a method body. The same is
shown below:
modifier returnType nameOfMethod (Parameter List) {
// method body
}
● The syntax shown above includes:
modifier: It defines the access type of the method and it is optional to use.
returnType: Method may return a value.
nameOfMethod: This is the method name. The method signature consists
of the method name and the parameter list.
Parameter List: The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, methods may contain zero
parameters.
method body: The method body defines what the method does with
statements.

● Example: Here is the source code of the above defined method called max. This
method takes two parameters num1 and num2 and returns the minimum
between the two:
/*
* the snippet returns the minimum between two numbers
*/
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2){
min = n2;
}
else{
min = n1;
}
return min;
}
Method Calling:
● For using a method, it should be called. There are two ways in which a method is
called i.e. method returns a value or returning nothing noreturnvalue. The
process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when:
o return statement is executed.
o reaches the method ending closing brace.
● The method returning void is considered as a call to a statement. Let is consider
an example:
System.out.println("Calling a method!");
● The method returning value can be understood by the following example:
int result = sum (6, 9);

54

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Example:
● The following is an example which demonstrate how to define a method and
how to call it:
public class ExampleMinNumber_Method{
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System .out.println("Minimum Value = " + c);
}
//returns the minimum of two numbers Sample Output:
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}

The void Keyword:


● The void keyword allows us to create methods which do not return a value. Here,
in the following example we're considering a void method methodRankPoints.
This method is a void method which does not return any value. Call to a void
method must be a statement i.e. methodRankPoints255.7;. It is a Java statement
which ends with a semicolon as shown in the following example.

Example:
public class ExampleVoid_Method {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}
else
if (points >= 122.4) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
}

55

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
This would produce the following result:

Passing Parameters by Value:


● While working under the calling process, arguments are to be passed. These
should be in the same order as their respective parameters in the method
specification. Parameters can be passed by value or by reference. Passing
Parameters by Value means calling a method with a parameter. Through this the
argument value is passed to the parameter.
● Example:
The following program shows an example of passing parameters by value. The
values of the arguments remain the same even after the method invocation.
public class SwappingExample_Method {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n*Now, Before and After swapping values will be same here*");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
This would produce the following result:

56

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Method Overloading:
● When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from overriding. In
overriding, a method has the same method name, type, number of parameters
etc. Let us consider the example shown before for finding minimum numbers of
integer type. If we want to find the minimum number of double type, then the
concept of Overloading will be introduced to create two or more methods with
the same name but different parameters. The below example explains the same:
public class ExampleOverloading_Method{
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
//same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This would produce the given output on the right result:

● Overloading methods makes the program readable. Here, two methods are
given the same name but with different parameters. The minimum number from
integer and double types is the result.

For additional information about methods: watch


● Module 10: Introduction To Methods.mp4

57

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
● Module 10: Adding Parameters to a Method & Returning Values.mp4

Problems for Program Development


1. Create a java program that will display a menu for choices to perform the following routines:
1. Input a number then determine and display the factors of the number.
2. Input a number then determine and display if the number is odd or even.
3. Input a number then determine and display if the number is a Perfect Number or Not.
4. Input the elements of a 1-dimensional array using the Random Class (random elements
from 0 to 9 and random size from 0 to 10) then display the sorted elements in ascending
order.
5. Input the elements (from 0 to 9) of a (5x5) 2-dimensional array using the Random Class
then display the sum of all odd elements in the array.
Depicted below are sample output when the program is executed.

58

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Module 11: Wrapper Classes and Strings

 Wrapper classes are used for converting primitive data types into objects, like int
to Integer.
 When working with Collection Objects, such as ArrayList and Vector, only objects
can be stored and not primitive types.

Primitive Data types and their Corresponding Wrapper class:

Primitive Data Type Wrapper Class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive types to the object of their corresponding
wrapper classes.

Creating Wrapper Objects


public static void main(String[] args) {
//create a wrapper object
Double weight = new Double(55.9);
//creating wrapper objects using autoboxing
Integer day = 21;
Character initial = 'A'; This will display the result:
System.out.println(weight); 55.9
System.out.println(day); 21
System.out.println(initial); A
}

 The general form for creating a wrapper object is:


WrapperClass objectName = new WrapperClass(value);

or

WrapperClass objectName = value;

Converting a primitive type to Wrapper object


public static void main(String args[]){
//Converting int primitive into Integer object
int day = 21;
Integer obj = Integer.valueOf(day);

59

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
//Using Autoboxing
Integer autoboxObj = day; This will display the result:

System.out.println(day+ " "+ obj+ " "+ autoboxObj); 21 21 21


}

 The general form for converting a primitive type to a wrapper object is:
WrapperClass objectName = WrapperClass.valueOf(primitiveDataTypeVariable);

or

WrapperClass objectName = primitiveDataTypeVariable;

Examples: Integer obj = Integer.valueOf(day);

Double weightObject = Double.valueOf(pounds);

Integer unboxingObj = day;

Double unboxingWeight = pounds;

 Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.

Unboxing
Automatically converting an object of a wrapper class to its corresponding
primitive type.

Converting Wrapper class object to Primitive


public static void main(String args[]){
//Creating Wrapper class object
Integer obj = new Integer(21);

//Converting the wrapper object to primitive


int day = obj.intValue();

//using Unboxing
int unboxDay = obj; This will display the result:
System.out.println(day+ " "+ unboxDay+ " "+ obj); 21 21 21
}

 The general form of converting a wrapper object to primitive data type is:
primitiveDataType variableName = objectName.primitiveDataTypeValue();

or

primitiveDataType variableName = objectName;

60

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
Examples: int day = obj.intValue();

double weight = objPounds.doubleValue();

int autoboxDay = obj;

double weight = objPounds;

 The following methods are used to get the value associated with the
corresponding wrapper object: intValue(), byteValue(), shortValue(),
longValue(), floatValue(), doubleValue(), charValue(), booleanValue().
 Since Java 5, we do not need to use the intValue() method of wrapper classes
to convert the wrapper type into primitives.

Converting Wrapper class object to String


public static void main(String[] args) {
//convert the integer object year to a String and
//display the number of characters present in the String
Integer year = 2020; This will display the result:
String myString = year.toString();
System.out.println(myString.length()); 4
}
String Class
 The String class provides a lot of methods to work on string.
 By the help of these methods, we can perform operations on string such as
trimming, concatenating, converting, comparing, replacing strings and more.

toUpperCase() and toLowerCase() method


 The java string toUpperCase() method converts this string into uppercase letter
and string toLowerCase() method into lowercase letter.

public static void main(String[] args) {


String str="HellO WorlD"; This will display the result:
//display the contents of str
System.out.println(str); HellO WorlD
System.out.println(str.toUpperCase()); HELLO WORLD
System.out.println(str.toLowerCase()); hello world
}
trim() method
 The string trim() method eliminates white spaces before and after string.

public static void main(String[] args) { This will display the result:
String str=" Hello World ";
System.out.println(str); Hello World
System.out.println(str.trim()); Hello World
}

61

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
length() method
 The string length() method returns length of the string.

public static void main(String[] args) { This will display the result:
String str="Hello World";
System.out.println(str); Hello World
System.out.println(str.length()); 11
}

concat() method
 The java string concat() method combines specified string at the end of this
string. It returns combined string. It is like appending another string.

public static void main(String args[]){ This will display the result:
String s1="Hello";
System.out.println(s1); Hello
s1=s1.concat(" World"); Hello World
System.out.println(s1); Hello World! 2020
s1=s1.concat("!").concat(" 2020");
System.out.println(s1);
}

equals() method
 The string equals() method compares the two given strings based on the content of the
string. If any character is not matched, it returns false. If all characters are matched, it
returns true.

public static void main(String[] args) {


String str1="Hello World";
String str2="Hello World";
String str3="HELLO WORLD"; This will display the result:
String str4="hello world";
System.out.println(str1.equals(str2)); true
System.out.println(str1.equals(str3)); false
System.out.println(str2.equals(str4)); false
System.out.println(str3.equals(str3)); true
}

equalsIgnoreCase() method
 The string equalsIgnoreCase() method compares the two given strings on the
basis of content of the string irrespective of case of the string. It is like equals()
method but doesn't check case. If any character is not matched, it returns false
otherwise it returns true.

62

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
public static void main(String[] args) {
String str1="Hello World";
String str2="Hello World";
String str3="HELLO WORLD"; This will display the result:
String str4="hello";
System.out.println(str1.equalsIgnoreCase(str2)); true
System.out.println(str1.equalsIgnoreCase(str3)); true
System.out.println(str2.equalsIgnoreCase(str3)); true
System.out.println(str3.equalsIgnoreCase(str4)); false
}
compareTo() method
 The string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
 It compares strings on the basis of Unicode value of each character in the strings.
 If first string is lexicographically greater than second string, it returns positive
number (difference of character value). If first string is less than second string
lexicographically, it returns negative number and if first string is lexicographically
equal to second string, it returns 0.
if string1 > string2, it returns positive number
if string1 < string2, it returns negative number
if string1 == string2, it returns 0
This will display the result:
public static void main(String args[]){
String s1="hello"; 0
String s2="hello"; -5
String s3="meklo"; -1
String s4="hemlo"; 2
String s5="flag";
//start comparing from the first character of the string
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}

 If you compare string with blank or empty string, it returns length of the string. If second
string is empty, result would be positive. If first string is empty, result would be negative.

public static void main(String args[]){


String s1="hello";
String s2=""; This will display the result:
String s3="me";
System.out.println(s1.compareTo(s2)); 5
System.out.println(s2.compareTo(s3)); -2
}

63

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
indexOf() method
 The java string indexOf() method returns index of given character value or
substring. If it is not found, it returns -1. The index counter starts from zero.

There are 4 types of indexOf method in java.


No. Method Description
1 int indexOf(int ch) returns index position for the given char value
2 int indexOf(int ch, int fromIndex) returns index position for the given char value
and from index
3 int indexOf(String substring) returns index position for the given substring
4 int indexOf(String substring, int fromIndex) returns index position for the given substring
and from index
Parameters
ch: char value i.e. a single character e.g. 'a'
fromIndex: the index to start the search from
substring: substring to be searched in this string

public static void main(String args[]){


String s1="this is index of example";
//passing substring
int index1=s1.indexOf("is"); //method No.3, returns the index of the first occurrence
int index2=s1.indexOf("index"); //of the substring "is"
System.out.println(index1+" "+index2);
This will display the result:
//passing substring with from index
int index3=s1.indexOf("is",4); //method No. 4 28
System.out.println(index3); 5
3
//passing char value
int index4=s1.indexOf('s'); //method No. 1
System.out.println(index4);
}

For additional information about java’s String methods: watch the following videos
Module 11: Changing a String to Lowercase or Uppercase
Module 11: Obtaining the Length of a String
Module 11: Combining Strings (Concatenation)
Module 11: Determining if Two Strings are Equal
Module 11: Comparing Two Strings
Module 11: Searching a String for a Substring

64

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.
References:

Charatan, Q., Kans, A. (2019). Java in Two Semesters. Springer


DataFlair Team. 2018. How to Read Java Console Input | 3 Ways To Read Java Input.
https://data-flair.training/blogs/read-java-console-input/https://www.sitepoint.com/beginning-
java-data-types-variables-and-arrays/
Java Methods. http://www.tutorialspoint.com/java/java_methods.htm
JavatPoint. The Best Portal to Learn Technologies. https://www.javatpoint.com/java-for-loop
just.edu.jo. (n.d.). Windows 7. Retrieved from http://www.just.edu.jo/:
http://www.just.edu.jo/~mqais/CIS99/PDF/Ch.02_Windows7.pdf
Liang, Y. D. (2017). Introduction to Java Programming. Pearson Education, Inc.
Microsoft. (n.d.). Insert a table of contents. Retrieved from Office Support.
Mount Allison University. (n.d.). Microsoft Excel. Retrieved from mta.ca:
https://www.mta.ca/uploadedFiles/Community/Administrative_departments/Human_Resources/
Training_and_professional_development/Classroom/Excel%20Training%20-
%20Level%201.pdf
Mwangi, I. (2017). Computer System - Lecture notes. Retrieved from StuDocu:
https://www.studocu.com/my/document/jomo-kenyatta-university-of-agriculture-and-
technology/introduction-to-computer-systems/lecture-notes/computer-system-lecture-notes-
12/1992140/view
nursing.ufl.edu. (n.d.). Microsoft Word - APA_Format_2007. Retrieved from
https://nursing.ufl.edu: https://nursing.ufl.edu/files/2011/05/APAFormattingwithWORD2007.pdf
Ogihara, M. (2018). Fundamentals of Java Programming. Springer
Savitch, W. (2015). Java : An Introduction to Problem Solving and Programming. Pearson
Education, Inc.
Schmieder, E. (2017, November 18). Tech Tip: Managing academic reference sources in
Microsoft Word. Retrieved from extbook Academic Authors Association Blog:
https://blog.taaonline.net/2017/11/tech-tip-managing-academic-reference-sources-in-microsoft-
word/
Sisson, R. (n.d.). Word Basics Class Handout. Retrieved from pagosalibrary.org.
Sumathi, P. (n.d.). Introduction to Computers. Retrieved from http://sdngnet.com/:
http://sdngnet.com/Files/Lectures/UJ-ARC-171-
Introduction%20to%20Computing%20in%20Architecture/Lecture%20Materials/Introduction%2
0to%20Computer%20Applications%20by%20Sumathi.pdf

65

Property of and for the exclusive use of SLU. Reproduction, storing in a retrieval system, distributing, uploading or posting online, or transmitting in any form or by any
means, electronic, mechanical, photocopying, recording, or otherwise of any part of this document, without the prior written permission of SLU, is strictly prohibited.

You might also like