0% found this document useful (0 votes)
45 views38 pages

CSC 211

This document provides an overview and introduction to the Java programming language. It discusses that Java was originally developed by Sun Microsystems in 1995 and the latest release is Java SE 9. It then lists some key features of Java, including that it is object-oriented, platform independent, simple, secure, portable, robust, multithreaded, and high performance. The document also provides instructions on setting up the Java environment and describes a basic "Hello World" Java program to get started learning the language.

Uploaded by

destiny gowon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views38 pages

CSC 211

This document provides an overview and introduction to the Java programming language. It discusses that Java was originally developed by Sun Microsystems in 1995 and the latest release is Java SE 9. It then lists some key features of Java, including that it is object-oriented, platform independent, simple, secure, portable, robust, multithreaded, and high performance. The document also provides instructions on setting up the Java environment and describes a basic "Hello World" Java program to get started learning the language.

Uploaded by

destiny gowon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

CSC211: COMPUTER PROGRAMMING I

USING JAVA
LECTURE NOTE (PART 1)

OVERVIEW OF JAVA PROGRAMMING LANGUAGE


Java programming language was originally developed by Sun Microsystems which was initiated by
James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0
[JSE]).
The latest release of the Java Standard Edition is Java SE 9. With the advancement of Java and its
widespread popularity, multiple configurations were built to suit various types of platforms. For
example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed
to be Write Once, Run Anywhere.
Java is:
 Object Oriented: In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
 Platform Independent: Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is interpreted by the Virtual
Machine (JVM) on whichever platform it is being run on.
 Simple: Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master.
 Secure: With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral: Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors, with
the presence of Java runtime system.
 Portable: Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable.
 Robust: Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
 Multithreaded: With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.
 Interpreted: Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and light-weight process.
 High Performance: With the use of Just-In-Time compilers, Java enables high
performance.

Environment Setup
This section guides you on how to download and set up Java on your machine. Following are the
steps to set up the environment.

Diploma Programme – Department of Computer Science, Federal University Lafia


Java SE is freely available from the
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html. You
can download a version based on your operating system. Follow the instructions to download Java
and run the .exe to install Java on your machine.
Once you installed Java on your machine, you will need to set environment variables to point to
correct installation directories:

Setting Up the Path for Windows


Assuming you have installed Java in c:\Program Files\java\jdk directory:
 Right-click on 'My Computer' and select 'Properties'.
 Click the 'Environment variables' button under the 'Advanced' tab.
 On the system variable section, alter the 'Path' variable so that it also contains the path to
the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then
change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program
Files\java\jdk\bin'.

To write your Java programs, you will need a text editor. There are even more sophisticated IDEs
available. But for now, you can consider one of the following:
 Notepad: On Windows machine, you can use any simple text editor like Notepad
(Recommended), TextPad.
 Netbeans: A Java IDE that is open-source and free, which can be downloaded
from http://www.netbeans.org/index.html.
 Eclipse: A Java IDE developed by the eclipse open-source community and can be
downloaded from http://www.eclipse.org

Syntax, Semantics, and Pragmatics of Java


A program is a sequence of instructions that a computer can execute to perform some
task. A simple enough idea, but for the computer to make any use of the instructions, they
must be written in a form that the computer can use. This means that programs have to be
written in programming languages. Programming languages differ from ordinary human
languages in being completely unambiguous and very strict about what is and is not allowed
in a program. The rules that determine what is allowed are called the syntax of the language. The
rules that determine what is allowed are called the syntax of the language. Syntax rules specify the
basic vocabulary of the language and how programs can be constructed using things like loops,
branches, and subroutines. A syntactically correct program is one that can be successfully compiled
or interpreted; programs that have syntax errors will be rejected (hopefully with a useful error
message that will help you fix the problem).
So, to be a successful programmer, you have to develop a detailed knowledge of the syntax of the
programming language that you are using. However, syntax is only part of the story. It’s not enough
to write a program that will run—you want a program that will run and produce the correct result!
That is, the meaning of the program has to be right. The meaning of a program is referred to as its
semantics. More correctly, the semantics of a programming language is the set of rules that
determine the meaning of a program written in that language. A semantically correct program is one
that does what you want it to.

Diploma Programme – Department of Computer Science, Federal University Lafia


Furthermore, a program can be syntactically and semantically correct but still be a pretty bad
program. Using the language correctly is not the same as using it well. For example, a good program
has “style.” It is written in a way that will make it easy for people to read and to understand. It
follows conventions that will be familiar to other programmers. And it has an overall design that will
make sense to human readers. The computer is completely oblivious to such things, but to a human
reader, they are paramount. These aspects of programming are sometimes referred to as
pragmatics. (I will often use the more common term style.)
When I introduce a new language feature, I will explain the syntax, the semantics, and some of the
pragmatics of that feature. You should memorize the syntax; that’s the easy part. Then you should
get a feeling for the semantics by following the examples given, making sure that you understand
how they work, and, ideally, writing short programs of your own to test your understanding. And
you should try to appreciate and absorb the pragmatics—this means learning how to use the
language feature well, with style that will earn you the admiration of other programmers.
Of course, even when you’ve become familiar with all the individual features of the language, that
doesn’t make you a programmer. You still have to learn how to construct complex programs to solve
particular problems. For that, you’ll need both experience and taste.

Basic Java Application


We begin our exploration of Java with the problem that has become traditional for such beginnings:
to write a program that displays the message “Hello World!” This might seem like a trivial problem,
but getting a computer to do this is really a big first step in learning a new programming language
(especially if it’s your first programming language). It means that you understand the basic process
of:

1. getting the program text into the computer,


2. compiling the program, and
3. running the compiled program.

The first time through, each of these steps will probably take you a few tries to get right. I won’t go
into the details here of how you do each of these steps; it depends on the particular computer and
Java programming environment that you are using. But in general, you will type the program using
some sort of text editor and save the program in a file. Then, you will use some command to try to
compile the file. You’ll either get a message that the program contains syntax errors, or you’ll get a
compiled version of the program. In the case of Java, the program is compiled into Java bytecode,
not into machine language. Finally, you can run the compiled program by giving some appropriate
command. For Java, you will actually use an interpreter to execute the Java bytecode. Your
programming environment might automate some of the steps for you—for example, the
compilation step is often done automatically—but you can be sure that the same three steps are
being done in the background.
Here is a Java program to display the message “Hello World!”. Don’t expect to understand what’s
going on here just yet; some of it you won’t really understand until a few chapters from now:

/* A program to display the message


* "Hello World!" on standard output.
*/

Diploma Programme – Department of Computer Science, Federal University Lafia


public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
} // end of class HelloWorld

