0% found this document useful (0 votes)
10 views

csc2321 Lecture 2 Java

Java program lecturenote 1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

csc2321 Lecture 2 Java

Java program lecturenote 1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Mansur Babagana

Department of Computer Science


Bayero University, Kano

February 21, 2017


C ONTENTS

Contents i

1 I NTRODUCTION 1
1.1 Java Platform & Java Virtual Machine . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 I NTRODUCTION TO J AVA A PPLICATION P ROGRAMS 3


2.1 Structure of a Java Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Creating/Running a Java Application . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 J AVA L ANGUAGE B ASICS 18


3.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.4 Declaration of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.5 Assigning Values to Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.6 Wrapper Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.7 Scope of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.8 Symbolic Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.9 Type Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.10 Getting Values of Variables – Output . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.11 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.12 Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.13 Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

4 Exercises 58

i
CHAPTER
1
I NTRODUCTION

1.1 Java Platform & Java Virtual Machine


A computer program is a series of instructions that a computer executes in order to
achieve a specific task. Computer programs are written in a Computer Programming Lan-
guage. Machine Languages consists of simple instructions (usually written as 0s and 1s) that
can be directly executed by a computer. But almost all programs are written in high-level
programming languages like Fortran, BASIC, C++ , or Java.
A program written in a high-level language cannot be run directly by a computer, it must
first be translated into machine language. Programs that converts a program written in high-
level language to a machine language are called translators. There are two main types of
translators – compilers and interpreters.

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.

Interpreters: An interpreter is a translates a program instruction-by instruction. In order


to execute a program the interpreter runs in a cycle in which it repeatedly reads one
instruction from the program, decides what is necessary to carry out that instruction,
and then performs the appropriate machine-language commands to do so.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 1 of 64


CHAPTER 1. INTRODUCTION
1.1. JAVA PLATFORM & JAVA VIRTUAL MACHINE

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 2 of 64


CHAPTER
2
I NTRODUCTION TO J AVA
A PPLICATION P ROGRAMS

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.

2.1 Structure of a Java Application


The best way learn features of a programming language is to write and dissect a simple
sample program written in that language. So we now look at a simple program that dis-
plays “Welcome to Java Programming” without the quotes. The line numbers in all our
programs are for references only and not part of the source code.
1 p u b l i c c l a s s FirstJavaApp{
2

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

7 } /* closing for FirstJavaApp */

The output of the above program is shown below


Welcome to Java Programming!

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 3 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.1. STRUCTURE OF A JAVA APPLICATION

We now dissect the program line by line.

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 2: is a blank line to make the program more readable.

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 4: System.out.println("Welcome to Java Programming!"); – is the only executable


statement of our sample program. The line begins with System.out.println
which outputs whatever is in the parenthesis that follows, in this case "Welcome
to Java Programming!" – without the quotes.

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 6: is a blank line to make the program more readable.

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.

To recap, a typical Java application template is

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 4 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

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.

2.2 Creating/Running a Java Application


Java Platform uses a two step process – namely:

• The source code is compiled into a byte-code,

• the byte-code is interpreted on a JVM.

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).

Using a Command Line


To create a Java application from a command line:

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:

On a Linux System: gedit MyFirstJavaApp.java

On a Windows System: notepad MyFirstJavaApp.java

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 5 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

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 1: Type gedit Greetings.java

Step 2: gedit text editor open with an empty file named Greetings.java

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 6 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Step 3: Type the code of the program in the gedit text editor

Step 4: Type javac Greetings.java in the console to compile the program

Step 5: Type java Greetings in the console to run the program

Step 6: The output of the program is displayed in the console screen

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 7 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Using an Integrated Development Environment (IDE)


An integrated development environment (IDE) also known as integrated design envi-
ronment or integrated debugging environment is a software application that provides com-
prehensive facilities to computer programmers for software development. An IDE normally
consists of:

• a source code editor

• a compiler and/or an interpreter

• build automation tools

