You are on page 1of 126

MODULE IN

Computer Fundamentals and


Programming(Lab)

COMPROG

Computer Applications Department

SCHOOL OF ACCOUNTANCY, MANAGEMENT, COMPUTING


AND INFORMATION STUDIES
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.
COMPROG
COURSE LEARNING OUTCOMES

At the end of the module, you should be able


to:
1. Practice Christian values while developing
solutions using computer.
2. Follow and comply with ethical standards
in the use of computer and information.
3. Develop the foundation in basic
information technology concepts.
4. Explain the impact of computer in creating
solutions in a global, economic,
environmental and social context and
apply current developments in computer
to the engineering field
5. Evaluate existing computer applications to
help simplify office tasks and explain the
impact of computer in creating solutions in
a global, economic, environmental and
social context.
6. Describe applicable engineering
techniques in problem solving using
computers and apply a wide range of
problem-solving skills using computers for
various applications and apply current
developments in computers to the
engineering field
7. Design and create algorithms to solve
problems, translate algorithms into
workable computer programs and create
computer program that follows standard
and conventions.
8. Work independently in analyzing problems
COMPUTER and their solutions for individually assigned
tasks and discuss effectively created
FUNDAMENTALS AND solutions to a given problem.
9. Practice appropriate programming skills
PROGRAMMING(LAB) and work effectively as member of team in
creating solutions to problems.

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.
Everyone should know how to program a
computer because it teaches you how to
think.
Steve Jobs

COURSE INTRODUCTION

The content of this module focuses on computers, computer system components


and basic information technology concepts. It also teaches the use of Windows and the
use of word processing and spreadsheet software applications.

This module also covers the fundamentals of algorithm development and


fundamental concepts of programming using Object Oriented Programming (OOP)
language. The concepts include basic syntax and semantics; variables, data types,
operators, and expressions; the role of algorithms in the problem-solving process; input
and output statements; conditional and iterative control structures; methods and
parameter passing; program structure decomposition/modularization; arrays; wrapper
classes; and string processing. The student will also use a high level programming
language in creating computer solutions to engineering problems.

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.
Table of Contents
Module 1: The Computer .............................................................................................................................. 2
Definition .................................................................................................................................................. 2
Data and Information................................................................................................................................ 2
Programs and Software ............................................................................................................................ 3
Windows Operating System...................................................................................................................... 4
The Desktop .......................................................................................................................................... 5
Icon Operations..................................................................................................................................... 7
Start Menu Parts ................................................................................................................................... 8
Windows ............................................................................................................................................... 8
Parts of a Folder/Library Window ....................................................................................................... 10
Dialog Boxes ........................................................................................................................................ 11
Working with Files and Folders ........................................................................................................... 12
Module 2: The Word Processing Program .................................................................................................. 14
Brief Introduction to MS Word ............................................................................................................... 14
Title Bar ............................................................................................................................................... 14
Quick Access Toolbar .......................................................................................................................... 14
Ribbon ................................................................................................................................................. 14
Status Bar ............................................................................................................................................ 15
Formatting your Technical Paper on MS Word ...................................................................................... 20
Formatting the Page Layout ................................................................................................................ 21
Creating a Title Page ........................................................................................................................... 21
Inserting a Page Break......................................................................................................................... 22
Abstract ............................................................................................................................................... 23
Body .................................................................................................................................................... 23
References .......................................................................................................................................... 25
Module 3: The Spreadsheet Program ......................................................................................................... 36
Getting Started........................................................................................................................................ 36
Application Window............................................................................................................................ 37
The Workbook Window ...................................................................................................................... 37
Cell Addressing ........................................................................................................................................ 39
Cell Basics ............................................................................................................................................ 40
Cell Content......................................................................................................................................... 41
Formulas and Functions .......................................................................................................................... 42
Arithmetic Operations ........................................................................................................................ 42
Order of Operation ............................................................................................................................. 42
Cell References.................................................................................................................................... 42
Functions ............................................................................................................................................. 43
Sorting Data ............................................................................................................................................ 50
Filtering Data ........................................................................................................................................... 52
Charts and Graphs................................................................................................................................... 52
Chart Layout and Style ........................................................................................................................ 52
Module 4: Java Fundamentals .................................................................................................................... 54
Programming Language .......................................................................................................................... 54
About Java ............................................................................................................................................... 54
Java Platform........................................................................................................................................... 54
Java Programming Environment ............................................................................................................. 54
How are Java Programs Written? ....................................................................................................... 55
Fundamental Concepts ........................................................................................................................... 55
Java Comments ....................................................................................................................................... 56
Java Statements, Blocks and Expressions ............................................................................................... 56
Java Identifiers ........................................................................................................................................ 57
Naming Rules and Styles ..................................................................................................................... 57
Java Keywords ......................................................................................................................................... 58
Primitive Data Types in Java ................................................................................................................... 58
Numeric Primitive Data ....................................................................................................................... 58
Boolean Primitive Data ....................................................................................................................... 58
Characters ........................................................................................................................................... 58
Character Strings ................................................................................................................................. 59
Separators ............................................................................................................................................... 59
Variables ................................................................................................................................................. 60
Variable Initialization .......................................................................................................................... 60
Assignment Statement............................................................................................................................ 60
Constants ................................................................................................................................................ 60
The println Method ................................................................................................................................. 61
The print Method .................................................................................................................................... 61
String Concatenation .............................................................................................................................. 61
Escape Sequences ................................................................................................................................... 62
Module 5: Java Operators, Flowcharting Symbols and Sample Programs ................................................. 63
Operators ................................................................................................................................................ 63
Arithmetic Operators .......................................................................................................................... 63
Increment/Decrement Operators ....................................................................................................... 63
Relational Operators ........................................................................................................................... 64
Logical Operators ................................................................................................................................ 64
Creating a Java Program ......................................................................................................................... 64
The Program Development Life Cycle ..................................................................................................... 66
Representing Algorithms Using Flowcharts ............................................................................................ 69
Module 6: Getting Program Input and Sequence Problems ....................................................................... 70
Problems for Program Development: Sequence Programs .................................................................... 71
Module 7: Java Control Structures: Decision Control Structure ................................................................. 74
Java’s Selection Statements .................................................................................................................... 74
If Statement ........................................................................................................................................ 75
Nested ifs ............................................................................................................................................ 75
The if-else-if Ladder ............................................................................................................................ 76
Problems for Program Development: Decision Control Structure ......................................................... 77
Switch ...................................................................................................................................................... 79
Problems for Program Development: Switch Statement ....................................................................... 81
Module 8: Java Control Structures: Iteration Control Structure ................................................................ 83
While Loop .............................................................................................................................................. 83
While Loop Flowchart Diagram........................................................................................................... 84
More While Loop Examples ................................................................................................................ 84
Flowchart Diagram of Series2 using While Loop ................................................................................ 85
Flowchart Diagram for Sphere Using While Loop ............................................................................... 87
Do-while Loop ......................................................................................................................................... 88
Do-while Loop Flowchart Diagram...................................................................................................... 88
More Do While Loop Examples ........................................................................................................... 90
Flowchart Diagram for Object Using Do While ................................................................................... 90
Flowchart Diagram for Bounce using DoWhile ................................................................................... 92
For Loop .................................................................................................................................................. 92
For Loop Flowchart Diagram ............................................................................................................... 93
More For Loop Examples .................................................................................................................... 93
Flowchart Diagram of Series3 using For Loop .................................................................................... 94
Flowchart Diagram for Factorial Using For Loop ................................................................................ 96
Java For Loop vs While Loop vs Do While Loop ...................................................................................... 96
Problems for Program Development: Repetition Control Structure ...................................................... 97
Module 9: Java Arrays ............................................................................................................................... 101
Arrays .................................................................................................................................................... 101
One-Dimensional Arrays ....................................................................................................................... 101
More examples of One Dimensional Array ....................................................................................... 103
Problems and Exercises for Program Development: One-Dimensional Array...................................... 104
Multidimensional Arrays ....................................................................................................................... 105
Problems for Program Development: Two-Dimensional Array ............................................................ 107
Module 10: Java Methods......................................................................................................................... 108
Creating Method ................................................................................................................................... 108
Method Calling: ..................................................................................................................................... 109
Example:............................................................................................................................................ 109
The void Keyword: ................................................................................................................................ 110
Example:............................................................................................................................................ 110
Passing Parameters by Value: ............................................................................................................... 111
Method Overloading: ............................................................................................................................ 111
Problems for Program Development .................................................................................................... 112
Module 11: Wrapper Classes and Strings ................................................................................................. 113
Autoboxing ........................................................................................................................................ 115
Creating Wrapper Objects ................................................................................................................ 115
Converting a primitive type to Wrapper object ................................................................................ 115
Unboxing ........................................................................................................................................... 116
Converting Wrapper class object to Primitive .................................................................................. 116
Converting Wrapper class object to String ....................................................................................... 117
String Class ............................................................................................................................................ 117
toUpperCase() and toLowerCase() method ...................................................................................... 117
trim() method.................................................................................................................................... 117
length() method ................................................................................................................................ 118
concat() method................................................................................................................................ 118
equals() method ................................................................................................................................ 118
equalsIgnoreCase() method .............................................................................................................. 119
compareTo() method ........................................................................................................................ 119
indexOf() method .............................................................................................................................. 120
References: ............................................................................................................................................... 121
Computer Fundamentals and Programming
Lecture Notes

Module 1: The Computer

Today’s world is an information-rich world and it has become a necessity for


everyone to know about computers. You can find computers almost everywhere from
the large ones that manage the different business processes of large companies to the
device(s) you’re using to read this. The main objective of this module is to greatly
enhance your computer literacy – that is, the knowledge and understanding of
computers and their uses.

Definition
A Computer is an electronic device that can perform activities that involve
mathematical, logical and graphical manipulations. Generally, the term is used to
describe a collection of devices that function together as a system. You can think of it as
an electronic machine operating under the control of instructions stored in its own
memory.

It performs the following three operations in sequence.

1. It receives data & instructions from the input device.


2. Processes the data as per instructions.
3. Provides the result (output) in a desired form

To make things easier to remember, these operations are also referred as the
Input-Process-Output(IPO) Model.

Figure1.1: IPO Model

Data and Information


Data is the complete list of facts and details like text, observations, figures, symbols
and description of things. It is the raw list of facts that are processed to gain information.
The basic concept of data is associated with scientific research collected by different
research organizations. If you have conducted a survey before, then the responses
you’ve gathered are an example of data.

2
Information is the processed, organized and structured data. It provides context
for data. However, both the terms are used together, information can be easily
understood than data. Going back to our previous example, if you compiled the
responses from your survey to a tabular form, in order for it to be interpreted easily, then
that’s how data can become information

Programs and Software


A computer program is a collection of instructions that can be executed by a
computer to perform a specific task. Think of it as a bunch of IPO models that work
together in order to do something.

A software is a program or set of instructions that causes the Hardware to function


in a desired way. The basic difference between the Hardware and Software is just the
same as that exists between TV and the TV studio. Without the TV studio (software) from
where the programs are telecast, the TV (Hardware) is a dead machine.