The command that actually displays the message is:

System.out.println("Hello World!");

This command is an example of a subroutine call statement. It uses a “built-in subroutine” named
System.out.println to do the actual work. Recall that a subroutine consists of the instructions
for performing some task, chunked together and given a name. That name can be used to “call” the
subroutine whenever that task needs to be performed. A built-in subroutine is one that is already
defined as part of the language and therefore automatically available for use in any program. When
you run this program, the message “Hello World!” (without the quotes) will be displayed on
standard output. Unfortunately, I can’t say exactly what that means! Java is meant to run on many
different platforms, and standard output will mean different things on different platforms. However,
you can expect the message to show up in some convenient or inconvenient place. (If you use a
command-line interface, like that in Oracle’s Java Development Kit, you type in a command to tell
the computer to run the program. The computer will type the output from the program, Hello
World!, on the next line. In an integrated development environment such as Eclipse, the output
might appear somewhere in one of the environment’s windows.)
You must be curious about all the other stuff in the above program. Part of it consists of comments.
Comments in a program are entirely ignored by the computer; they are there for human readers
only. This doesn’t mean that they are unimportant. Programs are meant to be read by people as well
as by computers, and without comments, a program can be very difficult to understand. Java has
two types of comments. The first type begins with // and extends to the end of a line. There is a
comment of this form on the last line of the above program. The computer ignores the // and
everything that follows it on the same line. The second type of comment starts with /* and ends
with */, and it can extend over more than one line. The first three lines of the program are an
example of this second type of comment.
Everything else in the program is required by the rules of Java syntax. All programming in Java is
done inside “classes.” The first line in the above program (not counting the comment) says that this
is a class named HelloWorld. “HelloWorld,” the name of the class, also serves as the name of the
program. Not every class is a program. In order to define a program, a class must include a
subroutine named main, with a definition that takes the form:

public static void main(String[] args) {


<statements>
}

When you tell the Java interpreter to run the program, the interpreter calls this main() subroutine,
and the statements that it contains are executed. These statements make up the script that tells the
computer exactly what to do when the program is executed. The main() routine can call other

Diploma Programme – Department of Computer Science, Federal University Lafia


subroutines that are defined in the same class or even in other classes, but it is the main() routine
that determines how and in what order the other subroutines are used.
The word “public” in the first line of main() means that this routine can be called from outside the
program. This is essential because the main() routine is called by the Java interpreter, which is
something external to the program itself. The remainder of the first line of the routine is harder to
explain at the moment; for now, just think of it as part of the required syntax.
The definition of the subroutine—that is, the instructions that say what it does—consists of the
sequence of “statements” enclosed between braces, { and }. Here, I’ve used statements as
a placeholder for the actual statements that make up the program. Throughout this textbook,
I will always use a similar format: anything that you see in <this style of text> (italic in angle
brackets) is a placeholder that describes something you need to type when you write an actual
program.
As noted above, a subroutine can’t exist by itself. It has to be part of a “class”. A program is defined
by a public class that takes the form:

public class <program-name>{


<optional-variable-declarations-and-subroutines>
public static void main(String[] args) {
<statements>
}
<optional-variable-declarations-and-subroutines>
}
The name on the first line is the name of the program, as well as the name of the class.
(Remember, again, that <program-name> is a placeholder for the actual name!) If the name of the
class is HelloWorld, then the class must be saved in a file called HelloWorld.java. When this file is
compiled, another file named HelloWorld.class will be produced. This class file, HelloWorld.class,
contains the translation of the program into Java bytecode, which can be executed by a Java
interpreter. HelloWorld.java is called the source code for the program. To execute the program, you
only need the compiled class file, not the source code.
The layout of the program on the page, such as the use of blank lines and indentation, is not part of
the syntax or semantics of the language. The computer doesn’t care about layout—you could run
the entire program together on one line as far as it is concerned. However, layout is important to
human readers, and there are certain style guidelines for layout that are followed by most
programmers.
Also note that according to the above syntax specification, a program can contain other subroutines
besides main(), as well as things called “variable declarations.

Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps:
 Open notepad and add the code as above.
 Save the file as: HelloWorld.java.
 Open a command prompt window and go to the directory where you saved the class.
Assume it's C:\.
 Type 'javac HelloWorld.java' and press enter to compile your code. If there are no errors in
your code, the command prompt will take you to the next line (Assumption : The path
variable is set).

Diploma Programme – Department of Computer Science, Federal University Lafia


 Now, type ' java HelloWorld ' to run your program.
 You will be able to see ‘Hello World!’ printed on the window.

C:\> javac HelloWorld.java


C:\> java HelloWorld
Hello World!

NAMES AND THINGS


Names are fundamental to programming. In programs, names are used to refer to many different
sorts of things. In order to use those things, a programmer must understand the rules for giving
names to them and the rules for using the names to work with them. That is, the programmer must
understand the syntax and the semantics of names.
According to the syntax rules of Java, the most basic names are identifiers. Identifiers can be used to
name classes, variables, and subroutines. An identifier is a sequence of one or more characters. It
must begin with a letter or underscore and must consist entirely of letters, digits, and underscores.
(“Underscore” refers to the character ‘_’.) For example, here are some legal identifiers:

N n rate x15 quite_a_long_name HelloWorld

No spaces are allowed in identifiers; HelloWorld is a legal identifier, but “Hello World” is not. Upper
case and lower case letters are considered to be different, so that HelloWorld, helloworld,
HELLOWORLD, and hElloWorLD are all distinct names.
Certain words are reserved for special uses in Java, and cannot be used as identifiers. These reserved
words include: class, public, static, if, else, while, and several dozen other words. (Remember that
reserved words are not identifiers, since they can’t be used as names for things.)
Java is actually pretty liberal about what counts as a letter or a digit. Java uses the Unicode character
set, which includes thousands of characters from many different languages and different alphabets,
and many of these characters count as letters or digits. However, I will be sticking to what can be
typed on a regular English keyboard.
The pragmatics of naming includes style guidelines about how to choose names for things. For
example, it is customary for names of classes to begin with upper case letters, while names of
variables and of subroutines begin with lower case letters; you can avoid a lot of confusion by
following this standard convention in your own programs. Most Java programmers do not use
underscores in names, although some do use them at the beginning of the names of certain kinds of
variables. When a name is made up of several words, such as HelloWorld or interestRate, it is
customary to capitalize each word, except possibly the first; this is sometimes referred to as camel
case, since the upper case letters in the middle of a name are supposed to look something like the
humps on a camel’s back.
Finally, I’ll note that in addition to simple identifiers, things in Java can have compound names which
consist of several simple names separated by periods. (Compound names are also called qualified
names.) You’ve already seen an example: System.out.println. The idea here is that things in Java can
contain other things. A compound name is a kind of path to an item through one or more levels of
containment. The name System.out.println indicates that something called “System” contains
something called “out” which in turn contains something called “println”.