• 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 2: Create a source file and add it to your program.

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 8 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Creating a Java Application Using Eclipse

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 9 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Step 4: After clicking on the workbench, the workspace is shown

Step 5: To create a new Project click File->New->Java Project

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 10 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 11 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Step 7: Your newly created project is shown in the workspace

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 12 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 13 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Step 10: Your newly created class will be added to your project and the display in the embed-
ded editor for modification

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 14 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 15 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A 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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 16 of 64


CHAPTER 2. INTRODUCTION TO JAVA APPLICATION PROGRAMS
2.2. CREATING/RUNNING A JAVA APPLICATION

Step 14: You can also run the program by pressing Ctrl+F11 key combination or by clicking
the run button in the tool bar

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 17 of 64


CHAPTER
3
J AVA L ANGUAGE B ASICS

A typical Java application template is

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

The source file must be saved as ProgramName.java. A package is a collection of classes


similar to the #include statement in C++. import statements are always the first statements
in a Java program.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 18 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.1. CONSTANTS

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.

Character Constants: A single character constant (or simply a character constant)


contains a single character enclosed within a pair of single quotation marks. ‘2’,
‘#’, ‘N’ and ‘ ’ are examples of character constants. Note that the last example

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 19 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.2. VARIABLES

(‘ ’) 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

String Constants: A string constant is a sequence of characters enclosed between a


pair double quotation marks. The characters may be alphabets, digit, blanks
spaces, special characters or empty. "CSC4313", "BUK", "*123#" and "" are all
valid string constants. The last example ("") is an empty string that contains no
(zero) characters.

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:

1. Identifiers must not start with a digit.

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.

3. An identifier must not correspond to one of Java’s keywords.

4. White (blank) spaces are not allowed.

5. Identifiers can be of any length.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 20 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.3. DATA TYPES

grandTotal, GreetingsFromJava, Nigeria_Good_People_Great_Country, a, x1 and


sum are all valid Java identifiers. Note that, every variable name is an identifier but not all
identifiers are variable names. For example class names are identifiers but they are not vari-
able names.

3.3 Data Types


In Java every variable has a data type. Data types specify the size and type of values that
can be stored. Data types in Java are sometimes categorized into Primitive types (also called
intrinsic or built-in types) and Derived types (also called known as reference types).

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 21 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.4. DECLARATION OF VARIABLES

Type Size Minimum Value Maximum Value


−38
float 4 byte 3.4e−38 (3.4 × 10 ) 3.4e+38 (3.4 × 10+38 )
double 8 bytes 1.7e−308 (1.7 × 10−308 ) 1.7e+308 (1.7 × 10308 )
In Java floating-point numbers are treated as double, to treated floating-point
numbers as as float append the letter F or f at the of the number. For exam-
ple, 123.45F or −.0234f.
Non-numeric Data Types: Non-numeric data types are data type that can hold non-
numeric data. They are divided into two – Character data type and Boolean data
type.
Character Data Type: Character data type is used to store character constants.
Java provides one character data type called char which has a size of 2 bytes
and can hold a single character.
Boolean Data Type: A Boolean data can be used to store only two values – true or
false . A boolean data type is called boolean and uses only 1 byte for storage.

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.

Classes: Classes are used to create user defined data types.


Interfaces: Interfaces are special type of classes used in inheritance used in Java to
simulate multiple inheritance.
Arrays: An array is a sequence of objects which have the same type.

3.4 Declaration of Variables


Variables are names of storage locations. After given our variable a name, we must de-
clare them to the compiler. Declaring a variable achieve three things:

1. It tells the compiler what the variable name is.

2. It specifies what type of data the variable will hold.

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:

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 22 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.5. ASSIGNING VALUES TO VARIABLE

i n t n;
byte b;
double x1, x2;
char a, b;

3.5 Assigning Values to Variable


A variable must be assigned a value after it has been declared but before been used in
any expression. A variable can be assigned values in at least one of three ways.

Using an Assignment Statement

A variable can be given using assignment statement by