There are five categories of software. They are:

● Operating System (OS): The software that manages the resources of a computer
system and schedules its operation is called Operating system. The operating
system acts as an interface between the hardware and the user programs and
facilitates the execution of programs.
Generally the OS acts as an interface between the user and the Hardware of the
computer. i.e. It is a bridge between the user and the Hardware.
The User interface provided by the OS can be character based or graphical:
o Character User Interface: It is operated with keyboard only. Ex: MS-DOS, UNIX
o Graphical User Interface: The system can be operated with mouse and
keyboard. Ex: Windows XP, Windows 7, etc.
● Translators: Computers can understand instructions only when they are written in
their own language – the machine language. Therefore, a program written in any
other language should be translated into machine language. The software that
―translates the instructions of different languages is known as translators. We’ll
discuss more about translators on the next topics.
● Utility Programs: These are pre-written programs supplied by the manufacturer for
maintaining day to day activities of a computer system. Example: COPY, SORT,
MAILING, virus scanning software etc.
● Application Programs: These are user written programs to do a specific job which
can be changed to meet the individual needs. These programs are written in
different languages such as BASIC or C or by using database packages like dBASE,
Oracle.
● General Purpose Packages: These packages are developed to suit the needs of
research workers/scientists in different fields. These packages are categorized as:
o Data Analysis – ex: SPSS (Statistical Package for Social Science), MSTAT,
MICROSTAT, GENSTAT, SAS etc.
o Word Processing – ex: MS-Word, Google Docs, NORTON EDITOR, etc.
o Spreadsheet – ex: LOTUS, Google Spreadsheets, MS-Excel, etc.

3
o Graphics – ex: Adobe Illustrator, Adobe Photoshop, etc.
o Databases – ex: Oracle, MS Access, etc.

Windows Operating System

From what’s mentioned before, we can say that the OS is one of the most
important software in a personal computer. Without it, you won’t be able to use other
software. Today, most operating systems perform the following important functions:

Processor management: It manages the assignment of the processor to different tasks


being performed by the computer system.

1. Memory management: It manages the allocation of main memory and other


storage areas to the system programs as well as user programs and data.
2. Input / Output management: It manages the coordination and assignment of
different Input and Output devices while one or more programs are executed.
3. File management: It allows all files to be easily changed and modified through the
use of text editors or some other file manipulation routines.
4. Establishment and enforcement of a priority system: It determines and maintains
the order in which jobs are to be executed in the computer system.
5. Interpretation of commands and instructions.
6. Facilitates easy communication between the computer system and the computer
operator.

Most personal computers use Windows as its operating system. Most likely, if you’re
using a laptop as your primary device for this course, it’s operating system (also referred
to as OS), is Windows. This module will help work around Windows-based computers with
more confidence.

In most cases, the first screen that appears after you turn on the power of a
computer is a desktop, as shown below.

Figure 1.2: Windows’ first screen

4
Figure 1.3: Windows’ Welcome Screen

If it is a shared PC, (which means there are more than one user who uses it), or one user
with password protected, you will arrive at a Welcome Screen.

The Desktop

The Desktop is the main Windows screen. It is the work area where dialog boxes,
windows, icons, and menus appear. Like an office desk, the desktop contains items you
can use to do your job. For instance, from your desktop, you can perform file-
management tasks and run software applications. You can customize the appearance
of the desktop to suit your preferences. The following are something that you might see
in an average Windows Desktop:

1. My Computer – Allows you to see what drives are attached to your computer (for
example, your local hard disk drive, your CD/DVD drives, any networked shared
drives, and external drives, such as a USB flash drive). You can also view the files
that are located on these drives.
2. My Documents – Supplies a ‘catch-all’ place for your personal files. Within here
you can see your files, any shared files from other computer users and any music
or pictures you may have stored. The Documents folder will sometimes be
identified by your name instead of the word “Documents.”
3. Recycle Bin – Stores any files you delete until you empty it.
4. Internet Explorer – Contains Windows’ built in web browser that integrates with
other Windows components

Components of a Desktop

The desktop usually consists of two main components:

1. Desktop that contains many components like icons (file, folder, shortcut. Etc.)
2. Task Bar

5
Figure 1.4: Components of a Desktop

On your desktop, you’ll find what’s called an icon. An icon is a graphic image, a
small picture or object that represents a file, program, web page, or command. Icons
help you execute commands, open programs or documents quickly. To execute a
command by using an icon, click or double-click on the icon. It is also useful to quickly
recognize an object in a browser list. For example, all documents using the same
extension have the same icon. We can classify icons as the following:

● Folder Icons –

● File Icons –

● Shortcut Icons –

Figure 1.5: Classification of Icons

All the data on your hard drive consists of files and folders. The basic difference
between the two is that files store data, while folders store files and other folders. The
folders, often referred to as directories, are used to organize files on your computer. The
folders themselves take up virtually no space on the hard drive. Files, on the other hand,
is a collection of data – stored in one unit, identified by a filename followed by a period
and a file extension (Figure 1.6). A file can range from a few bytes to several gigabytes.
It can be documents, programs, libraries, and other compilations of data.

6
Figure 1.6: Filename and extension

A shortcut is a link that points to a program on the computer. Shortcuts


allow users to create links to their programs in any folder, Start bar, Taskbar,
Desktop or other locations on their computer. A shortcut in Windows is
commonly identified by a small arrow in the bottom corner of the icon.

Icon Operations
You can do various operations on the icons on
your desktop. Here are some of them:

● Arrange Icons on the Desktop


o Right Click the desktop
o Click Sort by
o Select one of the 4 options to arrange icons
from sub-menu

● View/Hide Icons
o Right Click the desktop
o Click View
o Check to see if Auto Arrange has a check
mark
o If it does uncheck it

● Change Icon Size


o Right Click the desktop
o Click View
o Click on the desired size

7
Start Menu Parts
The start menu allows you some of the common operations on Windows by
clicking on the Windows button usually located at the bottom left corner of your screen.
You can use the Start Menu to perform
these activities:

● Start programs
● Open commonly used folders
● Search for files, folders, and
programs
● Adjust computer settings
● Get help with the Windows
operating system
● Turn off the computer
● Log off from Windows or switch to a
different user account

Shutting Down the Computer


At the bottom of the right pane is the Shut down button.
Click the Shut down button to turn off your computer. Clicking
the arrow next to the Shut down button displays a menu with
additional options for switching users, logging off, restarting, or
shutting down.