Diploma Programme – Department of Computer Science, Federal University Lafia


Variables
Programs manipulate data that are stored in memory. In machine language, data can only be
referred to by giving the numerical address of the location in memory where the data is stored.
In a high-level language such as Java, names are used instead of numbers to refer to data. It is the
job of the computer to keep track of where in memory the data is actually stored; the programmer
only has to remember the name. A name used in this way—to refer to data stored in memory—is
called a variable.
Variables are actually rather subtle. Properly speaking, a variable is not a name for the data itself but
for a location in memory that can hold data. You should think of a variable as a container or box
where you can store data that you will need to use later. The variable refers directly to the box and
only indirectly to the data in the box. Since the data in the box can change, a variable can refer to
different data values at different times during the execution of the program, but it always refers to
the same box. Confusion can arise, especially for beginning programmers, because when a variable is
used in a program in certain ways, it refers to the container, but when it is used in other ways, it
refers to the data in the container.
In Java, the only way to get data into a variable (that is, into the box that the variable names) is with
an assignment statement. An assignment statement takes the form:

<variable> = <expression>;

where <expression> represents anything that refers to or computes a data value. When the
computer comes to an assignment statement in the course of executing a program, it evaluates the
expression and puts the resulting data value into the variable. For example, consider the simple
assignment statement

rate = 0.07;

The <variable> in this assignment statement is rate, and the <expression> is the number 0.07.
The computer executes this assignment statement by putting the number 0.07 in the variable rate,
replacing whatever was there before. Now, consider the following more complicated assignment
statement, which might come later in the same program:

interest = rate * principal;

Here, the value of the expression “rate * principal” is being assigned to the variable interest. In the
expression, the * is a “multiplication operator” that tells the computer to multiply rate times
principal. The names rate and principal are themselves variables, and it is really the values stored in
those variables that are to be multiplied. We see that when a variable is used in an expression, it is
the value stored in the variable that matters; in this case, the variable seems to refer to the data in
the box, rather than to the box itself. When the computer executes this assignment statement, it
takes the value of rate, multiplies it by the value of principal, and stores the answer in the box
referred to by interest. When a variable is used on the left-hand side of an assignment statement, it
refers to the box that is named by the variable.
(Note, by the way, that an assignment statement is a command that is executed by the computer at
a certain time. It is not a statement of fact. For example, suppose a program includes the statement

Diploma Programme – Department of Computer Science, Federal University Lafia


“rate = 0.07;”. If the statement “interest = rate * principal;” is executed later in
the program, can we say that the principal is multiplied by 0.07? No!
The value of rate might have been changed in the meantime by another statement. The meaning of
an assignment statement is completely different from the meaning of an equation in mathematics,
even though both use the symbol “=”.)

Data Types
A variable in Java is designed to hold only one particular type of data; it can legally hold that type of
data and no other. The compiler will consider it to be a syntax error if you try to violate this rule by
assigning a variable of the wrong type to a variable. We say that Java is a strongly typed language
because it enforces this rule.
There are eight so-called primitive types built into Java. The primitive types are named byte, short,
int, long, float, double, char, and boolean. The first four types hold integers (whole numbers such as
17, -38477, and 0). The four integer types are distinguished by the ranges of integers they can hold.
The float and double types hold real numbers (such as 3.6 and -145.99). Again, the two real types
are distinguished by their range and accuracy. A variable of type char holds a single character from
the Unicode character set. And a variable of type boolean holds one of the two logical values true or
false.
Any data value stored in the computer’s memory must be represented as a binary number, that is as
a string of zeros and ones. A single zero or one is called a bit. A string of eight bits is called a byte.
Memory is usually measured in terms of bytes. Not surprisingly, the byte data type refers to a single
byte of memory. A variable of type byte holds a string of eight bits, which can represent any of the
integers between -128 and 127, inclusive. (There are 256 integers in that range; eight bits can
represent 256—two raised to the power eight—different values.) As for the other integer types,

• short corresponds to two bytes (16 bits). Variables of type short have values in the range
-32768 to 32767.
• int corresponds to four bytes (32 bits). Variables of type int have values in the range
-2147483648 to 2147483647.
• long corresponds to eight bytes (64 bits). Variables of type long have values in the range
-9223372036854775808 to 9223372036854775807.

You don’t have to remember these numbers, but they do give you some idea of the size of integers
that you can work with. Usually, for representing integer data you should just stick to the int data
type, which is good enough for most purposes.
The float data type is represented in four bytes of memory, using a standard method for encoding
real numbers. The maximum value for a float is about 10 raised to the power 38.
A float can have about 7 significant digits. (So that 32.3989231134 and 32.3989234399 would both
have to be rounded off to about 32.398923 in order to be stored in a variable of type float.) A
double takes up 8 bytes, can range up to about 10 to the power 308, and has about 15 significant
digits. Ordinarily, you should stick to the double type for real values.
A variable of type char occupies two bytes in memory. The value of a char variable is a single
character such as A, *, x, or a space character. The value can also be a special character such a tab or
a carriage return or one of the many Unicode characters that come from different languages. Values
of type char are closely related to integer values, since a character is actually stored as a 16-bit

Diploma Programme – Department of Computer Science, Federal University Lafia


integer code number. In fact, we will see that chars in Java can actually be used like integers in
certain situations.
It is important to remember that a primitive type value is represented using only a certain, finite
number of bits. So, an int can’t be an arbitrary integer; it can only be an integer in a certain finite
range of values. Similarly, float and double variables can only take on certain values. They are not
true real numbers in the mathematical sense. For example, the mathematical constant π can only be
approximated by a value of type float or double, since it would require an infinite number of decimal
places to represent it exactly. For that matter, simple numbers like 1/3 can only be approximated by
floats and doubles.

Literals
A data value is stored in the computer as a sequence of bits. In the computer’s memory, it doesn’t
look anything like a value written on this page. You need a way to include constant values in the
programs that you write. In a program, you represent constant values as literals.
A literal is something that you can type in a program to represent a value. It is a kind of name
for a constant value. For example, to type a value of type char in a program, you must surround it
with a pair of single quote marks, such as ’A’, ’*’, or ’x’. The character and the quote marks make up
a literal of type char. Without the quotes, A would be an identifier and * would be a multiplication
operator. The quotes are not part of the value and are not stored in the variable; they are just a
convention for naming a particular character constant in a program. If you want to store the
character A in a variable ch of type char, you could do so with the assignment statement

