csc2321 Lecture 2 Java
csc2321 Lecture 2 Java
Contents i
1 I NTRODUCTION 1
1.1 Java Platform & Java Virtual Machine . . . . . . . . . . . . . . . . . . . . . . . . . 1
4 Exercises 58
i
CHAPTER
1
I NTRODUCTION
Compilers: A compiler takes a high-level language program and translate it into an exe-
cutable machine language program. A compile program can only be executed in one
type of a computer. For example, suppose a program is compile in a Windows system,
for it to run in a Linux system it need to be re-compiled using a Linux compiler. A
compiler takes the whole program and translate it all at once.
The Java Platform uses a combination of compilation and interpretation. Programs writ-
ten in Java are compiled into machine language, but it is a machine language for a computer
that doesn’t really exist. This so-called “virtual” computer is known as the Java Virtual Ma-
chine, or JVM. The machine language for the Java Virtual Machine is called Java byte-code.
There is no reason why Java byte-code couldn’t be used as the machine language of a real
computer, rather than a virtual computer. But in fact the use of a virtual machine makes
possible one of the main selling points of Java: the fact that it can actually be used on any
computer. All that the computer needs is an interpreter for Java byte-code. Such an in-
terpreter simulates the JVM. (The term JVM is also used for the Java byte-code interpreter
program that does the simulation, so we say that a computer needs a JVM in order to run
Java programs. Technically, it would be more correct to say that the interpreter implements
the JVM than to say that it is a JVM.)
Of course, a different Java byte-code interpreter is needed for each type of computer, but
once a computer has a Java byte-code interpreter, it can run any Java byte-code program.
And the same Java byte-code program can be run on any computer that has such an inter-
preter. This is one of the essential features of Java: the same compiled program can be run
on many different types of computers.
The Java source files have a .java extension, whereas the Java byte-code files have a .class
extension.
To run Java programs one needs the Java Runtime Environment (JRE) which includes the
interpreter that implements the JVM. To develop Java programs you need the Java Develop-
ment Kit (JDK) that contains the compiler that compile a Java source code to a byte-code,
and the Java interpreter that implements the JVM.
There are two kinds of Java programs – applets and applications. An application or
application program is a regular program that is meant to be run from your computer, while
an applet (which means a little Java application) is meant to be run from a Web browser
over the Internet and is usually located on a remote server. Java application programs are
the focus of this course.
3 p u b l i c s t a t i c v o i d main(String args[]){
4 System.out.println(" Welcome to Java Programming !");
5 } // closing for main
6
Line 1: public class FirstJavaApp{ – A Java application is actually a class definition. Line
1 indicates that our program is a class called FirstJavaApp. All Java applications
must contains line 1, although it is not usually the first line of a Java application.
The first two words (public class) are Java keywords the third word is the name of
the Program, which can be any valid identifier.
Line 3: public static void main(String args[]){ – This begins the definition of the main
method. Java applications typically contains many methods (called functions in
C++) but only one of those is the main method – incidentally called main. All Java
applications start executing from the main method. We will explain the meaning of
public, static and void in due course.
Line 5: } //closing for main – is the closing curly brace of the opening brace at the
end of line 1, anything following // up to the end of the line is a comment an is
ignored by the compiler.
Line 7: } /*closing for FirstJavaApp */ is the closing curly brace of the opening
brace at the end of line 3, anything in between /* and */ is regarded as a comment
by the compiler. This type of comment can span multiple lines.
p u b l i c c l a s s ProgramName {
optional-variable-declarations-and-methods
p u b l i c s t a t i c v o i d main(String[] args) {
statements
}
optional-variable-declarations-and-methods
The source file must be saved as ProgramName.java, note that the file name is case sensi-
tive even in a Windows system.
Exercise 2.1
1. Write a Java program that prints your full name.
To create Java applications you need a text editor and the Java Development Kit (JDK).
We look at two ways to create a Java application, by using the command line and by using
an Integrated Development Environment (IDE).
Create the Source Code: You can use any text editor to create the source code. On a Linux
system you can use gedit and on a Windows system you can use notepad. For exam-
ple, suppose the program you want to create is called MyFirstJavaApp; you type the
following on the command prompt:
After typing the above command(s) the text editor will launch with a blank documents
named MyFirstJavaApp.java. Note the .java extension is written in lower case
characters. Remember that Java source file names are case sensitive.
Compile the Source Code to Byte-Code: To compile a source code to byte-code you use
the javac compiler. To invoke the javac compiler simply type javac followed by
the name of the source file including the .java extension. To continue our example
above, suppose you want to compile MyFirstJavaApp.java. You simply type (in
both Linux and Windows systems):
javac MyFirstJavaApp.java x
The above command compile the program and create the byte-code. The byte-code
will be contained in a file that have the same name as your .java source file but with
the extension of .java replaced by the extension .class. javac MyFirstJavaApp.java
will create a file named MyFirstJavaApp.class
To Run the Program: To run the program, you need to invole the Java interpreter program
called java. For our example, to run the MyFirstJavaApp.class (our byte-code) sim-
ply type the following (in both Linux and Windows systems):
java MyFirstJavaApp x
Next is a step-by-step tutorial on how to create, compile and run a Java application pro-
gram that prints "Welcome to Java Apps" on to the console screen. The program is named
Greetings, note that “~$” is the command prompt.
Step 2: gedit text editor open with an empty file named Greetings.java
Step 3: Type the code of the program in the gedit text editor
• a debugger
There are many Java IDEs, two of the most commonly used Java IDEs are Eclipse and Net-
Beans which are open-source and run on multiple platforms including Linux, Mac OS and
Windows. For this manuscript the Eclipse IDE is used.
Although the look of IDEs vary greatly, the steps needed to code, compile and run pro-
grams are similar. The steps are as follows:
Step 1: Create a Project. A project is used to contain all the resources of your program in-
cluding source files.
Step 3: Run the Program. When you invoke a run command, the IDE automatically com-
pile, link and run the program.
Next is a step-by-step tutorial on how to create a project, add a source file and run a Java
application that prints "Welcome to Java Apps" using Eclispe IDE.
Step 1: After starting the Eclipse IDE, the splash screen is shown
Step 2: Next the Workspace Launcher is shown where you can choose folder to use
Step 3: After choosing the Workspace and clicking the OK button the following is shown
Step 6: The New Java Project dialog is displayed where you can give a name to your project
in the Project Name text field. After given your project a name, click on the Finish
button
Step 8: Your project is empty, you need to add a source file. Remember a Java program is
actually a class definition, so to create a source file we need to actually create a new
Class. To add a new class to your project right click on your project in the workspace,
select New->Class
Step 9: A New Java Class dialog is displayed where you can give your new class a name and
choose various options. For now just give your class a name in the Name text field
and click the Finish button
Step 10: Your newly created class will be added to your project and the display in the embed-
ded editor for modification
Step 11: After typing your code as shown below you need to run the program.
Step 12: There several ways to run the program, two are shown here. First from the main
menu bar, click Run->Run As->1 Java Application
If you source file is not saved, a dialog is displayed asking whether the file should be
save below running the program. Choice the “Always save resource before launch-
ing” to automatically save before compiling the program.
Step 13: After the program compiles, the result is shown in an embedded console in the
Eclipse IDE as shown in the bottom of the following figure.
Step 14: You can also run the program by pressing Ctrl+F11 key combination or by clicking
the run button in the tool bar
import Packages
p u b l i c c l a s s ProgramName {
optional-variable-declarations-and-methods
p u b l i c s t a t i c v o i d main(String[] args) {
statements
}
optional-variable-declarations-and-methods
A Java program is a collection of classes, and a class is defined by a set of variable declara-
tions and methods containing executable statements. Most statements contain expressions,
these expressions are made up of variables and constants joined together by operators
3.1 Constants
A constant is a fixed value that does not change during the execution of a program. Java
supports several type of constants which can be grouped into two main categories – nu-
meric constants (which include integer constants and real constants) and character con-
stants (which include character constants and string constants).
Numeric Constants: are subdivided into two categories – integer constants and real con-
stants.
Integer Constants: An integer constant consist of series of digits. In Java there three
types of integer constants, namely, decimal integer, octal integer and hexadeci-
mal integer. Decimal integer constants are the default integer constants in Java,
examples of valid decimal integer constants include 123, 456, 789123, 0. Em-
bedded spaces, commas and other non-digit characters are not allowed between
integers. For example 12 345, $765 and 789,123 are invalid integer constants.
Octal integers constants are integer constants that consists of digits from 0 to 7
with a leading 0. 0123, 0765 and 0 are examples of valid octal integer constants.
Hexadecimal integer constants are integer constants that consists of digits form 0
to 9 and alphabets A to F (or a to f) that represents numbers 10 through 15. Hex-
adecimal integers are preceded by 0x or 0X. 0x12, 0XAF and 0x0 are examples
of valid hexadecimal integer constants.
Real Constants: A real constant consists of a series of digits from 0 through 9, a deci-
mal point and e or (E) character. In Java real constants can be expressed in either
decimal notation or scientific notation.
Real constants in decimal notation consist of a whole part followed by a decimal
point followed by the fractional part which is an integer. 123.45, −0.0012 and
−987.123 are all valid real constants in decimal notation.
A real constant can also be expressed in scientific (exponential) notation that con-
sists of an integer followed by a decimal point, followed by a character e (or E)
lastly followed by an integer. −123e4, 0.00E−3 and −9.76e−12 are all valid real
constants in scientific notation.
Character Constants: are subdivided into two categories – character constants and string
constants.
(‘ ’) is a blank space and the first example ‘2’ is a character constant ‘2’ and is
not the same as a number 2.
Java supports special backslash character constants called escape sequences. Es-
cape sequences are a combination of a backslash (\) followed by a character.
Escape sequences are usually used in output methods like println, although
escape sequences consists of two characters, they are considered as a single char-
acter constants.
Constant Meaning
‘\b’ back space
‘\n’ new line
‘\r’ carriage return
‘\t’ horizontal tab
‘\’’ single quote
‘\"’ double quote
‘\\’ backslash
3.2 Variables
A variable is a symbol that represents a storage location in a computer’s memory. Unlike
constants, the value of a variable can change during an execution of a program. A variable
name is any valid identifier. An identifier is a series of characters consisting of letters, digits,
a dollar sign ($) and underscore(_) that must not start with a digit. A valid identifier (hence
a variable name) in Java is subject to the following conditions:
2. Java is a case-sensitive language, this means uppercase and lowercase characters are
distinct. This means variable D1 is not the same as variable d1.
Primitive Data Type: Primitive data types are types that are built-in into the Java program-
ming Language. They are divided into numeric (which contains Integer data types and
Floating-point data types) and non-numeric (which contains Character data types
and Boolean data types).
Numeric Data Types: Numeric data types are data types that can hold numeric data.
They are divided into two – Integer data types and Floating-point data types. Java
does not support unsigned data types, therefore all numeric data types in Java
can be positive or negative.
Integer Data Types: Integer types can hold whole numbers. The size of the value
that can be stored depends on the type of the integer data type. There are
four types of integer data types in Java, they are byte, short, int and long. The
table below summarizes the size and range of the four integer data types.
Type Size Minimum Value Maximum Value
byte 1 byte -128 127
short 2 bytes -32,768 32,767
int 4 bytes -2,147,483,648 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
In Java integer numbers are treated as int , integers can be treated as long by
appending the letter L or l at the end of the number. For example, 987L or
987l.
Floating-Point Data Types: Floating-Points types can hold numbers with a frac-
tional part such as 123.45 and −987.12. There are two types of floating-
point data types in Java, they are float (for single precision numbers) and
double (for double precision numbers). The table below summarizes the size
and range of the two floating-point data types.
Derived Data Type: Derived data types are types that consists of classes, Interfaces and Ar-
rays. The definition of derived types is given here and are discussed later as and when
they are encountered.
3. The place of declaration (in the program) decides the scope of the variable.
A variable must be declared before it is used. The general format of variable declaration is:
type variable1, variable2, variable3, · · · · · · · · · , variableN ;
Variables of the same type are separated by a comma, variable of different types are declared
separately. Each variable declaration is separated by a semicolon. Example of valid variable
declarations include:
i n t n;
byte b;
double x1, x2;
char a, b;
variableName = value;
For example,
sum = 0;
product = 1;
x = ‘i’;
For example,
i n t sum = 0;
double product = 1.0;
char x = ‘i’;
Assigning values to variables the moment they are declared is called initialisation. Numeric
variables that are not initialise are automatically set to zero. The following are all valid Java
statements:
1 import java.util.Scanner;
2
3 p u b l i c c l a s s TestScanner{
4 p u b l i c s t a t i c v o i d main(String args[]){
5 Scanner sc = new Scanner(System.in);
6 i n t a, b, sum;
7 System.out.print(" Enter an integer : ");
8 a = sc.nextInt();
9 System.out.print(" Enter another integer : ");
10 b = sc.nextInt();
11 sum = a + b;
12 System.out.print(" Sum of " + a + " and " + b);
13 System.out.println(" is " + sum);
14 }
15 }
The output of the program above is shown below, the user input is in bold and underline.
Enter an integer: 12
Enter another integer: 33
Sum of 12 and 33 is 45
Line 1: import java.util.Scanner; –Before we use the Scanner class we must import
it using import java.util.Scanner;.
Line 5: declares a Scanner object named sc. Note that sc can be any valid identifier. Before
you can use the Scanner class to read input from the console, you must declare a
Scanner variable and create an instance of the Scanner class.
To create a Scanner object, you use the new keyword followed by a call to the Scanner
class constructor. Note that the Scanner class requires a parameter that indicates
the input stream that the input comes from. System.in is used here to specify stan-
dard keyboard console input.
Line 7: is a prompt to indicate to the user what is needed – in this case "Enter an integer:
"
Line 8: is used to read an integer from the user through the keyboard and store it in variable
a. To read an input from the user, you can use one of the methods of the Scanner
class as listed below:
Method Explanation
boolean nextBoolean() Reads a boolean value from the user
byte nextByte() Reads a byte value from the user
double nextDouble() Reads a double value from the user
float nextFloat() Reads a float value from the user
int nextInt() Reads an int value from the user
String nextLine() Reads a String value from the user
long nextLong() Reads a long value from the user
short nextShort() Reads a short value from the user
Notice in the first column of the table that each method listing begins with the type
of the value that is returned by the method. For example, the nextInt method returns
an int value. Also, notice that each of the methods ends with an empty set of paren-
theses. That means that none of these methods require parameters. If a method
requires parameters, the parameters are listed within these parentheses. Because
these methods read a value from the user and return the value, you most often use
them in statements that assign the value to a variable. For example, line 8 in our
program above reads an int and assigns it to a variable named a.
When the nextInt method is executed, the program waits for the user to enter a
value in the console window. To let the user know what kind of input the program
expects, you should usually call the System.out.print() method before you call
a Scanner method to get input. For example, line 7 in our program above calls
Line 9: is a prompt to indicate to the user what is needed – in this case "Enter another
integer: "
Line 10: is used to read an integer from the user through the keyboard and store it in variable
b.
Line 11: adds the values supplied on line 8 and line 10 and stores the in variable sum.
Line 13: prints "Sum of "+ a + "and "+ b + "is "+ sum" on to the console – where a, b
and sum are replaced by the actual values they contained.
1 import javax.swing.JOptionPane;
2
3 p u b l i c c l a s s TestJOptionPane{
4 p u b l i c s t a t i c v o i d main(String args[]){
5 String name;
6 name = JOptionPane.showInputDialog(" Enter Your Name :");
7 System.out.println(" Hello " + name);
8 }
9 }
After the program executes, Line 6 produce the following input dialog box
After the user enters his/her name (in our sample execution above, the user enters Musa as
his/her name) and clicks on the OK button, the following output is displayed on the console.
Hello Hanif
All the lines in the program above are already covered with the exception of Line 1, Line 5 &
Line 6.
Line 1: import javax.swing.JOptionPane; –As with the Scanner class, before we use
the JOptionPane class we must import it using import javax.swing.JOptionPane;.
Technically, the user can type anything in the text field of the input. If the user clicks
on the Cancel button, a runtim logic error occurs.
Primitive Type boolean byte char double float int long short
Wrapper Class Boolean Byte Character Double Float Integer Long Short
Note that the class names Character and Integer are not abbreviated like the corre-
sponding primitive types char and int . Wrapper classes are called so because they each en-
capsulates (wraps) a primitive type, so that a variable can be represented by an object when
necessary. They also provide the minimum and maximum values of the type, and the two
floating-point classes (Double and Float) defined the constants POSITIVE_INFINITY,
NEGATIVE_INFINITY and NaN.
Wrapper classes have a number of unique methods for handling primitive types and
objects. The following figure shows the six conversion methods that you can use to convert
between the int and the Integer and String classes.
Similar method exists for each of the other seven wrapper classes, the methods are listed in
the following series of tables
boolean⇐⇒Boolean⇐⇒ String
Function Call Conversion Action
n = Boolean.parseBoolean(s) String object s to primitive boolean type n
n = x.booleanValue() Boolean object x to primitive boolean type n
x = new Boolean(n) Primitive boolean type n to Boolean object x
s = Boolean.toString(n) Primitive boolean type n to String object s
s = x.toString() Boolean object x to String object s
byte⇐⇒Byte⇐⇒ String
Function Call Conversion Action
n = Byte.parseByte(s) String object s to primitive byte type n
n = x.byteValue() Byte object x to primitive byte type n
x = new Byte(n) Primitive byte type n to Byte object x
x = Byte.decode(s) String object s to Byte object x
s = Byte.toString(n) Primitive byte type n to String object s
s = x.toString() Byte object x to String object s
char⇐⇒Character⇐⇒ String
Function Call Conversion Action
n = x.charValue() Character object x to primitive char type n
x = new Character(n) Primitive char type n to Character object x
s = Character.toString(n) Primitive char type n to String object s
s = x.toString() Character object x to String object s
double⇐⇒Double⇐⇒ String
Function Call Conversion Action
n = Double.parseDouble(s) String object s to primitive double type n
n = x.doubleValue() Double object x to primitive double type n
x = new Double(n) Primitive double type n to Double object x
x = Double.decode(s) String object s to Double object x
s = Double.toString(n) Primitive double type n to String object s
s = x.toString() Double object x to String object s
long⇐⇒Long⇐⇒ String
Function Call Conversion Action
n = Long.parseLong(s) String object s to primitive long type n
n = x.longValue() Long object x to primitive long type n
x = new Long(n) Primitive long type n to Long object x
x = Long.decode(s) String object s to Long object x
s = Long.toString(n) Primitive long type n to String object s
s = x.toString() Long object x to String object s
short⇐⇒Short⇐⇒ String
Function Call Conversion Action
n = Short.parseShort(s) String object s to primitive short type n
n = x.shortValue() Short object x to primitive short type n
x = new Short(n) Primitive short type n to Short object x
x = Short.decode(s) String object s to Short object x
s = Short.toString(n) Primitive short type n to String object s
s = x.toString() Short object x to String object s
So we can use the parse() methods to convert a String object input from the user
into a desired numeric data type. The parse() method throws NumberFormatException
if the string argument passed is not in the correct format.
1. Instance variables.
2. Class variables.
3. Local variables.
Instance variables and class variables are declared inside a class. Instance variables are
created when the objects of the class are instantiated and therefore can be associated with
the objects. They take different values for each object. On the other hand, class variables
are global to a class and belong to the entire set of objects that the class creates. Only one
memory is created for each class variable.
Variables declared and used inside methods are called local variables. They are called
so because they are not available for use outside the method definition. Local variables can
also be declared inside program blocks that are defined between an opening brace ‘{’ and
a closing brace ‘}’. These variables are visible from where they are declared in a program
block to the end of the block. When a program control leaves a block, all the variables in the
block will cease to exist. The area of the program where the variable is accessible (i.e usable)
is called its scope.
We can have program blocks within other program blocks (called nesting) as shown be-
low
Each block can contain its own set of local variable declarations. We cannot however. declare
a variable to have the same name as one in an outer block. In the above diagram, the variable
x declared in “Block 1” is available in all the three blocks. However, the variable n declared
in “Block 2” is available only in “Block 2”, because it goes out of scope at the end of “Block
2”. Similarly, m is only available in “Block 3”.
Note that we cannot declare the variable x again in “Block 2” or “Block 3”, this is per-
fectly legal in C++.
Modifiability
We may like to change the value of “pi” from 3.142 to 3.14159 to improve the accuracy
of calculations or the number of voters from 50 to 100 to process the vote results of another
ward. In both cases, we will have to search throughout the program and explicitly change
the value of the constant wherever it is used. If any value is left unchanged, the program
may produce disastrous results.
Understandability
When a numeric value appears in a program its use is not always clear, especially when
the same value means different things in different places. For example, the number 50 may
mean the number of voters at one place and the “percentage of votes needed to win” at an-
other place of the same program. We mat forget that a certain number meant, when we read
the program some days later.
Assignment of a symbolic name to such constants free us from these problems. For ex-
ample, we may use the name NO_OF_VOTERS to denote the number of voters and PERCENTAGE_TO_WIN
to denote the percentage needed to win. Constant values are assigned to these names at the
beginning of the program. Subsequent use of the names NO_OF_VOTERS and PERCENTAGE_TO_WIN
in the program has the effect of causing their defined values to be automatically substituted
at the appropriate points. A constant is declared as follows:
f i n a l type symbolic_Name = value
f i n a l i n t NO_OF_VOTERS = 100;
f i n a l i n t PERCENTAGE_TO_WIN = 50;
f i n a l f l o a t PI = 3.145159F;
1. Symbolic names take the same form as variable names. But they are written in UPPER-
CASE to distinguish them from normal variables names. This is only a convention, not
a rule.
2. After declaration of symbolic constants, they should not be assigned any other value
within the program by using an assignment statement. For example. NO_OF_VOTERS
= 150; is illegal since NO_OF_VOTERS has been declared as final .
3. Symbolic constants are declared for types. This is not done in C++ where symbolic
constants are defined using the #define statement.
4. They can NOT be declared inside a method. They should be used only as class data
members in the beginning of the class.
The process of converting one data type to another is called casting. Examples
i n t n = 100;
byte b = (byte)n;
long k = (long)n;
Casting is often necessary when a method returns a type different from the one we require.
Four integer type (byte, short, int and long) can be case to any other type except boolean.
Casting into a smaller type may result in a loss of data. Similarly, float and double can be
cast to any other type except boolean. Again, casting to smaller type can result in a loss of
data. Casting a floating-point value to an integer will result in a loss of the fractional part.
Automatic Conversion
For some types, it is possible to assign a value of one type to a variable of a different type
without a cast. Java does the conversion of the assigned value automatically.This is known
as automatic type conversion. Automatic type conversion is possible only if the destination
type has enough precision to store the source value. For example, int is large enough to hold
a byte value. Therefore,
byte b = 123;
i n t n = b;
f l o a t f = 1.23;
f l o a t f = 1.23f;
print(): The print() method sends information into a buffer. This buffer is not flushed
until a newline (or end-of-line) character is sent. As a result, print() method prints
output on one line until a newline character is encountered. For example, the state-
ments
display the words "CSC4313: Programming in Java" in one line and waits for display-
ing further information on the same line. We may force the display to be brought to
the next line by printing a newline character – System.out.println(‘n’). For ex-
ample, the statements
will produce
CSC4313:
Programming in Java
println(): The println() method in contrast, takes the information provided and dis-
plays it on a line followed by a line feed (carriage-return). This means that the state-
ments
CSC4313:
Programming in Java
The statement
System.out.println();
1 import javax.swing.JOptionPane;
2
3 p u b l i c c l a s s TestJOptionPaneOutPut{
4 p u b l i c s t a t i c v o i d main(String args[]){
5 String course = " CSC4313 : Programming in Java ";
6 JOptionPane.showMessageDialog( n u l l , course);
7 }
8 }
We now take a closer look at the some of the lines of the above program
Line 1: import javax.swing.JOptionPane; –As with the Scanner class, before we use
the JOptionPane class we must import it using import javax.swing.JOptionPane;.
Parameter 3: is optional and it sets the title of the message dialog. If no title is given the
default title “Message” is used.
Parameter 4: is the final parameter and is a value indicating the type of message dialog to
display.
3.11 Operators
Java supports a rich set of operators. We have already used several of the, such as = and +.
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables. They
usually form part of mathematical or logical expression.
Most of Java operators are the same or similar to operators in C++. Where they are the
same, we only mentioned them. Where they are similar, we indicated the difference between
their use in C++ and Java. Where they are only available to Java, we gave them an in-depth
treatment. Java operators can be classified into a number of related categories as treated in
the following sections.
Arithmetic Operators
Arithmetic Operators in Java are the same as in C++ with the exception of the modulus
operator %. In C++, the modulus operator % can only be applied to integer operands; but
in Java the modulus operator % can be applied to floating-point data as well. The floating-
point modulus operator returns the floating-point equivalent of an integer division. What
this means is that division is carried out with both floating-point operands, but the resulting
divisor is treated as an integer, resulting in a floating-point remainder. The following table
list the arithmetic operators in Java.
Arithmetic Operators
Operator Meaning Math Java
+ Addition or unary plus a + b or +a a + b or +a
− Subtraction or unary minus a − b or −a a − b or −a
* Multiplication a ×b a * b
/ Division a/b a / b
% Modulo a mod b a % b
The following program illustrates how arithmetic operators work on floating-point val-
ues.
1 p u b l i c c l a s s TestArithmeticOperators{
2 p u b l i c s t a t i c v o i d main(String args[]){
3 f l o a t a = 98.7f, b = 6.54f;
4 System.out.println("a = " + a);
5 System.out.println("b = " + b);
6 System.out.println("a + b = " + (a + b));
7 System.out.println("a - b = " + (a − b));
8 System.out.println("a * b = " + (a * b));
9 System.out.println("a / b = " + (a / b));
10 System.out.println("a % b = " + (a % b));
11 }
12 }
Remember, in C++ the division operator returns an integer when both operators are integer
types and returns a floating-point when at least one of the operands is a floating-point type.
This is the same as in Java.
Relational Operators
Relational operators are used to compare two quantities. Java supports six relational
operators, which are listed in the following table.
Relational Operators
Operator Meaning Math Java
< is less than a <b a < b
<= is less than or equal to a ≤b a <= b
> is greater than a >b a > b
>= is greater than or equal to a ≥b a >= b
== is equal to a =b a == b
!= is not equal to a 6= b a != b
1 p u b l i c c l a s s TestRelationalOperators{
2 p u b l i c s t a t i c v o i d main(String args[]){
3 f l o a t x = 12.3f, y = 45.6F, z = 12.3f;
4 System.out.println("x = " + x);
5 System.out.println("y = " + y);
6 System.out.println("z = " + z);
7 System.out.println("x < y is " + (x < y));
8 System.out.println("x > y is " + (x > y));
9 System.out.println("x == y is " + (x == y));
10 System.out.println("x <= z is " + (x <= z));
11 System.out.println("x >= y is " + (x >= y));
12 System.out.println("x >= y is " + (x >= y));
13 System.out.println("y != z is " + (y != z));
14 System.out.println("y == x + y is " + (y == x + y));
15 }
16 }
x = 12.3
y = 45.6
z = 12.3
x < y is t r u e
x > y is f a l s e
x == y is f a l s e
x <= z is t r u e
x >= y is f a l s e
x >= y is f a l s e
y != z is t r u e
y == x + y is f a l s e
Relational operators are used in decision statements such as if and while to decide the course
of action of a running program.
Logical Operators
In addition to the relational operators, Java has three logical operators, which are given
in the following table.
Logical Operators
Operator Meaning Math Java
&& logical AND a ∧b a && b
|| logical OR a ∨b a || b
! logical NOT ∼a !a
The logical operators && and || are used when we want to form compound conditions
by combining two or more relations.
Like simple relational expressions, logical expressions also yields a value of true or false
according to the truth table as shown below.
Truth Table
a b a && b a || b
true true true true
true false false true
false true false true
false false false false
where op is one of Java binary operators. The operator op= is known as the shorthand as-
signment operator.
Some commonly used shorthand assignment operators are illustrated in the following
table.
1. What appears on the left-hand side need not be repeated and therefore it becomes
easier to write.
The increment and decrement operators in Java are exactly the same as those found in
C++. The increment and decrement operators are
++ and −−
The operator ++ adds 1 to the operand while −− subtract 1. Both are unary operators, works
only on variables (not constants or expressions) and are used in the following form:
++n; or n++;
−−n; or n−−;
++n; is equivalent to n = n + 1; (or n += 1;)
−−n; is equivalent to n = n − 1; (or n −= 1;)
These operators are extensively in for and while loops. The following program illustrates
the use of increment and decrement operators.
1 p u b l i c c l a s s TestPrePostOperators{
2 p u b l i c s t a t i c v o i d main(String args[]){
3 double x = 1.2, y = 3.4;
4 i n t a = 5, b = 6;
5 System.out.println("x = " + x + "\ty = " + y);
6 System.out.println("++x = " + ++x);
7 System.out.println("y++ = " + y++);
8 System.out.println("x = " + x + "\ty = " + y);
9 System.out.println("a = " + a + "\tb = " + b);
10 System.out.println(" --a = " + −−a);
11 System.out.println("b-- = " + b−−);
12 System.out.println("a = " + a + "\tb = " + b);
13 }
14 }
x = 1.2 y = 3.4
++x = 2.2
y++ = 3.4
x = 2.2 y = 4.4
a = 5 b = 6
−−a = 4
b−− = 6
a = 4 b = 5
Conditional Operator
As with C++, Java has a ternary operator which is formed by the character pair ? :. This
operator is used to construct conditional expression of the form
conditional_expression ? expression1 : expression2
Special Operators
Java supports some special operators of interest such as
instanceof Operator: is an object reference operator and returns true if the object on the
left-hand side is an instance of the class given on the right-hand side. This operator
allows us to determine whether an object belongs to a particular class. For example,
person i n s t a n c e o f Student;
is true if the object person belongs to the class Student; otherwise it is false .
Dot (.) Operator: is used to access the instance variables and methods of class objects. For
example,
The dot operator is also used to access classes and sub-packages from a package. For
example,
Math.functionName()
Example, the following declares a double variable y and initializes it to square root of 12.3:
double y = Math.sqrt(12.3);
The Math class also define two static constant – PI and E with following values:
Math.PI = 3.141592653589793
Math.E = 2.718281828459045
Selection Structures
The control statements that allow alternative actions based upon conditions that are
evaluated at runtime are generally called selection statements or selection structures. Java
support three selection statements – if , if ...else and switch:
if Selection
The if statement allows for conditional execution. The statement that is included will
be executed only if its condition is true. The syntax for the if statement is
i f (condition) statement ;
where condition is a boolean expression and statement is the statement that will execute if
the value of the boolean expression is true. The statement may be a single statement or a
block of statements.
Consider the following code
1
divide in two: to split or branch into two parts, or split something into two parts
The above code displays Passed on to the screen only if marks is greater than or equal to
40.
If we want more than a single instruction to be executed in case that condition is true we
specify a block of statements using curly brackets ({}). For example,
if...else Selection
The if ...else statement causes one of two alternative statements to execute depending
upon whether the condition is true. The format is:
i f (condition)
statement1;
else
statement2;
where condition is a boolean expression and statement1 and statement2 are executable state-
ments. If the value of condition is true then statement1 will be executed otherwise state-
ment2 will be executed. Consider the following code
The above code displays Passed on to the screen only if marks is greater than or equal to
40 and displays Failed otherwise.
Nested if Statements
You can also nest if statements inside each other (that is, define them inside other if
statements). Here is an example showing how this technique works. The following program
employs nested if ...else statements to determine the largest of three given numbers.
1 import java.util.Scanner;
2
3 p u b l i c c l a s s TestNestedIf{
4 p u b l i c s t a t i c v o i d main(String args[]){
5 Scanner sc = new Scanner(System.in);
6 i n t a, b, c;
7 System.out.print(" Enter three integers : ");
8 a = sc.nextInt();
9 b = sc.nextInt();
10 c = sc.nextInt();
11
The output of the program above is shown below, the user input is in bold and underline.
else...if Ladder
....................................................
....................................................
....................................................
i f (marks >= 70)
grade = ‘A’;
else if( marks >= 60)
grade = ‘B’;
e l s e i f (marks >= 50)
grade = ‘C’;
else if( marks >= 45)
grade = ‘D’;
e l s e i f (marks >= 40)
grade = ‘E’;
else
grade = ‘F’;
System.out.println(" Grade : " + grade);
....................................................
....................................................
....................................................
............................
............................
............................
i f (code == 1)
colour = " RED ";
e l s e i f (code == 2)
colour = " GREEN ";
e l s e i f (code == 3)
colour = " BLUE ";
else
colour = " WHITE ";
............................
............................
............................
Code numbers other than 1, 2 or 3 are consider to represent WHITE colour. The same result
can be obtained by using nested if ...else statements as follows:
.......................................
.......................................
.......................................
i f (code != 1)
i f (code != 2)
i f (code != 3)
colour = " WHITE ";
else
colour = " BLUE ";
else
colour = " GREEN ";
else
colour = " RED ";
.......................................
.......................................
.......................................
In such situations, the choice of the method is left to the programmer. However, in order
to choose an if structure that is both effective and efficient, it is important that the pro-
grammer is fully aware of the various forms of an if statement and the rules governing their
use.
Note that it is possible to create if ...else ladders as in the grading problem. Java actu-
ally includes a statement especially for situations like this – switch statement.
switch Selection
We have seen that the when one of the many alternatives is to be selected, we can design
a program using if statements to control the selection. However, the complexity of such
a program increases dramatically when the number of alternatives increase. The program
becomes difficult to read and follow. At times, it may confuse even the designer of the pro-
gram.
Fortunately, Java has a built-in multi-way selection statement known as switch. The
switch statement tests the value of a given variable (or expression) against a list of case val-
ues and when a match is found, a block of statement associated with that case is executed.
The general form of the switch statement is as shown below:
s w i t c h (expression){
case value1:
block1
break;
case value2:
block2
break;
case value3:
block3
break;
........................
........................
........................
case valueN :
blockN
break;
default:
default_block
break;
}
statementX
value of the expression, then the block of statements that follows the case are executed.
The optional break statement at the end of each block signals the end of a particular
case and causes an exit from the switch statement, transferring the control to the statementX
following the switch.
The default is optional. When present, it will be executed if the value of the expression
does not match with any if the case values. If not present, no action takes place when all
matches fail and the control goes to the statementX following the switch.
Notice the inclusion of the break instructions at the end of each block. This is necessary
because if for example we did not include it after block1 the program would not jump to
the end of the switch selection block (i.e. statementX ) and it will follow executing the rest
of the blocks of instructions until the first appearing of the break instruction or the end of
the switch statement block. This (usually) unintended consequence is called afall-through.
This makes it unnecessary to include curly brackets ({}) in each of the cases, and can also
be useful to execute one same block of instructions for different possible values of the ex-
pression evaluated.
The switch statement can be used to grade the students as discussed in the last section.
This is illustrated below:
....................................................
....................................................
....................................................
where index is defined as an integer. The variable index takes the following integer values.
marks index
100 10
90 – 99 9
80 – 89 8
70 – 79 7
60 – 69 6
50 – 59 5
40 – 49 4
30 – 39 3
20 – 29 2
10 – 19 1
0–9 0
grade = ‘A’;
break ;
Secondly, case 4 uses an if statement. Since index = 4 comprises two different grade
letters (D and E), an if statement is used to determine whether the grade is D or E.
Finally, default condition is used for all other cases where marks is less than 40.
i f (x < 0)
flag = 0;
else
flag = 1;
can be written as
flag = (x < 0) ? 0 : 1;
The conditional operator may be nested for evaluating more complex assignment de-
cisions. For example, consider the weekly salary of a salesperson selling some domestic
products. If x is the weekly number of products sold in a week, the salesperson’s salary is
given by
4x + 100 if x < 40
salary = 300 if x = 40
4.5x + 150 if x > 40
i f (x != 40)
i f (x < 40)
salary = 4 * x + 100;
else
salary = 4.5 * x + 150;
else
salary = 300;
When the conditional operator is used, the code becomes more concise and perhaps,
more efficient. However, the readability is poor. It is better to use if statements when more
than a single nesting of conditional operator is required.
Repetition Structures
A repetition structure (also called a looping structure or loop) allows the programmer to
specify that a program should repeat an action while some condition remain true.
A looping process, in general, would include the following four steps:
The test may either be to determine whether the loop has been repeated the specified num-
ber of times or to determine whether a particular condition has been met. The Java lan-
guage provides for three construct for performing loop operations – while, do...while and
for statements.
while Repetition
The simplest of all the looping structures in Java is the while statement. The basic format
of the while statement is
w h i l e (condition)
statement ;
where condition is a boolean expression and statement is any executable statement. If the
value of the expression is false then the statement is ignored and the program execution
immediately jumps to the next statement that follows the while statement. If the value of
the condition is true then the statement is executed repeatedly until the condition evaluates
to false .
Consider the following code segment
...............................................
...............................................
...............................................
sum = 0;
n = 1;
w h i l e (n <= 10){
sum = sum + n * n;
n = n + 1;
}
System.out.println(" Sum = " + sum);
...............................................
...............................................
...............................................
The body of the loop is executed 10 times for n = 1, 2, . . ., 10 each time adding to the square
of the value of n, which is incremented inside the loop. The test condition may also be
written as n < 11; the result would remain the same.
do...while Repetition
The do...while statement is essentially the same as the while statement, except the its
continuation condition is moved to the end of the loop. As a consequence, a do...while
loop will always iterate at least once (a while loop may not iterate at all).
The syntax for the do...while statement is
do
statement
w h i l e (condition);
observe the semicolon after the closing parentheses of the condition. Consider the following
code fragment:
...............................................
...............................................
...............................................
sum = 0;
i = 1;
do{
sum = sum + i;
i = i + 2;
} w h i l e ((sum < 40) || (i < 10));
System.out.println(" Sum = " + sum);
...............................................
...............................................
...............................................
The loop will execute as long as one of the two relations is true.
for Repetition
The format for the for statement is
f o r (initialization; condition; update)
statement ;
where initialization, condition, and update are optional expressions, and statement is any
executable statement. The three-parts (initialization; condition; update) controls the loop.
The initialization expression is used to declare and/or initialize control variable(s) for the
loop; it is evaluated first before any iteration occurs. The condition expression is used to
determine whether the loop should continue iterating; it is evaluated immediately after the
initialization; if it is true, the statement is executed. The update expression is used to update
the control variables(s); it is evaluated after the statement is executed. So the sequences of
events that generate the iteration are:
Step 2: if the value of the condition expression is false , terminate the loop;
Optionally, using the comma operator (,) we can specify, more than one instruction in
any of the fields included in a for loop, like in initialization, for example. The comma opera-
tor (,) is an instruction separator, it serves to separate multiple instructions in a place where
one instruction is generally expected. For example, suppose we want to initialize more than
one variable in our loop:
1 p u b l i c c l a s s TestForLoop{
2 p u b l i c s t a t i c v o i d main(String args[]){
3 f o r ( i n t n = 0, i = 100; n != i; n++, i−−){
4 System.out.println("n = " + n + ";\ ti = " + i);
5 }
6 }
7 }
Portion of last part of the output of the program above is shown below.
n = 44; i = 56
n = 45; i = 55
n = 46; i = 54
n = 47; i = 53
n = 48; i = 52
n = 49; i = 51
Exercise 1: Write a for , do...while and while statements to compute the following sums
and products
(a) 1 + 2 + 3 + · · · + 100
(b) 5 + 10 + 15 + · · · + 50
(c) 1 + 3 + 7 + 15 + 31 + · · · + (220 − 1)
1 1 1 1
(d) 1 + + + +···+
2 3 4 15
(e) 1 × 2 × 3 × 4 × · · · × 20
(f) 1 × 2 × 4 × 8 × · · · × 220
Exercise 2: Rewrite the following nested for statements, using nested do...while and while
statements
(a)
i n t sum = 0, number = 0;
f o r ( i n t i = 0; i <= 10; i++)
f o r ( i n t j = 10; j >= i; j−−){
number++;
sum += j − 1;
}
(b)
i n t product = 1, number = 0;
f o r ( i n t i = 1; i < 5; ++i)
f o r ( i n t j = 10; j < 5; j++){
number++;
product *= number;
}
Exercise 3: Write a program to find the number of and sum of all integers greater than 100
and less than 200 that are divisible by 7.
(Either)
i) Marks in Mathematics >=60
ii) Marks in Physics >=50
iii) Marks in Chemistry >=40
(or)
i) Marks in all three subjects >=200
(or)
i) Total in Mathematics & Physics >=150
Given the marks in the three subjects, write a program to process the application
to list the eligible candidates.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 ... ... ... 21
.
.
.
79 ... ... ... ... ... ... 91
(b) Modify the program to print the following form of the Floyd’s triangle
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
0 1 0 1 0 1
1 0 1 0 1 0 1
0 1 0 1 0 1 0 1
1 1 2 3 5 8 13 21 34 · · ·
are called Fibonacci numbers. Write a program using one of the looping struc-
tures to calculate and print the first n Fibonacci numbers. (Hint: after the first
two numbers in the sequence, each number is the sum of the two preceding
numbers).
Exercise 7: Write a program that print the following outputs using for loops
Exercise 9: (Greatest Common Divisor) A greatest common divisor of two integers a and
b, that are not both zero, is the largest integer that divides both a and b. An
algorithm for finding the greatest common divisor is given below
Algorithm 1 Euclid’s Algorithm for Finding the Greatest Common Divisor of Two Integers
Input: Two non-negative integers a and b
Output: The greatest common divisor of a and b.
1: while b 6= 0 do
2: r ← a mod b
3: a ← b, b ← r
4: end while
5: return (a)
Use algorithm 1 above to create and test a method gcd() that accepts two inte-
gers, calculates an returns their greatest common divisor
Exercise 10: (Extended Greatest Common Divisor) Algorithm 2 is called an Extended Euclid’s
Algorithm and is used for finding the greatest common divisor (d ) of integers a,
b as well as integers x, y ∈ Z such that ax + b y = d .
Algorithm 2 Extended Euclid’s Algorithm for Finding the Greatest Common Divisor (d ) of
Integers a, b and Determining x, y ∈ Z such that ax + b y = d
Input: Two non-negative integers a and b
Output: d = gcd(a, b) and integers x, y satisfying ax + b y = d
1: if b = 0 then
2: d ← a, x ← a, y ← 0
3: return (d , x, y)
4: end if
5: if a < b then . Swap contents of a and b
6: t emp ← a, a ← b, b ← t emp
7: end if
8: x 2 ← 1, x 1 ← 0, y 2 ← 0, y 1 ← 1
9: while b > 0 do
10: q ← ba/bc, R ← (a − q ∗ b), x ← (x 2 − q ∗ x 1 ), y ← (y 2 − q ∗ y 1 )
11: a ← b, b ← R, x 2 ← x 1 , x 1 ← x, y 2 ← y 1 , y 1 ← y
12: end while
13: d ← a, x ← x 2 , y ← y 2
14: return (d , x, y)
Use algorithm 2 above to create and test a method extGcd() that accepts two
integers, calculates an returns their greatest common divisor d , integers x, y ∈ Z
such that ax + b y = d .
Exercise 11: (Divisible) Write and test a function isDivisible() that accepts two integers,
determines and return whether the first integer argument is divisible by the sec-
ond integer argument.
Exercise 12: (Prime, Composite) An integer p ≥ 2 is said to be prime if its only divisors are 1
and p itself. Otherwise p is called composite. Write and test functions isPrime()
Exercise 13: (Coprime or Relatively Prime) Two integers a and b are said to be relatively
prime or coprime is gcd(a, b) = 1. Write and test a function isCoprime() that
accepts two integers, determines and returns whether they are coprime or not.
Exercise 14: (Euler Phi Function (φ)) For n ≥ 1, let φ(x) denote the number of integers in the
interval [1, n] which are relatively prime to n. The function φ is called the Euler
phi function (or Euler totient function). Write and test a method eulerPhi()
that accepts an integer n, calculates and returns φ(n).
Exercise 15: (Number of Divisors (τ)) The number of divisors function, denoted by τ, is de-
fined as τ(n) is the number of positive divisors of n. Write and test a method
noOfDivisors() that accepts an integer n, calculates and returns τ(n).
Exercise 16: (Sum of Divisors (σ)) The sum of divisors function, denoted by σ, is defined
as σ(n) is the sum of all the positive divisors of n. Write and test a method
sumOfDivisors() that accepts an integer n, calculates and returns σ(n).
Exercise 17: (Perfect Number) A perfect number is a positive number that is equal to the sum
of its divisors. A proper divisor is a positive integer other than the number itself
that divides the number evenly (i.e., no remainder). For example, 6 is a perfect
number because the sum of its proper divisors – 1, 2 and 3 – is equal to 6. 8 is
not a perfect number because 1 + 2 + 4 6= 8. Write an application program that
accepts a positive integer and determines whether the number is perfect. Also,
display all proper divisors of the number. Try a number between 20 and 30 and
another between 490 and 500.
Exercise 18: Write a program that displays all integers between l (lower) and u (upper) that
are the sum of the cube of their digits. In other words, find all numbers x y z such
that x y x = x 3 + y 3 + z 3 , for example 153 = 13 + 53 + 33 . Try l = 100 and h = 999.
Exercise 19: (Reversing Digits) Write and test a method reverseDigits() takes an integer
value and returns the number with its digits reversed. For example, given the
number 7534, the method should return 4357.
Exercise 20: (Factorial) Write and test a method factorial() that accepts an int type n,
calculates and returns n!, where n! = 1 × 2 × 3 × 4 · · · × (n − 1) × n.
Exercise 21: (Combination) Write and test a method comb() to calculate the combination
of n objects taking r objects at a time. Use the formula
n!
C (n, r ) =
(n − r )!r !
Exercise 22: (Permutation) Write and test a method comb() to calculate the permutation of
n objects taking r objects at a time. Use the formula
n!
P (n, r ) =
(n − r )!
Exercise 23: (Ulam Numbers) The Ulam numbers u n , n = 1, 2, 3 . . . are defined as follows. We
specify that u 1 = 1 and u 2 = 2. For each successive integer m, m > 2, this integer
is an Ulam number if and only if it can be written as the sum of two distinct
Ulam numbers. These numbers are named after Polish Stanislaw Ulam (1909 –
1984) who first described them in 1964. Write a program that accepts an integer
n, finds and displays the first n Ulam numbers.
i n t n = RandomVariable.nextInt();
i n t n = RandomVariable.nextInt(m);
i n t n = a + d * RandomVariable.nextInt(m);
where a is the first term in the range, m is the number of terms in the range and d
is the common difference of the terms. Write an application that simulates coin
tossing. Let the program allow the user to specify the number of times to toss
the coin. Count the number of times each side of the coin appears – use 0 for
heads and 1 for tails. Display the results.
[1] David J. Eck, Introduction to Programming Using Java, Sixth Edition Version 6.0 pre-
release, January 2011
[2] P. J. Deitel & H. M. Deitel, Java How To Program, Eighth Edition, ©2010 Pearson Educa-
tion, Inc.
[3] Doug Lowe, Java All-in-One Desk Reference for Dummies. 4th Edition, ©2014 Wiley Pub-
lishing, Inc., Indianapolis, Indiana
[4] E Balagurusamy, Programming with Java, Second Edition, ©2005 Tata McGraw-Hill Pub-
lishing Company Limited.
[5] John R. Hubbard (Ph.D) Schaum’s Outline of Theory and Problems of Programming with
Java, 2nd Edition, ©2004 Tata McGraw-Hill Publishing Company Limited.