● Switch user: If you have more than one user account on your computer, Fast User
Switching is an easy way for another person to log on to the computer without
logging you off or closing your programs and files.
● Log off: When you log off from Windows, all of the programs you were using are
closed, but the computer is not turned off.
● Lock: Locking your PC is a good option if you’ll be back soon. You'll have to enter
your password when you come back, which helps keep your work more secure.
● Restart: The Restart button "reboots" your computer (it is sometimes called a "warm
boot" or "soft boot.") That means it saves your information to the hard drive, turns
off the computer for a moment, and then turns it back on again.
● Sleep: Clicking on Sleep puts your computer in a low-power state, but doesn't turn
it off. The main advantage is that it allows you to get back to work quickly, without
having to wait for the computer to do a full reboot.

Windows
Whenever you open a program, file, or folder, it appears on your screen in a box
or frame called a window (that's where the Windows operating system gets its name).

8
Figure 1.7: Basic Parts of a Window

Because windows are everywhere in Windows, it's important to understand how


to move them, change their size, or just make them go away.

Although the contents of every window are different, all windows share some
things in common. For one thing, windows always appear on the desktop - the main work
area of your screen. In addition, most windows have the same basic parts.

● Title bar. Displays the name of the document and program (or the folder name if
you're working in a folder).
● Minimize, Maximize, and Close buttons. These buttons hide the window, enlarge it
to fill the whole screen, and close it, respectively (more details on these shortly).
● Menu bar. Contains items that you can click to make choices in a program.
● Scroll bar. Let’s you move the contents of the window to see information that is
currently out of view.
● Borders and corners. You can drag these with your mouse pointer to change the
size of the window.

Moving a window
To move a window, point to its title bar with the mouse pointer. Then drag the
window to the location that you want. (Dragging means pointing to an item, holding
down the mouse button, moving the item with the pointer, and then releasing the mouse
button.)

Changing the size of a window


To make a window fill the entire screen, click its Maximize button or double-
click the window's title bar. To return a maximized window to its former size, click its Restore
button (this appears in place of the Maximize button). Or, double-click the window's
title bar. To resize a window (make it smaller or bigger), point to any of the window's
borders or corners. When the mouse pointer changes to a two headed arrow (see picture
below), drag the border or corner to shrink or enlarge the window. A window that is
maximized cannot be resized. You must restore it to its previous size first.

9
Hiding a window
Hiding a window is called minimizing it. If you want to get a window out of the way
temporarily without closing it, minimize it. To minimize a window, click its Minimize button
. The window disappears from the desktop and is visible only as a button on the
taskbar, the long horizontal bar at the bottom of your screen.

Closing a window
Closing a window removes it from the desktop and taskbar. If you're done with a
program or document and don't need to return to it right away, close it. To close a
window, click its Close button .

Switching between windows


If you open more than one program or document, your desktop can quickly
become cluttered with windows. Keeping track of which window you have open isn’t
always easy, because some windows might partially or completely cover others.

● Using the taskbar. The taskbar provides a way to organize all of your windows.
Each window has a corresponding button on the taskbar. To switch to another
window, just click its taskbar button. The window appears in front of all other
windows, becoming the active window—the one you're currently working in.
● Using Alt +Tab. You can switch to the previous window by pressing Alt+Tab, or
cycle through all open windows and the desktop by holding down Alt and
repeatedly pressing Tab. Release Alt to show the selected window.

Parts of a Folder/Library Window

Figure 1.8: Parts of a Folder/Library Window

10
When you open a folder or library, you see it in a window. The various parts of this
window are designed to help you navigate around Windows or work with files, folders,
and libraries more easily. A typical window is shown in Figure 1.8 and each of its parts:
● Navigation pane: Use the navigation pane to access libraries, folders, saved
searches, and even entire hard disks. Use the Favorites section to open your most
commonly used folders and searches; use the Libraries section to access your
libraries. You can also click the expand button to browse folders and subfolders.

● Back and Forward buttons: Use the Back button and the Forward button
to navigate to other folders or libraries you've already opened without closing the
current window. These buttons work together with the address bar; after you use
the address bar to change folders.
● Toolbar: Use the toolbar to perform common tasks, such as changing the
appearance of your files and folders, burning files to a CD, or starting a digital
picture slideshow. The toolbar's buttons change to show only the tasks that are
relevant.
● Address bar: Use the address bar to navigate to a different folder or library or to
go back to a previous one.
● Column headings: Use the column headings to change how the files in the file list
are organized. For example, you can click the left side of a column heading to
change the order the files and folders are displayed in, or you can click the right
side to filter the files in different ways. (Note that column headings are available
only in Details view).
● File list: This is where the contents of the current folder or library are displayed. If
you type in the search box to find a file, only the files that match your current view
(including files in subfolders) will appear.
● Search box: Type a word or phrase in the search box to look for an item in the
current folder or library. The search begins as soon as you begin typing—so if you
type "B," for example, all the files with names starting with the letter B will appear
in the file list.
● Details pane: Use the details pane to see the most common properties associated
with the selected file. File properties are information about a file, such as the
author, the date you last changed the file, and any descriptive tags you might
have added to the file.

Dialog Boxes
A dialog box is a special type of window that asks you a question, allows you to select
options to perform a task, or provides you with information. You'll often see dialog boxes
when a program or Windows needs a response from you before it can continue. Unlike
regular windows, most dialog boxes can't be maximized, minimized, or resized. They can,
however, be moved.

11
Figure 1.9: Dialog Box

Working with Files and Folders


1. Selection
● Single object: To select a single object, click on it once.
● Multiple object:
o To select a consecutive group of files or folders, click the first item, press and
hold down the Shift key, and then click the last item.
o To select Multiple files or folders that are near each other, drag the mouse
pointer to create a selection around the outside of all the items that you
want to include.
o To select non-consecutive files or folders, press and hold down the Ctrl key,
and then click each item that you want to select.
o To select all of the files or folders in a window, on the toolbar, click Organize,
and then click Select all. If you want to exclude one or more items from your
selection, press and hold down the Ctrl key, and then click the items.
2. Rename
● Right-click the file or folder you want to rename, click Rename, type a name,
and then press Enter.
● You can also select the file, then press F2, type a name, and then press Enter.
3. Copying (When you copy an item, the original item remains in its original
location— plus you have the new copy)
● Open the location that contains the file you want to copy.
● Right-click the file, and then click Copy.
● Open the location where you want to store the copy.
● Right-click an empty space within the location, and then click Paste. The copy
of the original file is now stored in the new location.
● Another way to copy and paste files is to use the keyboard shortcuts Ctrl+C
(Copy) and Ctrl+V.
4. Moving/Cutting (Moving a file (or folder) is different from copying it. Moving cuts
the item from its previous location and places it in a new location. Copying leaves
the original item where it was and creates a copy of the item elsewhere. In other
words, when you copy something you end up with two of it. When you move
something, you only have one copy of it.
● Open the drive or folder containing the file or folder you want to move.
● Select the files or folders you want to move.
● Right-click an empty space within the location, and then click Paste.

12
● Another way to copy and paste files is to use the keyboard shortcuts Ctrl+X
(Cut) and Ctrl+V.
5. Creating a Folder
● Open the drive or folder where you want to create a folder.
● Right-click a blank area on the desktop or in the folder window, point to New,
and then click Folder.
6. Deleting
● Select the file(s) or folder(s).
● Right click on the item(s) and then click delete.
● You can also delete a file or folder by pressing the Del/Delete button on the
keyboard.
● The easiest way to delete anything on the desktop is by dragging and
dropping it into the Recycle Bin.
● When you delete a file or folder from your hard disk, it's not deleted right away.
Instead, it's stored in the Recycle Bin until the Recycle Bin is emptied.
● If you delete a file or folder from a network folder or from a USB flash drive, it
might be permanently deleted rather than being stored in the Recycle Bin.
● If a file can’t be deleted, it might be in use by a program that's currently
running. Try closing the program or restarting your computer to fix the problem.
● To permanently delete a file without first moving it to the Recycle Bin, select
the file, and then press Shift + Delete.
7. Permanently delete files from the Recycle Bin
● Open the Recycle Bin by double-clicking the Recycle Bin on the desktop
● Do one of the following:
o To permanently delete one file, click it, press Delete, and then click Yes.
o To delete all of the files, on the toolbar, click Empty the Recycle Bin, and then
click Yes.
● You can also empty the Recycle Bin by right-clicking the Recycle Bin and then
clicking Empty Recycle Bin.
8. Restoring items from the Recycle Bin
● Open the Recycle Bin by double-clicking the Recycle Bin on the desktop.
● Do one of the following:
o To restore a file, click it, and then, on the toolbar, click Restore this item.
o To restore all of the files, make sure that no files are selected, and then, on
the toolbar, click Restore all items.
● The files will be restored to their original locations on your computer.

13
Module 2: The Word Processing Program

LESSON OBJECTIVES
At the end of this unit, I can:

1. Use some of the advanced capabilities of Microsoft Word commonly used to


increase productivity and efficiency;
2. Effectively use these features to help improve the productivity of an organization
through maximizing the potential of Microsoft Word;
3. Create letters or documents for distribution to various recipients; and
4. Create labels and envelopes for distribution.

Brief Introduction to MS Word


Before we begin writing our technical paper or research articles, we must be at
least familiar with the basic features (and looks) of Microsoft Word (MS Word). This section
covers what you need to know about the user Interface of MS Word.

Title Bar
This is located at the very top of the screen. On the Title bar, MS Word displays the
name of the document you are currently using. If you have a document open right now,
at the top of your screen, you should see "Document1 - Microsoft Word" or a similar name.

If you’re currently using Microsoft Office 2010 or higher, and are familiar with
Microsoft Office 2007, you will notice some changes. The File tab replaces the Microsoft
Office Button and the File menu used in earlier releases of Microsoft Office.

Quick Access Toolbar


The Quick Access Toolbar is located in the upper left corner and below that is the
Ribbon. It is a customizable toolbar that contains commands that you will probably use
frequently. These features contain many of the functions that were in the menus and
toolbars of previous versions of Word.

Ribbon
The Ribbon is located underneath the Quick Access Toolbar in the top portion of
the document. It has eight tabs: File, Home, Insert, Page Layout, References, Mailings,
Review, and View that contain many features of Word. Each tab leads to a new ribbon

14
which is divided into groups. The groups are logical collections of features designed to
perform functions that you will utilize in developing or editing your Word document.

Status Bar
This bar appears at the very bottom of the screen and provides such information
as the current page, current section, total number of pages, inches from the top of the
page, current line number, and current column number. There is also a Zoom Slider at the
right end of the Status bar which can be easily manipulated to change the size of the
document as you view it. It does not affect the actual size, only the way you look at it on
the screen.

ENGAGE
Have you written a long document before? Maybe a research project or an
academic paper? When a document is very long it is difficult to remember which page
or pages contain what information. Good thing because MS Word allows you to insert a
Table of Contents to easily organize and navigate your document.

A table of contents is usually a list of chapters or section titles of a book or a report


together with the page number where that section or chapter begins.

Most people would do it manually but it would really take a lot of work. With the right
formatting, MS Word can create and update a Table of Contents automatically.

We will use MS Word 2016 to show you how to create a Table of Contents but you can
use the same method in earlier versions of MS Word.

STEP 1: Heading Styles

Using heading styles tells MS Word that you have started a new part of your document.
So every time you use a different heading style, a new section will be created for each
heading.

15
Let’s look at an example:

To create a Table of Contents with three sections, use Heading 1 for the Chapter heading
(Introduction and Mechanisms of Greenhouse Effect). Then use Heading 2 for the Section
title (Functional Units of the house) and use Heading 3 for the specific topics (Modeling
and Materials).

To apply the heading styles, go to the Home tab.

Go to styles group and format the text you want, in this case the Chapter Title, Section
title and so on. Don’t worry if the formatting changes after you apply a heading style.
You just need to highlight the text and format it as you want it to (ex: Times New Roman,
12).

STEP 2: Insert the Table of Contents

After using the heading styles and formatting the text, you can now insert the Table of
Contents (TOC). Make sure that you are on the page where you want to insert the TOC.
Select the References Tab, then click on the Table of Contents command. Choose a
built-in table then the Table of Contents will appear in your document.

16
Note: If you edit or added pages in your document, just click on Table of Contents and
select Update Table. Choose Update the entire table so MS Word will update the page
numbers and text.

17
For additional information about creating the Table of Contents: watch Module 2:
Creating a Table of Contents in Microsoft Word

Bibliography

If you need to write a research paper, then you would have to include a bibliography. It
is a list of sources such as books, articles or even websites that you used in your research
and write your paper. A bibliography makes it easy for someone else to see where you
found your information. It might look something like this;

We will use MS Word 2016 to show how to create a Bibliography. When creating a
bibliography, you must know what style to use. MS Word comes with built-in style guides
such as MLA, APA and others.

STEP 1: Choose the style guide

Click on the References tab, then select your preferred style in the Citations and
Bibliography group.

18
STEP 2: Citations and Sources

To add citations, click on the Insert Citation button and select Add new source

Then a dialog box will appear. Enter all the needed information such as author, title and
type of source (book, article or website) then click OK. The citation will appear in the
document, and the source will be saved. You can quickly add another citation for the
source by clicking Insert Citation and selecting the source from the drop-down menu.

19
STEP 3: Insert Bibliography

Now that you have added all your sources, just click Bibliography. The bibliography will
appear in the current page and you can transfer it where you want it to be, usually at
the end of the document. Your sources will already be formatted to match the selected
style guide. Again, you can change the font style and size (ex: Times New Roman, 12).

For additional information about setting up and inserting a Bibliography: watch Module
2: Adding Citations & References Using MS Word

EXPLORE
Formatting your Technical Paper on MS Word
This section provides instructions for formatting any technical paper with MS Word.
We’ll assume that you are already familiar with the basic features of MS Word. When you
write a research paper, it is important to follow a particular formatting style throughout
your paper. A consistent style enhances readability and helps to give your paper a
professional appearance. For this section, our basis will be on the format set out in the
Publication Manual of the American Psychological Association (APA).

20
Formatting the Page Layout
APA format states that page margins should be one inch in all directions (top,
bottom, left, right). The proper font size is 12-point font, and the acceptable font type is
Times New Roman. All of the text should be set flush with the left margin, creating an
uneven right margin (NOT justified). The paper should be double-spaced throughout,
including the title page, abstract, and body of the document; references, appendixes,
and tables.

● To set the margins:


1. Click the Page Layout tab.
2. Click the Margins button in the Page Setup group.
3. Select Normal.
● To set the font:
1. Click on the Home tab.
2. In the Font group, click the down arrow to the right of the font menu (the
default font type is Calibri).
3. Select Times New Roman.
4. Click the down arrow to the right of the font size menu (the default font size
is 11).
5. Select 12 as the font size.
● To set line spacing:
1. In the Paragraph group (still on the Home tab), click on the Line Spacing
button .
2. Select 2.0 for double-spacing.

Creating a Title Page


The first page of your paper is called the title page. This page includes the title of
your paper, your name, the name of your institution, the manuscript page header, and
the running head. A well-formatted title page can set the tone for your entire paper. To
create a title page:

1. Click on the Insert tab.


2. Click the Page Number button in the Header and Footer group.
3. On the Page Number menu, select Top of Page.
4. Select Plain Number 3 from the choices that appear on the left side of your
screen. This will position the page number on the upper right corner of each
page, beginning with the cover page of your paper. This will also let you edit
the header and footer section of your document.
5. Type the Running Head (which is an abbreviated version of your paper title)
followed by a space. This text will move to the left of the number.
6. Select all the text in the header (running head and page number) and set the
font to Times New Roman and the font size to 12.
7. Click on the red Close Header and Footer button located at the top right of
the tool bar.

21
8. On the first line of the page type the words “Running Head”, a colon, a space,
and a short title of your paper (no more than 50 characters) in ALL CAPITAL
LETTERS.
9. Press the [Enter] key 10 times.
10. Click on the Home tab.
11. Click the Center button in the Paragraph group.
12. Type the following information on separate lines: the full title of the paper, your
name, and the name of your institution.
13. Press [Enter].
14. Click the Align Left button in the Paragraph group.

By following the previous steps, your document should look like the following:

Inserting a Page Break


In a research paper formatted in APA style, you must start a new page for each
of the sections listed below and arrange them in the following order:

● Title page
● Abstract (if required)
● Body
● References
● Appendixes

Essentially, a page break is a point at which a piece of continuous text is split into
two pages. With the Page Break feature of Word, you can easily divide your paper into
sections. To insert a page break:

22
1. Place the cursor after the last text character you typed in a section
2. Click on the Insert tab.
3. Click the Page break button in the Pages group.

Abstract
The abstract is a one-paragraph, self-contained summary of the most important
elements of the paper. The abstract begins on a new page and should not exceed 120
words. All numbers in the abstract (except those beginning a sentence) should be typed
as digits rather than words. To format an abstract:

1. Click on the Home tab.


2. Click the Center button in the Paragraph group.
3. Type the word Abstract on the first line.
4. Press [Enter] to go to the next line of the page.
5. Click the Align Left button in the Paragraph group.
6. Type the text of your abstract. (Do not indent the first line.)
7. Press [Enter].
8. Insert a page break.

Body
The body of the paper begins on a new page. Subsections of the body of the
paper do not begin on new pages. All paragraphs are to be indented ½ inch from the
left margin.

Headings
Headings are used to organize the document and reflect the relative importance
of sections.

● Main (first level) headings use centered uppercase and lowercase letters (e.g.,
Method, Results, References).
● Subheadings (second level headings) are italicized and use flush left, uppercase
and lowercase letters (e.g., Participants, Apparatus, and Procedure as subsections
of the Method section).

Reference Citations in Text


Following APA style, source material must be documented in the body of the
paper by citing the author(s) and date(s) of the sources. The underlying principle here is
that ideas and words of others must be formally acknowledged. The reader can obtain
the full source citation from the list of references that follows the body of the paper.
Paraphrased or summarized material is documented in the following manner:

● If the names of the authors of a source are part of the formal structure of the
sentence, the year of publication appears in parentheses following the
identification of the authors. Example: Smith and Jones (2004) found Einstein’s
theory flawed.
● If the authors of a source are not part of the formal structure of the sentence, both
the authors and years of publication appear in parentheses, separated by

23
semicolons. Example: Subsequent research supports these results (Brown &
Greene, 2006; Hamilton, 2008).
● The same general rules regarding author(s) and date(s) apply to electronic
sources cited within your research paper. For a source without an identified
author, use the first few words of the title to document the source within the text,
followed by the date of publication, if given. Example: His status as a figure in pop
culture has grown in the last generation (“Einstein Online,” n.d.).

Please take note that the ampersand symbol (&) is used when multiple authors are
identified in parenthetical material, but “and” is used when multiple authors are identified
as part of the formal structure of the sentence. Also, if you refer to a work more than once
in a paper, give the author and date the first time you mention the work, and then give
only the author in subsequent mentions. We’ll show you how to automatically generate
these citations on the following section.

Quotations
When a direct quotation is used, always include the author, year, and page
number as part of the citation. Give the page number immediately after the quotation,
even in mid-sentence. The key is to remember that all 3 elements of the citation – author,
year, page number – must be given, whether in parentheses or as part of the sentence.
For example: In their 2007 article, Duncan and Sebastian claimed the results of the
university study were inconclusive due to the “unscientific method of data collection” (p.
121).

If the quotation came from an electronic source such as an online article or web
page, give the paragraph number if no page number is available. You may use the
abbreviation para. or the paragraph symbol. You can find the paragraph symbol (¶) by
going to the Insert tab and clicking Symbol.

A quotation of fewer than 40 words (such as the example above) should be


enclosed in double quotation marks and should be incorporated into the formal structure
of the sentence. However, a long quotation of more than 40 words should be set off
(without quotations marks) from the surrounding text. A long quotation is a double-
spaced block of text, indented ½ inch from the left margin. Place the parenthetical
reference 2 spaces after the end punctuation of the last sentence. To format a long
quotation:

1. Begin the quotation on a new line.


2. Type the quotation, and then select the text.
3. On the Home Tab, click the dialog box launcher (small arrow button in the lower-
right corner) in the Paragraph group.
4. In the Paragraph Dialog Box, under the Indents and Spacing tab, increase the left
indentation to 0.5”.
5. Click OK

24
References
All sources included in the References section must be cited in the body of the
paper. The References section begins on a new page with the heading “References”
centered on the first line below the manuscript page header. The references (with
hanging indent – see below) begin on the line following the References heading. Entries
are organized by last names of first authors. Most Reference entries have three
components:

1. Author(s): Multiple authors are listed in the same order as specified in the source,
using last names and initials. Commas separate all authors. When there are seven
or more authors, list the first six and then use “et al.” to represent the remaining
authors. If no author is identified, the title of the document begins the reference.
2. Year of Publication: Place the year in parentheses following the author(s), with a
period following the closing parenthesis. If no publication date is identified, use
“n.d.” in parentheses following the author(s).
3. Source Reference: For a journal article, this includes the article title, journal title,
volume (and sometimes issue) number, and page number(s); for a book, it
includes the title, city of publication, and publisher. In general, the source
reference for web documents includes author and date (if known) as well as title,
date of retrieval, and URL (web address). Italicize titles of journals, books, and web
pages, and periodical volume numbers.

If you’re writing a reference section for your paper, MS Word has a simple built-in
reference function at the References tab. Here you can manually enter references and
refer to them in the text and create a bibliography in the most common styles (APA,
Harvard, MLA, etc). The built-in function in Word is suitable if you have a limited number
of references and if you don't need to have access to your references from multiple
computers.

Setting the Bibliography Style


As you begin your research paper or article, the first step to ensure proper
formatting of your citations and bibliography references is to select the required
bibliography style from the References tab of the ribbon. The most current version of
common styles like APA, MLA, and Chicago are ready for selection. Choose the APA
style.

Please note that this option can be changed at any time and will automatically
update all citations and bibliography fields throughout the document to match the
selected style.

Create a source
Once the style has been established, you must add source information to be used
for generating the citations and bibliographic information included within the
manuscript. Depending on preference, you can create sources as a complete list of
references before developing your manuscript, or you can create sources as needed
within the document. Regardless, when a new source is created, it is added to a master

25
list of references for both the working document and the local computer. To add sources
to your document on a PC:

1. Click the Manage Sources button on the References tab.


2. Click the New button in the Source Manager dialog.
3. Select the type of source from the drop-down list, and then complete all known
fields on the form to add the source.
4. Click OK.

Inserting Citations
Once the source has been added to the citations list for the document, citations
are inserted where needed within the document. To insert a citation:

1. Place the insertion point in the document where the citation is needed
2. Click the Insert Citation button arrow.
3. Click the appropriate citation option from the list.

Creating a Bibliography
When all sources have been added to the document, a bibliography or works
cited page can be automatically generated. Before inserting the bibliography, however,
you should verify that you have cited all of the sources you will include in the bibliography
and to remove any unused sources from the reference list. To create a bibliography:

1. Click the Bibliography button on the References tab of the ribbon.


2. Select the desired option for inserting the bibliography in the selected style.

Review Questions for Reflection:

● What are the steps in inserting a Table of Contents in a document?


● Which is easier for you to do? To do TOC manually or to use the features
available in MS Word?
● Now that you have learned how to use the features of MS Word how can it help
you in your school requirements?

26
EXPLAIN
Usually, when you are writing a long document or a research paper and you have to
do different formatting styles such as different page numbers (i, ii, iii and 1, 2, 3 ...) or
placing a header starting from page 1, the easiest way to do it is to open a new
document every time you have to change a format. Am I right? Fortunately, MS Word
has the capability to create a document with different page numbers and headers
using Page Breaks.

STEP 1: Move your cursor to the place where you want to put the page break. But if you
want to change a formatting style such as from a title page (no page number) to the
next page which is a Table of Contents with page i, then you might as well put it at the
end of your title page. This will tell MS Word to separate the title page from the TOC
page.

27
STEP 2: Do not forget to click the Link to Previous button in the design tab once you
have inserted a page number in the next page. Then change the format of your TOC
page.

After you have clicked the Link to Previous button this will tell MS Word that formatting
you will apply to the next page will not be applied to the previous page. For this
example, we will use the page number i for the TOC page. Go to the Insert Tab and
select the Page Number then choose Format Page Numbers.

28
Then select the format you want, in this example we will use i,ii,iii. Do not forget to select
page numbering at the lower part which is Start at i then click OK. Notice that initially
your page number is 2 but when you change the number format it will change to i.

If you want to delete or remove a page break or section break, you can simply click on
the symbol for Show/Hide.

Then click on the page break/section break you want to remove then press delete.

29
ELABORATE
In the professional world, sending out information to convey important information
is vital. Because of technology, things are sent much faster than the traditional
newsletters or postal mail. You can now use the internet to send out information you need
to share. What if we could still do things much faster, an automated way of creating and
sending uniform letters with different recipients? Would that not be more convenient?

We will learn one of the most commonly used features of MS Word called “Mail
Merge”. As the name suggests, this feature allows you to create documents and
combine or merge them with another document or data file. It is commonly used when
sending out advertising materials to various recipients.

Mail merging basically requires two components: the document that contains the
message and the document or file that generally contains the list of names and
addresses.

Let’s look at this example:

30
Two components of Mail Merge

1. Form document

Our sample above is what we call a form document- the first components of our
mail merged document. It is generally the document that contains the main body
of the message we want to send.

Also in the form you can see some symbols or mark with double-headed arrows (
<< >> ). These are what we call place holders or data fields/merge fields. This marks
the position on your form document where individual data or information will be
inserted.

2. List or data file

The next component of our mail merged document is the list or data file. This is
where the individual data that needs to be merged to the form document is
placed and maintained. You can create the data file in MS Word or MS Excel or
other data formats. This way, fields that needed to be filled up on the form
document can be easily maintained without changing the form document. You
can easily add, remove or modify your data.

LABEL GENERATION

Included in the mail merge feature is the Label Generator. After you print out your form
letters, you will need to send it to individual recipients in an envelope with the matching
address printed directly on the envelope or on a mailing label to stick on. Doing the same
process as the standard mail merge, you can print individual labels.

STEPS IN CREATING A MAIL MERGE

1. Write the form document such as a letter, certificate or any document that you
want to merge.
2. On the Mailings Tab, choose Start Mail Merge then select Letters.

31
2. Still on the Mailings Tab, choose Select Recipients, then Type a New List.

3. Click on the Customize Columns button on the dialog box for the Address List.
Once you select that button a dialog box will appear.

If you want to delete a field, then just select it, then click the Delete button on
the right side of the dialog box. If you need to add another field just click the
Add button.

4. Type the individual data from your list corresponding to the Title, Name,
Company, Address. Press the Tab key each time you enter the next field. Click
New Entry to add another record.

32
5. Repeat step 4 until you enter all the records you want. Once you are done
typing your data, click the OK button on the Add New List dialog box to save
your data.
6. Insert the fields you need like First Name, Last Name, Company, Address Line 1
and City. Go to Insert Merge Field. Make sure that you place the cursor in the
place where you want it before selecting the field.

7. You can now preview the results and once you are done click Finish and Merge.
You can print the merge document or edit the individual documents.

33
For additional information about mail merge: watch the following videos

● Module 2: Word_ Mail Merge.mp4


● Module 2: Mail Merge from Excel to Microsoft Word.mp4

EVALUATE

Now that you have learned about the mail merge feature in MS Word do the GRADED
Activity #1 (M2.1) in MS Word.

34
GRADED Activity #1 (M2.1): Create a Certificate using the Mail Merge of MS Word

INSTRUCTIONS:

1. Create a certificate template with the following essential details;

a. Name and logo of institution or facility providing the certificate.


b. Course, training/seminar or competition the person completed in
order to be eligible for the certificate.
c. Name (Given Name Middle Initial. Family Name) of person
receiving the certificate.
d. Official signature and date.
*This would serve as the form document to be merged;

2. Create a list of names (your classmates’ names, a total of 50 names). If there are less
than 50 in the class, add other unique names.

3. Merge the certificate with the list to come up with a total of 50 certificates with
individual and unique names (no repetition of names please).

4. Save the merged document with the filename: LastnameFirstnameCertClasscode.


There should be 2 files, the word file(.docx) and a .pdf file and submit it to your
instructor.

Also answer the following True or False questions:

Name: ________________________________________ Score:___________


Class Code: ____________________________________ Date: ___________

True or False: Write T if the statement is True and F if the statement is False.

________1. When you want to insert a Table of Contents in MS Word you can simply go
to the References Tab and select the Automatic Table 1 found in the drop down list.
________ 2. You can create a Bibliography anytime after you have inserted one or more
sources into your document.
________ 3. Different heading styles can be used to create a Table of Contents in MS
Word.
________ 4. The form document contains the recipient’s information.
________ 5. The place holders or merge fields are denoted or marked by the text with
double-headed arrows (<< >>).

References:

Empowerment Technologies, Innovative Training Works Inc. 2016 Edition.


Creating Table of Contents in MS Word. https://edu.gcfglobal.org/en/word-tips/how-to-
create-a-table-of-contents-in-word/1/
Using Page Breaks in MS Word.
https://www.kimidatlantic.com/blog/how-to-insert-or-remove-a-page-break-in-
microsoft-word-2016/

35
Module 3: The Spreadsheet Program

This module demonstrates the use of worksheets to show statistical/mathematical


data and translate statistical data into meaningful charts. We’ll introduce and discuss the
interface of the spreadsheet software, cell addressing, data types, table formats, sorting
and filtering tables, creating mathematical expressions and the use of functions.

Getting Started
When you open MS Excel for the first time, a blank spreadsheet will appear (shown
below). In more recent versions however, the Excel Start Screen will appear instead,
allowing you to create a new workbook, choose a template, and access your recently
edited workbooks.

36
MS Excel’s interface is divided into two sections, the Application Window, and the
Workbook Window.

Application Window
The Application Window provides the space for your worksheets and workbook
elements such as charts. The components of the Application Window are described
below.

● The Quick Access Toolbar: The Quick Access Toolbar lets you access common
commands no matter which tab is selected. By default, it includes the Save, Undo,
and Repeat commands.
● The Ribbon: MS Excel uses a tabbed Ribbon system instead of traditional menus.
The Ribbon contains multiple tabs, each with several groups of commands. You
will use these tabs to perform the most common tasks in Excel.
● The Formula Bar: In the formula bar, you can enter or edit data, a formula, or a
function that will appear in a specific cell. In the image below, cell C1 is selected
and 1984 is entered into the formula bar. Note how the data appears in both the
formula bar and in cell C1.

● The Name Box: The Name box displays the location, or "name" of a selected cell.
In the image below, cell B4 is selected. Note that cell B4 is where column B and
row 4 intersect.

The Workbook Window


Excel files are called workbooks. Each workbook holds one or more worksheets
(also known as "spreadsheets"). Fun fact: There can be a max of 1,048,576 rows and
16,384 columns in an excel worksheet.

The Worksheet
Depending on the version of your MS Excel, whenever you create a new Excel
workbook, it will contain one or three worksheet(s) named Sheet1 (Sheet2 and Sheet3 if
you have three). A worksheet is a grid of columns and rows where columns are

37
designated by letters running across the top of the worksheet and rows are designated
by numbers running down the left side of the worksheet.

When working with a large amount of data, you can create multiple worksheets
to help organize your workbook and make it easier to find content. You can also group
worksheets to quickly add information to multiple worksheets at the same time.

● Renaming a worksheet:
1. Right-click the worksheet you wish to rename, then select Rename from the
worksheet menu.
2. Type the desired name for the worksheet.
3. Click anywhere outside of the worksheet, or press Enter on your keyboard. The
worksheet will be renamed.
● To insert a new worksheet:

1. Locate and select the New sheet button. or

2. A new, blank worksheet will appear.


● To delete a worksheet (Warning: The Undo button will not undo the deletion of a
worksheet):
1. Right-click the worksheet you wish to delete, then select Delete from the
worksheet menu.
2. The worksheet will be deleted from your workbook.
● To copy a worksheet
1. Right-click the worksheet you want to copy, then select Move or Copy from the
worksheet menu.

38
2. The Move or Copy dialog box will appear. Choose where the sheet will appear
in the Before sheet: field. In our example, we'll choose (move to end) to place
the worksheet to the right of the existing worksheet
3. Check the box next to Create a copy, then click OK.
4. The worksheet will be copied. It will have the same title as the original worksheet,
as well as a version number.
● To move a worksheet
1. Select the worksheet you wish to move. The cursor will become a small

worksheet icon .
2. Hold and drag the mouse until a small black arrow appears above the desired
location.
3. Release the mouse. The worksheet will be moved.

The Scrolling Buttons


These buttons scroll the display of sheet tabs one at a time or to display the first
and last grouping of sheet tabs and are located to the left of the sheet tabs.

The Scroll Bars


Your spreadsheet may frequently have more data than you can see on the screen
at once. Click, hold and drag the vertical or horizontal scroll bar depending on what part
of the page you want to see.

Cell Addressing
Whenever you work with Excel, you'll enter information, or content, into cells. Cells
are the basic building blocks of a worksheet. You'll need to learn the basics of cells and
cell content to calculate, analyze, and organize data in Excel.

39
Cell Basics
Every worksheet is made up of thousands of rectangles, which are called cells. A
cell is the intersection of a row and a column. Columns are identified by letters (A, B, C),
while rows are identified by numbers (1, 2, 3).

Each cell has its own name, or cell address, based on its column and row. In this
example, the selected cell intersects column C and row 5, so the cell address is C5. The
cell address will also appear in the Name box. Note that a cell's column and row
headings are highlighted when the cell is selected.

You can also select multiple cells at the same time. A group of cells is known as a
cell range. Rather than a single cell address, you will refer to a cell range using the cell
addresses of the first and last cells in the cell range, separated by a colon. In the images
below, two different cell ranges are selected:

● Cell range A1:A8

● Cell range A1:B8

40
Selecting a Cell Range
1. Click, hold, and drag the mouse until all of the adjoining cells you wish to select
are highlighted.
2. Release the mouse to select the desired cell range. The cells will remain selected
until you click another cell in the worksheet.

Cell Content
Any information you enter into a spreadsheet will be stored in a cell. Each cell can
contain several different kinds of content, including text, formatting, formulas, and
functions.

● Text: Cells can contain text, such as letters, numbers, and dates.
● Formatting Attributes: Cells can contain formatting attributes that change the way
letters, numbers, and dates are displayed. For example, percentages can appear
as 0.15 or 15%. You can even change a cell's background color.
● Formulas and Functions: Cells can contain formulas and functions that calculate
cell values (More on these later).

Inserting Content in a Cell


1. Click a cell to select it.
2. Type content into the selected cell, then press Enter on your keyboard.
3. The content will appear in the cell and the formula bar. You can also input and
edit cell content in the formula bar.

Deleting Cell Content


1. Select the cell with content you wish to delete.
2. Press the Delete or Backspace key on your keyboard. The cell's contents will be
deleted.

Deleting Cells
Take note that if you delete the entire cell, the cells below it will shift up and
replace the deleted cells.

1. Select the cell(s) you wish to delete.


2. Select the Delete command from the Home tab on the Ribbon.
3. The cells below will shift up.

Copying and Pasting Cell Content


1. Select the cell(s) you wish to copy.
2. Click the Copy command on the Home tab, or press Ctrl + C on your keyboard.
3. Select the cell(s) where you wish to paste the content. The copied cells will now
have a dashed box around them.
4. Click the Paste command on the Home tab, or press Ctrl + V on your keyboard.
5. The content will be pasted into the selected cells.

Using the Fill Handle


There may be times when you need to copy the content of one cell to several
other cells in your worksheet. You could copy and paste the content into each cell, but

41
this method would be very time consuming. Instead, you can use the fill handle to quickly
copy and paste content to adjacent cells in the same row or column.

1. Select the cell(s) containing the content you wish to use. The fill handle will appear
as a small square in the bottom-right corner of the selected cell(s).

2. Click, hold, and drag the fill handle until all of the cells you wish to fill are selected.
3. Release the mouse to fill the selected cells.

Continuing a Series Using the Fill Handle


The fill handle can also be used to continue a series. Whenever the content of a
row or column follows a sequential order, like numbers (1, 2, 3) or days (Monday, Tuesday,
Wednesday), the fill handle can guess what should come next in the series. In many
cases, you may need to select multiple cells before using the fill handle to help Excel
determine the series order.

Formulas and Functions


One of the most powerful features in Excel is the ability to calculate numerical
information using formulas. All formulas in Excel must begin with an equal sign (=). This is
because the cell contains, or is equal to, the formula and the value it calculates.

Arithmetic Operations
Excel uses standard operators for formulas, such as a plus sign for addition (+), a
minus sign for subtraction (-), an asterisk for multiplication (*), a forward slash for division
(/), and a caret (^) for exponents.

Order of Operation
Excel calculates formulas based on the following order of operations:
1. Operations enclosed in parentheses.
2. Exponential calculations (3^2, for example).
3. Multiplication and division, whichever comes first.
4. Addition and subtraction, whichever comes first.

Cell References
While you can create simple formulas in Excel manually (for example, =2+2 or
=5*5), most of the time you will use cell addresses to create a formula. This is known as
making a cell reference. Using cell references will ensure that your formulas are always
accurate because you can change the value of referenced cells without having to
rewrite the formula.

42
By combining a mathematical operator with cell references, you can create a
variety of simple formulas in Excel. Formulas can also include a combination of cell
references and numbers, as in the examples below:

=A1+A2 Adds cells A1 and A2


=C4-3 Subtracts 3 from cell A4
=E7/J4 Divides cell E7 by cell J4
=N10*1.05 Multiplies cell N10 by 1.05
=R5^2 Finds the square of cell R5
Relative and Absolute Cell References
● Relative cell references: By default, all cell references are relative references.
When copied across multiple cells, they change based on the relative position of
rows and columns. For example, if you copy the formula =A1+B1 from row 1 to row
2, the formula will become =A2+B2. Relative references are especially convenient
whenever you need to repeat the same calculation across multiple rows or
columns.
● Absolute cell references: There may be times when you do not want a cell
reference to change when filling cells. Unlike relative references, absolute
references do not change when copied or filled. You can use an absolute
reference to keep a row and/or column constant.
An absolute reference is designated in a formula by the addition of a dollar sign
($). It can precede the column reference, the row reference, or both.

$A$2 The column and the row do not change when copied
A$2 The row does not change when copied
$A2 The column does not change when copied
Note: When writing a formula, you can press the F4 key on your keyboard to switch
between relative and absolute cell references. This is an easy way to quickly insert an
absolute reference.

For more information on Cell References, watch Module 3 Excel_ Relative and Absolute
Cell References

Functions
A function is a predefined formula that performs calculations using specific values
in a particular order. Excel includes many common functions that can be useful for
quickly finding the sum, average, count, maximum value, and minimum value for a range
of cells. In order to use functions correctly, you'll need to understand the different parts
of a function and how to create arguments to calculate values and cell references.

The workbook “MS Excel Demo.xlsx” contains a demonstration of the most


commonly used functions in Excel. Please take time to check it out while reading this.

Parts of a Function
In order to work correctly, a function must be written a specific way, which is called
the syntax. The basic syntax for a function is an equal sign (=), the function name (SUM,

43
for example), and one or more arguments. Arguments contain the information you want
to calculate.

Arguments
Arguments can refer to both individual cells and cell ranges and must be enclosed
within parentheses. You can include one argument or multiple arguments, depending
on the syntax required for the function. For example, the function =AVERAGE(B1:B9)
would calculate the average of the values in the cell range B1:B9. This function contains
only one argument – that is, the cell range B1:B9.

Multiple arguments must be separated by a comma. For example, the function


=SUM(A1:A3, C1:C2, E2) will add the values of all the cells in the three arguments.

The Function Library


While there are hundreds of functions in Excel, the ones you use most frequently will
depend on the type of data your workbooks contain. There is no need to learn every
single function, but exploring some of the different types of functions will be helpful as
you create new projects. You can search for functions by category, such as Financial,
Logical, Text, Date & Time, and more from the Function Library on the Formulas tab. To
access the Function Library:

1. Select the Formulas tab on the Ribbon.

2. The Function Library will appear.

44
EXPLORE
In this Excel worksheet we will be looking at what’s so different about weighted averages
as compared to non-weighted averages. For this activity we will look at a typical
student’s grade records for an entire year in one particular class. First, before we begin,
what is a weighted average? A teacher may hand out a syllabus with a grading policy
that looks like this:

Computer Fundamentals Grading Policy:

3 Tests 30% Each Test 10%

5 Quizzes 30% Each Quiz 6%

7 Homework Assignments 28% Each Homework 4%

Participation 12% Participation 12%

TOTAL: 100%

This is a weighted average. One test is worth 10% of your grade while one quiz is
worth almost half of that.

Let’s look at what a grading policy might look like if nothing was weighted.

Computer Fundamentals Grading Policy:

3 Tests 18.75% Each Test 6.25%

5 Quizzes 31.25% Each Quiz 6.25%

7 Homework Assignments 43.75% Each Homework 6.25%

Participation 6.25% Participation 6.25%

TOTAL: 100%

Each test, quiz, and homework assignment are all worth 6.25%. No one thing is
weighted as being more important than the rest.

1.Open Microsoft Excel.

2. Click on cell A1 then type “Test Scores (%) ” then on cell B1 “Weight %” and cell C1 “
“Weighted Scores (Test)”. Your initial worksheet should look like this;

45
3. Input the Test Scores as follows; 95, 85, 89 to cell A2,A3 and A4. Followed by the
individual weight % in column B. Note that each test is 10% of the grade.

4. Enter the rest of the input as shown below:

The spreadsheet is split apart into two main sections. The first section which takes up
columns A, B, and C are the weighted averages. The second section, columns E and F,
are the non-weighted averages.

Column A shows all the student’s percentage scores he/she received on tests, quizzes,
homework assignments, and participation. Column B shows the percent that each test
or assignment was weighted. Column C will show the scores after they have been
weighted by the proper percentage.

Column F shows the percentage scores of the student’s grades without being weighted.
Column F is exactly the same as column A.

5. Make sure that the total weight % is equal to 100%. By using the SUM function, you can
easily compute for the total weight %. Because we are working with percentages, we

46
need to multiply the entire formula by 100. Note that you can also calculate it by using
the addition operator (=B1+B2+ … +B23) then multiply it with 100.

We used the SUM function, the syntax for this function is;

= SUM(number 1,[number2],{number3],...)

Note that the values can be numbers, cell references, cell range in any combination. In
our example above, we used a cell range (group of cells).

6. Move over to Column F. We need to get the average of the student’s scores in this
column. Click on cell F27.

The average function returns the average (arithmetic mean) of the arguments. For
example, if the range A1:A20 contains numbers, the formula =AVERAGE(A1:A20) returns
the average of those numbers.

SYNTAX:

AVERAGE(number1, [number2], ...)

The AVERAGE function syntax has the following arguments:

47
● Number1 Required. The first number, cell reference, or range for which you want
the average.
● Number2, ... Optional. Additional numbers, cell references or ranges for which
you want the average, up to a maximum of 255.

7. On cell F27 enter the formula; =AVERAGE open parenthesis then click and drag from
cells F2 to F4 then enter a comma then click and drag from cells F7 to F11 then enter a
comma then click and drag from cells F14 to F20 then enter another comma. Click cell
F23 and end with parenthesis. It should look like this:

Hit enter. Cell F23 should now read an average score of about 91.31

8. Move over to Row C. We need to figure out what the weighted score is of each test
or assignment. Let’s compute for the product of Test Score % and Weight %. Click on
cell C2 then enter the formula, = (A2* B2). Note that in excel the asterisk(*) is the
operator used for multiplication.

48
9. With your mouse, move over the bottom right hand corner of cell C2 until a small black
plus sign appears. Click and drag down to cell C4. This will move the formula you typed
in for cell C2 down into the next two cells with the corresponding rows.

10. In cell C7, enter in the formula, =(A7*B7), then hit enter. Drag that formula down to
cell C11. In cell C14, enter in the formula, =(A14*B14), then hit enter. Drag that formula
down to cell C20. In cell C23, enter in the formula, =(A23*B23), then hit enter.

11. Click on cell C27 and enter in the formula, =SUM( then Click and drag from cells C2
to C4 then enter a comma. Then drag from cells C7 to C11 and enter a comma. Then
drag from cells C14 to C20 and enter a comma. Then click on cell C23 and end with
parenthesis. Hit enter.

The cell should now read a Weighted Grade of about 91.26.

49
Commonly Used Functions (MS Excel Demo.xlsx)

= COUNT(value1,value2,…) counts the number of cells that contain numbers and


number within the list of arguments
value1, value2, ... are 1 to 255 arguments that can contain or refer to a variety
of different types of data, but only numbers are counted.
Remarks
- Arguments that are numbers, dates, or text representation of numbers are
counted.
- Logical values and text representations of numbers that you type directly into
the list of arguments are counted.
- Arguments that are error values or text that cannot be translated into numbers
are ignored.
- If an argument is an array or reference, only numbers in that array or reference
are counted. Empty cells, logical values, text, or error values in the array or
reference are ignored.
= MIN(number1,number2,...) returns the smallest number in a set of values
= MAX(number1,number2,...) returns the largest number in a set of values
= SUM(number1,number2,…) adds the total number in a range
= AVERAGE(number1,number2,…) return the arithmetic sum of the arguments
= ROUND(number,num_digits) rounds a number to a specified number of digits
number is the number you want to round.
num_digits specifies the number of digits to which you want to round number.
Remarks
- If num_digits is greater than 0 (zero), then number is rounded to the specified
number of decimal places.
- If num_digits is 0, then number is rounded to the nearest integer.
- If num_digits is less than 0, then number is rounded to the left of the decimal
point.
= COUNTIF(range,criteria) - Counts the number of cells within a range that meet the
given criteria
range is one or more cells to count, including numbers or names, arrays, or
references that contain numbers. Blank and text values are ignored.
criteria is the criteria in the form of a number, expression, cell reference, or text
that defines which cells will be counted. For example, criteria can be expressed as 32,
"32", ">32", "apples", or B4.
=SUMIF(range, criteria, [sum_range]) - sum the values in a range that meet criteria that
you specify.
range Required. The range of cells that you want evaluated by criteria. Cells in
each range must be numbers or names, arrays, or references that contain numbers.
Blank and text values are ignored.
criteria Required. The criteria in the form of a number, expression, a cell
reference, text, or a function that defines which cells will be added.
sum_range Optional. The actual cells to add, if you want to add cells other than
those specified in the range argument. If the sum_range argument is omitted, Excel
adds the cells that are specified in the range argument.

50
= IF(logical_test, value_if_true, value_if_false) returns one value if the condition you
specify evaluates to true and another value if it evaluates to false
logical_test is any value or expression that can be evaluated to TRUE or
FALSE.
For example, A10=100 is a logical expression; if the value in cell A10 is equal to
100, the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
This argument can use any comparison calculation operator.
value_if_true is the value that is returned if logical_test is TRUE.
value_if_false is the value that is returned if logical_test is FALSE.

Text Functions

=LEFT(text, num_char)
You can use the Left function when you want to extract the leftmost characters from a
string. Similarly, you can also use the RIGHT function to extract the rightmost characters
from a string.
=PROPER (text)
Proper function in Excel capitalizes each word in the string that is, it converts the case
into proper case.
=TRIM(text)
Trim function in Excel removes the unnecessary spaces from a particular string.
=UPPER(Text )
Upper function in Excel converts the text into Upper case from lower case.
=CONCATENATE (text1, text2….)
Concatenate function in Excel helps to join the text of two or more cells.

Sorting Data
As you add more content to a worksheet, organizing that information becomes
especially important. You can quickly reorganize a worksheet by sorting your data. For
example, you could organize a list of contact information by last name. Content can be
sorted alphabetically, numerically, and in many other ways.

When sorting data, it's important to first decide if you would like the sort to apply
to the entire worksheet or just a cell range.

● Sort sheet organizes all of the data in your worksheet by one column.
● Sort range sorts the data in a range of cells, which can be helpful when working
with a sheet that contains several tables. Sorting a range will not affect other
content on the worksheet.

To sort a sheet:

1. Select a cell in the column you wish to sort by.


2. Select the Data tab on the Ribbon, then click the Ascending command to Sort

A to Z, or the Descending command to Sort Z to A.


3. The worksheet will be sorted by the selected column.

51
Filtering Data
If your worksheet contains a lot of content, it can be difficult to find information
quickly. Filters can be used to narrow down the data in your worksheet, allowing you to
view only the information you need. To filter data

1. In order for filtering to work correctly, your worksheet should include a header row,
which is used to identify the name of each column.
2. Select the Data tab, then click the Filter command.
3. A drop-down arrow will appear in the header cell for each column.
4. Click the drop-down arrow for the column you wish to filter.
5. The Filter menu will appear.
6. Uncheck the box next to Select All to quickly deselect all data.
7. Check the boxes next to the data you wish to filter, then click OK.
8. To remove all filters from your worksheet, click the Filter command on the Data
tab.

Charts and Graphs


MS Excel has several different types of charts, allowing you to choose the one that
best fits your data. In order to use charts effectively, you'll need to understand how
different charts are used.

● Column charts use vertical bars to represent data. They can work with many
different types of data, but they're most frequently used for comparing
information.
● Line charts are ideal for showing trends. The data points are connected with lines,
making it easy to see whether values are increasing or decreasing over time.
● Pie charts make it easy to compare proportions. Each value is shown as a slice of
the pie, so it's easy to see which values make up the percentage of a whole.
● Bar charts work just like Column charts, but they use horizontal bars instead of
vertical bars.
● Area charts are similar to line charts, except that the areas under the lines are filled
in.
● Surface charts allow you to display data across a 3D landscape. They work best
with large data sets, allowing you to see a variety of information at the same time.

To insert a chart:

1. Select the cells you want to chart, including the column titles and row labels. These
cells will be the source data for the chart.
2. From the Insert tab, click the desired Chart command.
3. Choose the desired chart type from the drop-down menu.
4. The selected chart will be inserted in the worksheet.

Chart Layout and Style


After inserting a chart, there are several things you may want to change about
the way your data is displayed.

52
● Excel allows you to add chart elements—such as chart titles, legends, and data
labels—to make your chart easier to read. To add a chart element, click the Add
Chart Element command on the Design tab, then choose the desired element
from the drop-down menu.
● To edit a chart element, like a chart title, simply double-click the placeholder and
begin typing.
● Excel also includes several different chart styles, which allow you to quickly modify
the look and feel of your chart. To change the chart style, select the desired style
from the Chart styles group.
● Sometimes you may want to change the way charts group your data. From the
Design tab, select the Switch Row/Column command.
● If you find that your data isn't well suited to a certain chart, it's easy to switch to a
new chart type. From the Design tab, click the Change Chart Type command.
The Change Chart Type dialog box will appear, then select the desired chart
● Whenever you insert a new chart, it will appear as an object on the same
worksheet that contains its source data. Alternatively, you can move the chart to
a new worksheet to help keep your data organized.
1. Select the chart you wish to move.
2. Click the Design tab, then select the Move Chart command.
3. The Move Chart dialog box will appear. Select the desired location for the
chart.
4. Click OK.

GRADED Activity #2 (M3.1): Payroll Activity using MS Excel

INSTRUCTION: Open the Excel Payroll.xlsx file and perform the given instructions.

References:
COUNT Function https://support.office.com/client/en-us/videoplayer/embed/RWeWqL?pid=ocpVideo0-
innerdiv-oneplayer&jsapi=true&postJsllMsg=true&maskLevel=20&market=en-us

COUNTIF Function https://support.office.com/client/en-us/videoplayer/embed/RE4GSoN?pid=ocp


Video0-innerdiv-oneplayer&jsapi=true&postJsllMsg=true&maskLevel=20&market=en-us

IF Function https://support.office.com/client/en-us/videoplayer/embed/RE285qJ?pid=ocpVideo0-
innerdiv-oneplayer&jsapi=true&postJsllMsg=true&maskLevel=20&market=en-us

SUM Function https://support.office.com/client/en-us/videoplayer/embed/RE25Ncp?pid=ocpVideo0-


innerdiv-oneplayer&jsapi=true&postJsllMsg=true&maskLevel=20&market=en-us
SUMIF Function https://support.office.com/client/en-us/videoplayer/embed/RWe8KX?pid=ocpVideo0-
innerdiv-oneplayer&jsapi=true&postJsllMsg=true&maskLevel=20&market=en-us

Sorting Data https://support.office.com/client/en-us/videoplayer/embed/RWfzt5?pid=ocpVideo0-


innerdiv-oneplayer&jsapi=true&postJsllMsg=true&maskLevel=20&market=en-us

53
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

Java Programming Environment


● Java programming language specification
o Syntax of Java programs
o Defines different constructs and their semantics

54
● 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 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
● Module 4: How to Install JDK and JCREATOR LE.mp4
You may also choose to use some online java compilers enumerated below:
● 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

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.

55
● 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);
● 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”) ;
}

56
● 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.

Naming Rules and Styles


● 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 uppercase letter for the first character of class names.
o Use meaningful names.
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.
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.
● Not following these styles does not mean breaking the rules, but it is always good
to be in style!

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

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
short 2 bytes −32768 to 32767
Integer int 4 bytes −2,147,483,648 to 2,147,483,647
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 = ' ';

58
● 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, …
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.

59
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:

● multiple variables can be created in one


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;
60
● 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

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

61
● 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

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.

62
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;

63
// 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
Logical AND True && True = True
&& ● Returns True if all of its boolean True && False = 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||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

64
++ 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.

65
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.
● Usually, this step involves breaking up the problem into smaller and simpler sub-
problems.
66
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

67
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.

68
● 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.

69
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.

70
//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(); Start

//output a prompt message


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

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


int num2 = kbd.nextInt(); num2

//formula to add the two numbers


int sum = num1+num2; sum = num1+num2

//display the sum


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

For additional information about the Scanner class: watch


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

Problems for Program Development: Solve the following Sequence Programs

1. Filename: PipeProblem_FamilyName
Create 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.0

71
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
9
degrees Celcius: 𝐹 = 5 ∗ (𝐶 + 32)

3. Filename: AngleToRadianProblem_FamilyName
Create a java program that will read an
angle expressed in degrees (deg), minutes
(min) and seconds (sec), output in radians
(rad).
𝑚𝑖𝑛 𝑠𝑒𝑐
𝑑𝑒𝑔𝑑𝑒𝑔 + +
36 3600
Formula: 𝑟𝑎𝑑 = 𝜋 ∗ ( )
180

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: 𝑃_𝑊𝐴𝑇𝑇 = 𝑅_𝑂𝐻𝑀 ∗ 𝐼_𝐴𝑀𝑃2
Sample Output:

72
5. Filename: ChangeProblem_FamilyName
Input the amount of purchase which is
less than P100.00. Create a java program
that 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: 𝑠 = 2.0
𝐴
Also the radius of the largest inscribed circle is given by: 𝑟_𝑖𝑛𝑠𝑐 = 𝑠
𝑎∗𝑏∗𝑐
and the radius of the smallest circumscribed circle is: 𝑟_𝑐𝑖𝑟𝑐 = 4∗𝐴

r_circ
r_insc

Inscribed Circle Circumscribed Circle


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:

73
Graded Activity #3 (M6.1): Sequence Problem

Instruction:

Using the sequence programming concept, create a java program that will read
three resistors, determine and output the total resistance in terms of series and in
terms of parallel connection.
Type of Connection
Series Parallel
Formula to compute total resistance: Formula to compute total resistance:
totalResistance=resistor1 + resistor2 totalResistance = 1/((1/ resistor1)+(1/
+…+ resistorN resistor2)+…+(1/ resistor3))
Depicted below is sample a sample input/output when the program is executed
(the values in bold are inputted by the user, while the values in bold italics are
calculated and outputted by the program):

Resistor Computation
Enter resistor1: 2.34
Enter resistor2: 4.23
Enter resistor3: 6.72

Total resistance
Series Connection: 13.29
Parallel Connection: 1.230668398

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

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

74
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;
… true
conditio
false
else n
statementN
}
statement2; if true statements if false statements
else {
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;

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; // this if is
else
a = c; // associated with this else
}else
a = d; // this else refers to if(i == 10)

75
● 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 with if(i==10). The inner else refers to if(k>100) because
it is the closest if within the same block.

The if-else-if Ladder


● A common programming construct that is based upon a sequence of nested ifs is
the if-else-if ladder. It looks like this:
if(condition)
statement;
else
if(condition)
statement;
else
if(condition)
statement;
...
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 action
will take place. Here is a program that uses an if-else-if ladder to determine which
season a particular month is in.
// Demonstrate if-else-if statements.
public class SeasonProblem {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else
if(month == 3 || month == 4 || month == 5)
season = "Spring";
else
if(month == 6 || month == 7 || month == 8)
season = "Summer";
else
if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
} 76
}
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 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

