DCS105 Programming
DCS105 Programming
1. Identify the problem: the first step toward solving a problem is to identify the
problem, in a classroom situation; most problems have been identified for you and
given to you in the form of written assignments or problems out of a book. However
when you are doing a problem solving outside the classroom, you need to make sure
you identify the problem before you star solving it. If you don’t know what the
problem is, you cannot solve it.
2. Understand the problem: You must understand what is involved in the problem
before you can continue toward the solution. This includes understanding the
knowledge base of the person or machine for whom you are solving the problem. If
you are setting up a solution for a person, then you must know what that person
knows. A different set of instructions might have to used depending on this
knowledge base. For example, you would use a more detailed set of instructions to
tell someone how to find a restaurant in your city if he has a limited knowledge of
the city than if he knows it well. When you are working with a computer, its
knowledge base is the limited instructions the computer can understand in the
particular language or application you are using to solve the problem. Knowing the
knowledge base is very important since you cannot use any instructions outside this
base. You also must know your knowledge base. You cannot solve a problem if you
do not know the subject. For example, to solve a problem involving calculus, you
must know calculus; to solve a problem involving accounting, you must know
accounting. You must be able to communicate with your client and be able to
understand what is involved in solving the problem.
3. Identify alternative ways to solve the problem : this list should be as complete
as possible. You might want to contact/talk to other people to find other solutions
than those you have identified. Alternative solutions must be acceptable ones. You
could go from Kaduna to Lagos by road, but this would probably not an acceptable
solution to your travel needs.
Page 1 of 57
4. Select the best way to solve the problem from the list of alternative
solutions: here, you need to identify and evaluate the pros and cons of each
possible solution before selecting the best one. In order to do this, you need to select
criteria for the evaluation. These criteria will serve as the guidelines for evaluating
each solution.
5. List instructions that enable you to solve the problem using the selected
solution: these numbered, step-by-step instructions must fall within the knowledge
base set up in step 2. No instructions can be used unless the individual or the
machine can understand it. This can be very limiting, especially when working with
computers.
6. Evaluate the solution: to evaluate or test the solution means to check its result
to see if it is correct, and to see if it satisfies the needs of the person(s) with the
problem. If the result is either incorrect or unsatisfactory, then the problem solver
must start the process again.
The problem solver can use the six steps for both algorithmic and heuristic solutions.
However, in step 6, evaluating the solution, the correctness and appropriateness of heuristic
solutions are far less certain. It’s easy to tell if your completed checkbook balance is correct
and satisfactory, but it’s hard to tell if you have bought the best stock. With heuristic
solution, the problem solver will often need to follow the six steps more than once, carefully
evaluating each possible solution before deciding which is best. Furthermore, this same
solution may not be correct and satisfactory at another time, so the problem solver may
have to re-evaluate and resolve the same problem later. The stock that did well in January
may do poor in June.
Computers are built to deal with algorithmic solutions, which are often time consuming for
humans. People are better than computers at developing heuristic solution. Solving a
Page 2 of 57
complicated calculus problem or alphabetizing 10,000 names is an easy task for computers,
but the problem of how to throw a ball or how to speak English is not. The difficulty lies in
the programming. How can problems such as how to throw a ball or speak English be solved
in a set of steps that the computer can understand?
The field of computers that deals with heuristic types of problems is called artificial
intelligence. Artificial intelligence enables a computer to do things like build its own
knowledge bank and speak in a human language. As a result, the computer’s problem
solving abilities are similar to those of human being. Artificial intelligence is an expanding
computer field.
Until computers can be built to think like humans, people will process most heuristic
solutions and computers will process many algorithmic solutions. Therefore, this course will
deal only with algorithmic solutions. Heuristic problem solving can help determine
alternative solutions. However, for computer use, they must be transformed into an
algorithmic format.
The problem-solving process is not easy. It takes practice and time to perfect, but in the long
run the process to be of great benefit.
When solving problems on the computer, one of the most difficult tasks for the problem
solver is writing the instructions. Take the task of deciding which number is the largest from
a group of three numbers. Almost anyone can immediately tell which is the largest, but
many cannot explain the steps they followed to arrive at it. Most people will say, “I can’t
explain how I know, I just know it!” This explanation is not good enough for the computer.
The computer is a tool that will perform only tasks that the user can explain.
Has a specific system of communication that the programmers and users must learn. This
system demands that no step in the solution to a program is left unstated and that all steps
be in the proper order. You must assume the computer knows nothing except what you tell
it, and think of it as an ignorant but efficient aid to problem solving.
What is a Computer?
A computer is an electronic device that accepts, stores and processes data under the control
of stored program and produce information. It includes both hardware and software. In
general, hardware comprises the visible, physical elements of the computer examples are:
mouse, keyboard, Central Processing Unit (CPU), Memory and software provides the
invisible instructions that control the hardware and make it perform specific task. Writing
Page 3 of 57
instructions for computers to perform a task is called computer programming. Knowing
computer hardware is not essential to your learning a programming language, but it does
help you understand better the effect of the program instructions. In this section we will
introduce computer hardware components and their functions.
Memory
This rapid-access, relatively low-capacity “warehouse” section retains information that has
been entered through the input unit, making it immediately available for processing when
needed. The memory unit also retains processed information until it can be placed on
output unit. Information in the memory unit is volatile – it is typically lost when the
computer’s power is off. The memory unit is often called memory or primary memory.
A program and its data must be brought to memory before they can be executed.
A byte is the minimum storage unit. A small number such as 4 can be stored in a single byte.
To store a number that cannot be fit into a single byte, the computer uses several adjacent
bytes. No two data items can share or split the same byte.
A memory byte is never empty, but its initial content may be meaningless to your program.
The current content of a memory byte is lost whenever new information is places in it.
Every byte has a unique address. The address is used to locate the byte for storing and
retrieving data. Since byte can be accessed in any order, the memory is also referred to as
random access memory (RAM). Today’s personal computers usually have at least 1 gigabyte
(1GB), and terabyte (TB). A kilobyte is 210 – 1024 bytes.
Storage Devices
Storage device is where the computer used to store programs and data permanently for
future use. These programs and data are moved to memory when the CPU actually need
them, because memory is faster than storage devices. The four main types of storage
Page 4 of 57
devices are: Disk drives e.g., hard disk, CDs (compact disk) and DVDs (digital versatile disk /
digital video disk), tape drives and USB flash drives
The Keyboard
A computer keyboard resembles a typewriter keyboard with extra keys added for certain
special functions.
Function keys are located at the top of the keyboard and are numbered with prefix F. Their
used depends on the software.
A modifier key (e.g. Shift, Alt, Ctrl) that modifies the normal action of another key when the
two are pressed in combination.
Numeric keypad this is located on the right hand corner of the keyboard, is a separate keys
for quick input of numbers.
Arrow keys, located between the m ain keypad and the numeric keypad, they are used to
move the cursor up, down, left, and right.
The Insert, Delete, Page up and Page Down keys are located above the arrow keys, are used
in word processing for performing insert, delete, page up and page down.
The Mouse
A mouse is a pointing device. It is used to move an electronic pointer called a cursor around
the screen or to click on an the screen to trigger it to respond.
The Monitor
The monitor displays information (text and graphics). The screen resolution and dot pitch
determine the quality of the display.
The screen resolution specifies the number of pixel per square inch. Pixels (short for “picture
elements”) are tiny dots that form an image on the screen. A common for a 17inch screen is
1024 pixels wide and 768 pixels high. The resolution can be change manually. The higher the
resolution, the sharper and clearer the image is.
The dot pitch is the amount of space between pixels in millimetres. The smaller the dot
pitch, the better the display.
Communication Devices
Computers can be networked through communication devices, such as the dialup modem
(modulator/demodulator), DSL (digital subscriber line), cable modem, network interface
card, and wireless.
Page 5 of 57
Programs
Computer programs, known as software, are instructions to the computer, telling it what to
do. Computers do not understand human languages, so you need to use computer
languages in computer programs. Programming is the creation of a program that is
executable by a computer and performs the required tasks.
1. Machine languages
2. Assembly languages
3. High-level languages
Machine language: Any computer can directly understand only its own machine language.
This is the computer’s “natural language,” defined by its hardware design. It is in the form
of binary code, so in telling the machine what to do, you have to enter binary code.
Programming in machine language is a tedious process. Moreover, the programs are highly
difficult to read and modify. For example, to add two numbers, you might have to write an
instruction in binary like this:
1101101010011010
Assembly languages were developed to make programming easy. However, since the
computer cannot understand assembly language, a program called an assembler is used to
convert assembly-language programs into machine code
High level language: this allow you to write instructions that look almost like everyday
English and contain commonly used mathematical notations. For example , the high-level
language statement that computes the area of a circle with radius 5:
Page 6 of 57
Area = 5 * 5 * 3.1415;
Among the more than one hundred high-level languages, the following are well known:
Welcome to Java- a powerful computer programming language that is fun for novices to
learn and appropriate foe experienced programmers to use in building substantial
enterprise information systems. This hand book is an effective learning tool for each of these
audiences.
We use Ms Word processors to write documents, Web browsers to explore the Internet,
email to programs to send email. These are all examples of software that runs on
computers. Software is developed using programming languages. There are many
programming languages so why Java? The answer is that Java enables users to develop and
deploy applications on the Internet for servers, desktop computers, and small hand-held
devices.
A program written in high-level language is called a source program or source code. Since a
computer cannot understand a source program, a program called a compiler is used to
translate it into a machine-language program. The machine-language program is then linked
with other supporting library code to form an executable files.
Operating system
The operating system (OS) is the most important program that runs on a computer, which
manages and controls a computer’s activities. The popular operating systems are Microsoft
Windows, Mac OS, and Linux. Application programs, such as a Web browser or a word
processor, cannot run without an operating system. The interrelationship of hardware,
operating system, application software, and the user is shown in figure below:
Page 7 of 57
User
Application Programs
Operating System
Hardware
Fig. 2 The operating system is the software that controls and manages the system
The application program interface (API) contains predefined classes and interface for
developing Java programs. The java language is stable, but the API is still expanding. At the
sun java website ([Link]), you can view and download the latest version of the Java
API.
Java SE, EE, and ME Java is a full-fledge and powerful language that can be used in many
ways. It comes in three editions: Java Standard Edition (Java SE), Java Enterprise Edition
(Java EE) and Java Micro Edition (Java ME). Java SE can be used to develop client-side
standalone applications or applets. Java EE can be used to develop server-side applications
such as Java servlets and Javaserver Pages. Java ME can be used to develop applications for
mobile devices, such as cell phones. This course uses Java SE to introduce Java
Programming.
Page 8 of 57
Java programs normally go through five phases—edit, compile, load, verify and execute. We
discuss these phases in the context of the JDK
Phase-1: Edit
When we write a Java program on any editor & save it, then it is stored in a disk with an
extension of .java. This .java file is platform-independent therefore a Java program (.java
file) written in one operating system can be used in any operating system.
Page 9 of 57
Phase-2: Compile
The compiler’s work is to convert the high-level language to bytecodes then store it with an
extension of .class. To compile a program called [Link], we use the “javac”
command.
javac [Link]
After developing the Java program, we compile it through the “javac” command. The
compiler checks for syntax errors, and if everything is correct then it starts translating
the .java file else it gives a compile-time error. After compilation of the .java file, the .java
file is translated to .class file. similar to the .java file, the .class file is also platform-
independent.
Phase-3: Load
The class loader reads the code, compiles it, and puts those bytecodes from the disk to
primary memory. From the class loader, the codes are stored in primary memory.
When we execute the “java” command to run the Java application then the .class file (which
contains bytecode) is loaded into the RAM, and this task is done by the class loader. The
class loader also loads any of the .class files provided by the Java that your program uses.
Phase-4: Verify
This step confirms that the bytecodes are valid and make sure that they do not risk the Java security
restrictions.
Phase-5: Execute
In this step, the JVM (Java Virtual Machine) reads the byte and translates it to the language that the
machine can understand that is machine language then executes the program and stores it in values
in primary memory. This machine language will be different for different operating systems.
The line numbers are displayed for reference purposes but are not part of the program. So
don’t type line numbers in your program.
Line 2 define a class. Every Java program must have at least one class. Each class has a name.
By convention, class names start with an uppercase letter. In this example, the class name is
Welcome.
Page 10 of 57
Line 4 define the main method. In order to run a class , the class must contain a method
named main. The program is executed from the main method.
A method is a construct that contains statements. The main method in this program
contains the [Link] statement. This statement prints a message "Welcome to
Java Programming!" to the console (line 4). Every statement in Java ends with a semicolon
(;) known as the statement terminator.
Reserved words or keywords, have a specific meaning to the compiler and cannot be used
for other purposes in the program. For example, when the compiler sees the word class, it
understands that the word after class is the name for the class. Other reserved words in this
program are public, static, and void.
Line 1 and line 6 are comments that documents what the program is and how it is
constructed. Comments help programmers to communicate and understand the program.
They are not programming statements and thus are ignored by the compiler. In Java,
comments are preceded by two slashes (//) on a line, called a line comment, or enclosed
between /* and */ on one or several lines, called a block comment. When the compiler
sees //, it ignores all text after // on the line. When it sees /*, it scans for the next */ and
ignores any text between /* and */. Here are examples of comments:
A pair of braces in a program forms a block that groups the program’s components. In Java,
each block begins with an opening brace ({) and ends with a closing brace (}). Each class has
a block that groups the data and methods of the class. Every method has a method block
that groups the statements in the method. Blocks can be nested, meaning that one block
can be placed within another.
Note: The source file must end with extension .java and must have exactly the same name
as the public class name. For example, the file for the source code above should be named
[Link]. since the public class name is Welcome.
A Java compiler translates a Java source file into a Java bytecode file. The following
command compiles [Link]
Page 11 of 57
To prepare to compile the program, open a command window and change to the directory
where the program is stored. Many operating systems use the command cd to change
directories. For example,
c:\Users\ABU0151\Desktop\Java>
javac [Link]
If the program contains no syntax error, the preceding command creates a new file called
[Link] containing the platform-independent Java bytecodes that represent our
application. To execute the program, type
[Link]("Welcome to ");
[Link]("Java Programming!");
Page 12 of 57
Display one line of text in the command window. The first statement uses [Link]’s
method print to display a string. Unlike println, after displaying its argument print does not
position the output cursor at the beginning of the next line in the command window- the
next character the program displays will appear immediately after the last character that
print displays. Thus, line 10 positions the first character in its argument (the letter “J”)
immediately after the last character that line 9 displays (the space character before the
string’s closing double-quote character).each print or println statement resumes displaying
characters from where the last print or println statement stopped displaying characters.
Normally, the characters in a string are displayed exactly as they appear in the double
quotes. Note, however, that the two characters \ and n do not appear on the screen. The
backslash (\) is called an escape character. It indicates to [Link]’s print and println
methods that a “special character” is to be output.
Page 13 of 57
There are total of 8 escape sequence in java.
\t: It is used to insert a tab in the text.
The method call specifies two arguments, when a method requires multiple arguments, the
arguments are placed in a comma-separated list.
Line 9-10 represent only one statement. Java allows large statements to be split over many
line.
Format specifiers begin with a percent sign (%) and are followed by a character that
represents the data type. For example, the format specifier %s is a placeholder for a string.
Page 14 of 57
%e exponential floating-point number.
%f floating-point number.
%s String.
This program uses a Java class JOptionPane (line 9). Java’s predefined classes are grouped
into packages. JOptionPane is in the [Link] package. JOptionPane is imported to the
program using the import statement in line 4 so that the compiler can locate the class
without the full name [Link]. JOptionPane.
The first argument can always be null. Null is a Java keyword, the second argument is a
string for the text to be displayed.
There are several ways to use the showMessageDialog method. For the time being, you
need to know only two ways. One is to use a statement, as shown in the example below.
[Link](null,x);
Page 15 of 57
Where x is a string for the text to be displayed.
String y = “Welcome”;
[Link](null,x,y,[Link]
ATION_MESSAGE);
Where x is a string for the text to be displayed, and y is a string for the title of the message
box. The fourth argument causes the icon (i) to be displayed in the message box.
Writing a program involves designing algorithms and translating algorithms into code. An
algorithms describes how a problem is solved in terms of the actions to be executed and the
order of their execution. Algorithms can be described in natural languages or in pseudocode
(i.e natural language mixed with programming code). The algorithm for computing area of a
circle is as follows:
Page 16 of 57
Assume that we have chosen ComputeArea as the class name. The outline of the program
would look like this:
Declare radius and area as double-precision floating point numbers. The program can be
expanded as follows:
double radius;
double area;
The first step is to read in radius. Reading a number from the keyboard is not a simple
matter. For the time being, let us assign a fixed value to radius in the program.
The second step is to compute area by assigning the result of the expression radius * radius
* 3.14159 to area.
In the final step, display area on the console by using the [Link] method.
Page 17 of 57
Variables such as radius and area correspond to memory locations. Every variable has a
name, a type, a size and a value. Line 3 declares that radius can store a double value. The
value is not define until you assign a value. Line 7 assigns 20 into radius. Similarly, line4
declares variable area, and line 10 assigns a value into area.
The plus (+) sign has two meanings: one for addition and the other for concatenating strings.
It combines two strings if two of the operands are strings. If one of the operand is a
nonstring, the nonstring value is converted into a string and concatenated with the other
string.
Caution: a string constant cannot be cross lines in the source code. Thus the following
statement would result in a compile error:
[Link](“Introduction to Java
To fix the error, break the string into separate substrings, and use the concatenation
operator (+) to combine them:
The syntax new Scanner ([Link]) creates an object of the Scanner type. The syntax
Scanner input declares that input is a variable whose type is Scanner. The whole line Scanner
input = new Scanner ([Link]); creates a Scanner object and assigns its reference to the
variable input.
Page 18 of 57
Method Description
For now we will see how to read a number that includes a decimal point by invoking the
nextDouble() method. Other methods will be covered when they are used. We will rewrite
the previous example to prompt the user to enter a radius.
after the user enters a number and presses the Enter key, the number is read and assigned
to radius.
Page 19 of 57
Average of two numbers
Identifiers
Identifiers are a sequence of characters to identify something in a program. They are names
given to a class, variable, package, method, or interface and allow the programmer to refer
to the specific item from any place in the program. In our last example ComputeAverage,
main,input, num1, num2, average are the names of things that appear in the program, such
names are called identifiers. All identifiers must obey the following rules:
ComputeAverage, main,input, num1, num2, average are legal identifiers, whereas 2A, and
d+4 are not because they do not follow the rules. The Java compiler detects illegal identifiers
and reports syntax errors.
Note: Since Java is case sensitive, area, Area, and AREA are all different identifiers.
Variables
Variables are used to store values to be used later in a program. They are called variables
because their values can be changed. In our previous example we have seen variables like:
radius, area, num1, num2, average etc of double-precision, floating point type. You can
assign any numerical value to these variables and their values can be reassigned. For
example, you can write the code
Page 20 of 57
Radius = 2.5;
Radius = 3.0;
Variables Declaration
The variable declaration tells the compiler to allocate appropriate memory space for the
variable based on its data type. The syntax for declaring a variable is:
datatype variableName;
int count;
double radius;
float interestRate;
If variables are of the same data type, they can be declared together, as follows:
Examples:
int i, j, k;
You can also declare a variable and initialize it in one step. For example:
int count = 1;
You can also use shorthand form to declare and initialize variables of the same type
together. For example,
Page 21 of 57
int i = 1, j=2;
Variable = expression;
For example
int x = 1;
x = 5 * (3 / 2) +3 *2;
x=x+1
Named constant
This represents permanent data that never changes. In our ComputeArea program, π is a
constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can
declare a constant for π. Here is the syntax for declaring a constant:
A constant must be declared and initialixed in the same statement. The word final is a Java
keyword for declaring a constant.
Page 22 of 57
Numeric Data Types and Operations
The compiler allocates memory space for each variables or constant according to its data
type. Java provides eight primitives data types for numeric values, characters, and Boolean
values. This section introduces numeric data types.
Java uses four types for integers: byte, short, int, and long. Choose the type that is appropriate
for your variables. It also uses two types for floating-point numbers: float and double. The
double type is twice as big as float.
Numeric Operators
The operators for numeric data types include the standard arithmetic operators as shown
below:
Shorthand operators
Very often the current value of a variable is used, modified, and then reassigned back to the
same variable. Example:
i = i+8;
Java allows you to combine assignment and addition operators using a shorthand operator.
For example, the preceding statement can be written as:
i += 8;
Shorthand Operators
Operator Name Example Equivalent
+= Addition assignment i += 8 i = i + 8
-+ Subtraction assignment i -= 8 i = i - 8
*= Multiplication i *= 8 i = i * 8
assignment
Page 23 of 57
/= Division assignment i /= 8 i = i /8
%= Remainder assignment i %= 8 i = i % 8
The syntax is the target type in parenthesis, followed by the variable’s name or the value to
be cast. For example:
[Link]((int)1.7);
displays 1. When double value is cast into an int value, the fractional part is truncated.
[Link]((double)1/2);
displays 0.5, because 1 is cast to 1.0 first, then divided by 2. However, the statement
[Link](1/2);
displays 0, because 1 and 2 are both integers and the resulting value should also be an
integer.
//0041 is assigned to ch
Note: all numeric operators can be applied to char operands. A char operand is
automatically cast into a number if the other operand is a number or a character. If the
Page 24 of 57
other operand is a string, the character is concatenated with the string. For example, the
following statements
Two Strings can be concatenated. The plus sign (+) is the concatenated operator, if two of
the operands are a String. If one of the operands is nonstring, the nonstring value is
converted into a sting and concatenated with the other string. Here are some examples:
The shorthand += operator can also be used for string concatenation. For example:
String Methods
Page 25 of 57
specified index
Page 26 of 57
string to an array of chars
Page 27 of 57
the given replacement
Page 28 of 57
Boolean Data Type
Java has eight primitive data types and boolean is one of them. Such data type has only two
possible values i.e. a Java boolean variable can be either “true” or “false”. This is the same
value that is returned by all the rational operators (a<b or b>c…. etc).
A boolean data type is also used in conditional checks using if statements or loops. Given
below is the syntax of boolean Java.
Syntax:
Page 29 of 57
Relational / Comparison Operators
Operators Description Example
You can also compare characters. Comparing characters is the same as comparing their
Unicodes. For example ‘a’ is larger than ‘A’ because the Unicode of ‘a’ is larger than the
Unicode of ‘A’.
If Statements
The previous example displays a message such as “6 + 2 = 7 is: false” if you wish the message
to be “6 + 2 = 7 is: incorrect” you have to use a selection statement to carry out this minor
change.
One-Way if statements
A one-way if statement executes an action if and only if the condition is true. The syntax for
a one-way if statement is shown below:
If (Boolean-expression) {
Statement(s);
Page 30 of 57
}
If the Boolean-expression evaluates to true, the statements in the block are executed. As an
example, see the following code:
If (radius >=0) {
The block braces ({}) can be omitted if they enclose a single statement. For example, the
following statements are equivalent:
if (i > 0) {
If (i > 0)
[Link](“i
is positive”); [Link](“i is
positive”);
}
Example below is a program that prompts a user to enter an integer. If the number is a
multiple of 7, print number is a multiple of 7. If the number is divisible by 2, print number is
even.
Page 31 of 57
Two-Way if Statements
A one-way if statement takes action if the specified condition is true. If the condition is false,
nothing is done. But what if you want to take alternative actions when the condition is false?
You can use a two-way if statement. The actions that a two-way if statement specifies differ
based on whether the action is true or false.
If (Boolean-expression) {
Statement(s)-for-the-true-case;
Else {
Statement(s)-for-the-false-case;
If the Boolean-expression evaluates to true, the statement(s) for the true case are executed;
otherwise, the statement(s) for the false case are executed. For example, consider the
following code:
If (radius >=0) {
Page 32 of 57
double area = radius*radius*PI;
else {
[Link](“Nagative input”);
If the radius >= 0 is true, area is computed and displayed; if it is false, the message
“Nagative input” is printed.
Here is another example of using the if ... else statement. The example check whether a
number is even or odd, as follows
If (num % 2 ==0)
[Link](num + “ is even.”);
else
[Link](num + “ is odd.”);
Nested if Statements
Nested if refers to an if statement within an if statement. When we write an inner if
condition within an outer if condition, then it is referred to as a nested if statement in java.
No limit to the depth of the nesting. For example, the following is a nested if statement:
If (i > k) {
If (j > k)
else
Page 33 of 57
The nested if statement can be used to implement multiple alternatives. The statement
below, for instance, assigns a letter grade to the variable grade according to the score, with
multiple alternatives.
if (score >= 90.0) if (score >= 90.0)
grade = ‘A’; grade = ‘A’;
else else if (score >= 80.0;
if (score >= 80.0) Equivalent grade = ‘B’;
grade = ‘B’; else if (score >= 70.0)
else grade = ‘C’;
if (score >= 70.0) if (score >= 60.0)
grade = ‘C’; grade = ‘D’;
if (score >= 60.0) else
grade = ‘D’; grade = ‘F’;
else
grade = ‘F’;
The first condition (score >=90.0) is tested. If it is true, the grade becomes ‘A’. If it is false,
the second condition (score >=80.0) is tested. If the second condition is true, the grade
becomes ‘B’. If that condition is false, the third condition and the rest of the conditions
continue to be tested until a condition is met or all of the conditions prove to be false. If all
of the conditions are false, the grade becomes ‘F’. Note that a condition is tested only when
all of the conditions that come before it are false.
Suppose you want to write a program that randomly generates two single-digit
integers,num1 and num2, with num1 >= num2 and display to the student a question such as
“What is 9 – 2?” after the student enters the answer, the program displays a message
indicating whether it is correct. The program may work as follows
Page 34 of 57
Check the student’s answer and display whether the answer is correct.
Logical Operators
A logical operator is a symbol or word used to connect two or more relational/ comparison
expressions such that the value of the compound expression produced depends only on that
of the original expressions and on the meaning of the operator. Common logical operators
include AND (&&) , OR (||), exclusive OR (^) and NOT (!).
A year is a leaf year if it is divisible by 4 but not by 100 or if it is divisible by 400, the program
below accept from the user a year and determine if the year is a leaf year or not.
Page 35 of 57
Switch Statements
Instead of writing many if..else statements, you can use the switch statement. The switch
statement selects one of many code blocks to be executed. A switch works with the byte,
short, char, and int primitive data types. It also works with enumerated types, and String.
case value1:
// code block
break;
case values2:
// code block
break;
case valuesN:
// code block
break;
default:
// code block
Page 36 of 57
The switch statement observes the following rules:
Conditional Expressions
You might want to assign a value that is restricted by certain conditions. For example, the
following statement assigns 1 to y if x is greater than 0, and -1 to y if x is greater than or
equal 0.
if (x > 0)
y = 1;
else
y = -1;
Alternatively, as in this example, you can use a conditional expression to achieve the same
result.
Page 37 of 57
The syntax of conditional expression is as shown below:
Precedence Operator
(type)(Casting)
! (Not)
==, != (Equality)
^ (Exclusive Or)
&& (AND)
|| (OR)
Loops
Supposed that you need to print a string (e.g., “Welcome to Java!”) a hundred times. It
would be tedious to have to write the following statement a hundred times:
100׿
Java provides a powerful construct called a loop that controls how many times an operation
or a sequence of operations is performed in succession.
Loops are constructs that control repeated executions of a block of statements. The concept
of looping is fundamental to programming. Java provides three types of loop statements:
while loops, do-while loops, and for loops.
Page 38 of 57
The while Loop
The syntax for the while loop is as follows:
while (loop-continuation-condition) {
//Loop body
Statement(s);
Using while loop the above problem can be solve easily as follows:
int count = 0;
[Link](“Welcome to Java!”);
Count++;
In this example, you know exactly how many times (99 – 0 +1) the loop body needs to be
executed. We use 99 because 100 is not inclusive.
int sum = 0, i = 1;
i++;
If i < 10 is true, the program adds i to sum. Variable i is initially set to 1, then incremented to
2, 3, and up to 10, when i is 10, i < 10 is false, the loop exits. So the sum is 1 + 2 + 3 + .. + 9 =
45.
int sum = 0, i = 1;
Page 39 of 57
}
The loop is infinite; because i is always 1 and i < 10 will always be true.
Below is program GuessNumberOneTime that prompts user to guess a number, the next
example is the same program using loop.
The while statement checks the condition before executing the statement(s), if the condition
is false, the loop terminate.
Page 40 of 57
The do-while loop
The do-while loop is a variation of the while loop. Its syntax is given below:
do {
//Loop body;
Statement(s);
} while (loop-continuation-condition);
The do-while loop executes the loop body first, then checks the loop-continuation-condition
to determine whether to continue or terminate the loop.
The loop body is executed first. Then the loop-continuation-condition is evaluated. If the
evaluation is true, the loop body is executed again; if it is false, the do-while loop
terminates. The difference between a while loop and do-while loop is the order in which the
loop-continuation-condition is evaluated and the loop body is executed.
The program below reads and calculates the sum of an unspecified number of integers. The
input 0 (sentinel value) signifies the end of the input.
Page 41 of 57
action-after-each-iteration) {
//Loop body;
Statement(s);
The for loop statement starts with the keyword for, followed by a pair of parentheses
enclosing the control structure of the loop. The control structure is followed by the loop
body enclosed inside braces. The initial-action, loop-continuation-
condition, and action-after-each-iteration are separated by semicolons.
A for loop generally uses a variable to control how many times the loop body is executed
and when the loop terminates. This variable is referred to as a control variable. For example,
the following for loop prints Welcome to Java! A hundred times.
int i;
[Link](“Welcome to Java!”);
If there is only one statement in the loop as in the above example, the braces can be
omitted.
Nested loops
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop
is repeated; the inner loops are reentered, and started anew.
Page 42 of 57
Finding Greatest Common Divisor
The greatest common divisor of two integers 4 and 2 is 2. The greatest common divisor of
two integers 16 and 24 is 8. How do you find the greatest common divisor? Let the two input
integers be n1 and n2. You know that number 1 is a common divisor, but it may not be the
greatest common divisor. So, you can check whether k (for k = 2, 3, 4, and so on) is a
common divisor for n1 and n2, until k is greater than n1 or n2. Store the common divisor in a
variable named gcd. Initially, gcd is 1. Whenever a new common divisor is found, it becomes
the gcd. When you have checked all the possible common divisors from 2 up to n2 or n2, the
value in variable gcd is the greatest common divisor. The idea can be translated into
following program:
Page 43 of 57
Keywords break and continue
The break and continue statements are the jump statements that are used to skip some
statements inside the loop or terminate the loop immediately without checking the test
expression. These statements can be used inside any loops such as for, while, do-while loop.
Break: The break statement in java is used to terminate from the loop immediately. When a
break statement is encountered inside a loop, the loop iteration stops there, and control
returns from the loop immediately to the first statement after the loop. Basically, break
statements are used in situations when we are not sure about the actual number of iteration
for the loop, or we want to terminate the loop based on some condition.
Syntax :
break;
To exit a loop.
Used as a “civilized” form of goto.
Terminate a sequence in a switch statement.
Using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When we use break inside the
nested loops, it will only break out of the innermost loop.
Example:
The continue statement in Java is used to skip the current iteration of a loop. We can use
continue statement inside any types of loops such as for, while, and do-while loop. Basically
Page 44 of 57
continue statements are used in the situations when we want to continue the loop but do
not want the remaining statement after the continue statement.
Syntax:
continue;
The program GuessNumber can also be written using a break statement, as shown below:
Page 45 of 57
Methods
Introduction
Suppose that you need to find the sum of integers from 1 to 10,from 20 to 30 and from 35
to 45, respectively, you may write the code as follows:
int sum = 0;
sum +=i;
int sum = 0;
sum +=i;
int sum = 0;
sum +=i;
The above code is very similar, except that the starting and ending integers are different.
Wouldn’t it be nice defining a method. The method is for creating reusable code.
Page 46 of 57
The syntax for defining a method is as follows:
The first line is the method header which consist of modifier, return-type, method-name,
parameter-list.
A method may return a value. The return-type is the data type of the value the method
returns. Some methods perform desired operations without returning a value. In the above
case, the return-type is the keyword int, and for main method the return-type is void as well
as in [Link], [Link],println and [Link]. If a method
returns a value, it is called a value-returning method, otherwise it is a void method.
The variables defined in the method header are known as formal parameters or simply
parameters. A parameter is like a placeholder. When a method is invoked, you pass a value
Page 47 of 57
to the parameters. This value is referred to as an actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a method. The
method name and the parameter list together constitute the method signature. Parameters
are optional; that is a method may contain no parameters. For example, the method
[Link]() method has no parameters.
The method body contains a collection of statements that define what the method does.
The method body of the max method uses an if statement to determine which number is
larger and return the value of that number.
Calling a Method
To use a method, you have to call or invoke it. There are two ways to call a method,
depending on whether the method returns a value or not.
If the method returns a value, a call to the method is usually treated as a value. For
example,
calls max(3,4) and assigns the result of the method to the variable larger. Another example
of a call that is treated as value is:
[Link](Max(3,5));
If the method returns void, a call to the method must be a statement. For example,
the method println returns void. The following call is a statement:
[Link](“Welcome to Java!”);
When a program calls a method, program control is transferred to the called method. A
called method returns control to the caller when its return statement is executed or when
its method ending closing brace is reached.
Page 48 of 57
This program contains the main and max methods. The main method is just like any other
method except that it is invoked by the JVM.
The main method’s header is always the same. Like the one in this example, it includes the
modifiers public and static, return value type void, method name main, and a parameter of
the String[] type. String indicates that the parameter is an array of String.
The statements in main may invoke other methods that are defined in the class that
contains the main method or in other classes. In this example, the main method invokes
max(i,j), which is defined in the same class with main method.
When the max method is invoked, variable i’s value 6 is passed to num1, and variable j’s
value is passed to num2in the max method. The flow of control is transfers to the max
method. The max method is executed. When the return statement in the max method is
executed, the max method returns the control to its caller (in this case the caller is the main
method).
Page 49 of 57
Passing Parameters by Values
When you invoke a method with a parameter, the value of the argument is passed to the
parameter. This is referred to as pass-by-value. If the argument is a variable rather than a
literal value, the value of the variable is passed to the parameter. The variable is not
affected, regardless of the changes made to the parameter inside the method.
Page 50 of 57
The program above shows that: the values of num1 and num2 have not been swapped even
after calling the swap method. The values of the arguments num1 and num2 are passed to
n1 and n2, but n1 and n2 have their own memory locations independent of num1 and
num2. Therefore, changes in n1 and n2 do not affect the contents of num1 and num2.
Modularizing Code
Methods can be used to reduce redundant code and enable code reuse. Methods can also
be used to modularize code and improve the quality of the program.
Page 51 of 57
Advantages of modularizing code
It isolates the program for computing a problem from the rest of the code in the
main method. Thus, the logic becomes clear and the program is easier to read.
The errors on computing the problem are confined in the method, which narrows the
scope of debugging.
The method can be reused by other programs.
The scope of a local variable starts from its declaration and continues to the end of the block
that contains the variable. A local variable must be declared and assigned a value before it
can be used
A parameter is a local variable. The scope of a method parameter covers the entire method.
A variable declared in the initial-action part of a for-loop header has its scope in the entire
loop. But a variable declared inside a for-loop body has its scope limited in the loop body
from its declaration to the end of the block that contains the variable.
Page 52 of 57
Arrays
Supposed , for instance, that you need to read 100 numbers, compute their average, and
find out how many numbers are above the average. Your program first read the numbers
and compute their average, then compare each number with the average to determine
whether it is above the average. In order to do this task, the numbers must all be stored in
variables. You have to declare 100 variables and repeatedly write almost identical code 100
times. Writing a program this way is impractical. So, how do we solve this type of problem?
Java and most other high-level language provide a data structure, the array, which stores a
fixed-size sequential collection of elements of the same type. In the present case, you can
store all 100 numbers into an array and access them through a single array variable. The
solution may look like this:
Page 53 of 57
An array is collection of variables of the same type, the same name but different index.
Instead of declaring individuals variables such as num0, num1, ..., and mu,99, you declare
one array variable such as numbers and use numbers[0], numbers[1]..., numbers[99] to
represent individual variables.
elementType[] arrayRefVar;
The elemetType can be any data type, and all elements in the array will have the same name
and data type but different index. For example, the following code declares a variable myList
that references an array of double elements.
double[] myList;
Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array variable
does not allocate ant space in memory for the array. It creates only storage location for the
reference to an array. If a variable does not contain a reference to an array, the value of the
variable is null. You cannot assign elements to an array unless it has already been created.
After an array variable is declared, you can create an array by using the new operator with
the following syntax:
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement as shown below:
or
or
Page 54 of 57
This statement declares an array variable, myList, creates an array of ten elements of double
type, and assigns its reference to myList. To assign values to the elements, use the syntax:
arrayRefVar[index] = value;
myLis[0] = 4.6;
myLis[1] = 14.6;
myLis[2] = 56.5;
myLis[3] = 34.6;
myLis[4] = 23.67;
myLis[5] = 174.566;
myLis[6] = 94.788;
myLis[7] = 12.36;
myLis[8] = 3.54;
myLis[9] = 45.365;
myLis[0] = 34.16;
When an array is created, its elements are assigned the default value of 0 for the numeric
primitive data types, ‘/u0000’ for char types, and false for Boolean types.
Each element in the array is represented using the following syntax, known as indexed
variable:
arrayRefVar[index];
For example, myList[9] represents the last element in the array myList.
After an array is created, an indexed variable can be used in the same way as a regular
variable. For example, the following code add the values in myList[0] and myList[1] to
myList[2].
Page 55 of 57
myList[2] = myList[0] + myList[2];
myList[i] = i;
Array Initializers
Array initializer is the short hand notation which combines in one statement declaring an
array, creating an array, and initializing an array, using the following syntax:
or
For example:
or
This statement declares, creates, and initializes the array myList with four elements.
Processing Arrays
When processing array elements, you will often use for loop- for two reasons:
All of the elements in the array are of the same type. They are evenly processed in
the same fashion repeatedly using a loop.
Since the size of the array is known, it is natural to use a for loop.
Page 56 of 57
myList[i] = [Link]();
2. Initialising arrays with random values between 0.0 to 100.0, but less than 100.
myList[i] = [Link]()*100;
[Link](myList[i]);
double total = 0;
Total +=myList[i];
For-each Loops
Java supports a convenient for loop, known as a for-each loop or enhanced for loop, which
enables you to traverse the array sequentially without using an index variable. For example:
[Link](u);
You can read the code as “for each element u in myList do the following.” Note that the
variable u must be declared the same type as the elements in myList.
Page 57 of 57