ch = ’A’;

Certain special characters have special literals that use a backslash, \, as an “escape character”.
In particular, a tab is represented as ’\t’, a carriage return as ’\r’, a linefeed as ’\n’, the single quote
character as ’\’’, and the backslash itself as ’\\’. Note that even though you type two characters
between the quotes in ’\t’, the value represented by this literal is a single tab character.
Numeric literals are a little more complicated than you might expect. Of course, there are the
obvious literals such as 317 and 17.42. But there are other possibilities for expressing numbers in a
Java program. First of all, real numbers can be represented in an exponential form such as 1.3e12 or
12.3737e-108. The “e12” and “e-108” represent powers of 10, so that 1.3e12 means 1.3 times 1012
and 12.3737e-108 means 12.3737 times 10−108. This format can be used to express very large and
very small numbers. Any numeric literal that contains a decimal point or exponential is a literal of
type double. To make a literal of type float, you have to append an “F” or “f” to the end of the
number. For example, “1.2F” stands for 1.2 considered as a value of type float. (Occasionally, you
need to know this because the rules of Java say that you can’t assign a value of type double to a
variable of type float, so you might be confronted with a ridiculous-seeming error message if you try
to do something like “x = 1.2;” if x is a variable of type float. You have to say “x = 1.2F;". This is one
reason why I advise sticking to type double for real numbers.)
Even for integer literals, there are some complications. Ordinary integers such as 177777 and -32 are
literals of type byte, short, or int, depending on their size. You can make a literal of type long by
adding “L” as a suffix. For example: 17L or 728476874368L. As another complication, Java allows
binary, octal (base-8), and hexadecimal (base-16) literals. I don’t want to cover number bases in
detail, but in case you run into them in other people’s programs, it’s worth knowing a few things:

Diploma Programme – Department of Computer Science, Federal University Lafia


Octal numbers use only the digits 0 through 7. In Java, a numeric literal that begins with a 0 is
interpreted as an octal number; for example, the octal literal 045 represents the number 37, not the
number 45. Octal numbers are rarely used, but you need to be aware of what happens when you
start a number with a zero. Hexadecimal numbers use 16 digits, the usual digits 0 through 9 and the
letters A, B, C, D, E, and F. Upper case and lower case letters can be used interchangeably in this
context. The letters represent the numbers 10 through 15. In Java, a hexadecimal literal begins with
0x or 0X, as in 0x45 or 0xFF7A. Finally, binary literals start with 0b or 0B and contain only the digits 0
and 1; for example: 0b10110.
As a final complication, numeric literals in Java 7 can include the underscore character (“_”), which
can be used to separate groups of digits. For example, the integer constant for seven billion could be
written 7_000_000_000, which is a good deal easier to decipher than 7000000000.
There is no rule about how many digits have to be in each group. Underscores can be especially
useful in long binary numbers; for example, 0b1010_1100_1011.
I will note that hexadecimal numbers can also be used in character literals to represent arbitrary
Unicode characters. A Unicode literal consists of \u followed by four hexadecimal digits. For
example, the character literal ’\u00E9’ represents the Unicode character that is an “e” with an acute
accent.
For the type boolean, there are precisely two literals: true and false. These literals are typed just as
I’ve written them here, without quotes, but they represent values, not variables.
Boolean values occur most often as the values of conditional expressions. For example,

rate > 0.05

is a boolean-valued expression that evaluates to true if the value of the variable rate is greater than
0.05, and to false if the value of rate is not greater than 0.05. As you’ll see in in the subsequent
chapters, boolean-valued expressions are used extensively in control structures. Of course, boolean
values can also be assigned to variables of type boolean. For example, if test is a variable of type
boolean, then both of the following assignment statements are legal:

test = true;
test = rate > 0.05;

Strings and String Literals


Java has other types in addition to the primitive types, but all the other types represent objects
rather than “primitive” data values. For the most part, we are not concerned with objects for the
time being. However, there is one predefined object type that is very important: the type String.
(String is a type, but not a primitive type; it is in fact the name of a class, and we will return to that
aspect of strings in the next section.)
A value of type String is a sequence of characters. You’ve already seen a string literal: "Hello World!".
The double quotes are part of the literal; they have to be typed in the program. However, they are
not part of the actual String value, which consists of just the characters between the quotes. A string
can contain any number of characters, even zero. A string with no characters is called the empty
string and is represented by the literal "", a pair of double quote marks with nothing between them.
Remember the difference between single quotes and double quotes! Single quotes are used for char

Diploma Programme – Department of Computer Science, Federal University Lafia


literals and double quotes for String literals! There is a big difference between the String "A" and the
char ’A’.
Within a string literal, special characters can be represented using the backslash notation.
Within this context, the double quote is itself a special character. For example, to represent the
string value

I said, "Are you listening!"

with a linefeed at the end, you would have to type the string literal:

"I said, \"Are you listening!\"\n"

You can also use \t, \r, \\, and Unicode sequences such as \u00E9 to represent other special
characters in string literals.

Variables in Programs
A variable can be used in a program only if it has first been declared. A variable declaration
statement is used to declare one or more variables and to give them names. When the computer
executes a variable declaration, it sets aside memory for the variable and associates the variable’s
name with that memory. A simple variable declaration takes the form:

<type-name> <variable-name-or-names>;

The <variable-name-or-names> can be a single variable name or a list of variable names separated
by commas. (We’ll see later that variable declaration statements can actually be somewhat more
complicated than this.) Good programming style is to declare only one variable in a declaration
statement, unless the variables are closely related in some way. For example:

int numberOfStudents;
String name;
double x, y;
boolean isFinished;
char firstInitial, middleInitial, lastInitial;

It is also good style to include a comment with each variable declaration to explain its purpose in the
program, or to give other information that might be useful to a human reader.
For example:

double principal; // Amount of money invested.


double interestRate; // Rate as a decimal, not percentage.

In this chapter, we will only use variables declared inside the main() subroutine of a program.
Variables declared inside a subroutine are called local variables for that subroutine. They exist only
inside the subroutine, while it is running, and are completely inaccessible from outside. Variable
declarations can occur anywhere inside the subroutine, as long as each variable is declared before it
is used in any way. Some people like to declare all the variables at the beginning of the subroutine.

Diploma Programme – Department of Computer Science, Federal University Lafia


Others like to wait to declare a variable until it is needed. My preference: Declare important
variables at the beginning of the subroutine, and use a comment to explain the purpose of each
variable. Declare “utility variables” which are not important to the overall logic of the subroutine at
the point in the subroutine where they are first used. Here is a simple program using some variables
and assignment statements:

/*
* This class implements a simple program that
* will compute the amount of interest that is
* earned on N17,000 invested at an interest
* rate of 0.027 for one year. The interest and
* the value of the investment after one year are
* printed to standard output.
*/
public class Interest {
public static void main(String[] args) {
/* Declare the variables. */
double principal; // The value of the investment.
double rate; // The annual interest rate.
double interest; // Interest earned in one year.
/* Do the computations. */
principal = 17000;
rate = 0.027;
interest = principal * rate; // Compute the interest.
principal = principal + interest;
// Compute value of investment after one year, with interest.
// (Note: The new value replaces the old value of principal.)
/* Output the results. */
System.out.print("The interest earned is ₦");
System.out.println(interest);
System.out.print("The value of the investment after one year
is ₦");
System.out.println(principal);
} // end of main()
} // end of class Interest

This program uses several subroutine call statements to display information to the user of the
program. Two different subroutines are used: System.out.print and
System.out.println.
The difference between these is that System.out.println adds a linefeed after the end of the
information that it displays, while System.out.print does not. Thus, the value of interest,
which is displayed by the subroutine call “System.out.println(interest);”, follows on
the same line as the string displayed by the previous System.out.print statement. Note that
the value to be displayed by System.out.print or System.out.println is provided in
parentheses after the subroutine name. This value is called a parameter to the subroutine. A
parameter provides a subroutine with information it needs to perform its task. In a subroutine call
statement, any parameters are listed in parentheses after the subroutine name. Not all subroutines

Diploma Programme – Department of Computer Science, Federal University Lafia


have parameters. If there are no parameters in a subroutine call statement, the subroutine name
must be followed by an empty pair of parentheses.

INPUT AND OUTPUT (I/O)


Computer programs are only useful if they interact with the rest of the world in some way. This
interaction is referred to as input/output, or I/O. Possible sources and destinations of information
include user, file, or another computer on the network.
In Java, all I/O are based on Streams, which are objects that represent input and output devices.
You have already seen that output can be displayed to the user using the subroutine
System.out.println. This subroutine is part of the predefined object called System.out. The
purpose of this is precisely to display output to the user. There is a corresponding object called
System.in that exists to read data input by the user, but it provides only very primitive input
facilities, and it requires some advanced Java programming skills to use it effectively.
In order to simplify the use of System.in in a program, the Scanner class was introduced as part of
Java 5, however, it still requires some knowledge of object-oriented programming to use the class.
The Scanner class is defined as part of the java.util package. To use it, we have to import the package
using the statement import java.util.Scanner; before the class definition and then
include the following statement at the beginning of our program.
Scanner input = new Scanner (System.in);
This creates a variable named input of type Scanner. We can then use input in our program to access
a variety of subroutine for reading user input. For example, the function input.nextInt() reads
one value of type int from the user and returns it. There are corresponding methods for reading
other types of data. These include:

Input.nextDouble()
Input.nextLong()
Input.nextLine()// for reading entire line of input
Input.nextBoolean()// accepts only true or false as input

As an example, consider the following program:

// Program Convert: This program converts measurements


// in feet and inches into centimetres using the formula
// that 1 inch is equal to 2.54 centimetres.
import java.util.*;
public class Conversion{
static Scanner input = new Scanner(System.in);
static final double CENTIMETERS_PER_INCH = 2.54;
static final int INCHES_PER_FOOT = 12;
public static void main(String[] args){
//declare variables
int feet;
int inches;
int totalInches;
double centimeters;
System.out.print("Enter feet: ");

Diploma Programme – Department of Computer Science, Federal University Lafia


feet = input.nextInt();
System.out.println();
System.out.print("Enter inches: ");
inches = input.nextInt();
System.out.println();
System.out.println("The numbers you entered are " + feet + "
for feet and "+ inches + " for inches.");
totalInches = INCHES_PER_FOOT * feet + inches;
System.out.println();
System.out.println("The total number of inches = "+
totalInches);
centimeters = totalInches * CENTIMETERS_PER_INCH;
System.out.println("The number of centimeters = " +
centimeters);
}
}
Sample Run: (In this sample run, the user input is shaded.)
Enter feet: 15
Enter inches: 7
The numbers you entered are 15 for feet and 7 for inches.
The total number of inches = 187
The number of centimeters = 474.98

OPERATORS
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Other Operators

The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and
variable B holds 20, then:

Operator Description Example

+ Addition - Adds values on either A + B will give 30


side of the operator
- Subtraction - Subtracts right A - B will give -10
hand operand from left hand
operand

Diploma Programme – Department of Computer Science, Federal University Lafia


* Multiplication - Multiplies A * B will give 200
values on either side of the
operator
/ Division - Divides left hand B / A will give 2
operand by right hand operand
% Modulus - Divides left hand B % A will give 0
operand by right hand operand
and returns
Remainder
++ Increment - Increases the value B++ gives 21
of operand by 1
-- Decrement - Decreases the B-- gives 19
value of operand by 1
Example
The following simple example program demonstrates the arithmetic operators. Copy and paste the
following Java program into Test.java file and compile and run this program:

public class Test {


public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}

This would produce the following result:


a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27

Diploma Programme – Department of Computer Science, Federal University Lafia


The Relational Operators
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


Checks if the values of two operands are equal or not, if yes
(A == B) is not
== then condition
true.
becomes true.
Checks if the values of two operands are equal or not, if
!= (A != B) is true.
values are not equal
> Greater than A > B = false
< Less than A < B = true
>= Greater than or equals to A >= B =false
<= Less than or equals to A <= B = true

Example
The following simple example program demonstrates the relational operators.
Copy and paste the program in Test.java file and compile and run this program. :

public class Test {


public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

This would produce the following result:


a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

THE BITWISE OPERATORS:


Java defines several bitwise operators, which can be applied to the integer types, long, int, short,

Diploma Programme – Department of Computer Science, Federal University Lafia


char, and byte.
Bitwise operator works on bits and performs bit‐by‐bit operation. Assume if a = 60; and b = 13; now
in binary
format they will be a = 0011 1100 and b = 0000 1101.
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators. Assume integer variable A holds 60 and variable B
holds 13 then:

Operator Description Example

Binary AND Operator copies a bit to the result if it exists (A & B) will give 12
&
in both operands. which is 0000 1100

Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is


|
operand. 0011 1101

Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49
^
operand but not both. which is 0011 0001

(~A ) will give -61


which is 1100 0011
Binary Ones Complement Operator is unary and has the
~ in 2's complement
effect of 'flipping' bits.
form due to a signed
binary number.

Binary Left Shift Operator. The left operands value is


A << 2 will give 240
<< moved left by the number
which is 1111 0000
of bits specified by the right operand.

Binary Right Shift Operator. The left operands value is


A >> 2 will give 15
>> moved right by the
which is 1111
number of bits specified by the right operand.

Shift right zero fill operator. The left operands value is


moved right by the
A >>>2 will give 15
>>> number of bits specified by the right operand and shifted
which is 0000 1111
values are filled up
with zeros.

Example
The following simple example program demonstrates the bitwise operators. Copy and paste the

Diploma Programme – Department of Computer Science, Federal University Lafia


following Java
program in Test.java file and compile and run this program:

public class Test {


public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 215 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}
}

This would produce the following result:


a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15

THE LOGICAL OPERATORS

The following table lists the logical operators. Assume Boolean variables A holds true and variable B
holds false, then:

Operator Description Example

Called Logical AND operator. If both the operands are non-zero,


&& then the (A && B) is false.
condition becomes true.

Diploma Programme – Department of Computer Science, Federal University Lafia


Called Logical OR Operator. If any of condition becomes true. the
|| (A || B) is true.
two operands are non-zero, then the

Called Logical NOT Operator. Use to reverses the logical state of


! its operand. !(A && B) is true.
If a condition is true then Logical NOT operator will make false.

Example
The following simple example program demonstrates the logical operators. Copy and paste the
following Java program in Test.java file and compile and run this program:

public class Test {


public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
This would produce the following result:

a && b = false
a || b = true
!(a && b) = true

THE ASSIGNMENT OPERATORS


The following assignment operators are supported by Java language:
Operator Description Example

Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand value of A + B into C

Add AND assignment operator, It adds right operand to the left C += A is equivalent
+=
operand and assign the result to left operand to C = C + A

Subtract AND assignment operator, It subtracts right operand C -= A is equivalent


-=
from the left operand and assign the result to left operand to C = C - A

Multiply AND assignment operator, It multiplies right operand


C *= A is equivalent
*= with the left
to C = C * A
operand and assign the result to left operand

Divide AND assignment operator, It divides left operand with C /= A is equivalent


/=
the right operand and assign the result to left operand to C = C / A

Diploma Programme – Department of Computer Science, Federal University Lafia


Modulus AND assignment operator, It takes modulus using two C %= A is equivalent
%=
operands and assign the result to left operand to C = C % A

C <<= 2 is same as C =
<<= Left shift AND assignment operator
C << 2

C >>= 2 is same as
>>= Right shift AND assignment operator
C = C >> 2

C &= 2 is same as C =
&= Bitwise AND assignment operator
C&2

C ^= 2 is same as C
^= bitwise exclusive OR and assignment operator
=C^2

C |= 2 is same as C
|= bitwise inclusive OR and assignment operator
=C|2

Example
The following simple example program demonstrates the assignment operators.

Copy and paste the following Java program in Test.java file and compile and run this program:

public class Test {


public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
c <<= 2 ;
System.out.println("c <<= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );

Diploma Programme – Department of Computer Science, Federal University Lafia


c >>= 2 ;
System.out.println("c >>= a = " + c );
c &= a ;
System.out.println("c &= 2 = " + c );
c ^= a ;
System.out.println("c ^= a = " + c );
c |= a ;
System.out.println("c |= a = " + c );
}
}
This would produce the following result:
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a = 0
c ^= a = 10
c |= a = 10

OTHER OPERATORS
There are few other operators supported by Java Language:

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide which value
should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

EXAMPLE
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );

Diploma Programme – Department of Computer Science, Federal University Lafia


}
}