77
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 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

78
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 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 12123.69

Graded Activity #4 (M7.1): Decision Control Structure (if) Problem

Instruction:

A certain store has the following scheme:


Commodity Code:
A - commodities are discounted by 10%
B - commodities are taxed by 13%
C - commodities are charged as priced
Using a Decision Control Structure (if), 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: A


Enter commodity code: E Enter quantity of commodity: 2
Invalid Code Enter unit price: 53.25
Amount to be paid is P95.85
Enter commodity code: B
Enter quantity of commodity: 2 Enter commodity code: C
Enter unit price: 53.25 Enter quantity of commodity: 2
Amount to be paid is P120.35 Enter unit price: 53.25
Amount to be paid is P106.50

Required: The .java file (FamilyName_CommodityCode.java) containing the code and 4


image files (Sample1, Sample2, Sample3, and Sample4) containing different sample
input/output of the program.

79
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 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.

80
● The following are java programs that uses a switch statement:

//Switch Example2
//Switch Example1
public class MonthEnd {
// An improved version of the season program.
public static void main(String[] args) {
public class SeasonProblemUsingSwitch {
int month = 2;
public static void main(String args[]) {
int year = 2000;
int month = 4;
int numDays = 0;
String season;
switch (month) {
switch (month) {
case 1:
case 12:
case 3:
case 1:
case 5:
case 2:
case 7:
season = "Winter";
case 8:
break;
case 10:
case 3:
case 12: numDays = 31;
case 4:
break;
case 5:
case 4:
season = "Spring";
case 6:
break;
case 9:
case 6:
case 11: numDays = 30;
case 7:
break;
case 8:
case 2:
season = "Summer";
if ( ((year % 4 == 0) && !(year % 100 == 0))
break;
|| (year % 400 == 0) )
case 9:
numDays = 29;
case 10:
else
case 11:
numDays = 28;
season = "Autumn";
break;
break;
default:
default:
System.out.println("Invalid month.");
season = "Bogus 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
80 – 86 C
70 – 79 D
65 - 69 E

81
Using switch, create a java program that reads a numeric grade and output the equivalent letter
grade.
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:
A - commodities are discounted by 15%
B - commodities are taxed by 12%
C - 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 red bold
characters are inputted by the user, while the items in blue bold characters are calculated and
outputted by the program):
Enter commodity code: A
Enter commodity code: E Enter quantity of commodity: 2
Invalid Code Enter unit price: 53.25
Amount to be paid is P90.53
Enter commodity code: B
Enter quantity of commodity: 2 Enter commodity code: C
Enter unit price: 53.25 Enter quantity of commodity: 2
Amount to be paid is P119.28 Enter unit price: 53.25
Amount to be paid is P106.50

Graded Activity #5 (M7.2): Decision Control Structure (switch) Problem

Instruction:

The areas of the following figures are computed as follows:

1. trapezoid: (h/2) (b1+b2)


2. ellipse: (r1+r2)
3. equilateral triangle:
 
3 a2
4

Using switch for the choices, write a Java program that will display a menu and the user
can choose which figure to compute. When the user decides whether 1. Trapezoid, 2.

82
Ellipse, or 3. Equilateral Triangle, compute the area of the figure chosen and output the
results.

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):

Menu: Compute Area of Menu: Compute Area of Menu: Compute Area of


1. Trapezoid 1. Trapezoid 1. Trapezoid
2. Ellipse 2. Ellipse 2. Ellipse
3. Equilateral Triangle 3. Equilateral Triangle 3. Equilateral Triangle
Choice: 1 Choice: 2 Choice: 3
Trapezoid Ellipse Equilateral Triangle
Enter h: 3 Enter r1: 2 Enter a: 3
Enter b1: 2 Enter r2: 3 Area of Equilateral
Enter b2: 2 Area of Ellipse is 18.85 Triangle is 3.9
Area of Trapezoid is 6

Required: The .java file (FamilyName_Figure.java) containing the code and 3 image files
(Sample1, Sample2, and Sample3) containing different sample input/output of the
program.

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.

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
}
● 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:

83
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;
}
if condition is true
condition
if condition is false

while loop body

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

More While Loop Examples

Filename: Series2Problem_FamilyName
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:

84
//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++;
Start
}
}
}
Flowchart Diagram of Series2 using While Loop x=1
n=1