variableName = value;

For example,

sum = 0;
product = 1;
x = ‘i’;

A variable can also be assigned a value the moment it is declared as follows:

type variableName = value;

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:

i n t a, b, c; //declare three int variables


double x1=1.2, x2=−3.5; //declares & initializes 2 doubles
f l o a t a, b = 2.3f; //declares a and b and initializes b

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 23 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.5. ASSIGNING VALUES TO VARIABLE

Through the Console (Using Scanner Class)


We have seen how to send output to the console using System.out.println(). Get-
ting an input from the keyboard in Java is not as easy. The easiest to get input is to use the
Scanner class. To use the Scanner class you need to import it using the import statement.
Scanner class is part of the java.util package; util is short for utility. A package is a
collection of classes similar to the #include statement in C++. The use of the Scanner class
for input is best describe by an example. The following example is a program that prompts
for and accepts an integer, prompts and accepts another integer; calculates and prints the
sum.

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

We now take a closer look at the above program line-by-line.

Line 1: import java.util.Scanner; –Before we use the Scanner class we must import
it using import java.util.Scanner;.

Line 2: is a blank line to make the program more readable.

Line 3: indicates the name and opening of our program – TestScanner.

Line 4: the header and opening brace of our main() method.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 24 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.5. ASSIGNING VALUES TO VARIABLE

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 6: declares three int variables – a, b and sum.

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

Table 3.1: Scanner Class Methods for Getting Inputs

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 25 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.5. ASSIGNING VALUES TO VARIABLE

System.out.print() to display the message "Enter an integer: " on the con-


sole. That way, the user knows that the program is waiting for input.

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 12: together with

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.

Line 14: closing brace of our main() method.

Line 15: closing brace of our TestScanner class.

Through an Input Dialog Box (Using JOptionPane Class)


The third way in which variables can be given values is through an input dialog box.
The following program illustrates the use of the JOptionPane class for input, the program
accepts the user’s name and greets the user.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 26 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.6. WRAPPER CLASSES

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;.

Line 5: Creates a String object variable call name.

Line 6: name = JOptionPane.showInputDialog("Enter Your Name :"); reads from the


user a string and assign it to String object variable name.

Method JOptionPane.showInputDialog() displays the input dialog shown above.


The argument to showInputDialog() indicated what the user should type in the
text field. This message is called a prompt, because it directs the user to take a specific
action. The user types characters in the text field, and then clicks the OK button or
presses the Enter key to return the string to the program.

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.

3.6 Wrapper Classes


The input of our previous program is a string: a sequence of character read as text. Com-
puter distinguish between strings and numbers, they are stored differently. For example, the
+ operator works on both types with different results. The expression "12" + "34" is equal
to the string "1234", while the expression 12 + 34 is equal to 46.
Remember JOptionPane.showInputDialog() and nextLine() the Scanner class
return user input as strings, to input numeric data we need to convert what the user inputted
from a string to a numeric data. This is done using Wrapper Classes.
Each of Java’s eight primitive types (boolean, byte, char, double, float , int , long and short)
has a corresponding class called a wrapper class that generalizes the type. Wrapper classes
are defined in the java.lang package which is automatically available, so you can use them
without an import statement. The eight wrapper classes are

Primitive Type boolean byte char double float int long short
Wrapper Class Boolean Byte Character Double Float Integer Long Short

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 27 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.6. WRAPPER CLASSES

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 28 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.6. WRAPPER CLASSES

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

float ⇐⇒Float⇐⇒ String


Function Call Conversion Action
n = Float.parseFloat(s) String object s to primitive float type n
n = x.floatValue() Float object x to primitive float type n
x = new Float(n) Primitive float type n to Float object x
x = Float.decode(s) String object s to Float object x
s = Float.toString(n) Primitive float type n to String object s
s = x.toString() Float object x to String object s

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 29 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.7. SCOPE OF VARIABLES

int ⇐⇒Integer⇐⇒ String


