CPS 202: Computer Programming II
Module One
i. Concept of problem solving (applying algorithmic thinking to solve programming
problems)
ii. Principles of good programming
iii. First java program.
iv. Variables, data types, and expressions- Identifier rules, Naming variables, constants
(final) and references
v. Primitive data types, Arithmetic Operators, Assignment Operators, Relational and
Logical Operators
vi. Program control flow-Sequence structure, Repetition structure
CONCEPT OF PROBLEM SOLVING
To be a skilful problem solver, and, therefore, to become a skilful programmer, you must use
good problem-solving techniques. One common problem-solving technique includes
analysing a problem, outlining the problem requirements, and designing steps, called an
algorithm, to solve the problem.
Algorithm: A step-by-step problem-solving process in which a solution is arrived at in a
finite amount of time.
In the programming environment, the problem-solving process involves the following steps:
1. Analyse the problem and outline the problem and its solution requirements.
2. Design an algorithm to solve the problem.
3. Implement the algorithm in a programming language, such as Java.
4. Verify that the algorithm works.
5. Maintain the program by using and improving it, and modifying it if the problem
domain changes.
Example 1: Design an algorithm to find the perimeter and area of a rectangle
The algorithm to find the perimeter and area of the rectangle is:
i. Get the length of the rectangle.
ii. Get the width of the rectangle.
iii. Find the perimeter using the following equation: perimeter = 2 * (length + width)
iv. Find the area using the following equation: area = length * width
PRINCIPLES OF GOOD PROGRAMMING
Good programming practices are essential for writing code that is efficient, maintainable, and
scalable. Here are some key principles of good programming:
1. Write Readable Code
- Clear and Consistent Naming Conventions: Use meaningful variable, function, and
class names.
- Commenting and Documentation: Write comments to explain why certain decisions
were made, not just what the code does. Maintain up-to-date documentation.
- Code Formatting: Follow a consistent style guide (e.g., PEP 8 for Python). Properly
indent and space your code.
2. Keep It Simple
- KISS Principle (Keep It Simple, Stupid): Simplify code to make it more
understandable and less prone to bugs.
- Avoid Over-Engineering: Don’t add unnecessary complexity or features.
3. Write Modular Code
- Single Responsibility Principle: Each function or module should have one
responsibility.
- Reusability: Write functions and classes that can be reused in different parts of the
application.
4. Practice DRY (Don’t Repeat Yourself)
- Eliminate Redundancy: Avoid duplicating code. Abstract common functionality into
functions or modules.
5. Error Handling
- Graceful Error Handling: Anticipate possible errors and handle them gracefully.
- Use Exceptions: Utilize try-catch blocks or similar mechanisms to manage
exceptions.
6. Test Your Code
- Unit Testing: Write tests for individual units of code.
- Integration Testing: Ensure that different modules or services work together as
expected.
- Continuous Testing: Automate testing and run tests frequently.
7. Version Control
- Use Version Control Systems: Git or similar systems help track changes, collaborate
with others, and manage code versions.
8. Optimize Performance
- Efficient Algorithms and Data Structures: Use the right algorithms and data structures
to optimize performance.
- Code Profiling: Profile your code to identify and eliminate bottlenecks.
9. Security
- Secure Coding Practices: Write code with security in mind to prevent vulnerabilities.
- Data Validation and Sanitization: Validate and sanitize all input to avoid injection
attacks.
10. Collaboration
- Code Reviews: Regularly review code with peers to catch issues early and share
knowledge.
- Pair Programming: Work together with other developers to solve problems more
efficiently.
11. Continuous Improvement
- Refactoring: Regularly improve and refactor code to maintain quality.
- Stay Updated: Keep learning about new tools, languages, and best practices.
12. Use Appropriate Tools
- IDEs and Text Editors: Use tools that enhance productivity and help detect errors
early.
- Linters and Formatters: Automate code formatting and enforce style rules.
FIRST JAVA PROGRAM
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World");
}
}
This program is called the source program. The program must be saved in a text file named
[Link], where ClassName is the name of the Java class contained in the file. For
this program, you save the program as [Link]
To compile: javac [Link]
This will create a new file called [Link] which is the bytecode equivalent of the
source code.
To Execute: java HelloWorld
This is run the program and give the output HelloWorld at the terminal. Interpreter: A
program that reads and translates each bytecode instruction into your computer’s machine
language, and then executes it
Class Work:
public class ASimpleJavaProgram {
public static void main(String[] args) {
[Link]("My first Java program.");
[Link]("The sum of 2 and 3 = " + 5);
[Link]("7 + 8 = " + (7 + 8));
}
}
Execute the Program
Figure 1 - Processing a Java program
VARIABLES AND DATA TYPES
Identifiers are names of things, such as variables, constants, and methods, that appear in
programs. Some identifiers are predefined; others are defined by the user. All identifiers must
obey Java’s rules for identifiers.
Basic Rules for Identifiers
1. Start with a Letter, Currency Character ($), or Underscore (_):
- Identifiers must begin with a letter (a-z, A-Z), a dollar sign ($), or an underscore (_).
- They cannot begin with a digit (0-9).
2. Subsequent Characters:
- After the first character, identifiers can contain letters, digits, dollar signs, or
underscores.
3. No Spaces Allowed:
- Identifiers cannot contain spaces.
4. Case Sensitivity:
- Java is case-sensitive, meaning `myVariable` and `myvariable` would be considered
different identifiers.
5. No Reserved Words:
- Identifiers cannot be the same as Java's reserved words or keywords (e.g., `class`,
`public`, `void`, `if`, etc.).
Examples
- Valid Identifiers:
- myVariable
- _myVariable
- $myVariable
- myVariable2
- Invalid Identifiers:
- 2myVariable (cannot start with a digit)
- my Variable (contains a space)
- class (reserved word)
Conventions (Not Rules, but Best Practices)
- Camel Case for Variables and Methods: Use camelCase for naming variables and
methods (e.g., myVariable, calculateTotal).
- Pascal Case for Classes: Use PascalCase (also known as UpperCamelCase) for
naming classes (e.g., MyClass, EmployeeDetails).
- Upper Case with Underscores for Constants: Use ALL_UPPER_CASE with
underscores for naming constants (e.g., MAX_VALUE, DEFAULT_TIMEOUT).
DATA TYPES
The primitive data types are the fundamental data types in Java. There are three categories of
primitive data types:
Integral, which is a data type that deals with integers, or numbers without a decimal
part (and characters)
Floating-point, which is a data type that deals with decimal numbers
Boolean, which is a data type that deals with logical values
Integral data types are further classified into five categories: char, byte, short, int, and long.
int DATA TYPE
This section describes the int data type, but this discussion also applies to other integral data
types. Integers in Java, as in mathematics, are numbers such as the following:
-6728, -67, 0, 78, 36782, +763
Note the following two rules from these examples:
• Positive integers do not require a + sign in front of them.
• No commas are used within an integer. Recall that in Java, commas are used for
separating items in a list. Thus, 36,782 is interpreted as two integers: 36 and 782.
char DATA TYPE
The char data type has 65536 values, 0 to 65535. However, the main purpose of this data type
is to represent single characters—that is, letters, digits, and special symbols. Therefore, the
char data type can represent any key on your keyboard. When using the char data type, you
enclose each character represented within single quotation marks. Examples of values
belonging to the char data type include the following:
'A', 'a', '0', '*', '+', '$', '&', ' '
Note that a blank space is a character and is written as ' ', with a space between the single
quotation marks
boolean DATA TYPE
The data type boolean has only two values: true and false. Also, true and false are called the
logical (Boolean) values. The primary purpose of this data type is to manipulate logical
(Boolean) expression. An expression that evaluates to true or false is called a logical
(Boolean) expression.
FLOATING-POINT DATA TYPES
To deal with decimal numbers, Java provides the floating-point data type. Java provides two
data types to represent decimal numbers: float and double. As in the case of integral data
types, the data types float and double differ in the set of values.
float: The data type float is used in Java to represent any real number between -
3.4E+38 and 3.4E+38. The memory allocated for the float data type is 4 bytes.
double: The data type double is used in Java to represent any real number between -
1.7E+308 and 1.7E+308. The memory allocated for the double data type is 8 bytes.
Other than the set of values, there is one more difference between the data types float and
double. The maximum number of significant digits—that is, the number of decimal places—
in float values is 6 or 7. The maximum number of significant digits in values belonging to the
double type is typically 15. The maximum number of significant digits is called the
precision. Sometimes float values are called single precision, and values of type double are
called double precision.
Arithmetic Operators
One of the most important features of a computer is its ability to calculate. You can use the
standard arithmetic operators to manipulate integral and floating-point data types. Java has
five arithmetic operators:
+ (addition),
- (subtraction or negation),
* (multiplication),
/ (division),
% (mod, (modulus or remainder))
Example
public class ArithmeticOperators {
public static void main(String[] args) {
[Link]("2 + 5 = " + (2 + 5));
[Link]("13 + 89 = " + (13 + 89));
[Link]("34 - 20 = " + (34 - 20));
[Link]("45 - 90 = " + (45 - 90));
[Link]("2 * 7 = " + (2 * 7));
[Link]("5 / 2 = " + (5 / 2));
[Link]("14 / 7 = " + (14 / 7));
[Link]("34 % 5 = " + (34 % 5));
[Link]("4 % 6 = " + (4 % 6));
}
}
Allocating Memory
To allocate memory, we use Java’s declaration statements. The syntax to declare a named
constant is:
static final dataType IDENTIFIER = value;
In Java, static and final are reserved words. The reserved word final specifies that the value
stored in the identifier is fixed and cannot be changed.
Consider the following Java statements:
final double CENTIMETERS_PER_INCH = 2.54;
final int NO_OF_STUDENTS = 20;
final char BLANK = ' ';
final double PAY_RATE = 15.75;
The first statement tells the compiler to allocate enough memory to store a value of type
double, call this memory space CENTIMETERS_PER_INCH, and store the value 2.54 in it.
Throughout a program that uses this statement, whenever the conversion formula is needed,
the memory space CENTIMETERS_PER_INCH can be accessed. The other statements have
similar meanings.
Certain data must be modifiable during program execution. For example, after each test, a
student’s average test score may change; the number of tests also changes. Similarly, after
each pay increase, an employee’s salary changes. This type of data must be stored in memory
cells whose contents can be modified during program execution. In Java, memory cells
whose contents can be modified during program execution are called variables.
dataType identifier1, identifier2, ..., identifierN;
Consider the following statements:
double amountDue;
int counter;
char ch;
int num1, num2;
The first statement tells the compiler to allocate enough memory to store a value of type
double and call it amountDue. Statements 2 and 3 have similar conventions. The fourth
statement tells the compiler to allocate two different memory spaces (each large enough to
store a value of the type int), name the first memory space num1, and name the second
memory space num2.
ASSIGNMENT STATEMENT
The assignment statement takes the following form:
variable = expression;
In an assignment statement, the value of the expression should match the data type of the
variable. The expression on the right side is evaluated, and its value is assigned to the
variable (and thus to a memory location) on the left side. A variable is said to be initialized
the first time a value is placed in the variable.
In Java, = (the equal sign) is called the assignment operator.
Suppose you have the following variable declarations:
int num1;
int num2;
double sale;
char first;
String str;
Now consider the following assignment statements:
num1 = 4;
num2 = 4 * 5 - 11;
sale = 0.02 * 1000;
first = 'D';
str = "It is a sunny day.";
For each of these statements, the computer first evaluates the expression on the right and then
stores that value in a memory location named by the identifier on the left. The first statement
stores the value 4 in num1, the second statement stores 9 in num2, the third statement stores
20.00 in sale, and the fourth statement stores the character 'D' in first. The fifth statement
assigns the string "It is a sunny day." to the variable str.
Increment and Decrement Operators
Now you know how to declare a variable and enter data into a variable.
Suppose count is an int variable. The statement:
count = count + 1;
increments the value of count by 1. To execute this assignment statement, the computer first
evaluates the expression on the right, which is count + 1. It then assigns this value to the
variable on the left, which is [Link] expedite the execution of such statements, Java
provides the increment operator, ++, which increases the value of a variable by 1, and the
decrement operator, --, which decreases the value of a variable by 1. Increment and
decrement operators each have two forms: pre and post. The syntax of the increment operator
is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: --variable
Post-decrement: variable--
Because increment and decrement operators are built into Java, the value of a variable is
quickly incremented or decremented without having to use the form of an assignment
statement.
What is the difference between the pre and post forms of these operators? The difference
becomes apparent when the variable using these operators is employed in an expression.
Suppose that x is a variable of type int. If ++x is used in an expression, first the value of x is
incremented by 1, and then the new value of x is used to evaluate the expression. On the other
hand, if x++ is used in an expression, first the current value of x is used in the expression, and
then the value of x is incremented by 1. The following example clarifies the difference
between the pre- and post-increment operators.
Suppose that x and y are int variables. Consider the following statements:
x = 5;
y = ++x;
The first statement assigns the value 5 to x. To evaluate the second statement, which uses the
pre-increment operator, first the value of x is incremented to 6, and then this value, 6, is
assigned to y. After the second statement executes, both x and y have the value 6.
Now consider the following statements:
x = 5;
y = x++;
As before, the first statement assigns 5 to x. In the second statement, the post-increment
operator is applied to x. To execute the second statement, first the value of x, which is 5, is
used to evaluate the expression, and then the value of x is incremented to 6. Finally, the value
of the expression, which is 5, is stored in y. After the second statement executes, the value of
x is 6, and the value of y is 5.
INPUT & OUTPUT
Output Statement
In Java, output on the standard output device is accomplished by using the standard output
object [Link]. The object [Link] has access to two methods, print and println, to
output a string on the standard output device.
The syntax to use the object [Link] and the methods print and println is:
[Link](expression);
[Link](expression);
[Link]();
These are output statements. The expression is evaluated, and its value is printed at the
current insertion point on the output device. After outputting the value of expression, the
method print leaves the insertion point after the last character of the value of expression,
while the method println positions the insertion point at the beginning of the next line.
Moreover, the statement:
[Link]();
only positions the insertion point at the beginning of the next line. In this statement, notice
the empty parentheses after println. They are still needed even though there is no expression
between them.
Input Statement
Reading data using the scanner class
To put data into variables from the standard input device, Java provides the class Scanner.
Using this class, first we create an input stream object and associate it with the standard input
device. The following statement accomplishes this:
static Scanner console = new Scanner([Link]);
This statement creates the input stream object console and associates it with the standard
input device. (Note that Scanner is a predefined Java class and the preceding statement
creates console to be an object of this class.) The object console reads the next input as
follows:
a. If the next input token can be interpreted as an integer, then the expression:
[Link]()
retrieves that integer; that is, the value of this expression is that integer.
b. If the next input token can be interpreted as a floating-point number, then the expression:
[Link]()
retrieves that floating-point number; that is, the value of this expression is that floating-point
number. (Note that an integer can be treated as a floating-point number with 0 decimal part.)
c. The expression:
[Link]()
retrieves the next input token as a string; that is, the value of this expression is the next input
string. (Note that if the next input token is a number, this expression interprets that number as
a string.)
d. The expression:
[Link]()
retrieves the next input as a string until the end of the line; that is, the value of this expression
is the next input line. (Note that this expression also reads the newline character, but the
newline character is not stored as part of the string.)
Example
import [Link].*;
public class ScannerTest {
static Scanner console = new Scanner([Link]);
public static void main(String[] args) {
int feet;
int inches;
[Link]("Enter two integers separated by spaces.");
feet = [Link]();
inches = [Link]();
[Link]("feet = " + feet);
[Link]("inches = " + inches);
}
}
Execute the program
Class Work:
Write Java statements that accomplish the following.
a. Declare int variables x and y.
b. Initialize an int variable x to 10 and a char variable ch to 'B'.
c. Update the value of an int variable x by adding 5 to it.
d. Declare and initialize a double variable payRate to 12.50.
e. Copy the value of an int variable firstNum into an int variable tempNum.
f. Swap the contents of the int variables x and y. (Declare additional variables, if
necessary.)
g. Suppose x and y are double variables. Output the contents of x, y, and the expression
x + 12 / y – 18.
h. Declare a char variable grade and set the value of grade to 'A'.
i. Declare int variables to store four integers.
j. Copy the value of a double variable z to the nearest integer into an int variable x
PROGRAM CONTROL FLOW-SEQUENCE STRUCTURE
A computer can process a program in one of three ways:
• In sequence
• By making a selection or a choice, which is also called a branch
• By repetition, executing a statement over and over using a structure called a loop
Relational Operators
An expression that has a value of either true or false is called a logical (boolean) expression.
The values true and false are called logical (boolean) values. In Java, a condition is
represented by a logical (boolean) expression; conditions are either true or false. Logical
(boolean) expression: An expression that has a value of either true or false. Suppose i and j
are integers. Consider the expression:
i>j
This is a logical expression. It will have the value true if the value of i is greater than the
value of j; otherwise, it will have the value false. The symbol > is called a relational operator
because the value of i > j is true only when the relationship ‘‘greater than’’ holds for i relative
to j.
Relational operator: An operator that allows you to make comparisons in a program. Java
includes six relational operators that enable you to make comparisons.
PROGRAMMING EXERCISES
i. Write Java statements that declare the following variables: num1, num2, and newNum
of type int; name of type String; hoursWorked and wages of type double.
ii. Write Java statements that prompt the user to input two integers and store the first
number into num1 and the second number into num2.
iii. Write a Java statement(s) that outputs the value of num1 and num2, indicating which
is num1 and which is num2. For example, if num1 is 8 and num2 is 5, then the output
is: The value of num1 = 8 and the value of num2 = 5.
iv. Write a program that prompts the user to input a decimal number and outputs the
number rounded to the nearest integer.
v. Write a program that prompts the user to input the length and width of a rectangle and
then prints the rectangle’s area and perimeter.
vi. Write a program that prompts the user to enter five test scores and then prints the
average test score