False True
x<211

End

x=x+n
n = n +1

85
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 terminted
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++;
}
}}

86
Flowchart Diagram for Sphere Using While Loop

Start

r=1
pi = 3.1416

False True
r<=20

a = 4*pi*Math.pow(r,2)
v = 4*pi*Math.pow(r,3)/3.0
End

r,v,a

r++

87
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);
● 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;
do-while loop body }
while (condition);

if condition is true

condition

if condition is 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

88
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 least
break; 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;
} }}

89
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);
}
} Start

Flowchart Diagram for Object Using Do While

s=1
d = 16

d = d +32
s++

False True
End s,d s<15
90
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);
}
}

91
Flowchart Diagram for Bounce using DoWhile

Start

d = 50
dist = 50
b=1

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

False b<=10 True

dist = dist - d

b,dist

End

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.
● 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.

92
● 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

initialization

for(initialization; condition; iteration)


{
//for loop body/statements;
}
if condition is true
condition
if condition is false

//for loop body/statements


//iteration

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

More For Loop Examples

FileName: Series3Problem_FamilyName
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:

93
//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

x
End

x=x+3

94
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);

}
}

95
Flowchart Diagram for Factorial Using For Loop

Start

num

x=1
F=1

False

x<=num
True

F=F*x
num,F