Function Call Conversion Action
n = Integer.parseInt(s) String object s to primitive int type n
n = x.intValue() Integer object x to primitive int type n
x = new Integer(n) Primitive int type n to Integer object x
x = Integer.decode(s) String object s to Integer object x
s = Integer.toString(n) Primitive int type n to String object s
s = x.toString() Integer 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.

3.7 Scope of Variables


Java variables are actually classified into three kinds:

1. Instance variables.

2. Class variables.

3. Local variables.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 30 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.7. SCOPE OF 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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 31 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.8. SYMBOLIC CONSTANTS

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++.

3.8 Symbolic Constants


We often use certain unique constants in a program. These constants may appear re-
peatedly in a number of places in the program. One example of such a constant is 3.142,
representing the value of the mathematical constant “pi” (i.e., π). Another example is the
total number of voters in a ward whose vote-sheets are analyzed by a “vote analysis pro-
gram”. The number of voters say 50, may be used for calculating the percentage of votes.
We face two problems in the subsequent use of the programs. They are:

1. Problem in modification of the program

2. Problem in understanding the program

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 32 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.9. TYPE CASTING

Valid examples of constant declarations are:

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;

Symbolic constants have some unique properties as follows:

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.

3.9 Type Casting


We often encounter situations where there is need to store a value of one type into a
variable of another type. In such situations we must cast the value to be stored by preceding
it with the type in parentheses. The syntax is

type1 variable1 = (type2)variable2;

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 33 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.10. GETTING VALUES OF VARIABLES – OUTPUT

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;

are valid statements.


The process of assigning a smaller type to a larger type is known as widening or promo-
tion, and that of assigning a large type to a smaller one is known as narrowing. Note that
narrowing may result in loss of information.
Note that floating-point constants have a default value of double. What happens when
we want to declare a float variable and initialize it using a constant? Example

f l o a t f = 1.23;

will cause the following compiler error

Exception in thread " main " java.lang.Error: Unresolved


compilation problem:
Type mismatch: cannot convert from double to f l o a t

Above initialization should be written as

f l o a t f = 1.23f;

3.10 Getting Values of Variables – Output


A computer program is written to manipulate a given set of data and and to display or
print the result. We will discuss two ways to output data

Onto the Console (Using print() & println() Methods)


Java supports two output methods that can be used to send results to the screen

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 34 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.10. GETTING VALUES OF VARIABLES – OUTPUT

System.out.print(" CSC4313 : ");


System.out.print(" Programming in Java ");

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

System.out.print(" CSC4313 : ");


System.out.print("\n");
System.out.print(" Programming in Java ");

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

System.out.println(" CSC4313 : ");


System.out.println(" Programming in Java ");

will produce the output

CSC4313:
Programming in Java

The statement

System.out.println();

will print a blank line.

Through Message Dialog Box (using JOptionPane Class)


We can use a message dialog box from JOptionPane class to output information from
our programs. We illustrate the use of method showMessageDialog() of JOptionPane
class via an example. The following program displays a message box with a message "CSC4313:
Programming in Java".

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 35 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.10. GETTING VALUES OF VARIABLES – OUTPUT

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 }

The output of the program above is shown below.

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;.

Line 5: Creates a String object variable call course.

Line 6: Method JOptionPane.showMessageDialog() displays the message dialog shown


above.

The version of of JOptionPane.showMessageDialog() we are interested in takes four


arguments and has the following syntax:

JOptionPane.showMessageDialog( n u l l , message, title, dialog_Type);

We now discuss each of the four parameters

Parameter 1: is always null

Parameter 2: is the message/string to be displayed in the message dialog.

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 36 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

The message dialog types are shown below:

OptionPane constants for showMessageDialog()


