Professional Documents
Culture Documents
COMPROG
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
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
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.
To make things easier to remember, these operations are also referred as the
Input-Process-Output(IPO) Model.
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
● 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.
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:
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.
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
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 –
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
Icon Operations
You can do various operations on the icons on
your desktop. Here are some of them:
● 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
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
● 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
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.)
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 .
● 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.
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
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:
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.
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.
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.
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).
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).
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.
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.
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:
● 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:
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).
● 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.
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.
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:
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:
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.
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.
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.
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
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:
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).
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:
35
Module 3: The Spreadsheet Program
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 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:
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.
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:
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).
Deleting Cells
Take note that if you delete the entire cell, the cells below it will shift up and
replace the deleted cells.
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.
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:
$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.
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.
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:
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.
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.
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.
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:
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.
49
Commonly Used Functions (MS Excel Demo.xlsx)
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:
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.
● 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.
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.
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
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
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
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
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
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 */
*/
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.
57
Java Keywords
● Keywords are predefined identifiers reserved by java for specific purposes. You
cannot use keywords as names of variables, classes, methods, etc.
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:
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
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.");
● 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
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++;
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
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.
- 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
Connector Represents any entry from, or exit to, another part of the
Symbol flowchart. Also serves as an off-page connector.
● 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.
● 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.
● 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.
● 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
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 {
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
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.
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:
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.
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):
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):
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):
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):
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):
Instruction:
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);
}
}
}
}
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):
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
Instruction:
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):
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.
● 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! ");
}
}
initialization
while (condition)
{
//while loop body/statements;
}
if condition is true
condition
if condition is false
For additional information about the while loop: watch Module 8: The While Loop.mp4
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:
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.
initialization
do
{
statement block;
do-while loop body }
while (condition);
if condition is true
condition
if condition is false
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:
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++
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
A java program using for loop that displays the numbers from 1 to 10;
initialization
For additional information about the for loop: watch Module 8: The FOR Loop.mp4
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+" ");
}
}
}
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
}
}
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
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)
97
Depicted below is a sample output when the program is executed:
98
Depicted below is a sample output when the program is executed:
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.
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.
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):
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] + " ");
}
}
}
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
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.
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):
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
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.
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:
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.
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;
}
}
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.
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?
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.
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.
System.out.println(weight); 55.9
System.out.println(day); 21
System.out.println(initial); A
}
or
115
int day = 21;
Integer obj = Integer.valueOf(day);
//Using Autoboxing
Integer autoboxObj = day; This will display the result:
The general form for converting a primitive type to a wrapper object is:
WrapperClass objectName = WrapperClass.valueOf(primitiveDataTypeVariable);
or
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.
//using Unboxing
int unboxDay = obj; This will display the result:
The general form of converting a wrapper object to primitive data type is:
primitiveDataType variableName = objectName.primitiveDataTypeValue();
116
or
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.
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.
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.
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.
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.
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.
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