x++
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
Introduction
programs multiple times. a part of the program executes a part of the
repeatedly on the basis program at least once
and the further

96
of given boolean execution depends
condition. upon the given
boolean condition.
If the number of iterations If the number of If the number of
is fixed, it is recommended iterations is not fixed, it iterations is not fixed
to use a for loop. is recommended to use and you must have to
When to use a while loop. execute the loop at
least once, it is
recommended to use
the do-while loop.
for(init;condition;iteration) 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
infinitive 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 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.

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

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 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.

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

5. FileName: PrimeOrComposite_FamilyName (Use for Loop)


Create a java program that reads an integer, determine and output a message if the integer
is prime or composite.
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:

Graded Activity #6 (M8.1): Repetition Control Structure (while, do-while)

Instruction:
A mathematician named Ulam proposed generating a sequence of numbers from any
positive integer N greater than 1 using the following procedure:
If N is 1, stop.
If N is even, replace it with N/2.
If N is odd, replace it with 3 * N + 1.

Continue with this process until N reaches 1.

Here are some examples of the Ulam sequence for the first few integers.
2, 1
3, 10, 5, 16, 8, 4, 2, 1
4, 2, 1
5, 16, 8, 4, 2, 1
6, 3, 10, 5, 16, 8, 4, 2, 1