Message Dialog Type Icon Description
Displays a dialog that
JOptionPane.ERROR_MESSAGE indicates an error to the
user.
Displays a dialog with an
informational message to
JOptionPane.INFORMATION_MESSAGE
the user. The user can
simply dismiss the dialog.
Displays a dialog that warns
JOptionPane.WARNING_MESSAGE the user of a potential
problem.
Displays a dialog that poses
a question to the user. This
JOptionPane.QUESTION_MESSAGE dialog normally requires a
response, such as clicking a
Yes or a No button.
Displays a dialog that simply
JOptionPane.PLAIN_MESSAGE no icon contains a message, with no
icon.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 37 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

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 }

The output of the program above is shown below.


a = 98.7
b = 6.54
a + b = 105.24
a − b = 92.159996
a * b = 645.498
a / b = 15.0917425
a % b = 0.5999975

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 38 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

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

The following program illustrates the use relational operators.

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 }

The output of the program above is shown below.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 39 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

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

Shorthand Assignment Operators


Assignment operators are used to assign the value of an expression to a variable. We have
already been using the usual assignment operator =. In addition, Java has a set of shorthand
assignment operators which are used in the form

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 40 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

variable op= expression;

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.

Shorthand Assignment Operators


Simple Operator Shorthand Operator
a = a + 1 a += 1
a = a − 1 a −= 1
a = a * (n + 1) a *= n + 1
a = a / (n − 1) a /= n − 1
a = a % 1 a %= 1

The use of shorthand assignment operators has three advantages:

1. What appears on the left-hand side need not be repeated and therefore it becomes
easier to write.

2. The statement is more concise and easier to read.

3. Use of shorthand operator result in a more efficient code.

Increment and Decrement Operators

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;)

The following table summarizes the increment/decrement operators.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 41 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

Increment and Decrement Operators


Operator Called Sample Expression Explanation
Increment the current value of x by
++ Preincrement ++x 1, then use the new value of x in the
expression that contains x.
Use the current value of x in the
++ Postincrement x++ expression that contains x, then
increment x by 1.
Decrement the current value of y by
−− Predecrement −−y 1, then use the new value of y in the
expression that contains y.
Use the current value of y in the
−− Postdecrement y−− expression that contains y, then
decrement y by 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 }

The output of the program above is shown below.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 42 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.11. OPERATORS

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

Where conditional_expression is a boolean expression that is evaluated first and evaluates


to either true or false . If conditional_expression is true expression1 is returned. On the other
hand if conditional_expression is false expression2 is returned.

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,

person.level; // Reference to the variable level


person.cgpa(); // Reference to the method cgpa();

The dot operator is also used to access classes and sub-packages from a package. For
example,

import java.util.Scanner; // access the Scanner class


import javax.swing.*; // access all classes and
// sub−packages under swing

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 43 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.12. MATHEMATICAL FUNCTIONS

3.12 Mathematical Functions


Mathematical functions such as cos, sqrt, log, etc are frequently used in analysis of
real-life problems. Java supports these basic math functions through Math class defined in
the java.lang package. Remember, the java.lang package is automatically available to
all Java applications; so you do not need to import it. The following table list some math
functions defined in the Math class. These functions are used as follows:

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);

Some Math Functions defined inside the Math class


Function Math Description
abs(x) |x| returns the absolute value of x
−1
acos(y) cos (y) returns an angle whose cosine is y
asin(y) sin−1 (y) returns an angle whose sine is y
atan(y) tan−1 (y) returns an angle whose tangent is y
−1 x
x
µ ¶
atan2(x,y) tan returns an angle whose tangent is
y y
ceil(x) dxe returns the smallest integer greater than or equal to x
cos(x) cos(x) returns the cosine of x (x in radians)
exp(x) ex returns the exponential of x
floor(x) bxc returns the largest integer less than or equal to x
log(x) ln(x) returns the natural logarithm of x in base e ≈ 2.7182818
max(a,b) max(a, b) returns the maximum of a and b
min(a,b) min(a, b) returns the minimum of a and b
y
pow(x,y) x returns x raised to power y
rint(x) returns the truncated value of x
sin(x) sin(x) returns the sine of x (x in radians)
p
sqrt(x) x returns the positive square root of x with x ≥ 0
tan(x) tan(x) returns the tangent of x (x in radians)
Note: x and y are double type parameters, a and b may be int s, longs, float s or doubles