This would produce the following result:


Value of b is : 30
Value of b is : 20

instanceof Operator

NOTE: This is only for documentation purposes. This operator is used only for object reference
variables. The operator checks whether the object is of a particular type(class type or interface type).
The instanceof operator is wriiten as:

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS‐A check for the
class/interface type on the right side, then the result will be true. Following is the example:
EXAMPLE
String name = = 'James';
boolean result = name instanceof String;
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with
the type on the right. Following is one more example:

EXAMPLE

class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}

This would produce the following result:


true

PRECEDENCE OF JAVA OPERATORS


Operator precedence determines the grouping of terms in an expression. This affects how an

Diploma Programme – Department of Computer Science, Federal University Lafia


expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.

Example
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>> = <<= &= ^= |= Right to left

Comma , Left to right

CONTROL STRUCRURES

DECISION MAKING

There are three types of decision making statements in Java. They are:

Diploma Programme – Department of Computer Science, Federal University Lafia


 if statements

 if .. else tatements

 switch statements

The if (Single Option) Statement:


An if statement consists of a Boolean expression followed by one or more statements.
SYNTAX:
The syntax of an if statement is:

if(Boolean_expression){
//Statements will execute if the Boolean expression is true
}

If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}

This would produce the following result:

This is if statement

The if...else (Dual Option) Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
SYNTAX:
The syntax of an if...else is:

if(Boolean_expression){
//Executes when the Boolean expression is true
}else{

Diploma Programme – Department of Computer Science, Federal University Lafia


//Executes when the Boolean expression is false
}

Example:

public class Test {


public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}

This would produce the following result:


This is else statement

The if...else if...else (Multiple Option) Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
 When using if , else if , else statements there are few points to keep in mind:
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.

SYNTAX:
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}

EXAMPLE:
public class Test {
public static void main(String args[]){
int x = 30;

Diploma Programme – Department of Computer Science, Federal University Lafia


if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}

This would produce the following result:


Value of X is 30

Nested if...else Statement:


It is always legal to nest if‐else statements which means you can use one if or else if statement inside
another if or else if statement.

SYNTAX:
The syntax for a nested if...else is as follows:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.

EXAMPLE:

public class Test {


public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}

Diploma Programme – Department of Computer Science, Federal University Lafia


}
}

This would produce the following result:


X = 30 and Y = 10

The switch Statement:


A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.

SYNTAX:
The syntax is:

switch(expression){
case value1 :
//Statements
break; //optional
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:


 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is followed by the value to
be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to
subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the switch.
The default case can be used for performing a task when none of the cases is true. No break is
needed in the default case.

Diploma Programme – Department of Computer Science, Federal University Lafia


EXAMPLE:
public class Test {
public static void main(String args[]){
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
This would produce the following
Well done
Your grade is a C

LOOPS
There may be a situation when we need to execute a block of code several number of times, and is
often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
 while Loop
 do...while Loop
 for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays and we will not
explain it.

while Loop

A while loop is a control structure that allows you to repeat a task a certain number of times.
SYNTAX:
The syntax of a while loop is:
while(Boolean_expression)

Diploma Programme – Department of Computer Science, Federal University Lafia


{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed.
This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested
and the result is false, the loop body will be skipped and the first statement after the while loop will
be executed.
EXAMPLE

public class Test {


public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

do … while Loop

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
SYNTAX:
The syntax of a do...while loop is:
do
{
//Statements
} while(Boolean_expression);

Diploma Programme – Department of Computer Science, Federal University Lafia


Notice that the Boolean_ expression appears at the end of the loop, so the statements in the loop
executes once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.

EXAMPLE:

public class Test {


public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The for Loop:

for loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.

SYNTAX:
The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{

Diploma Programme – Department of Computer Science, Federal University Lafia


//Statements
}

As you can see, for loop consist of three parts, or steps.


The initialization step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and flow of control jumps to the next statement past the for
loop.
After the body of the for loop executes, the flow of control jumps back up to the update statement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.

EXAMPLE:

public class Test {


public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement.

Diploma Programme – Department of Computer Science, Federal University Lafia


The break keyword will stop the execution of the innermost loop and start executing the next line of
code after the block.

SYNTAX:
The syntax of a break is a single statement inside any loop:

break;
EXAMPLE:
public class Test {
public static void main(String args[]) {
int x;
for(x=0; x<=50; x++ ) {
if( x == 3 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:


0
1
2

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

SYNTAX:
The syntax of a continue is a single statement inside any loop:

continue;

EXAMPLE:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;

Diploma Programme – Department of Computer Science, Federal University Lafia


}
System.out.print( x );
System.out.print("\n");
}
}
}

This would produce the following result:


10
20
40
50

SUBROUTINES

One way to break up a complex program into manageable pieces is to use subroutines. A subroutine
consists of the instructions for carrying out a certain task, grouped together and given a name.
Elsewhere in the program, that name can be used as a stand-in for the whole set of instructions. As a
computer executes a program, whenever it encounters a subroutine name, it executes all the
instructions necessary to carry out the task associated with that subroutine.
Subroutines can be used over and over, at different places in the program. A subroutine can even be
used inside another subroutine. This allows you to write simple subroutines and then use them to
help write more complex subroutines, which can then be used in turn in other subroutines. In this
way, very complex programs can be built up step-by-step, where each step in the construction is
reasonably simple. Subroutines in Java can be either static or non-static.

Subroutine Definitions
A subroutine must be defined somewhere. The definition has to include the name of the subroutine,
enough information to make it possible to call the subroutine, and the code that will be executed
each time the subroutine is called. A subroutine definition in Java takes the form:

<modifiers> <return-type> <subroutine-name> ( <parameter-list> ) {


<statements>
}

The <statements> between the braces, { and }, in a subroutine definition make up the body of the
subroutine. These statements are the inside, or implementation part of the subroutine. They are the
instructions that the computer executes when the method is called.
The <modifiers> that can occur at the beginning of a subroutine definition are words that set certain
characteristics of the subroutine, such as whether it is static or not. The modifiers that you’ve seen
so far are “static” and “public”. There are only about a half-dozen possible modifiers altogether.
If the subroutine is a function, whose job is to compute some value, then the <return-type> is used
to specify the type of value that is returned by the function. It can be a type name such as String or
int or even an array type such as double[ ]. If the subroutine is not a function, then the <return-type>

Diploma Programme – Department of Computer Science, Federal University Lafia


is replaced by the special value void, which indicates that no value is returned. The term “void” is
meant to indicate that the return value is empty or non-existent.
Finally, we come to the <parameter-list> of the method. Parameters are part of the interface of a
subroutine. They represent information that is passed into the subroutine from outside, to be used
by the subroutine’s internal computations. The parameters that are passed when the subroutine is
called are called actural parameters or arguments. The once that are used in the subroutine’s
definition are called formal or dummy parameters.

For example, consider the following program.

public class Circle{

public static void main(String[] args){

double radius = 7.5;

final double PI = 3.14;

double area, circumference;

area = computeArea(radius, PI);

circumference = computeCircumference(radius, PI);

System.out.println("Area = "+ area);

System.out.println("Circumference = "+ circumference);

public static double computeArea(double r, double p){

double area = p*r*r;

return area;
}

public static double computeCircumference(double r, double p){

double circumference = 2*p*r;

return circumference;
}

Global and Local Variables

A class can include other things besides subroutines. In particular, it can also include variable
declarations. Of course, you can declare variables inside subroutines. Those are called local
variables. However, you can also have variables that are not part of any subroutine. To distinguish
such variables from local variables, we call them member variables, since they are members of a

Diploma Programme – Department of Computer Science, Federal University Lafia


class. Another term for them is global variable. Just as with subroutines, member variables can be
either static or non-static.

Example
Consider the class BankingSystem which implements some of the basic banking transactions like
withdrawal, deposit, and checking balance.

import java.util.*;
public class BankingSystem{

public static double balance = 2000.00;//global variable

public static void main(String[] args){

double amount;//local variable

Scanner input = new Scanner(System.in);


System.out.println("Enter 1 for withdrawal, 2 for
deposit, and 3 for balance");
int response=input.nextInt();

switch(response){
case 1:
System.out.println("Enter the amount to
withdraw: ");
amount = input.nextDouble();
withdraw(amount);
break;
case 2:
System.out.println("Enter the amount to
deposit: ");
amount = input.nextDouble();
deposit(amount);
break;
case 3:
showBalance();
break;
default:
System.out.println("Invalid input");
}
}

public static void withdraw(double wAmount){


if(wAmount>balance){
System.out.println("Sorry, You don’t have that
much");
}else{
balance = balance - wAmount;
}
showBalance();
}
public static void showBalance(){
System.out.println("Your Balance is "+balance);
}
public static void deposit(double dAmount){

Diploma Programme – Department of Computer Science, Federal University Lafia


balance = balance + dAmount;
showBalance();
}
}

Built-in Subroutines

Recall that a subroutine is a set of program instructions that have been chunked together and
given a name. A subroutine is designed to perform some task. To get that task performed in a
program, you can “call” the subroutine using a subroutine call statement. In the previous lectures,
you learned how to write your own subroutines, but you can get a lot done in a program just by
calling subroutines that have already been written for you. In Java, every subroutine is contained
either in a class or in an object. Some classes that are standard parts of the Java language contain
predefined subroutines that you can use. A value of type String, which is an object, contains
subroutines that can be used to manipulate that string. These subroutines are “built into” the Java
language. You can call all these subroutines without understanding how they were written or how
they work. Indeed, that’s the whole point of subroutines: A subroutine is a “black box” which can be
used without knowing what goes on inside.
Let’s first consider subroutines that are part of a class. One of the purposes of a class is to group
together some variables and subroutines, which are contained in that class. These variables and
subroutines are called static members of the class. You’ve seen one example: In a class that defines a
program, the main() routine is a static member of the class. The parts of a class definition that
define static members are marked with the reserved word “static”, such as the word “static” in
public static void main...
When a class contains a static variable or subroutine, the name of the class is part of the full name of
the variable or subroutine. For example, the standard class named System contains a subroutine
named exit. To use that subroutine in your program, you must refer to it as System.exit. This full
name consists of the name of the class that contains the subroutine, followed by a period, followed
by the name of the subroutine. This subroutine requires an integer as parameter, so you would
actually use it with a subroutine call statement such as System.exit(0); Calling
System.exit will terminate the program and shut down the Java Virtual Machine. You could use
it if you had some reason to terminate the program before the end of the main routine. (The
parameter tells the computer why the program was terminated. A parameter value of 0 indicates
that the program ended normally. Any other value indicates that the program was terminated
because an error was detected, so you could call System.exit(1) to indicate that the program is
ending because of an error. The parameter is sent back to the operating system; in practice, the
value is usually ignored by the operating system.)
System is just one of many standard classes that come with Java. Another useful class is called
Math. This class gives us an example of a class that contains static variables: It includes the variables
Math.PI and Math.E whose values are the mathematical constants π and e. Math also contains a
large number of mathematical “functions.” Every subroutine performs some specific task. For some
subroutines, that task is to compute or retrieve some data value. Subroutines of this type are called
functions. We say that a function returns a value. Generally, the returned value is meant to be used
somehow in the program that calls the function.
You are familiar with the mathematical function that computes the square root of a number. The
corresponding function in Java is called Math.sqrt. This function is a static member subroutine of the
class named Math. If x is any numerical value, then Math.sqrt(x) computes and returns the square
root of that value. Since Math.sqrt(x) represents a value, it doesn’t make sense to put it on a line by
itself in a subroutine call statement such as Math.sqrt(x); // This doesn’t make sense!

Diploma Programme – Department of Computer Science, Federal University Lafia


What, after all, would the computer do with the value computed by the function in this case? You
have to tell the computer to do something with the value. You might tell the computer to display it:

System.out.print( Math.sqrt(x) ); // Display the square root of x.

or you might use an assignment statement to tell the computer to store that value in a variable:

lengthOfSide = Math.sqrt(x);

The function call Math.sqrt(x) represents a value of type double, and it can be used anyplace
where a numeric literal of type double could be used.
The Math class contains many static member functions. Here is a list of some of the more
important of them:

• Math.abs(x), which computes the absolute value of x.

• The usual trigonometric functions, Math.sin(x), Math.cos(x), and Math.tan(x). (For all the
trigonometric functions, angles are measured in radians, not degrees.)

• The inverse trigonometric functions arcsin, arccos, and arctan, which are written as:
Math.asin(x), Math.acos(x), and Math.atan(x). The return value is expressed in radians, not degrees.

• The exponential function Math.exp(x) for computing the number e raised to the power
x, and the natural logarithm function Math.log(x) for computing the logarithm of x in the base e.

• Math.pow(x,y) for computing x raised to the power y.

• Math.floor(x), which rounds x down to the nearest integer value that is less than or equal to x.
Even though the return value is mathematically an integer, it is returned as a value of type double,
rather than of type int as you might expect. For example, Math.floor(3.76) is 3.0. The function
Math.round(x) returns the integer that is closest to x, and Math.ceil(x) rounds x up to an integer.
(“Ceil” is short for “ceiling”, the opposite of “floor.”)

• Math.random(), which returns a randomly chosen double in the range 0.0 <= Math.random() < 1.0.
(The computer actually calculates so-called “pseudorandom” numbers, which are not truly random
but are effectively random enough for most purposes.) We will find a lot of uses for Math.random in
future examples.

For these functions, the type of the parameter—the x or y inside the parentheses—can be any value
of any numeric type. For most of the functions, the value returned by the function is of type double
no matter what the type of the parameter. However, for Math.abs(x), the value returned will be the
same type as x; if x is of type int, then so is Math.abs(x). So, for example, while Math.sqrt(9) is the
double value 3.0, Math.abs(9) is the int value 9. Note that Math.random() does not have any
parameter. You still need the parentheses, even though there’s nothing between them. The
parentheses let the computer know that this is a subroutine rather than a variable. Another example
of a subroutine that has no parameters is the function System.currentTimeMillis(), from the System
class. When this function is executed, it retrieves the current time, expressed as the number of
milliseconds that have passed since a standardized base time (the start of the year 1970, if you care).
One millisecond is one thousandth of a second. The return value of System.currentTimeMillis() is of
type long (a 64-bit integer). This function can be used to measure the time that it takes the
computer to perform a task. Just record the time at which the task is begun and the time at which it
is finished and take the difference. Here is a sample program that performs a few mathematical

Diploma Programme – Department of Computer Science, Federal University Lafia


tasks and reports the time that it takes for the program to run. On some computers, the time
reported might be zero, because it is too small to measure in milliseconds. Even if it’s not zero, you
can be sure that most of the time reported by the computer was spent doing output or working on
tasks other than the program, since the calculations performed in this program occupy only a tiny
fraction of a millisecond of a computer’s time.

/*
* This program performs some mathematical computations and displays
the
* results. It also displays the value of the constant Math.PI. It
then
* reports the number of seconds that the computer spent on this
task.
*/
public class TimedComputation {
public static void main(String[] args) {
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in milliseconds.
double time; // Time difference, in seconds.
startTime = System.currentTimeMillis();
double width, height, hypotenuse; // sides of a triangle
width = 42.0;
height = 17.0;
hypotenuse = Math.sqrt( width*width + height*height );
System.out.print("A triangle with sides 42 and 17 has hypotenuse
");
System.out.println(hypotenuse);
System.out.println("\nMathematically, sin(x)*sin(x) + "
+ "cos(x)*cos(x) - 1 should be 0.");
System.out.println("Let’s check this for x = 1:");
System.out.print(" sin(1)*sin(1) + cos(1)*cos(1) - 1 is ");
System.out.println( Math.sin(1)*Math.sin(1)
+ Math.cos(1)*Math.cos(1) - 1 );
System.out.println("(There can be round-off errors when"
+ " computing with real numbers!)");
System.out.print("\nHere is a random number: ");
System.out.println( Math.random() );
System.out.print("The value of Math.PI is ");
System.out.println( Math.PI );
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.print("\nRun time in seconds was: ");
System.out.println(time);
} // end main()
} // end class TimedComputation

Diploma Programme – Department of Computer Science, Federal University Lafia

You might also like