2.
2 Writing a Simple Program
Ѻ Writing a program involves designing a strategy for solving the problem and then using a programming
language to implement that strategy.
Ѻ An algorithm describes how a problem is solved by listing the actions (steps) that need to be taken and
the order of their execution.
Ѻ I.e. The algorithm for calculating the area of a circle can be described as follows:
1. Read in the circle’s radius.
2. Compute the area using the following formula; (area = radius × radius × 3.14159 )
3. Display the result.
Ѻ Every Java program begins with the keyword class is followed by the class name; i.e. (ComputeArea).
Ѻ Every Java program must have a main method where program execution begins.
Ѻ I.e. The program needs to read the radius entered by the user from the keyboard. This raises two
important issues:
1. Reading the radius.
2. Storing the radius in the program.
Ѻ In order to store the radius, the program needs to declare a symbol called a variable. A variable
represents a value stored in the computer’s memory and must take a descriptive-names.
Ѻ To let the compiler know what radius and area are, specify their data types. The kind of data stored in
a variable, whether integer, real number, or something else; this is known as declaring variables.
Ѻ The first step is to prompt the user to designate the circle’s radius.
Ѻ The second step is to compute area by assigning the result of the formula.
1|Page
Ѻ The final step, the program will display the value of area on the console by using the [Link]
method.
Ѻ Every variable has a name, a type, a size, and a value.
Ѻ Tracing programs are helpful for understanding how programs work, and they are useful tools for
finding errors in programs.
Ѻ The plus sign (+) is called a string concatenation operator; It combines two strings into one. If a string
is combined with a number, the number is converted into a string and concatenated with the other
string.
2.3 Reading Input from the Console
2.3.1 Accept Console Input
Ѻ You can use the Scanner class for console input.
Ѻ Java uses [Link] to refer to the standard output device and [Link] to the standard input device.
Ѻ To perform Console output, you simply use the println method to display a primitive value or a string to
the console. Console input is not directly supported in Java, but you can use the Scanner class to create
an object to read input from [Link].
Ѻ The whole line Scanner input = new Scanner ([Link]); creates a Scanner object and assigns its
reference to the variable input.
2|Page
Ѻ You can invoke the nextDouble() method to read a double value.
Ѻ Prompt is a string that directs the user to enter an input.
Ѻ The print; does not advance to the next line when completed.
Ѻ The println; moves to the beginning of the next line after displaying the string.
Ѻ There are two types of import statements: specific import and wildcard import.
o Specific_import; specifies a single class in the import statement.
o Wildcard_import; imports all the classes in a package by using the asterisk as the wildcard.
2.3.2 Display Console’s Output
Ѻ In Java; we use [Link] (); or [Link] (); to be display messages on the Screen.
2.4 Identifiers
Ѻ Identifiers are the names that identify the elements such as classes, methods, and variables in a
program.
Ѻ All identifiers must obey the following rules:
1. An identifier is a sequence of characters that consists of letters, digits, underscores (_), and
dollar signs ($).
2. An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start
with a digit.
3. An identifier cannot be a reserved word.
4. An identifier cannot be true, false, or null.
Ѻ Since Java is case sensitive, area, Area, and AREA are all different identifiers.
2.5 Variables
3|Page
Ѻ A variable is a location in the computer’s memory where a value can be stored for use by a program.
Ѻ All variables must be declared with a name and a data type before they can be used in a program.
Ѻ To use a variable, you declare it by telling the compiler its name as well as what type of data it can
store. The variable declaration tells the compiler to allocate appropriate memory space for the variable
based on its data type.
Ѻ If variables are of the same type, they can be declared together with separated by commas (,).
Ѻ Variables often have initial values. You can declare a variable and initialize it in one step.
Ѻ Every variable has a scope. The scope of a variable is the part of the program where the variable can
be referenced.
2.6 Assignment statement and Assignment expression
Ѻ After a variable is declared, you can assign a value to it by using an assignment statement.
Ѻ In Java, the equal sign (=) is used as the assignment operator.
Ѻ An expression represents a computation involving values, variables, and operators that, taking them
together, evaluates to a value.
2.7 Named constants
Ѻ A named constant is an identifier that represents a permanent value that never changes.
Ѻ A constant must be declared and initialized in the same statement. The word final is a Java keyword for
declaring a constant.
Ѻ There are three benefits of using constants:
4|Page
1. You don’t have to repeatedly type the same value if it is used multiple times.
2. If you have to change the constant value, you need to change it only in a single location.
3. A descriptive name for a constant makes the program easy to read.
2.8 Naming conventions
Ѻ The conventions for naming variables, methods, and classes are followed;
Use lowercase for variables and methods. If a name consists of several words, concatenate
them into one, making the first word lowercase and capitalizing the first letter of each
subsequent word.
Capitalize the first letter of each word in a class name.
Capitalize every letter in a constant, and use underscores between words.
2.9 Numeric Data Types and Operations
Ѻ Java has six numeric types for integers and floating-point numbers with operators +, -, *, /, and %.
2.9.1 Numeric Types
Ѻ Java has two categories of data:
1. Primitive Data Type: such as Boolean, char, int, short, byte, long, float, and double.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.
5|Page
Ѻ The double is known as double precision and float as single precision. Normally, you should use the
double type, because it is more accurate than the float type.
2.9.2 Reading Numbers from the Keyboard
Ѻ You can use the followed methods to read a numbers of all Data types.
Ѻ If you enter a value with an incorrect range or format, a runtime error would occur.
2.9.3 Numeric Operators
Ѻ The operands are the values operated by an operator.
Ѻ The types of Operation’s result;
1. Integer; if all operands are integer.
2. Float; if at least one operand is float.
3. Double; if at least one operand is double.
6|Page
Ѻ A unary operator has only one operand; a binary operator has two operands.
2.9.4 Exponent Operations
Ѻ The [Link] (a, b) method can be used to compute ab. The pow method is defined in the Math class in
the Java API.
2.10 Numeric Literals
Ѻ A literal is a constant value that appears directly in a program.
2.10.1 Integer literals
Ѻ An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compile
error will occur if the literal is too large for the variable to hold.
Ѻ An integer literal is assumed to be of the int type; to denote an integer literal of the long type, append
the letter L to it.
Ѻ To denote a binary integer literal, use a leading 0b or 0B (zero B), to denote an octal integer literal, use
a leading 0 (zero), and to denote a hexadecimal integer literal, use a leading 0x or 0X (zero X).
2.10.2 Floating-Point Literals
7|Page
Ѻ Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as
a double type value.
Ѻ You can make a number a float by appending the letter f or F, and you can make a number a double by
appending the letter d or D. For example, you can use 100.2f or 100.2F for a float number, and 100.2d or
100.2D for a double number.
2.10.3 Scientific Notation
Ѻ Floating-point literals can be written in scientific notation in the form of a * 10 b. For example, the
scientific notation for 123.456 is 1.23456 * 102 and for 0.0123456 is 1.23456 * 10-2. A special syntax is
used to write scientific notation numbers. For example, 1.23456 * 102 is written as 1.23456E+2 and
1.23456 * 10-2 as 1.23456E-2.
2.11 Evaluating Expressions and Operator Precedence
Ѻ Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression
and its corresponding arithmetic expression is the same.
Ѻ Operator precedence rule;
1. Multiplication, division, and remainder operators are applied first. If an expression contains
several multiplication, division, and remainder operators, they are applied from left to right.
2. Addition and subtraction operators are applied last. If an expression contains several addition
and subtraction operators, they are applied from left to right.
2.12 Displaying the Current Time
Ѻ You can invoke [Link]() to return the current time in GMT (Greenwich Mean Time) in
the format hour: minute: second.
Ѻ You can use this method to obtain the current time, and then compute the current second, minute, and
hour as follows.
8|Page
1. Obtain the total milliseconds since midnight, January 1, 1970, in totalMilliseconds by invoking
[Link] () (e.g., 1203183068328 milliseconds).
2. Obtain the total seconds totalSeconds by dividing totalMilliseconds by 1000 (e.g., 1203183068328
milliseconds / 1000 = 1203183068 seconds).
3. Compute the current second from totalSeconds % 60 (e.g., 1203183068 seconds % 60 = 8, which
is the current second).
4. Obtain the totalMinutes by dividing totalSeconds by 60 (e.g., 1203183068 seconds / 60 = 20053051
minutes).
5. Compute the current minute from totalMinutes % 60 (e.g., 20053051 minutes % 60 = 31, which is
the current minute).
6. Obtain totalHours by dividing totalMinutes by 60 (e.g., 20053051 minutes / 60 = 334217 hours).
7. Compute the current hour from totalHours % 24 (e.g., 334217 hours % 24 = 17, which is the current
hour).
2.13 Augmented Assignment Operators
9|Page
Ѻ The operators +, -, *, /, and % can be combined with the assignment operator to form augmented
operators.
Ѻ Very often the current value of a variable is used, modified, and then reassigned back to the same
variable. Java allows you to combine assignment and addition operators using an augmented operator.
2.14 Increment and Decrement Operators
Ѻ The increment operator (++) and decrement operator (––) are for incrementing and decrementing a
variable by 1.
Ѻ Additional examples to illustrate the differences between the prefix form of (++) or (--) and the postfix
form of (++) or (--).
10 | P a g e
2.15 Numeric Type Conversions
Ѻ Casting is an operation that converts a value of one data type into a value of another data type.
Ѻ Casting a type with a small range to a type with a larger range is known as widening a type.
Ѻ Casting a type with a large range to a type with a smaller range is known as narrowing a type.
Ѻ Java will automatically widen a type, but you must narrow a type explicitly.
Ѻ The syntax for casting a type is to specify the target type in parentheses, followed by the variable’s
name or the value to be cast. I.e. the following statement [Link] ((int) 1.7); displays 1.
Ѻ A compile error will occur if casting is not used in situations of this kind. However, be careful when
using casting, as loss of information might lead to inaccurate results.
Ѻ Casting does not change the variable being cast. For example, d is not changed after casting in the
following code:
2.16 Software Development Process
Ѻ The software development life cycle is a multistage process that includes requirements specification,
analysis, design, implementation, testing, deployment, and maintenance.
11 | P a g e
Ѻ Requirements specification is a formal process that seeks to understand the problem that the software
will address and to document in details what the software system needs to do.
Ѻ System analysis seeks to analyze the data flow and to identify the system’s input and output.
Ѻ System design is to design a process for obtaining the output from the input. This phase involves the
use of many levels of abstraction to break down the problem into manageable components and design
strategies for implementing each component.
Ѻ Implementation involves translating the system design into programs. Separate programs are written
for each component and then integrated to work together.
Ѻ Testing ensures that the code meets the requirements specification and weeds out bugs.
Ѻ Deployment makes the software available for use. Depending on the type of software, it may be installed
on each user’s machine or installed on a server accessible on the Internet.
Ѻ Maintenance is concerned with updating and improving the product.
2.18 Common Errors and Pitfalls
Ѻ Common elementary programming errors often involve undeclared variables, uninitialized variables,
integer overflow, unintended integer division, and round-off errors.
Ѻ A variable must be declared with a type and assigned a value before using it. A common error is not
declaring a variable or initializing a variable.
Ѻ If a variable is declared, but not used in the program, it might be a potential programming error.
Ѻ Numbers are stored with a limited numbers of digits. When a variable is assigned a value that is too
large (in size) to be stored, it causes overflow.
12 | P a g e
Ѻ Java does not report warnings or errors on overflow, so be careful when working with numbers close
to the maximum or minimum range of a given type.
Ѻ A round-off error is the difference between the calculated approximation of a number and its exact
mathematical value.
Ѻ When two operands are integers, the result of the operation is an integer. The fractional part is
truncated. To force two integers to perform a floating-point division, make one of the integers into a
floating-point number.
Ѻ Common Pitfall: Redundant Input Objects;
New programmers often write the code to create multiple input objects for each input. For
example, the following code reads an integer and a double value.
13 | P a g e