The Math class also define two static constant – PI and E with following values:

Math.PI = 3.141592653589793
Math.E = 2.718281828459045

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 44 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

3.13 Control Structures


A program is usually not limited to a linear sequence of instructions. During its process
it may bifurcate1 , repeat code or take decisions. For that purpose, Java provides control
structures that serve to specify what and how to perform our program.
With the introduction of control sequences we are going to have to introduce a new con-
cept: the block of instructions.
A block of instructions is a group of instructions separated by semicolon (;) but grouped
in a block delimited by curly bracket signs: { and }.
Most of the controls structures that we will see in this section allow a generic statement
as parameter; this refers to either a single instruction or a block of instructions, as we want.
If we want the statement to be a single instruction we do not need to enclose it between
curly brackets ({}). If we want the statement to be more than a single instruction we must
enclose them between curly brackets ({}) forming a block of instructions. In Java programs,
a statement block can be used anywhere that a single statement can be used.
In programming there are basically three forms of control, namely Sequence, Selection
and Repetition. The sequence structure is trivial, simply list the statements to execute in the
order in which they should execute.
Most Java control structures are identical to those of C++, with few exceptions which are
explicitly state if and when encountered during our discussion of Java control structures.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 45 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

i f (marks >= 40)


System.out.println(" Passed ");

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,

i f (marks >= 40){


System.out.println(" Passed ");
System.out.println(" Proceed to next level ");
}

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

i f (marks >= 40)


System.out.println(" Passed ");
else
System.out.println(" Failed ");

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{

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 46 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

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

12 System.out.print(" The Largest value is ");


13

14 i f (a > b){ // 1st if


15 i f (a > c){ // 2nd if
16 System.out.println(a);
17 }
18 else{ // else of 2nd if
19 System.out.println(c);
20 }
21 }
22 else{ // else of 1st if
23 i f (c > b){ // 3rd if
24 System.out.println(c);
25 }
26 else{ // else of 3rd if
27 System.out.println(b);
28 }
29 }
30 }
31 }

The output of the program above is shown below, the user input is in bold and underline.

Enter three integers: 122 3223 213


The Largest value is 3223

else...if Ladder

It is possible to create an entire sequence of if ...else statements, which is known as an


else...if ladder. Let us consider an example of grading the first degree students in Bayero
University. The grading is done to the following rule:

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 47 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

Average Marks Grade


70 to 100 A
60 to 69 B
50 to 59 C
40 to 49 D
40 to 44 E
0 to 39 F

This grading can be done using the else...if ladder as follows:

....................................................
....................................................
....................................................
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);
....................................................
....................................................
....................................................

Consider another example given below

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 48 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

............................
............................
............................
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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 49 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

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

where expression is an integer expression or characters, value1, value2, . . . are constants or


constant expressions (evaluated to an integral constant) and are known as case labels. Each
of these values should be unique within a switch statement. block1, block2, . . . are statements
lists and may contain zero or more statements. There is no need to put braces around these
blocks but it is important to note that case labels end with a colon (:).
When the switch statement is executed, the value of the expression is successively com-
pared against the values value1, value2, . . .. If a case is found whose value matches with the

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 50 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

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:

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 51 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

....................................................
....................................................
....................................................

index = marks / 10;


s w i t c h (index){
case 10:
case 9:
case 8:
case 7: grade = ‘A’;
break ;
case 6: grade = ‘B’;
break;
case 5: grade = ‘C’;
break ;
case 4: if( marks >= 45)
grade = ‘D’;
else
grade = ‘E’;
break ;
default : grade = ‘F’;
break;
}
System.out.println(" Grade : " + grade);
....................................................
....................................................
....................................................

Note the we have used a conversion statement

index = marks / 10;

where index is defined as an integer. The variable index takes the following integer values.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 52 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

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

The segment of the program illustrates three important features.