99
Write a Java program using while/do-while that accepts as input an integer value N
(assume N > 1) and prints out the Ulam sequence that begins with the input value N.

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 calculated and
printed by the program):

Input N: 14 Input N: 5
Ulam Sequence: Ulam Sequence:
14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 5, 16, 8, 4, 2, 1

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

Graded Activity #7 (M8.2): Repetition Control Structure (for)

Instruction:

Write a Java program that reads a positive, non-zero integer as input and checks if the
integer is deficient, perfect, or abundant.

A positive, non-zero integer, N, is said to be perfect if the sum of its positive proper divisors
(i.e., the positive integers, other than N itself, that divide N exactly) is equal to the number
itself. If this sum is less than N, the number is said to be deficient. If the sum is greater than
N, the number is said to be abundant.

The first few perfect numbers are 6, 28, 496, and 8128.
Illustrations:
Number Factors of the number less than itself Sum of Factors
6 3, 2, 1 6
28 14, 7, 4, 2, 1 28
For example, the number 6 is perfect, since 6 = 1 + 2 + 3, the number 8 is deficient, since
8 > 1 + 2 + 4, while the number 12 is abundant, since 12 < 1 + 2 + 3 + 4 + 6.
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 calculated and
printed by the program):

Input N: 5 Input N: 6 Input N: 18


