Read the book and do the lab answer the questions
Chapter 6 Arrays and ArrayLists
Java Arrays:
1. Definition: An array in Java is a fixed-size, ordered collection of elements of the same data type.
It is a contiguous block of memory that can store multiple values of the same type.
2. Declaration: Arrays are declared using square brackets ([]) after the data type. For example, int[]
numbers; declares an integer array.
3. Initialization: Arrays can be initialized using the new keyword, like numbers = new int[5];, which
creates an integer array with space for five elements.
4. Accessing Elements: Array elements are accessed using square brackets and zero-based indices.
For example, to access the first element: int firstElement = numbers[0];
5. Length: The length of an array is fixed and can be obtained using the length property, e.g., int
arrayLength = numbers.length;
6. Iterating Through Arrays: Arrays can be traversed using loops like for or foreach to access and
manipulate each element.
7. Arrays of Objects: Arrays can hold objects of any class, allowing you to create arrays of custom
objects.
8. Arrays of Primitives: Arrays can also hold primitive data types like int, char, boolean, etc.
ArrayLists (java.util.ArrayList):
1. Definition: ArrayList is a part of the Java Collections Framework and is a dynamic array-like data
structure that can resize itself automatically. It allows you to store and manipulate a collection of
objects.
2. Import Statement: To use ArrayList, you need to import it: import java.util.ArrayList;
3. Declaration and Initialization: An ArrayList can be declared and initialized like this:
Code example
ArrayList numberList = new ArrayList();
1. Adding Elements: You can add elements to an ArrayList using the add() method, e.g.,
numberList.add(42);
2. Accessing Elements: Elements in an ArrayList are accessed using the get() method, e.g., int value
= numberList.get(0);
3. Size: Unlike arrays, ArrayLists can dynamically change in size. You can get the current size using
the size() method.
4. Removing Elements: Elements can be removed using methods like remove(int index) or
remove(Object obj).
5. Iterating Through ArrayLists: You can use an enhanced for loop or an Iterator to traverse
through the ArrayList.
6. Generics: ArrayLists are generic, which means you can specify the type of objects they will hold.
This helps ensure type safety.
7. Auto-Resizing: ArrayLists automatically resize themselves when they reach their capacity,
making them more flexible than arrays.
8. Performance: ArrayLists are generally slower for random access than arrays but more efficient
for dynamic resizing and inserting/removing elements.
9. Search and Manipulation: ArrayLists provide methods for searching (contains(), indexOf()) and
manipulation (add(), remove(), set()).
In summary, Java arrays provide a fixed-size, low-level way to store elements of the same type, while
ArrayLists offer dynamic resizing and additional features for working with collections of objects. The
choice between the two depends on the specific requirements of your program.
Copying Array
To copy arrays in Java, you have several options, depending on your requirements. Here are a few
common methods:
Using a Loop: You can manually copy the elements from one array to another using a loop. Here’s an
example for copying an integer array:
Code example
int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
destinationArray[i] = sourceArray[i];
}
Using System.arraycopy(): Java provides a built-in method System.arraycopy() for efficiently copying
elements between arrays. Here's how you can use it:
Code example
int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = new int[sourceArray.length];
System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
The method signature is:
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
int[] sourceArray = {1, 2, 3, 4, 5};
int[] destinationArray = Arrays.copyOf(sourceArray, sourceArray.length);
Using Arrays.copyOfRange(): If you want to copy a specific range of elements from an array, you can use
Arrays.copyOfRange().
These methods allow you to copy the contents of one array to another, whether it's a complete copy or a
subset of the source array. Choose the method that best fits your specific copying requirements.
Passing Arrays to Methods
In Java, you can pass arrays to methods just like you pass any other variable.
When you pass an array to a method, you are essentially passing a reference to
the array, not a copy of the array itself. This means that any changes made to the
array inside the method will affect the original array outside the method. Here's
how you can pass arrays to methods:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
// Calling a method and passing the array
modifyArray(numbers);
// The original array has been modified
for (int num : numbers) {
System.out.print(num + " ");
}
}
public static void modifyArray(int[] arr) {
// Modify the array within the method
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2;
}
}
}
In the example above, we define a method modifyArray that takes an integer
array as a parameter. Inside the method, we double the values of each element in
the array. When we call this method with the numbers array, the original array is
modified, and those modifications are reflected outside the method.
Keep in mind the following points when passing arrays to methods:
1. Changes made to the elements of the array inside the method will affect
the original array since you're working with a reference to the same array.
2. If you want to prevent a method from modifying the original array, you can
create a copy of the array within the method and work with the copy.
3. You can return arrays from methods in Java just like any other data type,
allowing you to encapsulate array creation and manipulation within
methods.
Here's an example of returning an array from a method:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = createArray(5);
for (int num : numbers) {
System.out.print(num + " ");
}
}
public static int[] createArray(int size) {
int[] newArray = new int[size];
for (int i = 0; i < size; i++) {
newArray[i] = i + 1;
}
return newArray;
}
}
In this example, the createArray method creates and initializes an array of a
specified size and returns it to the calling code.
Two-dimensional Arrays
A two-dimensional array in Java is an array of arrays, where each element of the
array is itself an array. It can be thought of as a table or grid of elements, where
rows and columns define the dimensions of the array. Two-dimensional arrays are
often used to represent matrices, tables, or grids of data.
Here's how to declare, initialize, and work with two-dimensional arrays in Java:
Declaration and Initialization:
You can declare a two-dimensional array using square brackets for both
dimensions. For example, to declare a 3x4 integer array:
int[][] twoDArray = new int[3][4];
This creates a 3x4 array filled with default values (0 for integers).
You can also initialize a two-dimensional array with specific values:
int[][] twoDArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Accessing Elements:
Elements in a two-dimensional array are accessed using two indices: the row
index and the column index. Both indices start from 0. For example, to access the
element in the second row and third column:
int element = twoDArray[1][2]; // Row 2 (index 1), Column 3 (index 2)
Iterating Through a 2D Array:
You can use nested loops to iterate through all the elements of a two-dimensional
array. Here's an example that prints all elements of the array:
for (int i = 0; i < twoDArray.length; i++) {
for (int j = 0; j < twoDArray[i].length; j++) {
System.out.print(twoDArray[i][j] + " ");
}
System.out.println(); // Move to the next row
}
Multidimensional Arrays:
Java allows you to create arrays of more than two dimensions, often referred to as
multidimensional arrays. For example, a three-dimensional array can be declared
and initialized like this:
int[][][] threeDArray = new int[3][4][5];
In practice, you can have as many dimensions as needed, but readability and
understanding become more challenging as the number of dimensions increases.
Two-dimensional arrays are versatile and are commonly used in various
programming tasks, such as representing game boards, spreadsheet-like data
structures, and storing matrices for mathematical operations.
Array Algorithms
Here are some common array algorithms that you might encounter in
programming:
1. Linear Search: Search for a specific element in an array by sequentially
checking each element until a match is found or the end of the array is
reached. Linear search has a time complexity of O(n) for an array of n
elements.
2. Binary Search: Search for a specific element in a sorted array by repeatedly
dividing the search interval in half. Binary search has a time complexity of
O(log n) for a sorted array.
3. Sorting Algorithms:
•
Bubble Sort: Repeatedly swap adjacent elements if they are in the
wrong order until the entire array is sorted. Bubble sort has a time
complexity of O(n^2).
•
Selection Sort: Find the minimum element from the unsorted portion
and move it to the beginning of the sorted portion of the array.
Selection sort also has a time complexity of O(n^2).
•
Insertion Sort: Build a sorted array by repeatedly taking elements
from the unsorted portion and inserting them into their correct
position in the sorted portion. It has a time complexity of O(n^2).
•
Merge Sort: Divide the array into smaller sub-arrays, sort them, and
then merge them back together in a sorted manner. Merge sort has a
time complexity of O(n log n).
•
Quick Sort: Choose a "pivot" element and partition the array into two
sub-arrays: one with elements less than the pivot and another with
elements greater than the pivot. Recursively sort the sub-arrays.
Quick sort also has an average time complexity of O(n log n).
4. Maximum and Minimum Element: Find the maximum and minimum
elements in an array by iterating through the array and keeping track of the
current maximum and minimum values.
5. Reverse Array: Reverse the elements of an array, effectively flipping the
order of the elements.
6. Duplicates Detection: Detect duplicate elements in an array by using a data
structure like a HashSet or by sorting the array and checking adjacent
elements.
7. Counting Occurrences: Count the number of occurrences of a specific
element in an array by iterating through the array and keeping a count.
8. Finding Missing Element: Find a missing element in an array of consecutive
integers. This can be done efficiently using mathematical formulas.
9. Rotate Array: Rotate the elements of an array by a specified number of
positions, either left or right.
10.Kth Largest/Smallest Element: Find the Kth largest or Kth smallest element
in an array using techniques like quickselect or a priority queue.
11.Subarray Sum: Find a subarray (contiguous sequence of elements) with a
specific sum, often using techniques like the sliding window or prefix sum.
12.Intersection and Union of Arrays: Compute the intersection and union of
two arrays, which can be useful for various set operations.
These algorithms provide a foundation for working with arrays in various
programming tasks and are essential to solving a wide range of problems
efficiently. Depending on the specific problem, you may need to choose the most
suitable algorithm to achieve the desired outcome while considering factors like
time complexity and space complexity.
The ArrayList
ArrayList is a dynamic data structure provided by the Java Collections Framework
that is built on top of arrays. It offers many useful features and methods for
working with lists of objects. Here are some additional details and operations you
can perform with ArrayLists:
1. Dynamic Sizing: ArrayLists can automatically resize themselves when
elements are added or removed, making them convenient for situations
where the number of elements is not known in advance.
2. Capacity: An ArrayList has a capacity, which is the maximum number of
elements it can hold without resizing. When the capacity is exceeded, the
ArrayList automatically grows by creating a larger underlying array and
copying the elements.
3. Initialization with Capacity: You can specify an initial capacity when
creating an ArrayList to optimize performance if you know the approximate
size of the list in advance. For example:
ArrayList list = new ArrayList(10); // Initial capacity of 10
1. Adding Elements:
•
add(E element): Adds an element to the end of the ArrayList.
•
add(int index, E element): Inserts an element at the specified index,
shifting existing elements to the right.
2. Removing Elements:
•
remove(int index): Removes the element at the specified index.
•
remove(Object obj): Removes the first occurrence of the specified
object.
•
clear(): Removes all elements from the ArrayList.
3. Checking for Elements:
•
contains(Object obj): Checks if the ArrayList contains a specific
object.
•
isEmpty(): Checks if the ArrayList is empty.
4. Accessing Elements:
•
get(int index): Retrieves the element at the specified index.
•
set(int index, E element): Replaces the element at the specified index
with a new element.
5. Size and Capacity:
•
size(): Returns the current number of elements in the ArrayList.
•
ensureCapacity(int minCapacity): Increases the capacity of the
ArrayList to at least the specified minimum capacity.
6. Iterating Through ArrayList:
•
You can use for-each loops, iterators, or streams to iterate through
the elements of an ArrayList.
7. Conversion:
•
You can convert an ArrayList to an array using toArray(), and vice
versa, using Arrays.asList().
8. Sorting:
•
You can sort an ArrayList using the Collections.sort() method if the
elements are comparable.
9. Sublist:
•
You can create a sublist of an ArrayList using the subList(int
fromIndex, int toIndex) method.
10.ArrayList vs. LinkedList:
•
ArrayList is backed by an array and is efficient for random access but
less efficient for frequent insertions and removals in the middle.
LinkedList, on the other hand, is more efficient for frequent insertions
and removals but less efficient for random access.
11.Synchronization:
•
ArrayList is not synchronized, which means it is not thread-safe. If you
need thread safety, you can use Collections.synchronizedList() to
create a synchronized ArrayList.
12.Performance Considerations:
•
The time complexity of various operations on an ArrayList, such as
adding and accessing elements, is important to consider when
choosing it for a specific use case.
ArrayLists are widely used in Java for managing collections of objects due to their
flexibility, ease of use, and dynamic sizing capabilities. They are suitable for many
list-based data storage and manipulation tasks in Java programs.
Regenerate
Introduction to Java
Computer Programming and
Problem Solving
Second Edition
Chris Simber
Assistant Professor, Computer Science
Rowan College at Burlington County
Cataloging Data
Names: Simber, Chris, author.
Title: Introduction to Java: Computer Programming and Problem Solving
Subjects: Java (Computer Programming Language)
Chris Simber
Assistant Professor of Computer Science
Rowan College at Burlington County
Author contact: csimber@RCBC.edu
Introduction to Java: Computer Programming and Problem Solving by
Christopher Simber is licensed under a Creative Commons Attribution –
NonCommercial-ShareAlike 4.0 International License, except where
otherwise noted. Images may not be distributed individually.
All screenshots included on the basis of Fair Use.
Creative Commons — Attribution-NonCommercial-ShareAlike 4.0 International — CC BYNC-SA 4.0
Under the following terms: Attribution — You must give appropriate credit, provide
a link to the license, and indicate if changes were made. You may do so in any
reasonable manner, but not in any way that suggests the licensor endorses you or
your use.
creativecommons.org
Introduction
This book is intended for use in an introductory course in programming using
the Java programming language, and includes content for students who are not
familiar with programming. The book introduces general computer information
and basic computer operations, as well as software engineering principles and
processes used in industry to implement computer-based solutions. Algorithm
development and problem-solving techniques are introduced as well.
The Eclipse integrated development environment (IDE) is utilized and
instructions to obtain, install, and “Getting Started in Eclipse” are provided in
the appendices. The goal is to provide students with an overview of computers,
software engineering tools and techniques, and to introduce them to computer
programming in Java quickly for hands-on instruction.
The examples and exercises reinforce the material being introduced while
building on previous material covered, and follow the programming standards
for Java publicized by the World Wide Web Consortium (W3C) and set forth in
the Java Coding Guidelines created by Joe McManus MGR at Carnegie Mellon
University, Software Engineering Institute. Appendix G provides an adequate
abridgement of programming standards. The in-chapter exercises are numbered
for clarity using a shaded box, and can be used as in-class exercises or as
assignments.
The Java version in use at the time of this writing is Version 8. The Integrated
Development Environment (IDE) selected is Eclipse which is free to download
and use. The Eclipse interface has the common look and feel associated with
most integrated development environments and is used extensively in industry.
Instructions for obtaining and installing Eclipse are provided in Appendix B,
including resolving the most common JRE and JDK issues.
Getting started in Eclipse is provided in Appendix C with a sample start-up
program. Links to the Eclipse web site, Java Tutorials, and the Java Coding
Guidelines are included in Appendix F which also includes a link to the Java
Tutorial at the W3Schools website.
There are end-of-chapter assignments, and an answer key, exams, and
accompanying lecture slides are available.
Acknowledgements:
Rowan College at Burlington County Student Feedback
Revision History:
First Edition: August 2022
Second Edition: January 2023
Changes to the Second Edition include minor rewording, corrections to
typographical errors, and an additional assignment (#2B) in chapter 2.
Contents
Chapter 1
Computers and Programming
1
Chapter 2
Java Language Basics
19
Chapter 3
Decision Structures and Boolean Logic
53
Chapter 4
Loops and Repetition Structures
81
Chapter 5
Methods, Modules, and Basic Graphics
111
Chapter 6
Arrays and ArrayLists
139
Chapter 7
File Operations and Exceptions
167
Chapter 8
Classes and Objects
191
Chapter 9
Inheritance and Interfaces
227
Chapter 10
Graphical User Interfaces
253
Chapter 11
GUI Programs
289
Chapter 12
Technology and Society
318
Appendix A
ASCII Character Set (partial list)
Appendix B
Obtaining and Installing Eclipse
Appendix C
Getting Started with Eclipse
Appendix D
Modular Programming
Appendix E
Creating and Input Data File
Appendix F
Helpful Links to Information
Appendix G
Java Programming Style and Standards
Appendix H Multiple Panels and Layout Managers Example
“Five minutes of design time, will save hours of programming” –
Chris Simber
1
Chapter 1
Computers and Programming
Computers are simply data processing devices. They are machines that receive
input, process it in some way, and produce output. Computer programs are
made up of a series of statements that tell a computer what to do and in what
order to do it.
These programs provide a sequence of small steps for the
computer to execute and produce the desired result. Millions or even billions of
these small steps are being executed by the computer as we run programs. This
may seem odd to the casual computer user, but these small steps combine to
provide what appear to be seamless operations as we interact with the computer.
Computer programs are referred to as software and they are needed to make
the computer useful. People who design, write, and test software are commonly
referred to as software engineers, software developers, or computer
programmers. To better understand the computing process and programming in
general, a familiarity with the parts that make up a computer is necessary.
The Central Processing Unit (CPU)
Any part of the computer that we can physically touch (including inside the
casing) is referred to as hardware. One important piece of hardware is the
Central Processing Unit CPU which is the “Brains” of the computer. The CPU
performs millions of basic instructions per second and controls computer
operations. The CPU has two parts. The Arithmetic Logic Unit (ALU) handles
Chapter 1 Computers and Programming
2
basic arithmetic and comparisons of data such as less than, greater than,
equivalent, and not equivalent. The Control Unit retrieves and decodes program
instructions and coordinates activities within the computer.
Brown and Green Computer Processor Pixabay is licensed under CC0
Figure 1.1 - Central Processing Unit (CPU)
The CPU (shown upside down above) has pins that plug into a socket located on
a circuit board called the motherboard.
Main Memory
RAM stands for Random Access Memory and is often referred to as main
memory. RAM is a series of memory chips on a circuit board installed in the
computer on the motherboard along with the CPU. The memory in these chips
contains a series of memory addresses that enable the computer to store and
locate information.
These memory addresses are volatile and when the
computer is turned off, RAM does not retain information. It is erased. When a
program is launched, the program is copied into RAM for the CPU to use.
RAM by Headup222 is licensed under Pixabay License
Figure 1.2 - Laptop Main Memory (RAM)
The CPU can access instructions and data from RAM very quickly, and RAM is
located close to the CPU on the motherboard. The RAM circuit card for a laptop
Chapter 1 Computers and Programming
3
computer is shown above.
The large rectangles are the memory chips, the
notches are an aid for inserting the RAM into position on the motherboard, and
the gold edge makes the connections for data access. Since RAM is erased when
the computer is turned off, secondary storage is used to retain information.
Read Only Memory or ROM contains the startup instructions for the computer
including the BIOS or Basic Input Output System. It is non-volatile and retains
information between sessions.
Secondary Storage
Secondary storage devices are non-volatile and the information stored is not
erased when the power is off. Secondary storage devices include the hard drive
inside the computer, external drives connected to the computer, and flash drives.
The hard drive inside the computer may be a disk drive which houses a rotating
disk and data access arm (shown below), or a solid-state drive which has no
moving parts and operates faster than a traditional disk drive.
Laptop-hard-drive-exposed by Evan Amos is licensed under CC BY-SA 3.0
Figure 1.3 - Hard Drive (cover removed)
External drives are typically solid-state and connect to the computer through a
cable plugged into a USB (Universal Serial Bus) connector, or plug directly into
the USB port of the computer as in the case of flash drives. Flash drives use flash
memory, and do not have a disk drive.
Chapter 1 Computers and Programming
4
Input and Output Devices
Input devices are anything that provides input or data for a computer.
Common input devices are the keyboard, mouse, microphone, and camera.
Output devices include anything that accepts computer output such as
monitors, speakers, and printers.
Since data files located on storage devices can be used for reading data into a
computer or writing output from a computer, they could be considered both
input and output devices.
Software
Computers are machines that follow an input, processing, output sequence of
operations and need to be told what to do and in what order to do it. This is
accomplished through sets of instructions called software. There are essentially
two types of software: system software (Operating Systems), and application
programs (all other software).
The operating system (OS) provides an interface for us to use computers more
easily. Initially command line interfaces were used, followed by menu driven
interfaces, and then the Graphical User Interface (GUI) was introduced and has
been used since. Most operating systems provide a Graphical User Interface that
is now commonly used to interact with the computer. It acts like an orchestra
conductor by controlling computer hardware, managing devices connected to
the computer, and interacting with programs that are running.
Operating
systems commonly in use today are Windows, macOS, and Linux.
Application software includes the computer programs that we commonly use to
accomplish work such as word processors, spreadsheet programs, collaboration
tools, and audio/video editing tools, as well as gaming software.
The Language of Computers
The language of computers is a binary language consisting of ones and zeros.
This is the beauty and simplicity of the computer. At the basic level, everything
is a 1 or a 0, is either On or Off, Yes or No, True or False. The bit, or binary digit
Chapter 1 Computers and Programming
5
used in computing represents a logical state that can be 0 or 1. It is the smallest
information representation in a computer.
A Byte is 8 bits consisting of a
combination of 0s and 1s, and in computers, each letter, number, and special
character consists of a binary representation. For example, a lower case “f” is
represented in binary as 01100110 in accordance with the ASCII standard
(pronounced askee).
ASCII stands for the American Standard Code for
Information Interchange which was developed as a character encoding standard.
The ASCII table consists of 256 binary representations for the 26 uppercase and
26 lowercase letters, and the 9 digits, as well as special characters, punctuation
marks, and other symbols and keyboard keys. Appendix A provides a partial list
of the binary and decimal representations for the upper and lowercase letters,
digits, and punctuation. A portion is shown here with the decimal equivalent.
ASCII Table (excerpt)
The Unicode standard incorporates the 256 item ASCII standard and expands to
include the binary representations for symbols and characters for most of the
world’s languages. Unicode 13.0 contains representations for 143,859 characters.
Instructions for the computer must be in its’ language including numbers that
are stored or used in computations. Numeric integers (whole numbers) are
represented in computers using the positions of the bits and powers of 2 starting
from right and working left.
Binary Number Bit Representations
Chapter 1 Computers and Programming
6
As an example, the number 90 would be represented in binary as 01011010. Each
bit is either 0 or 1 and is multiplied by the power of 2 at its position. The results
are then added together.
0
0 x 27
1
0
1
+ 1 x 26 + 0 x 25 +
1
0
1
0
1 x 24 + 1 x 23 + 0 x 22 + 1 x 21 + 0 X 20
(0 x 128) + (1 x 64) + (0 x 32) + (1 x 16) + (1 x 8) + (0 x 4) + (0 x 2) + (0 x 1)
0
+
64
+
0
+
16
+
8
+
0
+
2
+
0
= 90
Binary Number Conversion
The limit to the numbers that can be stored using 8 bits is 255 with all 8 bits being
1’s. To store larger numbers, two Bytes would be used with a combination of
sixteen 1’s and 0’s. That would allow storing numbers as large as 65535. To store
larger numbers, more Bytes could be used. To store negative numbers and
floating-point numbers (numbers with a decimal or fractional part), other
numbering schemes are used such as the two’s complement and floating-point
notation.
Images (which are made up of pixels) are stored by converting each pixel to a
numeric value which is then stored in binary. Sound is stored using samples that
are converted to the nearest numeric value.
Programming Languages
Although the computers’ language, referred to as machine language, is a binary
language, it would be tedious for us to write instructions for computers in
Binary. Machine language is one of the two languages commonly referred to as
low-level languages for computers, the other being Assembly language.
Assembly language consists of very basic instructions like move a value into
memory, add another value to that one, and store the result in memory. An
assembler is used to convert Assembly language programs into executable
machine code. Both of these low-level languages mirror the operations of the
CPU in simplicity and basic operations.
Chapter 1 Computers and Programming
7
The CPU goes through what is called a machine cycle in which it performs the
same series of simple steps: fetch, decode, execute, and store. The instructions
executed during a machine cycle are very simple, but billions of instructions can
be processed per second.
CPU Machine Cycle
1. fetch the required piece of data or instruction from memory
2. decode the instruction
3. execute the instruction
4. store the result of the instruction
CPU Machine Cycle
The processing power of a CPU is dependent upon the number of instructions
that the CPU can execute per second, and is measured in hertz (cycles-persecond). This is often referred to as the CPU clock-speed. This does not refer to a
wall clock, but the computer’s clock or the internal timing of the computer. A
one-gigahertz (1 GHz) CPU can execute one billion cycles (instructions) per
second, and the clock-speed would be one-gigahertz.
Writing software (programming) in a low-level language is possible, but high-
level languages provide a much easier way. As more software was written,
high-level languages were introduced to make programming easier and more
efficient.
In high-level languages, multiple instructions are combined into a
single statement. There are hundreds of high-level languages (700+) that have
been developed. Today there are approximately 250 high-level programming
languages in use by programmers. Some of these are used extensively, others
not so much. Each language was created for a purpose and has benefits and
limitations as well as a following, proponents, and detractors.
The following is a short list of some popular high-level languages and their
intended uses.
Chapter 1 Computers and Programming
8
BASIC
Beginners All-purpose Symbolic Instruction Code
C, C++
powerful general-purpose programming
COBOL
Common Business-Oriented Language - business programs
FORTRAN
FORmula TRANslator for math and science
Pascal
teaching programming
Java
applications running over the internet
JavaScript Web site operations (not related to Java)
PHP
web server applications and dynamic web pages
Python
general-purpose applications and data handling
Popular High-level Programming Languages
Writing software in any of these languages is much easier than the low-level
languages of Machine and Assembly, but the computer is still only interested in
machine language. To translate programs written in a high-level language to the
machine language for the computer, compilers and interpreters are used.
A compiler translates the high-level language into a separate machine language
program.
Software engineers refer to this as compiling or “building” the
program. A “Build” is a compiled version of the software and the program can
then be run whenever needed because it is a stand-alone executable program.
Java uses a compiler.
An interpreter on the other hand, reads, translates, and executes the program
one line at a time. As an instruction in the program is read by the interpreter, it
converts the instruction into machine language and then executes that one
instruction. The Python programming language is an interpretive language and
uses an interpreter to execute the instructions.
The instructions (programs) written by programmers are referred to as source
code, which is written using a text editor in an Integrated Development
Environment (IDE). IDEs are software applications that include integrated
tools for software developers to write, execute, and test software. There are
many IDEs available, but they are very similar in the way that they look, are
used, and operate.
Chapter 1 Computers and Programming
9
Developing Software
There are specific phases in the process of developing software that provide for
the development of accurate, maintainable, and scalable software, that meets
project or program requirements. These phases include design, development,
test and integration, and delivery and maintenance. But before any work can
begin, a complete understanding of what the program is supposed to do is
required. This is derived from the project or program requirements.
Requirements
The requirements for a computer program detail what the program is supposed
perform. How it will do what it is supposed to do will be determined as the
design phase is completed during the software development phase (SDP).
Requirements Decomposition is the act of discovering in detail from the
requirements what the program is required to accomplish. As requirements are
reviewed, additional information may be needed and questions may arise. It is
important to determine the specifics before moving forward. This process also
assists in decomposing the project into manageable “chunks” in terms of the
schedule and team assignments for development. Once the requirements are
thoroughly understood, the software development lifecycle begins.
Software Development Life Cycle (SDLC)
The Software Development Life Cycle includes the steps necessary to design,
develop, deliver, and maintain the computer program. The phases follow one
another and are often accomplished by different team members with
collaboration as questions and issues arise. As an example, a software developer
may meet with a design engineer to clarify information in the design, or a Test
Team member may contact a software developer regarding test results.
Software Development Lifecycle
Chapter 1 Computers and Programming
10
Design
As the requirements are decomposed and documented, the design phase begins,
and the break-down of required tasks and logical steps in the program are
developed. Design is a very important part of the software development life
cycle due to the increased costs of making changes or fixing errors later in the
process (errors in code are referred to as bugs). The sooner an issue is resolved,
the less rework and testing of the code are needed. This is highlighted in the
chart below from the IBM Systems Sciences Institute.
Cost of Fixing Errors by Phase
Software engineering tools that assist in the design (and development stage as
well) include pseudocode (sort of code). Pseudocode is a short-hand version of
the order of operations for a program. Consider a requirement for a program
that obtains age and salary information from a user, computes Recommended
Net Worth, and displays the result. The pseudocode for the solution might be:
Step 1
Start the program
Step 2
Obtain the age and salary information
Step 3
Compute the RNW (age x salary divided / 10)
Step 4
Display the output
Step 5
End the program
Pseudocode
Chapter 1 Computers and Programming
11
A flowchart often provides a clearer representation of the algorithm (logical
steps to the solution). Various geometric shapes are used to indicate different
operations (shapes may vary depending on industry). The order of operations is
typically top down, and lines with arrows are used to indicate the order or flow
of control.
Flowcharts can ensure that steps in the process haven’t been
overlooked and that there is a complete understanding of the operational flow of
the program. They can also be used to assist programmers when developing a
complex part of a program.
Example Flowchart
A flowchart can be a simple sketch or developed using a flowcharting
application such as LucidChart or SmartDraw. Flowcharts are often required
to be delivered to a development team or subcontractor together with specific
requirements for the code, and are often required in customer documentation.
Many software engineers use a combination of tools. Pseudocode may be used
for a high-level description of the program or a program area, and a flowchart
might be used for more complex sections. Either way, the goal is to have a
comprehensive understanding of the requirements at every level to ensure that
the final product meets the requirements and is as error-free as possible.
Chapter 1 Computers and Programming
12
Development
Once a design is complete (or nearly complete since some aspects of the solution
may not be knowable during design), the development phase begins.
The
development phase includes writing the code that will be executed to produce
the desired result and meet the requirements. Most often, the development of a
program is divided among multiple programmers and requires collaboration
and regular discussion to ensure a cohesive solution.
To manage software
development projects and enable multiple people to work on the same program
at the same time, a Configuration Management System (CMS) is used with a
source code repository that stores and maintains all of the program files.
Software Development Collaboration
Programmers access this repository to obtain a copy of a file containing the
source code to add functionality or make modifications. The code is written in
the copy of the file, and this changed file is tested with the other files in the
source code repository.
After testing, the modified file is placed into the
repository and is used by all of the other programmers in place of the original
file. The original file is retained by the configuration management tool as a
version control mechanism.
If a new file needs to be created, it is created in the configuration management
tool and added to the source code repository. CMS tools facilitate collaborative
Chapter 1 Computers and Programming
13
development, and version control of the files and the overall project. Many
industries and customers require their use.
Many configuration management systems have integrated suites that include:
scheduling and tracking, task assignment, defect reporting, and issue tracking
systems. In addition, tools for software teams and software project managers are
commonly used in industry to plan and measure project progress, and to provide
visibility into the design, schedule status, cost, and quality of the code.
Software Development Processes
For the software development phase, the Agile Development Process is a
popular method in use today. Agile processes go by various names (a few listed
below), but all are iterative and incremental software methodologies.
This
process of developing portions of the software and adding them to the overall
project incrementally is commonly referred to as Iterative Enhancement.
Common Agile Methodologies
•
Scrum – regular meetings, with periodic cycles called sprints
•
Crystal - methodology, techniques, and policies
•
Dynamic Systems Development Method (DSDM)
•
Extreme Programming (XP)
•
Lean Development
•
Feature-Driven Development (FDD)
Agile Software Development Methodologies
A key component of the Agile Development Process is the sprint (the
development period between status meetings). Sprint status meetings (scrums)
are review and planning events that occur regularly. Tasks completed from the
previous sprint plan are reviewed, and completed work is demonstrated to
stakeholders for feedback and approval. The tasks that were not completed from
the previous sprint plan are reviewed with a course of action (re-plan) for the
next development cycle. The scope of new work that will be completed during
the next sprint cycle is planned, and engineers are assigned to the tasks.
Chapter 1 Computers and Programming
14
The phases in the Agile Development Process include: Plan, Design, Develop,
Test, and Evaluate, and are repeated during each sprint. Once delivered, the
project would be in the maintenance phase.
Agile Development Process Phases
Another software development methodology is the Waterfall model which
uses similar phases, but they are sequential, and are non-repeating. Each phase
depends on the completion of the previous phase, although there may be some
overlap. The Waterfall model was used extensively in the past, and is still
common in some industries today. The maintenance phase follows the delivery
of the software and includes updates.
Waterfall Development Process Phases
Chapter 1 Computers and Programming
15
Test and Integration
As development is completed, the next phase in the software development life
cycle is test and integration. In the initial test phase, the programmer runs the
program to ensure that there are no errors in the code, and that it performs
correctly (meets the requirements). In large organizations, a test team or test
engineer will also run the program and report any errors found to the developer
for correction. On large-scale programs, a formal Test and Integration Team
would be responsible for this phase and would run a variety of tests including:
Unit Tests on the modules (portions of code being added or modified), and an
Integration Test which verifies that the parts of the program work well together
when the new code is integrated into the overall project. Adding the new or
modified code into the program may introduce new errors which must be
corrected. Regression testing compares new test results with previous results
and ensures that the program functions correctly.
Types of Errors
The three types of errors that are looked for during the test phase are syntax
errors, logic errors, and runtime errors.
Syntax errors have to do with violating language specific rules like indentation
and punctuation and are found by the compiler or interpreter and the code will
not execute. The programmer must correct these and most IDEs will highlight
them as an aid in development.
Logic errors are errors in the algorithm or the way that the algorithm was
written by the programmer. For example, if the requirement is that the program
multiply a number by two only if it is greater than ten, and the programmer
writes the code so that a number is multiplied by two if it is less than ten, that
would be a logic error.
The program compiles and runs, but it produces
incorrect results.
Runtime errors are logic errors that cause the program to stop executing. An
example would be a part of the program attempting to divide a number by zero.
Most IDEs will provide a Traceback of the sequence causing the error. Runtime
errors can be avoided by thoroughly designing and testing the algorithm.
Chapter 1 Computers and Programming
16
Delivery and Maintenance
The final phase of the software development life cycle is the delivery and
maintenance phase. In this phase, the program is delivered to the client or
customer and a period of maintaining the program begins. Maintenance of a
program would include updates that fix errors or security issues found after
initial delivery, or upgrades that provide additional functionality or capability.
Updates to software programs are commonplace today.
Ergonomics
The set-up or arrangement of the computer and furniture to minimize the risk of
injury or discomfort is a field of engineering called ergonomics. It includes the
study of the physical effects of repetitive motion and working in a stationary
position for an extended period. As more people spent their days working at
computers, a variety of health issues surfaced. Some guidelines include:
•
Monitor position – with respect to eye level (dry eyes)
•
•
Adjustable chair – arm posture (tennis elbow)
•
•
Elbows should be at 90-degree angles
Proper posture – back posture (lumbar issues)
•
•
Eyes should be looking slightly downward
Lumbar support and back straight
Taking periodic breaks – eye strain, posture, repetitive motion
•
20-20-20 rule says every 20 minutes look 20 feet way for 20
seconds
•
•
Standing or walking away for few minutes
Adequate lighting – eye strain
•
Dark areas and dark backgrounds cause eye strain
Ergonomic Guidelines
Chapter 1 Computers and Programming
17
Chapter 1 Review Questions
1. Computers are simply _________ __________ devices.
2. The physical parts of the computer are referred to as _____________.
3. The CPU is considered the ___________ of the computer.
4. The CPU performs basic ____________ and controls computer _________.
5. Main memory (RAM) is ________ and is erased when a computer is turned off.
6. __________ Storage device memory is non-volatile and is retained when the
power is turned off.
7. A computer keyboard, mouse, and camera are examples of _________ devices.
8. Computer monitors, speakers, and printers are examples of __________devices.
9. Sets of programmed instructions for a computer are referred to as __________.
10. _____________ and _____________ are the two basic types of software.
11. The language of computers is a _________ language.
12. The smallest information representation in computing is a _____ or binary digit.
13. A binary digit can have a logical state of _____ or _____.
14. A Byte is a combination of ________ bits that are either one or zero.
15. The number represented by 0110 1001 is _______.
16. The binary representation of the number 255 is ___________.
17. The names of the two low-level languages are __________ and __________.
18. A Machine cycle consists of ________, ________, ________, and ________.
19. A 2 GHz (gigahertz) processor can execute __________ instructions per second.
20. High-level languages make programming a computer _____ and more _______.
21. Java is a _______ -level language.
22. A (n) ___________ translates a high-level language into a separate machine
language program.
23. A (n) ___________ reads, translates, and executes a program one line at a time.
24. The four steps in the Software Development Life Cycle are ________,
____________, _______________, and _________________.
25. The costs associated with fixing errors in code are __________ when caught
early in the process.
Chapter 1 Computers and Programming
18
26. A written shorthand version of the steps to complete a task in a computer
program is called _______________.
27. The act of discerning in detail from the requirements what the program is to
accomplish is called ___________________ ____________________.
28. A set of logical steps taken to complete a task is called a(n) _____________.
29. Plan, design, develop, test, and evaluate are the five steps in the ___________
development process.
30. The three types of programming errors are _________, __________ and
____________ errors.
Chapter 1 Short Answer Exercises
31. Explain the major difference between main memory and secondary storage.
32. List at least three (3) input devices.
33. List at least three (3) output devices.
34. List the two (2) types of software.
35. Write the word Java using the binary representations of the letters.
36. Write the binary representation for the number 176.
37. List the two low-level languages.
38. What is the purpose of a source code repository?
39. List the five phases of the Agile Development cycle.
40. Explain the difference between logic and syntax errors.
Chapter 1 Programming Exercises
41. Write the pseudocode for the steps required to determine the total
price for some number of items entered by the user priced at $9.00
each with a 7% sales tax.
42. Draw a flowchart of the steps in Programming Exercise 1 above.
43. Ensure that you have access to a copy of Eclipse (ref. Appendix B).
Chapter 1 Computers and Programming
19
Chapter 2
Java Language Basics
The Java programming language was initiated as a project in 1991 by James
Gosling, Mike Sheridan, and Patrick Naughton, and was originally designed for
embedded systems. With the introduction of web browsers, and the reduction in
prices and speed increases for computers in the 1990’s, Java developed into a
general-purpose programming language with the release of version 1.2 (Java 2)
in 1998. The current version is Java SE13 released in September 2019. Java is a
class-based, object-oriented language that is compiled to bytecode and runs on
any virtual machine.
JVM - The Java Virtual Machine (JVM) enables computers to run Java programs.
The JVM converts Java bytecode into machine language, manages memory, and
is part of the JRE. It allows Java programs to run on most devices and operating
systems.
JDK - The Java Development Tool-kit (JDK) is a development environment for
creating Java programs and applets that includes the JRE, an interpreter,
compiler, archiver, and documentation generator. There are a variety of JDK’s
for different operating systems and environments available.
JRE - The Java Runtime Environment (JRE) is an implementation of the Java
Virtual Machine that executes Java programs.
Chapter 2 Java Language Basics
20
The Eclipse IDE
The Eclipse IDE provides all of the Java development tools necessary to develop
programs in Java. It is the most widely used IDE for Java programming, is used
by many companies, and is suitable for starting out in Java as well as advanced
programming and collaboration. It is free to download and use, and is similar to
most IDEs in look-and-feel and capability. The Eclipse version used in this text is
2019-06. Obtaining a copy is covered in Appendix B and Getting started in
Eclipse is covered in Appendix C and should be completed before continuing.
The Eclipse IDE
Parts of a Java Program
The “Hello World” program from the appendix is repeated below with line
numbers for explanations of the parts. On line 1 is the package or project name.
The package in Java is used to group related classes and files. On line 3 is the
class name for the program. Every Java program has at least one class. The
word public is an access specifier indicating that the class is publicly accessible
for use. Other access specifiers will be covered later.
Chapter 2 Java Language Basics
21
The brace following the class name on line 3 begins a block of code for the class.
The closing brace for the class is at the margin on line 10 and aligns vertically
with the word public preceding the class. Aligning braces with the block of code
that they close is important for readability and the IDE will automatically align
and indent them. Line 5 is the header for the main method for the program. This
is where execution of the program begins when it runs. Note the brace at the end
of the line which begins another block of code. The closing brace is on line 8 and
is aligned with the indented header for the main method (the word public).
The parts of the main method header are:
•
public – specifying that it is accessible outside the class
•
static – designation that it is a class method and not associated with any
object
•
void – indicating that it has no return value
•
(String[ ] args) – a provision for command line arguments
Line 6 is a comment added by Eclipse indicating that the main method was
automatically created as a result of the checkbox when the class was created.
Line 7 is an output statement executed by the program. This line ends with a
semicolon which is the end-of-line marker in Java. To the compiler, a semicolon
indicates the end to a statement just as a closing brace indicates the end of a block
of code.
Chapter 2 Java Language Basics
22
Syntax and Grammar
Each programming language has some characteristics and rules that must be
followed when writing programs in that language. Two of these are the syntax
and grammar of the language.
The syntax of a language refers to the rules for properly combining symbols,
operators, and punctuation, as well as the proper use of operators.
The grammar of a programming language determines the structure of the
sentences containing the symbols, operators, and punctuation that make up the
instructions for the computer.
Another characteristic of programming languages is the use of keywords or
reserved words. Keywords are reserved by the language for a specific use and
cannot be used for another purpose. Eclipse will display them in a color font to
highlight them as shown below (package, public and class).
The following is a list of some of the Java keywords.
boolean
catch
char
class
double
else
extends
final
finally
for
if
implements
import
int
new
package
private
public
return
static
String
throw
try
void
while
Java Keywords (partial list)
Note: True, false, and null are literals and are reserved in Java as well.
Comments
In addition to the tools mentioned in Chapter 1 for designing and developing
software, comments within the code can be helpful and are often required.
Chapter 2 Java Language Basics
23
Comments in programs are lines of code that are not executed, and are ignored
by the compiler. They are provided for human readers, and are used to clarify
values or sections, or explain complex operations. This is important because
most software is maintained, updated, and expanded. Code is written once, but
is read many times, and the person who wrote the code may not be the person
making the modifications, or the person who wrote the code may not remember
why a section was written a certain way or why a specific value was used.
Adding comments to code while it is being written can save hours of reading
through the lines later when the code is being changed.
Comments can also be used as a development tool. Pseudocode can be written
in the edit window as a comment to act as a place-holder or reminder that will be
replaced later by actual code.
Single line comments in Java begin with two forward slashes. The Eclipse IDE
used in this text will color code comments in green font as the default. For multiline comments, a forward slash with an asterisk “/*” begins the paragraph and an
asterisk forward slash “*/” ends the paragraph. For the Javadoc documentation
generator, which creates HTML documents from Java source code, the opening
paragraph indicator is a forward slash and two asterisks “/**” and it ends the
same as the multi-line comment.
// a single line comment in Java
/* a multiline
comment in Java
*/
/** A Javadoc comment for the document generator
*/
Java Comment Types
Variables
Variables are elements in programs that are used to allocate memory and store
information that the program will use. They are called variables because what is
stored in them can vary as the program runs. A variable is declared and named
Chapter 2 Java Language Basics
24
by the programmer to allocate memory for use by the program. The computer
remembers the memory address of where it is stored, and the programmer refers
to it in the program by the name that was used to declare it.
In the Hello world program, a literal string (sequence of characters) was passed
to the output statement. A variable could also be used as shown in Ex. 2.1 below.
In the example, a String variable is declared on line 7 and is assigned the value
“initially”. This is referred to as initializing the variable. The equal sign is the
assignment operator in Java and is used to assign a value to a variable. The
computer allocates memory for a String named myWord and stores the value
“initially” there. On line 8, the variable is passed to the output statement. The
variable is then assigned “currently” on line 10 which replaces the value that was
previously stored and line 11 displays it again. The Eclipse console output is
shown below the program. The use of println() instead of print on lines 8 and 11
causes the output to be on separate lines.
Ex. 2.1 – String Variable Declaration, Initialization, and Modification
Variable Declaration and Utilization
Notice in the example that when the variable myWord is assigned a
new value, it is not preceded by the word String. String is the data
type (covered next) of the variable which is only used when a variable
is being declared.
Chapter 2 Java Language Basics
25
Data Types
The example in Ex. 2.1 declared a String variable and assigned it a value that was
a literal string (a series of characters within double quotes). When a variable is
used to store a number, a different data type is declared. The data types in Java
include int for integers (whole numbers), and float and double for floating-point
numbers (numbers with a decimal). The data type tells the computer how much
memory to reserve for the variable. To store an integer, or float, 4 bytes are
allocated. To store a double, 8 bytes are allocated to accommodate more precise
numbers (the double data type is recommended for fractional numbers). The
numeric ranges for integers and doubles in Java are sufficient for most program
requirements and are used for whole and fractional numbers in this text.
Table 2.1 below lists some of the basic data types used in Java.
Table 2.1 - Java Primitive (simple) Data Types
The next example declares two integer variables and uses them in three different
output statements to highlight some additional considerations when working
with numbers in Java. Each of the output statements uses println() which adds a
line feed after the output is displayed. The first output statement adds the two
Chapter 2 Java Language Basics
26
values of the variables, but the second does not. The difference is the occurrence
of the literal string that precedes the expression. This causes Java to interpret the
plus sign as adding textual output and not numbers. Note that num1 could not
be mathematically added to the literal string. The value stored in num2 could be
added to num1, but the individual values are displayed.
The third output
statement forces the addition of the values using parenthesis.
Ex. 2.2 – Numeric Variable Declaration, Initialization, and Output
Program Output
Variable Names
The variable naming convention most used in Java is called uppercasing. A
single word variable is all lower case, and a two-word variable has the first word
in lower case and the first letter of the second word in uppercase. This aligns
with W3C (World Wide Web Consortium) as well as other Guides and Standards
for the language. When naming variables, there are a few rules that need to be
followed:
•
none of the Java keywords can be used as a variable name
•
there cannot be any spaces in the name
•
the first character must be a letter (or an underscore)
•
uppercase and lowercase letters are distinct
Chapter 2 Java Language Basics
27
In addition, the name of a variable should describe the data that it stores.
Software engineering principles and programming standards require descriptive
variable names to enhance readability. A longer name is usually better. Using
variable names like var or pd are ambiguous and make removing errors
(debugging) and maintaining the code more difficult. If a comment is needed to
describe a variable, then the name of the variable is inadequate.
Table 2.2 below lists some examples of good and bad variable names.
Table 2.2 - Variable Naming
Error Notifications
Java is case sensitive and common programming errors include case errors and
misspelling a previously declared variable name. These types of errors will be
highlighted in most IDEs as they are introduced so they can be corrected
immediately. If errors exist in the code and an attempt is made to run the
program, it will cause a compiler error and will not run. In the error example
below, the variable number is declared with all lowercase letters, but an
uppercase letter is used in the output statement. The IDE underlines the variable
name with red and places an error indicator at the margin on the line containing
the error. Hovering over the indicator provides a description of the error.
Chapter 2 Java Language Basics
28
When an attempt is made to run the program, a compiler error is output to the
console area of Eclipse with a description and line number containing the error.
Error Example
Variable Assignments
When a variable is declared, it is typically assigned an initial value. This is
referred to as initialization. A single equal sign is the assignment operator, and
the variable being assigned is on the left side of the operator. The right side of
the assignment operator can be a value or an expression. In this statement, a
variable userAge is declared as an integer, and is assigned the value 29.
int userAge = 29;
// userAge is assigned 29
As shown previously, a variable can be changed while the program is running.
The new value assigned to a variable overwrites the old value in memory where
the variable is stored.
Ex. 2.3 – Changing the Value Stored by a Variable
Chapter 2 Java Language Basics
29
In Ex. 2.3, a variable is declared and initialized. The variable is then changed
using the old value in the expression to assign a new value. Note that a variable
can be on both sides of the assignment operator. The right side is evaluated first
by the computer and the result is assigned to the left side.
Constant Variables (Named Constants)
A constant is a variable that cannot be changed by the program, must be
initialized when declared, and cannot be assigned a new value. There are several
situations when this is preferred. One is to eliminate the use of unidentified
numbers in programs, and another is to ensure that a specific value is used
throughout the program.
An unidentified number in programming is referred to as a magic number.
They are literal numbers in a program without an obvious meaning. When a
program is being modified and an expression uses a magic number, it may be
difficult to determine what the number means even by the original programmer.
As an example, the following line appears in a program that declares a double as
diameter, but the meaning of 3963.2 is unknown. Since the equation results in a
diameter, it appears to be a radius. It isn’t clear.
By using a named constant in the code, the meaning is clear. The constant is
declared and initialized and then used in place of the literal number wherever it
is needed in the program. Constants are declared using the final keyword
followed by the data type, name, and initialization. The standard for naming
constants is all uppercase letters with underscores between words.
Named constants are also used to ensure that the same value is used throughout
the program and by all programmers. If multiple programmers are working on a
program that calls for them to use the radius of the earth in various equations,
they can use a named constant to ensure that the same value is used. The earth is
not a sphere and there are multiple values for its radius.
Chapter 2 Java Language Basics
30
Named constants also prevent typographical errors when the same value is being
used multiple times. In addition, when a new value is needed for the constant,
the change is made in a single place in the code. As an example, a scientist
overseeing a program using EARTH_RADIUS may decide that the equatorial
radius being used in the program should be changed to the pole radius of 3950.0.
It will only need to be changed to the new value in one place in the code. This
eliminates the possibility of typographical errors or missing an occurrence when
updating all of the equations that use the value.
Global Variables
A global variable is a variable that is declared outside all methods including the
main method. This makes them accessible to all parts of the program. Most
programming standards do not permit their use except when they are global
constants, because they could be changed arbitrarily by any part of the program
making debugging very difficult. Since a constant cannot be changed, a global
constant provides for using a consistent value across all of the code in a program.
Java doesn’t explicitly have global variables since every variable must belong to a
class, but once declared, they can be accessed using the class name.
Mathematical Operators and Expressions
The operators for mathematical expressions in Java include: addition (+),
subtraction (-), multiplication (*), division (/), and the modulus operator (%).
Table 2.3 - Arithmetic Operators
Chapter 2 Java Language Basics
31
The mathematical operators combine with variables and expressions in programs
to perform operations. The lines of code in Ex. 2.4 declare three integers and use
them in various equations. Recall that the computer evaluates the right-hand
side of the assignment operator, and then assigns the result to the left-hand side.
Ex. 2.4 – Mathematical Operators
The results from division in Java are different for different data types and data
type combinations. If one of the values is a floating-point number (number with
a decimal), the result is a floating-point number. If both numbers are integers as
in the first example below, the result is truncated to an integer and the decimal
portion is discarded. One way to remember this is “int divided by int is an int”.
However, an integer divided by an integer will result in a double if the variable it
is assigned to is declared as a double.
The modulus operator produces the remainder after division (sometimes
referred to as modulo divide). The operand on the left of the operator is divided
by the operand on the right and the result is the remainder after division.
Chapter 2 Java Language Basics
32
Precedence in Java is parenthetical expressions first, followed by multiplication,
division, modulo division, and lastly addition and subtraction. Operators with
the same precedence are handled left to right, and precedence can be forced
using parenthesis. The use of parenthesis is often preferred even when they
align with precedence. This enhances the readability of the expression and helps
to eliminate errors. The equations in the table below are the same, but the results
are quite different.
Table 2.4 - Precedence and Parentheses
Mixed-type expressions are promoted to the higher data type in use. In an
expression with an integer and a double, the integer is temporarily converted to
a double, and the expression is promoted resulting in a double. The same rule
applies to an expression with an integer and float.
When using floating-point (fractional) numbers, the double data type is
recommended over float for variables since it is more precise as the
results below illustrate.
Chapter 2 Java Language Basics
33
Programming Algebraic Expressions
When converting mathematical expressions into Java code, the translation may
require adding operators and parentheses to ensure the correct result. As an
example, the expression 3xy in algebra would produce a syntax error. The
multiplication operator must be inserted as in 3 * x * y. When an expression
contains fractions, precedence requires careful consideration to ensure that
operations occur in the correct order.
With extremely complex equations,
breaking the expression into parts may be the best course of action.
Conversion examples:
Converting Algebraic Expressions
Math Methods
The Java Math library contains constants like PI and methods for exponentiation,
rounding numbers, and other common operations. To use these operations, the
method is preceded by the library name “Math” as shown below. The functions
are passed arguments which are values passed to methods and functions for
their use.
As an example, for rounding numbers, Java has a Math.round()
function. The line of code below passes the number 9.4 as an argument to the
round function. The function executes and the result is assigned to the variable.
Chapter 2 Java Language Basics
34
For operations with exponents, the Math.pow() function is used. In this case,
two arguments are required. The first argument is the number to be raised, and
the second is the exponent.
In addition to the round() and pow() functions, the java.lang.Math library contains
functions for performing other mathematical operations including: abs(x), acos(x),
asin(x), atan(x), cos(x), hypot(x), log(x), sin(x), sqrt(x), and tan(x) among others.
Below is an example that uses the square root function.
Converting Data Types
Converting from one data type to another in code is referred to as casting. The
round method in the example below returns a double, which is then cast to an
integer so that it can be assigned to the integer variable roundInt. The data type
that the value is being cast to is in parenthesis.
Obtaining Keyboard Input
To obtain input from the keyboard in Java requires a Scanner. To use a Scanner,
the class java.util.Scanner must be imported. Import statements are located
between the project package and the class, and provide access to Java libraries.
Ex. 2.5 – Keyboard Input
Chapter 2 Java Language Basics
35
The line of code below declares a Scanner named in (can be any appropriate
name) and assigns it a Scanner using “new” and “System.in” which is the
standard system input source (the keyboard).
When a program needs to obtain keyboard input, a prompt is used to describe
the input being requested. Once the requested data is entered, the user will press
the Enter key. To obtain the input, a variation of the next() method is used. In
the example below, the prompt requests a number and nextInt() is used which
reads an integer. Note that nextInt() is preceded by the name of the scanner and
the dot operator to access the method.
When the program runs, the prompt is displayed and the program waits. Once a
value is entered in the console area of Eclipse and the Enter key is pressed,
nextInt() will obtain the value and it will be assigned to the variable. After the
output statement, the Scanner is closed (a recommended practice).
Obtaining Keyboard Input
The Scanner has methods to obtain input for various data types. During the
design phase of the program, different approaches and methods should be
considered depending upon how the data will be used.
different versions of the method are shown below.
Chapter 2 Java Language Basics
Examples using the
36
Scanner Methods for Obtaining Input
Design Consideration
The next() method will read input until whitespace is encountered. Whitespace
can be a space, tab, or line feed. Consider a program that requires the user to
enter the name of a city. If the city name entered is Denver, then next() will read
the full name. If the name of the city is New Brunswick, then next() would only
read the word New. In this situation, using nextLine() would ensure that the
entire city name would be read.
Formatting Output
The print() function that was used in previous examples to display output has
two other versions. One version, println() adds a line feed after the output is
displayed.
Ex. 2.6 – Line Feed Output
Program Output
Chapter 2 Java Language Basics
37
The other version for output is printf() which is used when formatting output.
A format specifier is used to indicate the formatting to be applied. Arguments
are passed to the function: the format specification(s) in quotes, and the value(s)
or string(s) to be formatted. The specifier begins with “%”, is followed by the
formatting, and ends with the type: “f” (float), “d” (integer), and “s” (string). An
integer is placed after a decimal in the specifier for the number of decimal places.
In Ex. 2.7 below, three different decimal specifiers are used. Note that using
printf() eliminates the ability to use println(), so line feeds are added as separate
output statements in the example.
Ex. 2.7 – Formatted Output
Program Output
Previously the “+” operator was used in output statements that
combined text with numeric values. With format specifiers, a comma
separates the specifier and the variable as shown in Ex 2.7.
A decimal place specifier that is fewer than the number to be
formatted will cause rounding as shown in the example.
Chapter 2 Java Language Basics
38
When a literal String is part of the output, the format specifier can be located
within the same quotes as shown here.
When more than one variable is included in the output, the specifiers are
included in the string portion in the order in which they are to be used in the
output. The actual variables are included afterward as shown here. Notice that
the numbers in the output were rounded due to specifying two decimal places.
To add commas for large numbers, a comma is included in the specifier after the
percent sign. Other formatting techniques and methods will be covered later in
the text.
This line of code adds the dollar sign to the output.
Chapter 2 Java Language Basics
39
Numeric data is often output in columns and right-aligned. To designate a
specific amount of space to use for output, the number of spaces is added to the
format specifier before the decimal or designator if no decimal is used.
A
negative sign before the spacing value is used for left alignment of the output. In
Ex 2.8, the descriptions are left-aligned and the prices are right-aligned.
Ex. 2.8 – Specifying Alignment and Output Spacing
Program Output
In Ex. 2.8, the word “Beverage” used all of the allocated space. If a String or
value does not fit in the specified space, the item will still be displayed entirely
but without any spaces.
Escape Sequences
To insert certain characters and formatting within literal strings, escape
characters are used. The escape sequences include: new line “\n”, tab “\t”,
Chapter 2 Java Language Basics
40
double quote \”, and back slash “\\”. The sequence is surrounded by quotes
unless it is within a literal string. When println can’t be used because printf is
being used, a line feed can be inserted as “\n” anywhere a line feed is needed.
Table 2.5 - Escape Characters
Ex. 2.9 – Escape Sequences
Strings
A string is a sequence of characters. When a literal string is written in the code,
it is surrounded by double quotes and is referred to as a string literal. A String
variable is the String object in Java and can contain a large amount of text
Chapter 2 Java Language Basics
41
(2,147,483,647 characters). A character is a data type that can store a single
character. It is declared using char and is assigned using single quotes. A String
can contain a single character, but is always surrounded by double quotes.
Characters are stored using their ASCII numeric values, so the assignment
statement above would actually store 65 as the value for “A” (see Appendix A).
The computer knows that the data type is char and handles the translation.
The characters contained in a String are in positions called indexes beginning
with index zero. In the String below, the “e” is at index 3 although it is the 4th
letter in the word.
To obtain a character from a String the charAt() method is used and is passed
the index of the character to obtain. Note that the method is preceded by the
String variable’s name and the dot operator (or dot notation). In the code below,
the character “e” would be assigned to the char variable letter.
To obtain a portion of a String, the substring() method is used. When two
arguments are passed to substring(), the first argument is the index of the starting
point of the substring to obtain, and the second argument is one index beyond
the portion to obtain. As an example, the following statements assign “friend” to
the String variable portion.
Chapter 2 Java Language Basics
42
When one argument is passed to substring(), the argument is the index of the
starting point of the substring to obtain, and the ending point is the end of the
String. The following statements assign “car” to the String variable ending.
Strings also have a method for obtaining their length. The length() method
returns the number of characters in a String including any spaces. In the code
below, 8 would be assigned to the variable len. Remember that the indexes for
the characters are 0 through 7, one less than the length.
Combining two or more Strings is referred to as concatenation.
operator is used to concatenate Strings.
The “+”
The operators will not add spaces
between the Strings. They are simply joined together as shown in Ex. 2.10 below.
Ex. 2.10 – String Concatenation
To add a space between the Strings, it can be added to either of the Strings being
combined or separately as shown here.
Chapter 2 Java Language Basics
43
The lines of code in Ex. 2.11 below prompt for a first and last name, and use the
next() method to obtain the input.
The inputs are stored in Strings, and
concatenation is used in the output statement to add a space between the names
and to add a period at the end.
Ex. 2.11 – String Concatenation
The ability to manipulate Strings is an important skill in programming.
Most interfaces receive input as Strings and perform error checking
and conversion of numeric values. Some of these techniques are
covered in the next chapter.
Methods, Functions, and Dot Notation
In this chapter, the examples used methods and functions to perform operations.
Although the terms tend to be interchangeable, for clarification, a method
typically refers to functionality associated with an object of a class, and a
function is not. As an example, the String variables declared in this chapter are
declared using an upper case “S” whereas the integer and double data types are
not capitalized.
Classes are capitalized in accordance with programming
standards, and the String is a class. The String class has other methods available
including toLower() and toUpper() for converting. To use them, the variable name
Chapter 2 Java Language Basics
44
for the String is followed by the dot notation and the method name. In the
statements below, a String is declared called word. The variable is actually an
object of the String class and inherits the methods of that class. The methods are
accessed using the dot operator as shown on the line below that uses length().
The Scanner is also a class that provides methods some of which were used in
this chapter. Again, after declaring a Scanner, dot notation was used to utilize
the methods. The Math functions that were used did not require declaring a
Math object before using them, but did use dot notation. The Package (Library)
name Math, the dot operator, and the function name were used as shown here.
Classes and Objects are covered in a later chapter.
Programming Style and Standards
Proper programming style and format of the code make a program easier to read
and maintain, and help to prevent errors from being introduced. The cost to fix
errors increases dramatically as the software development cycle progresses.
Anything that decreases the chances of introducing bugs is welcome and
utilized. For these reasons, Programming Standards have been developed to
provide uniformity and enhance the readability and maintainability of code.
They include proper spacing and indentation among others. An entire program
could be written on a single line and the computer would have no problem with
it, but someone trying to debug the code or add functionality would have a very
difficult time. Appendix G contains a set of Programming Standards for Java.
Programming Standards and Style Guides are used in industry to
ensure the readability and maintainability of programs due to the time
and cost associated with poorly written and ambiguous code.
Chapter 2 Java Language Basics
45
Chapter 2 Review Questions
1. The characteristics and rules that must be followed when writing programs in a
high-level language are ___________ and ___________.
2. Words that are reserved in a programming language are called ____________.
3. Words added to programs to explain complex areas or to add clarity and are not
executed when the program runs are _______________.
4. __________ are used in computer programs to store values in memory.
5. The __________ data type is used to store whole numbers.
6. Numbers with a decimal should be stored in the _________ data type.
7. The equal sign is used to ______________ a value to a variable.
8. The ______ side of the assignment operator is assigned to the ______ side.
9. A variable must be __________ before it can be used by the program.
10. Variable names (can or cannot) _______ begin with a number.
11. A ___________ should be used in place of a magic number.
12. A value passed to a method is called a(n) ___________ .
13. The __________ escape character is used to produce a tab.
14. Converting an item to a different data type is known as ___________.
15. Errors in programing are typically referred to as __________.
16. Which of the following variable names follow proper naming conventions?
a.
b.
c.
d.
e.
average
8pieces
netPay$
grossPay
hourlyRate
17. The first character in a String occupies index ________ in the String.
18. The _________ data type can store one character.
19. Concatenation refers to _____________ two or more Strings.
20. Programming _____________ provide uniformity and enhance the readability
and maintainability of code.
Chapter 2 Java Language Basics
46
Chapter 2 Short Answer Exercises
21. What type of variable is defined in this expression?
final double INTEREST_RATE = 0.07;
22. What do the following lines of code display?
double ouncesPerCan = 8.0;
System.out.print(ouncesPerCan);
23. What is the resulting output when the following lines of code are executed?
int number = 23;
number = 52;
System.out.print(number);
24. What do the following lines of code display?
int number = 12;
number = number + 8;
System.out.print(number);
25. What value is assigned to num3 in the lines below?
int num1 = 32, num2 = 6;
int num3 = num1 + num2;
26. What do the following lines of code output?
double num1 = 2.5;
int num2 = 5;
num1 = num1/num2;
System.out.print(num1);
27. In these expressions, what value will be assigned to the variable result?
a. result = 5 / 2.0;
b. result = 7 / 2;
c. result = 4 * 3 / 2;
d. result = 5 % 2;
Chapter 2 Java Language Basics
47
28. Express the following equations using Java expressions.
e. 4xy
f. z = 2ab
g. y = b2-4ac
𝑎+𝑏
h. 𝑡 = 𝑥 − 𝑦
29. In the expressions below, what will be the value assigned to the variable num1?
a. num1 = Math.round(2.3);
b. num1 = Math.pow(4,2);
c. num1 = Math.sqrt(25);
d. num1 = Math.sqrt(Math.sqrt(81));
30. In following statement, what does the number “8” specify?
System.out.printf(“%8.2f”, number);
31. After the lines below execute, what will be the output?
double number = 123.453;
System.out.printf(“%.2f”, number);
32. What is the output from the following statement?
System.out.print(“She said \”hello\”.”);
33. After the lines below execute, what will be stored in the variable name?
String first = “Angela”;
String init = “P.”;
String last = “Harad”;
String name = first + “ “ + init + “ “ + last;
34. After the lines below execute, what will be stored in the variable letter?
String name = “Sheila”;
char letter = name.charAt(1);
Chapter 2 Java Language Basics
48
35. After the lines below execute, what will be stored in the variable part?
String word = “cartoon”;
String part = word.substring(0, 4);
36. After the lines below execute, what will be stored in the variable portion?
String word = “classroom”;
String portion = word.substring(5);
37. After the lines below execute, what will be stored in the variable len?
String cafe = “Angelo’s”;
int len = café.length();
38. Which of the following should be used to read a line of text including spaces to
store in the variable phrase?
a. phrase = in.nextInt( );
b. phrase = in.nextDouble( );
c. phrase = in.nextLine( );
d. phrase = in.next( );
Chapter 2 Programming Exercises
39. Complete the “Hello World” exercise in Appendix C and provide a screen
capture of the IDE with the output.
40. Write a line of code that displays the following text.
Java is a high-level language.
41. Write a line of code that displays the following text with the quotes.
The waiter said “The special is good!”
42. Write a program that prompts the user to enter their name, stores the input in a
String variable, and then displays ‘Hello ‘, and the name that was entered.
Chapter 2 Java Language Basics
49
43. Write a program with three integer variables: first, second, and third. Assign
the values 5, 6, and 7 to the variables and display each on a separate line using
the variable names.
44. Write a program that declares the constant below and displays “The interest
rate is “ followed by the constant and a percent sign.
INTEREST_RATE = 7
45. Write a program that assigns the variable tickets the value 125 and then
displays “The tickets sold today were “ followed by the variable.
46. Write a program that defines three String variables named word1, word2, and
word3. Assign abc to word1, def to word2, and then assign word1 and
word2 combined to word3 using concatenation. Then display word3.
47. Write a program that uses a double that is assigned 12345.678 and use a format
specifier to display the number with commas and two decimal places.
12,345.68
48. Write a program using variables to display the numbers below on separate lines,
with two (2) decimal places, and in fields that are eight (8) characters wide.
123.45
1452.56
56.80
49. Write a program that uses three (3) print statements to display the words No,
lines, and between all on one line with spaces between the words.
50. Write a program that prompts the user to enter their age, stores the age in a
variable named age, and then displays “Your age is “ and the age that was
entered.
51. Write a program that prompts the user to enter a number, and then a second
number. The program will add the numbers, store the result in a variable and
display “The sum of the numbers is: “ and the result.
52. Write a program that computes the total cost of a meal based on the meal price
entered by the user, plus a 20% tip, and 5% sales tax. The output should be
displayed as shown below and include a dollar sign and two (2) decimal places.
Chapter 2 Java Language Basics
50
53. Expand number 14 to include output of the tip, and tax amounts, before the
total price. The output should include a blank line between the input prompt
and the output, dollar signs, two (2) decimals, and amounts aligned right.
54. Write a program that prompts the user to enter a Fahrenheit temperature,
computes the Celsius temperature, and displays ”The Celsius temperature
is: “ and the result. The equation for the conversion is:
C = (F – 32) / 1.8
Test data: When F = 23, C = -5
55. Write a program that prompts the user to enter the lengths of the two sides of a
rectangle. The program will compute the area and perimeter, and assign the
values to two variables. Then display the computed values with their titles as
shown in the example below.
56. Write the pseudocode for a program for a Yogurt vendor that computes the
total sales and profit for a day’s sales based on the number sold at $6.50 each,
and the cost of the Yogurt to the vendor which is $4.25 each. The profit is the
total sales minus the total cost.
57. Write the program for the Yogurt vendor in #56 above. The program will display
the output as shown in the example below. Note the dollar signs and
alignment.
Chapter 2 Java Language Basics
51
58. Write a program that prompts the user for two integers (x and y) and computes
a result using the equation below. Note the output when y is entered as 1.
𝑎𝑛𝑠𝑤𝑒𝑟 =
𝑥+2
𝑦−1
59. Part #1: The surface area of a sphere is given by the equation below. Write a
program that prompts the user for the radius of a sphere as a double and the
units of measure (feet, miles, etc.), computes the surface area, and displays the
result with the square units. Use Math.pow() in the solution, and format the
output to 3 decimal places. Use 3.14159 as the value for PI.
Surface area = 4 π r2
Part #2: The volume of a sphere is given by the equation below. Write a
program that prompts the user for the radius of a sphere as a double and the
units of measure (feet, miles, etc.), computes the volume, and displays the
result with the units. Use 3.14159 as the value for PI.
𝑉𝑜𝑙𝑢𝑚𝑒 = 4𝜋
𝑟3
3
Part #3: Combine parts 1 and 2 into a single program and add the computation
and output for the circumference. The program will prompt the user for a
radius as a double and the units of measure. Two examples are provided using
3.14159 as the value for PI, for testing to validate the output.
𝐶𝑖𝑟𝑐𝑢𝑚𝑓𝑒𝑟𝑒𝑛𝑐𝑒 = 2𝜋𝑟
Volley Ball radius: approx. 4.1 inches
The Earth’s moon radius: approx. 1,080 miles (note the commas in the output)
Chapter 2 Java Language Basics
52
Chapter 2 Programming Challenge
Loan Calculator
Design and develop a program for a car dealer that computes the monthly payment,
total payback amount, and total interest paid for a car loan based upon the loan
amount, interest rate, and loan duration in months.
The equation for determining the monthly payment for a loan is:
Monthly Loan Payment Formula: MP = L * ( r / (1 - (1 + r)-N)).
o
MP = monthly payment amount
o
L = principal, meaning the amount of money borrowed
o
r = effective interest rate. Note that this is usually not the annual
interest rate (see below).
o
N = total number of payments
Calculate the effective interest rate (r) - Most loan terms use the "nominal annual
interest rate", but that is an annual rate. Divide the annual interest rate by 100 to
put it in decimal form, and then divide it by the number of payments per year (12)
to get the effective interest rate. Note that the user enters the interest rate as a
percentage (4 for 4%).
o
Example, if the annual interest rate is 5%, and payments are made monthly
(12 times per year), calculate 5/100 to get 0.05, then calculate the rate:
Effective rate = 0.05 / 12 = 0.004167.
Sample output:
Chapter 2 Java Language Basics
53
Chapter 3
Decision Structures and Boolean Logic
Decision structures determine the statements that execute based upon a
conditional expression that is used to determine whether or not a line or lines of
code execute. Decision structures provide multiple paths through a program
based on the status of a true or false condition. If the condition is true, then a
statement or statements are executed, otherwise they are not executed.
The if Condition
As an example, assume that a Theater has seating for 400 customers. Once the
Theater has sold 400 tickets, the show has been sold out. When this occurs, the
Theater displays a “Sold Out” sign at the box office. The decision to display the
sign is made based upon whether or not 400 tickets have been sold. The decision
structure is implemented using the if statement.
Ex. 3.1 – Conditional Statement Pseudocode
If 400 tickets have been sold
-
Display the “Sold Out” sign
The condition tests if 400 tickets have been sold, and if it is true, the “Sold Out”
sign is displayed. If the condition is false and 400 tickets have not been sold,
then the sign will not be displayed.
Chapter 3 Decision Structures and Boolean Logic
54
Conditional expressions are represented in flowcharts as diamonds.
The
different paths that the program can take are shown using lines from the corners
of the diamond, arrows indicate the direction, and text indicates the result.
These paths in the program are often referred to as the Flow of Control or the
Order of Operations. In the example, if the condition is true then the flow of
control follows the path to display the sign. Otherwise (if the condition is false),
the program continues without displaying the sign.
Conditional Expression Flowchart
When programming a conditional expression in Java, the syntax includes
parenthesis around the conditional expression, and braces to enclose the
statement(s) executed when the condition is true. The statements to be executed
are indented for readability (most IDEs automatically indent these lines). The
general format is shown below with the opening brace on the line with the
condition. Some programmers place the opening brace on the line following the
expression, however most Java Style Guides prefer the format shown here.
Ex. 3.2 – Theater Ticket Sales “if” Condition (note the use of two equal signs)
Chapter 3 Decision Structures and Boolean Logic
55
When multiple statements are associated with a condition, they form a block of
code. A block of code is a group of associated statements. In this case, they are
associated with the conditional expression. If the condition is true, all of the
statements within the braces (the block of code) will be executed. If the condition
is false, all of the statements within the braces will be skipped over.
Continuing the Theater example, assume that when the show is sold out, the box
office is closed in addition to the sold-out sign being displayed. A standard
practice is to indent the pseudocode the same way that the lines would be
indented in the actual code.
If 400 tickets have been sold
-
Display the “Sold Out” sign
-
Close the box office
The flowchart for the Theater example has been modified to include closing the
box office if the condition is true.
Note how clearly the pseudocode and flowchart indicate the path taken if the
condition is true. The modified code is shown in Ex. 3.3 below.
Chapter 3 Decision Structures and Boolean Logic
56
Ex. 3.3 – Theater Ticket Sales “if” Condition Expanded
Boolean Expressions
Conditional expressions are either true or false, and are referred to as Boolean
Expressions named after the mathematician George Boole (1815-1864). Boolean
expressions are implemented using Relational Operators that resolve to either
true or false by testing relationships. The result of the expression determines the
next step or path for the program. For example, one value can be greater than
another, or less than another, or equal to another. One of these three cases must
be true, and the others would be false. Table 3.1 lists the Boolean operators
available in Java. Note that two equal signs are used to test for equivalence (a
single equal sign is the assignment operator).
Table 3.1 – Relational Operators
Some examples follow.
Chapter 3 Decision Structures and Boolean Logic
57
For the examples below: x = 5, y = 8, z = 5
x>y
5>8
False
5 is not greater than 8
x= 5
True
5 is equivalent to 5
x