First, it uses empty cases. The first four cases will execute the same statement

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.

The ?: Operator Revisited


As discussed earlier on page 43, the Java language has an unusual operator, useful for
making two-way decision. This operator is a combination of ? and :, and takes three operands.
This operator is popularly known as the conditional operator. The general form of the con-
ditional operator is as follows:

conditional_expression ? expression1 : expression2

The conditional_expression is evaluated first. If the result is true, expression1 is evaluated


and is returned as the value of the conditional expression. Otherwise, expression2 is evalu-
ated and its value is returned. For example, the segment

i f (x < 0)
flag = 0;
else
flag = 1;

can be written as

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 53 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

flag = (x < 0) ? 0 : 1;

Consider the evaluation of the following function



1.5x + 3 if x ≤ 2
y=
2x + 5 if x > 2

which can be evaluated using the conditional operator as follows:

y = (x > 2) ? (2 * x + 5) : (1.5 * x + 3);

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

This complex equation can be written as

salary = (x!=40) ? ((x<40) ? (4*x + 100) : (4.5*x + 150)) : 300

The same can be evaluated using if ...else statements as follows

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:

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 54 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

Step 1: Setting and initialization of a counter.

Step 2: Execution of the statements in the loop.

Step 3: Test for a specific condition for execution of the loop

Step 4: Increment the counter.

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);
...............................................
...............................................
...............................................

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 55 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 56 of 64


CHAPTER 3. JAVA LANGUAGE BASICS
3.13. CONTROL STRUCTURES

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 1: evaluate the initialization expression;

Step 2: if the value of the condition expression is false , terminate the loop;

Step 3: execute the statement;

Step 4: evaluate the update expression;

Step 5: repeat steps 2 – 4.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 57 of 64


CHAPTER
4
E XERCISES

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;
}

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 58 of 64


CHAPTER 4. EXERCISES

(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.

Exercise 4: Admission to a professional course is subject to the following conditions:

(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.

Exercise 5: (Floyd’s Triangle) Shown below is a Floyd’s triangle

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 ... ... ... 21
.
.
.
79 ... ... ... ... ... ... 91

(a) Write a program to print a Floyd’s Triangle.

(b) Modify the program to print the following form of the Floyd’s triangle

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 59 of 64


CHAPTER 4. EXERCISES

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

Exercise 6: (Fibonacci Sequence) The numbers in the sequence:

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

(a) (b) (c)


1 # # # # # 1
2 2 # # # # 2 2
3 3 3 # # # 3 3 3
4 4 4 4 # # 4 4 4 4
5 5 5 5 5 # 5 5 5 5 5

Exercise 8: (Pythagorean Tripes) Pythagorean Tripes is a set of three numbers a, b, c such


that a > b > c and a 2 = b 2 + c 2 . Write a program that accepts integers l and
u representing the lower and upper bound, determines and calculates all the
Pythagorean triples between l and u.

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

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 60 of 64


CHAPTER 4. EXERCISES

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()

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 61 of 64


CHAPTER 4. EXERCISES

and isComposite() that both accept a single integer. isPrime() determines


and returns whether the integer argument is prime, whereas isComposite()
determines and returns whether the integer argument is composite.

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 62 of 64


CHAPTER 4. EXERCISES

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.

Exercise 24: (Random-Number Generation) In Java, a random-number can be generated in


at least ways, either by using the static method random() from the Math class
or by using the Random class in the java.util package. To generate random-
numbers using Random class, you need to first create a Random object using

Random RandomVariable = new Random();

then the following will generate a random-number n with −231 ≤ n ≤ 231 − 1.

i n t n = RandomVariable.nextInt();

While the following will generate a random-number n with 0 ≤ n ≤ m − 1.

i n t n = RandomVariable.nextInt(m);

Random numbers in a range can be generated with

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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 63 of 64


R EFERENCE

[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.

Mansur Babagana MICT[ICT8306] Module 1: Java Primer Page 64 of 64

You might also like