5 is deficient. 6 is perfect. 18 is abundant.

Required: The .java file (FamilyName_Perfect.java) containing the code and 3 image files
(Sample1, Sample2 and Sample3) containing different sample input/output of the
program.

100
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.

101
● 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.");
}
}

102
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

103
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 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:

104
Graded Activity #8 (M9.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 (10 to 99) for the one-dimensional arrays (List A and List B). The program 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.

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.

105
int twoD[][] = new int[5][5];
● The above code allocates a 5 by 5 array and assigns it to twoD. Internally this matrix
is implemented as an array of arrays of int.
● 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 (5x5)
int twoD[][]= new int[5][5];
int i, j, k = 0;
System.out.println("The array elements: ");
//allocating the elements of a 5 by 5 array using the random class
for(i=0; i<5; 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<5; i++) {
for(j=0; j<5; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}

● 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 following figure is a conceptual view of a 4 by 5, two-
dimensional array.

106
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 #9 (M9.2): Two-Dimensional Array

Instruction:

Create a java program that generates elements (randomly from 10 – 50) of a 2-dimensional array
(5x5) using the Random Class then perform the following:

1) Output the array elements


2) Output the sum of prime numbers in the array
3) Output the elements in the main diagonal.
4) Output the sum of the elements below the diagonal.
5) Output the sum of the elements above the diagonal.
6) Output the odd numbers below the diagonal.
7) Output the even numbers above the diagonal.

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):

107
1) Output the array elements
21 30 33 45 32
50 10 50 35 42
25 12 35 12 11
45 14 50 28 21
15 41 15 19 41
2) Output the sum of prime numbers in the array.
112
3) Output the elements in the main diagonal.
21 10 35 28 41
4) Output the sum of the elements below the diagonal.
286
5) Output the sum of the elements above the diagonal.
311
6) Output the odd numbers below the diagonal.
25 45 15 41 19
7) Output the even numbers above the diagonal.
30 32 50 42 12

Required: The .java file (FamilyName_2Dim.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 Method
● 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
● Method definition consists of a method header and a method body. The same is
shown below:
modifier returnType nameOfMethod (Parameter List) {
// method body
}

108
● 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);

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;

109
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");
}
}
}
This would produce the following result:

110
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:

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) {
111
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 multidimensional arrays: watch


● Module 10: Introduction To Methods.mp4
● 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.

112
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 is a sample output when the program is exercise?

Graded Activity #10 (M10.1): Methods

Instruction:

Create a java program using user-defines methods that will perform the 3 major
functionalities of an Automated Teller Machine(Withdraw, Deposit, Balance Check)

1. Withdraw
* Input the amount to be withdrawn. Compute for the remaining balance after
the operation (balance = balance - withdrawn)
2. Deposit
* Input the amount to be deposited. Compute for the updated balance after
the operation (balance = balance + deposit)
3. Balance Check
* Display the remaining balance.

Use the following method names: withdraw, deposit, checkBalance

113
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 calculated and
printed by the program):

---------------------ATM----------------
1. Withdraw
2. Deposit
3. Check Balance
4. EXIT
Choose operation: 1
Enter amount to be withdrawn: 1000
Collect your money
Check Balance? 1. Yes 0. No: 1
Balance: 4000

---------------------ATM----------------
1. Withdraw
2. Deposit
3. Check Balance
4. EXIT
Choose operation: 2
Enter amount you want to deposit: 500
Check Balance? 1. Yes 0. No: 0

---------------------ATM----------------
1. Withdraw
2. Deposit
3. Check Balance
4. EXIT
Choose operation: 3
Balance: 4500

---------------------ATM----------------
1. Withdraw
2. Deposit
3. Check Balance
4. EXIT
Choose operation: 1
Enter amount to be withdrawn: 6000
Insufficient Balance
Check Balance? 1. Yes 0. No: 1
Balance: 4500
Required: The .java file (FamilyName_ATM.java) containing the code and 4 image files
(Sample1, Sample2, Sample3, and Sample4) containing different sample input/output of
the program.

114
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

115
int day = 21;
Integer obj = Integer.valueOf(day);

//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();

116
or

primitiveDataType variableName = objectName;

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.

117
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
}

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
}

118
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.

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";

119
String s2=""; This will display the result:
String s3="me";
System.out.println(s1.compareTo(s2)); 5
System.out.println(s2.compareTo(s3)); -2
}
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

120
References:

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
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
Schildt, H. 2007. Java: The Complete Reference, Seventh Edition. ISBN: 978-0-07-163177-8
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.
Suchato, A. (2011). Learning Computer Programming Using Java with 101 Examples. Knowledge
Collection and Contribution Initiatives by the Department of Computer Engineering,
Chulalongkorn University. ISBN 978-616-551-368-5.
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

121

You might also like