[Go to site: main page, start]

0% found this document useful (0 votes)
7 views99 pages

Understand Java Programming Notes

This document provides an introduction to Java programming, covering its features, platform architecture, and terminology. It outlines the history of Java, its characteristics such as platform independence and object-oriented nature, and details the Java Development Kit (JDK) and Java Runtime Environment (JRE). Additionally, it explains basic Java concepts, naming conventions, and includes exercises for self-assessment.

Uploaded by

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

Understand Java Programming Notes

This document provides an introduction to Java programming, covering its features, platform architecture, and terminology. It outlines the history of Java, its characteristics such as platform independence and object-oriented nature, and details the Java Development Kit (JDK) and Java Runtime Environment (JRE). Additionally, it explains basic Java concepts, naming conventions, and includes exercises for self-assessment.

Uploaded by

yungdenno130
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

LECTURE ONE: INTRODUCTION TO JAVA PROGRAMMING

1.1 Introduction

Welcome to lecture one of Java programming module. In this lecture we will learn typical
features of Java programming language and java platform architecture.

1.1.1 Specific Objectives:

By the end of this lesson you should


be able to:
i. Background
ii. Features of java
programming language iii. Java
Platform

1.3 Lecture outline [Link]


1.3.2. features of java programming language
1.3.3. Java Platform versions
1.3.3. Java Platform architecture

1.3.1. Background
• Java : is a high-level, third generation programming language, like C, Fortran, Smalltalk,
Perl, and many others.
• Java is a programming language created by James Gosling from Sun Microsystems (Sun)
in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
• Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the
steermanship for Java.
• Over time new enhanced versions of Java have been released.
• From the Java programming language the Java platform evolved. The Java platform allows
software developers to write program code in other languages than the Java programming
language which still runs on the Java virtual machine. The Java platform is usually
associated with the Java virtual machine and the Java core libraries.

1.3.2 Features of java programming language

• Platform independent: Java programs use the Java virtual machine as abstraction and
do not access the operating system directly. This makes Java programs highly
portable. A Java program (which is standard-compliant and follows certain rules) can
run unmodified on all supported platforms, e.g., Windows, solaris, macintosh, or
Linux. This can be illustrated in figure1

2
Figure1: platform independence property

• Object-orientated programming language: Except the primitive data types, all


elements in Java are objects.
• Strongly-typed programming language: Java is strongly-typed, e.g., the types of the
used variables must be pre-defined and conversion to other objects is relatively strict,
e.g., must be done in most cases by the programmer.
• Interpreted and compiled language: Java source code is transferred into the bytecode
format which does not depend on the target platform. These bytecode instructions
will be interpreted by the Java Virtual machine (JVM). The JVM contains a so called
Hotspot-Compiler which translates performance critical bytecode instructions into
native code instructions.
• Automatic memory management: Java manages the memory allocation and
deallocation for creating new objects. The program does not have direct access to the
memory. The so-called garbage collector automatically deletes objects to which no
active pointer exists.
• Web access capability: Java can be used to develop Web applications.

1.3.3 Java Platform

Java platform is also is called java software development kit (Jdk) or sdk and it is used to
provide a development environment for building applications, applets and components
using the java language. So far there are two main java platforms (JDK). These are: i)
Java 1 platform and ii) Java 2 platform.

Java 1 platform

This platform had two main releases


i) Java 1.0 was released in 1995
ii) Java 1.1 was released in early 1997 Features

The features of this platform include :


• Event handling model that is based on listeners
• Remote method invocation (RMI) and serialization
• Java database connectivity (JDBC)API for for connecting relations databases

3
• Javabeans component architecture
• Use of applets

Java2 Platform

• Core language plus additional APIs is called the Java 2 platform and it was released in
December 1998.
• There are 3 versions of the Java 2 Platform. These are:

1. Java 2 Enterprise Edition (J2EE) Focuses ecommerce solutions, which can be used to
develop server-side applications such as Java servlets and Java ServerPages. It is used to
develop business applications, web services, mission-critical systems Transaction processing,
databases, distribution, replication Java mail to send and receive mail

2. Java 2 Micro Edition (J2ME): Very small Java environment for smart cards, pages,
phones, and set-top boxes. It has subset of the standard Java libraries aimed at limited size and
processing power. J2ME can be used to develop applications for mobile devices such as cell
phones.

3. Java 2 Standard Edition (J2SE) is used to deploy portable applications for general use.
Java2 SE consists of a virtual machine, which must be used to run Java programs, together with
a set of libraries (or "packages") needed to allow the use of file systems, networks, graphical
interfaces, etc and so on, from within those programs.

Over the years, several Jav2 SE have been released. A summary of various J2SE versions can
be illustrated using the following table:

Version Release date

java2 Standard Edition (J2SE) JDK 1.2 December 1998

java2 Standard Edition (J2SE) JDK 1.3 May 2000

java2 Standard Edition JDK 1.4 (Java SE 6) Feb 2002

java2 Standard Edition JDK 1.5 (Java SE 5) September 2004

java2 Standard Edition JDK 1.6 (Java SE 6) December 2006

java2 Standard Edition JDK 1.7(Java SE7) July 2011

java2 Standard Edition JDK 1.8 (Java SE 8 2014

Table 1: Java2 SE versions

4
In this course, we will use java2 Standard Edition JDK 1.8, which is the current version of
Java 2 Standard Edition.

1.3.4 Java Platform architecture

A Java distribution typically comes in two flavors, the Java Runtime Environment (JRE) and
the Java Development Kit (JDK).

i) Java Runtime Environment (JRE)

The Java runtime environment (JRE) consists of the JVM and the Java class libraries. Those
contain the necessary functionality to start Java programs. There two key technologies of
deploying JRE: i). Java Plug-in, which enables applets to run in popular browsers, and; ii)
Java Web Start, which deploys standalone applications over a network.

ii) Java Development Kit (JDK).

The JDK additionally contains the development tools necessary to create Java programs. The
JDK therefore consists of the following components:

Java compiler(Javac): is the progam module that Converts Source code written by
programmer to bytecode. When java programs are run the bytecode produced by the
compiler is fed to an interpreter that converts it to machine code for a particular CPU e.g a
Pentium cpu

Java Virtual Machine (JVM) is an abstract computing software that loads and interprets
bytecode (class files) to machine code.

JVM Software runs on top of a real hardware and it allows A single java application to run on
different machines where the VM is available. This makes Java to be machine independent.
This can be illustrated using figure2

Figure2: JVM Software


There are two components of JVM. These are:

• JIT (just in time) compilers, which attempt to increase speed of compiling bytecode to
machine language(native language).

5
• Java Interpreter : A converts one instruction or line of code from bytecode to machine
code and then executes that instruction.
The following figure illustrates the two components of JVM

Fig3: Components of JVM

1.4 End of lecture activities

1.4.1 Activity 1: Exercise

Differentiate the difference between the following Java versions i)


J2SE
ii) J2ME
iii) J2EE

1.4.2 Activity1: Solution


i) J2SE: for developing applications that can run personal computers
ii) J2ME: for developing applications that can run mobile devices iii)
J2EE: for developing applications for networked environment

1.5 Self Assessment Questions

i) Discuss components of JVM


ii) Explain the difference between JDK and JRE

1.6 Suggestion for further reading

Vogel,L.(2014). Introduction to Java programming - Tutorial. Retrieved from:


[Link]

6
LECTURE TWO: JAVA TERMINOLOGY

2.1 Introduction

Welcome to lesson two of Java programming module. In this lecture we will learn Terminologies
used in Java programming language

2.1 Specific Objectives:


By the end of this lesson you should be able to:
i) Definition of java basic concepts ii).
Understand naming conventions

2.3. Lecture outline


2.3.1. Definition of java basic concepts
2.3.2. Naming convections

2.1.1 Definition of java basic concepts

Code or source code: The sequence of instructions in a particular program written by a developer.
Output: The messages printed by the computer program.
Console: The text box or window onto which output is printed.
Compiler: a program that converts a program in one language to another language e.g compile
source code to bytecode
Java core language: the language used to write a java program which is compiled to byte code
Bytecode: a language for an imaginary cpu

Class
A class is a description of properties (variables) and subroutines (methods) to operate on
those properties. The class definition can be used as a model or blueprint for creating
objects(i.e actual examples of the class). The behaviour of the class is defined as methods that
operate on the attributes of the class. Attribute values are stored as variables, either for a specific
instance of the class (instance variables) or as variables shared by all instances of the class (class
variables).
The class definition includes the following components:
1. Package name: Name of the package where this class belongs.
2. access modifier Keyword to specify how external access to this class is managed. Options
include public or private.
3. Class keyword to specify that it as a class. this is a mandatory keyword.
4. Instance variables : are variables defined outside of a method and available to all methods
in the class.
5. Class variables: refers to variables defined with the static keyword. Such a variable is
shared by all instances of the class. they are also known as static variables.

6. Instance variables are created when the class is loaded initially and can be set and accessed
even before new instances of the class are created.
.
7. Local variables: are variables defined inside a method. The variable scope is inside the
method where it is declared.

10
8. Instance methods: refers to functions (subroutines) that operate on instances of the class.
They are also called non-static methods
9. Class methods: Functions (subroutines) that operate on class variables of the class. They
are also called static methods.

10. ._Constructors Methods that have the same name as the class and are automatically called
11. to create new instances of the class (initialise instance variables).

Fig 2.1: class definition

Packages

Java uses ―packages‖ to both group related classes and ensure that potential namespace conflicts
are minimized. Each class resides in a package – if the class does not include a package specifier,
the class is a member of the default package. Each Java class is fully qualified by the fully qualified
class name, which consists of the package name and the class name, concatenated with dot
notation.
For example: [Link]

This statement specifies fully qualified name of the Object class. The [Link] package is included
in every java class by default.

11
One generally accepted convention for package naming is to use the author‘s internet domain name
as the initial components of the package name. Furthermore, the initial portion of the package name
is often uppercased.

For example, packages created for use by Microsoft, with their domain name of ‗[Link]‘,
would typically have a package name of ―[Link]‖. If Microsoft were to create a class
called ―Customer‖ for their ―licence‖ subsystem, the fully qualified class name would be
―[Link]‖. Package names of ―java‖, ―javax‖ and ―sun‖ are reserved for
java language .

Method:
A method is a named sequence of statements that can be executed together to perform a
particular action or computation. Each method is defined within a class, and can be equivalent
to a subroutine, a procedure or a function in other programming languages. For each method,
the following forms part of the definition:

1. Access modifier is a Keyword for specifying how external access to this method is
managed. Examples of access modifiers include:
i. public - accessible from other classes
ii. private - not accessible outside this class iii.
protected - accessible from sub-classes of this class
iv. default - accessible from other classes in the same package (the default keyword does not
appear but is assumed).
2. Return type: The data type returned by this method. If the method does not return a value,
the data type void must be used.
3. Method name The name of the method.
4. Arguments are comma separated list of values passed as parameters to a method.
5. Method body Java statements that provide the functionality of this method.

Statement:
An executable piece of code that represents a complete command to the computer.
every basic Java statement ends with a semicolon(;)
Statements may be Java statements (variable declaration, assignment, logic statements) or
references to methods within the same or another class.
Compound statements are contained within a code block, delimited by braces.
Multiple statements can appear on a single line of source code, provided that each statement is
delimited with a semi-colon. This is not good practice for coding clarity reasons and should be
avoided whenever possible.

Examples
private String employeeName;
private float salary;;
Code blocks
The body of a method appears as a code block, a set of Java statements enclosed within curl brackets or
brace characters ({and}).
Example: The following figure shows an example of code block enclosed with curl brackets or
brace characters ‗{}‘. Each statement in a code block is terminated with semi colon(;)

{
[Link]("Hello, World"); employeeName
= "Jeremy";

12
showMessage("Hello, from a method"); }

2.3.2 Naming Convections


Files: Source code are stored in files with the .java extension and must use the class name within
the file as the prefix of the file name itself. The compiled classes are stored in a file with a .class
suffix – the prefix must again be the same as the name of the initial class held within the file.

Classes
Class names should be nouns. The first letter of each word in the class name should be capitalised.
For example, OrderLine.

Methods
The name of each method is typically a verb. The first letter of the method name should be
lowercase; the first letter of subsequent words should be capitalized. For example,
getClientName().

Variable(also known as identifier)


A variable name should be short but descriptive, avoiding where possible the common variable
names like i and j etc.. Use the same mixed case as for method names.
Example:
employeeTaxCode.

13
2.4 End of lecture activities

2.4.1 Activity 1: Exercise


Distiguish between a class,package and a method
2.4.2 Activity 2: Exercise
Describe naming convection of a method

2.4.1 Activity1: Solution


A class: is an executable code that describes properties and state of an object A
package is a collection of one or more related classes
Method: is a sequence of statements that performs a single task

2.4.2 Activity2: Solution


The name of each method is typically a verb that indicates the tasks to be performed by
the method

2.5 Self Assessment Questions

i) Describe 4 naming conventions(or rules) of a variable


ii) List examples of packages names that are reserved for java language

2.6 Suggestion for further reading

Java language structure


[Link]

LECTURE THREE: INSTALLATION AND RUNNING JAVA PROGRAMS

14
3.1 Introduction

Welcome to lecture three of Java programming module. In this lecture we will learn how to install
java and run programs.

3.1 Specific Objectives:


By the end of this lesson you should be able to:
ii).Installing Java and IDE i)
Running java programs

3.2 Lecture outline

3.2.1. Installing Java platform.


3.2.2. Installing IDE.
3.2.3. Running Java programs.

3.2.1 Installing Java platform


Before writing any java program, Java development software needs to be downloaded and installed
using the following steps:

Downloading steps

1. Goto Java SE download site using th following web address:


[Link]

2. Click the "Download" button under "JDK" of " Java SE8".


Choose your operating platform, e.g., Windows x86 (for 32-bit Windows OS - "jdk-8u2-windows-
[Link]" 84MB); or Windows x64 (for 64-bit Windows OS).
You can type dxdiag command at command line prompt or at run field to check system
information of your computer.

Installing steps

1. The File Download dialog box appears prompting you to run or save the download file
2. To run the installer, click Run.
3. To save the file for later installation, click Save.
4. Choose the folder location and save the file to your local system.
5. Tip: Save the file to a known location on your computer, for example, to your desktop.
6. Double-click on the saved file to start the installation process.

15
7. The installation process starts. Click the Install button to accept the license terms and to
Continue with the installation.

Fig 3.1: installing Java

8. By default, the JDK and JRE will be installed into directories "C:\Program
Files\java\jdk1.7.0" and "C:\Program Files\java\jre7", respectively.
9. For beginners, accept the defaults.

3.3.3 Installing IDE


These are set of developments tools that give a windowing interface to the edit/compile/run or
view program output. Some of these tools provide environments that can also track projects and
help generate code for user interface components. Examples are:
• Eclipse
• NetBeans Open Source by Sun
• Eclipse Open Source by IBM
• Microsoft Visual J++
• Symantec Visual Café
• Java Workshop from Sun
• Borland Jbuilder

In this course, we are going to use eclipse to develop java programs

Downloading eclipse

1. Download Eclipse from the following website: [Link] .


2. Click on "downloads" in either the main panel or the navigation panel;
This will bring a page for selecting either the Main Eclipse download site or one of several
mirrors.
3. Download ―Latest Release.― as indicated in the download page.
4. Unzip the file and double-click [Link].
5. NB: Before installing Eclipse, ensure you have already installed Java SDK.

16
3.3.2. Writing and Running Java programs using eclipse To
write a program using eclipse, use the following steps:

a) create a new project


1. Start Eclipse.
2. Create a new Java Project:
3. File->New->Project.
4. Select "Java" in the category list.
5. Select "Java Project" in the project list. Click "Next".
6. Enter a project name into the Project name field, for example, "Hello World Project".
7. Click "Finish―.

b). Create a new java class

1. Click File menu.


2. Select New.
3. Then select class.
This can process can illustrate using the following figure:

Fig3.2: process for creating a java class

17
4. In the dialogue box that appears ensure the package name is the name of your project

Fig3.3: Naming a class

5. Write the name of your class into the Name field. E.g Greetings

6. Click the checkbox indicating that you would like Eclipse to create a "public static void
main (String[] args)" method.

7. Click "Finish".

Step3: writing a simple program

8. A Java editor for [Link] will open. In the main method enter the following line.

[Link]("Hello World");
[Link]("Welcome to KCA University");

9. Save using ctrl-s. This automatically compiles [Link].


10. Click the "Run" button in the toolbar.

18
11. You will to run the Hello World program.

12. The console will open and display "Hello World" as shown in the following figure.

Fig 3.5 : writing a simple program

19
3.4 End of lecture activities

3.4.1 Activity 1: Exercise


Install java and eclipse in your computer

3.4.1 Activity 2: Exercise

i. Use eclipse to create a new Project known as Focim ii. In the focim project, create a
new java class known as Courses iii. Add java code in courses class that displays a list
of Degree courses offered by Focim as shown below :

Courses offered
1. Bsc IT
2. BBIT
3. Msc Data coms

3.4.1 Activity1: Solution


Successful Installation of java and eclipse

3.4.2 Activity2: Solution


Package focim
Public class courses{
Public courses(){
}
Public static void main(String [] args)
{[Link](― Courses offered‖);
{[Link](― BSC IT‖);
{[Link](― BBIT ‖);
{[Link](― Msc Data coms ‖); }
}

3.5 Self Assessment Questions

i). Describe the meaning of the term ‗Integrated development environments(IDE)‘ as used

20
in java programming. ii). Discuss any three examples of IDE that can be used to create java
programs

3.6 Suggestion for further reading

i. How do I manually download and install Java for my Windows computer?

Java [Link]

21
LECTURE FOUR: PROGRAMMING ERRORS AND IDENTIFIERS

4.0 Introduction

Welcome to lecture four of Java programming module. In this lecture we will learn types of
programming errors and identifiers.

4.1 Specific Objectives:


By the end of this lesson you should be able to:
ii).Understand types programming errors in java
i) Understand identifiers

4.3. Lecture outline


4.3.1. Types programming errors in java
4.3.2. Identifiers

4.3.1 Types programming errors in java

There are three types of programming errors. They include:-


1. Syntax errors
2. Run time errors
3. Logic errors

1. Syntax errors
These are errors that occurs when the compiler does not understand the code written (source code).
Syntax error causes the compiler to fail.
It is also called compiler error or grammatical errors Example:
[Link]("Hello, world!")_

Syntax errors in the above example statement include a)


A missing semi-colon at the end of the statement.
b) one spelling mistake at: 'owt'

2. Run time errors


• An error that occurs when a program is actually running.
• A run-time error causes a running program to stop immediately, and print an error message.
• The program should compile with no errors, but when the program runs, it crashes--maybe with a
message "encountered a problem and needs to close" .
The message indicates that the program did something that the Windows operating system won't
allow.

22
For example:
int x=1
int y = 0;
Avg= 1/y;

In this example, program includes an arithmetic expression x/y, and y happens to be zero—then a
run-time error will occur when the expression x/y is encountered. But, this error only occur when
a program is actually running.

Logic Error
The program consists of logic error if it produces wrong results. The program compiles correctly,
and runs without producing a run-time error. These errors, also called ―program bugs‖ They are the
toughest errors to find and eliminate. Example1:
int x; x =
x + 1;
[Link]("X = " + x);
... would produce unpredictable results (the value of x is some random number)

To fix the problem, initialize the value stored in x to a known value (like 0) ...

int x=0;
x = x + 1;
[Link]("X = " + x);

Example2:
Missing the "main" method
All java applications must have a main( ) method that has the following form ...

public static void main (String []args)


{
}
If you mistype any part of this line or miss out a keyword, then a run-time error will be generated.

For example, if you omit the keyword static then an error message of the form:
Exception in thread main.....
will be generated at run time.

Example3:
The Java programming language follows the Mathematic order of operations (BEDMAS) and it is a
common programming error to omit brackets when doing math opeartions.

For example3: x = a * b + c; may result in a different value stored in x then would ...

x = a * (b + c);

23
4.3.2. Identifier
• A name that is given to a piece of data or part of a program.
• Identifiers are used for referencing data or code later in the program.
• Identifiers give names to:
1. Classes
2. Methods
3. Variables (named pieces of data; seen later)

Identifiers Rules
1. First character must be a letter or _ or $
2. Following characters can be any of those characters, underscore symbol or a number
3. Identifiers are case-sensitive; name is different from Name
4. Cannot be a reserved word-these are valid identifiers that have special significance to a
programming language.
5. Name should be meaningful: reflect the function of the variable
6. There should be white space between characters

Examples of legal Java identifiers


• olivia
• second_place
• _myName

Examples of Illegal identifiers


• me+u
• :-)
• question?
side-swipe

Keywords keyword is an identifier that you cannot use, because it already has a reserved meaning
in the Java language.

Examples:
abstract, default, if, private, this,
boolean, do, implements, protected, throw, break,
double, import, public, throws, byte,
else, instanceof, return, transient, case,
extends, int, short, try,
catch, final, interface,

24
4.4 End of lecture activities

4.4.1 Activity 1: Exercise


state whether the following identifiers are legal or
illegal and give reason
$variable ph.d
TheCure
belles's
2%milk
ANSWER_IS_42

4.4.1 Activity 2: Exercise


Identify two syntax errors in the following java code

[Link]("Hello, world)

4.4.1 Activity1: Solution


$variable : legal - since it starts with $ ph.d
:illegal- It has period (.) character TheCure :
legal- starts with a letter belles's : illegal -has
apostrophe(') character
2%milk : illegal- it has modulas (%) sign
ANSWER_IS_42 : legal-starts with a letter

4.4.1 Activity2: Solution

1. 's' should be capital


2. missing semi colon at the of the statement The
correct statement is as follows:

[Link]("Hello, world);

4.5 Self Assessment Questions

i). Distiguish between logic error and runtime error. Give one example for each case.
ii).Explain the meaning of the term 'Key word'. Give one example

4.6 Suggestion for further reading

i. Common Logic Errors in Java


[Link]
25
ii Common Syntax Errors in Java
[Link]

LECTURE FIVE: BASIC JAVA SYNTAX

5.1 Introduction
Welcome to lecture five of Java programming module. In this lecture we will learn basic Java
syntax.

5.2 Specific Objectives:


By the end of this lesson you should be able to:
ii).Understand how to write comments ii)
Understand variable declaration
iii) Understand how to store values in variables

5.3 Lecture outline


5.3.1. Comments
5.3.2. Data types
5.3.3. variable declaration
5.3.4. Assignments

5.3.1. Comments
Comment is a note written in the source code by the programmer to make the code easier to
understand.
Usually comments are not executed when a program runs.
Most Java editors turn comments into a special color (e.g green when using eclipse) so that they can
be easily be identified.
Comment is used to help programmers work together since one programmer can understand the
other's code.

Comment syntax
The following symbols can be to enclose comments in java

1.) //
Works only for one line. It causes the remainder of line to be ignored. Example

2.) /* */
These symbols are used for multiple lines comments that are enclosed

26
Using comments
Comments can be used in the following sections of a program.
1. Program header: almost all programs have a "comment header" at the top of each file, naming
the author and explaining what the program does.

2. Beginning of a method: comment is placed at the start of every method, describing the
method's behaviour.

3. Inside a method: comments are placed inside methods to explain particular pieces of code.

Exa mple

Program h eader
5.3.2. Variable declaration
beginning of main
method
5.3.3. Initializatio n and a ssignments

In side main method

5.3.2. Data types

A data type is a set of values and a set of operations defined on those values Data
types that are already defined in java are known as primitive data type The eight
primitive data types supported by the Java programming language are:

byte:
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an int.

27
Example: byte a = 100 , byte b = -50
Short
Short data type is a 16-bit signed two's complement integer. Minimum
value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can be used to save memory as byte data type. A short is 2 times smaller than an int
Default value is 0.

Example: short s = 10000, short r = -20000

Int:
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there is a concern about
memory.
The default value is 0.

Example: int a = 100000, int b = -200000

Long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed. Default
value is 0L.

Example: Long a = 100000L, int b = -200000L

float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.

Example: Float f1 = 234.5f

Double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally the default
choice.
Double data type should never be used for precise values such as currency. Default
value is 0.0d.

Example: Double d1 = 123.4


Boolean
Boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions. Default
value is false.

28
Example: Boolean >

char: char data type is a single 16-bit Unicode


character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive). Char
data type is used to store any character.

Example: char letterA ='A'

5.3.3. Variables

Variable is a piece of computer's memory that is given a name and type and can store a value.
The process of Using variables consists of the following steps:
i. Variable declaration
ii. Putting values into a
variable
iii. Using values in a variable

i. Variable declaration
Variable declaration statement is a statement that creates a new variable of a given type.

Variables must be declared before they can be used.


Declaring a variable sets aside a piece of memory in which you can store a value.
A variable is declared by specifying is data type, and the identifier (name) using the following
format:

< data type> <identifier> ;

Examples:

Int sum;
Double average;

these statements sets aside 2 pieces of memory has no values in it yet as shown in the following
2 figures

Sum average
Multiple declarations per line multiple variables can be declared on one
line using the following format:

<type> <name>, <name>, ..., <name> ;

Examples:
Int sum, position, marks;
Double average,weight,temperature

Syntax errors in variable declaration

29
A compiler error will result if you declare a variable twice, or declare two variables with the same
name. Example: Int marks;
Int marks; // ERROR: x already exists

5.3.4. Assignments
Assignment statement is a Java statement that stores a value into a variable's memory location.
Variables must be declared before they can be assigned a value.
The assignment statement uses the ‘= ‗ character, which means, "store the value on the right in the
variable on the left“

Assignment statement format as follows:

<name> = <value> ;

Example
Marks = 25;
This statement means store 25 in Marks variable.
The memory allocated to marks will now be occupied with value 25 as follows:

Marks 25

A Variable can also be assigned with results of a complex expression as shown in the following
example:
Average = (25 + 15)/ 2;
The memory allocated to average will now be occupied with value 20 as follows:

Average 20

If a variable is assigned a value more than once, the most latest value replaces the previous value.
Example:
int Marks; // declaration Marks
= 3; // first assignment
Marks = 4 + 7; //second assignment
In this example, value 3 is initially assigned to Marks variable and later the results of 4+7 are
assigned to the same variable.
value 3 will therefore be replaced with 11 as shown in this figure: 11 Marks

Assignment and Data types


A variable can only store a value of its own type.

Example: Int
Marks;
Marks = 2; // Marks can only store int value

Initialization
Initialization means setting a value before using the variable.
If no value is assigned prior to use, then the compiler will generate an error.
Java sets basic variables to zero or false in the case of a Boolean variable

30
A variable can be declared and assigned an initial value in the same statement using the following
format:
<type> <name> = <value> ;

Example of declaration and initialization statements;

Double average = 3.95;


Int marks= 20;

Mathematical operators

Arithmetic operators that are used in java programming include


• + addition
• - subtraction
• * multiplication
• / division
• % remaider after division (modulus)
• () Rounded brackets may also be used in matched pairs in expressions to indicate the order
of evaluation

Examples
• Sum=0.0
• Perimeter = 2.0 *(length+breadth);
• Ratio =(a+b) /(c+d);
Increment and decrement operators

Java has an increment operator ++ and a decrement operator -- example


n++ //this statement means decrease the value of n by 1 n-
- // this statement means increase the value of n by 1

5.4 End of lecture activities

5.4.1 Activity 1: Exercise


Write comments explaing the following java statements
Int retVal, index = 2;
Double gamma = 1.2, brightness;

5.4.1 Activity1: Solution

Int retVal, index = 2; //Declare retVal and index variables as integers


// initialize index variable with value 2

Double gamma = 1.2, Brightness; //Declare gamma and brightnes variables as Double
//Initialize gamma with 1.2 value

31
5.5 Self Assessment Questions
i). Categorize each of the following quantities by whether an int or double variable would
best to store it:
Integer (Int) real number (Double)

1. Temperature in degrees Celsius 2. The population of students


3. Your grade point average 4. A person's age in years
5. A person's weight in pounds 6. A person's height in meters
7. Number of miles traveled 8. Number of dry days in the past month
9. Your locker number 10. Number of seconds left in a game
11. The sum of a group members 12. An average of student marks

ii). Write and run the following java


program

in

5.6 Suggestion for further reading

1. Java Basic data types:


[Link]

2. Java Basic Syntax


[Link]

LECTURE SIX: STRUCTURED PROGRAMMING USING JAVA

6.1 Introduction
Welcome to lecture six of Java programming module. In this lecture we will learn how to
implement structured programming methodology using Java language.

6.2 Specific Objectives:


By the end of this lesson you should be able to:
i).Understand structured programming methodology
ii).Understand types of control structures
iii).Understand how to apply control structures in java programming
32
6.3 Lecture outline
6.3.1. Defining structured programming methodology
6.3.2. Elements of structured programming
6.3.3. Types of control structures

6.3.1. Defining structured programming methodology

• Structured programming is a technique of write a program as one or more combined structures


according to a set of rules that prescribe good style habits for programmer.
• The aim of structured programming is to improve clarity, quality, and development time of a
computer program by making extensive use of subroutines, and control structures—in contrast to
using simple tests and jumps such as the goto statement which could lead to "spaghetti code"(i.e
twisted and tangled code) that is difficult both to follow and to maintain.
• A Structure is a program construct with one or more Instructions Combined and has only one
point of entry and one exit.
• Structures are used to specify what has to be done by program, when and under which
circumstances.
• They control the execution or logic flow of a program.

6.3.2. Elements of Structured programming


i. Subroutines: Callable units such as procedures, functions, methods, or subprograms are used
to allow a sequence to be referred to by a single statement. Subroutines are more frequently used to
help make a program that is more structured, e.g. by isolating some particular algorithm or hiding
some particular data access method. If many programmers are working on a single program,
subroutines are one kind of modularity that can help split up the work.

ii. Blocks: Groups of statements to be treated as if they were one statement. Statements in a
block are separated by semicolons ‗;‘, but grouped together in a block enclosed in curl braces: { }
as follows:
{
statement1; statement2;
statement3;
}

iii) Control structures: refers to program construct that defines the order in which the individual
statements, in a program are executed or evaluated.

6.3.3. Types control structures in a program


There are three types of control structures that can be implemented using Java language.
These are:
i. Sequential,: e.g sequence of instructions
i. Selection : (decision ), e.g if, if else, switch ii.
Repetition: (loops) e.g for, while, do while

i. Sequential structure

Sequential structure is a set of statements that are executed one statement after the other order.
Sequential means that program flow moves from one statement to the next.

33
The fact that one instruction follows another in sequence it establishes the control and order of
operations. Figure 6.1 illustrates a sequential structure

Figure 6.1 Sequential structure

Sequential structure example public


class sequence_example

// start of class
{

Public static void main (String[] args)

// start sequence structure


{ int number; number =
2 + 3 * 4;
[Link](number - 1);
[Link](2 * number);
} // end sequence structure }
// end of class

ii. Selection structure


This is a structure that is used to choose among alternative courses of action It
makes decision and executes commands based on that decision.
There are three types Selection
a. if statements,
b. if/else statements
c. switch selection structure

a. If-structure
A structure that allows the next statement to be selected if some condition Is true
Format: if ( condition)
statement;

Example1: The following structure evaluates if the value of x is less than 10 and if it is true then
10 is assigned to variable X
if ( x < 10 ) x = 10;

When more than a single statements are to be executed in case the condition is
true ,a block have to be specified using curl braces { } Format :

if ( conditional_expression )

34
{ statement1;
statement2;
statement3;
}

Example2: The following if structure states that if X is less than 10 then assign 9 to X and finally
increment X by 1 if ( x < 10 )
{ x = 9;
x=++1;
}
b). If/else structure
This statement evaluate an expression and performs an action when condition is true. Otherwise if
the condition is false it performs a different action.

The format:

If ( condition)
{ statement;
}
else
{ statement;
}

Example:
The following program initializes marks variable with value 30,then checks whether the value in
marks variable is equal to 50.
If the condition marks==50 evaluates true, the program prints pass and If the condition marks==50
evlautes false the program prints fail

Results: In this example, the program will print false since the marks value is 30 and instead of
50.

The following figure shows command line output:

Figure 6.1 If/else example results


c). Else if Selection structure
This structure is used to choose between alternatives if they are more than two.
35
Format:

if ( condition1 )
{ statement1; // execute 1st block of statements
} else if
(condition2 )
{ statement2; // execute 2nd block of
statements }

Else
{
Statement 3; // if all previous tests have failed, last block of statements }

Example: the following program initializes X variable with 30, then evaluates whether value of X
is equal to 10.
If it is true, the program prints ―value of x is 10‖
If the condition evaluates false, the program checks whether value of X is equal to 20. If
it is true, the program prints ―value of x is 20‖
If the condition evaluates false, the program checks whether value of X is equal to 30.
If it is true, the program prints ―value of x is 30‖
If the condition evaluates false, the program prints ―this is else statement‖.

After running this program, it will print the following output

d) Switch structure
This is selective structure which is a concatenation of several if and else if structures . "Switch
statements" focus on the value of a particular variable and execute different "cases" accordingly

Format :
switch (selector)
{ case label:
statements;

36
Break; case
label:
statements;
Break;
……………
default :
statements; }

Switch structure uses selector values in choosing the alternative to be executed. If the
selector value matches a given label, the statement following selector values is
executed.
If there is no return or break then Execution moves to the next case.
If the selector value does not match any label, then the structure executes the default
statement
Selector may be an integer or character variable or an expression that evaluates to an integer or
a character.
The case labels must have the same type as the selector and they must all be different. The
statement associated with a case label can be a single statement or a sequence of
statements.

Example: The following Switch structure writes out the day of the week depending on the value of
an integer variable day. It assumes that day 1 is Sunday

switch (day)
{ case 1:
[Link] (―sunday " ); break;
case 2:
[Link] (―Tuesday " ); break;

case 3:
[Link] (―Wednesday " ); break;

case 4:
[Link] (―Thursday" ); break;
case 5:
[Link] (―Friday " ); break;
case 6:
[Link] (―Saturday" ); break;

default : [Link] (―unknown " );


break;

6.4 End of lecture activities

37
6.4.1 Activity 1: Exercise
Write and run the following Java program

6.4.1 Activity1: Solution

This program will print the following output:


Well done
Your grade is a C

38
6.5. Self Assessment Questions

Question1: Convert the following Pseudocode to java


if/else structure

if student‟s grade is greater than or equal to 90


Print “A” else
if student‟s grade is greater than or equal to 80
Print “B” else
if student‟s grade is greater than or equal to 70 Print
“C” else if student‟s grade is greater than or
equal to 60 Print “D”
else
Print “F”

Question 2. Compile and run the program

6.6 Suggestion for further reading

Java Decision Making tutorial


[Link]

LECTURE SEVEN: REPETITION STRUCTURES

7.1 Introduction
Welcome to lecture seven of Java programming module. In this lecture we will learn how to
Repetition structures in the context of structured programming using Java language.

7.2 Specific Objectives:


By the end of this lesson you should be able to:
i).Understand repetition structures. ii).Understand
types of repetition structures
iii).Understand how to apply repetition structures in java programming

7.3 Lecture outline


7.3.1. Defining repetition structures
7.3.2. Types repetition structures

7.3.1. Defining repetition structures

Loops are control structures that repeat a series of statements without re-typing them.
Statements that are repeated are called the body of the loop
39
Loops are commonly used for performing repetitive tasks such as counting,repeated multiplication,
increment, decrementing, keeping track of values (current, previous),repeating a sequence of
commands or actions.

7.3.2. Types repetition structures


There are three types of structures. These are:

a. While loop
b. Do/while loop
c. For loop

a. While Loop structure


This structure repeats the body of a structure if some condition remains True. If
the condition is initially false then the loop body is never executed

Format:

While (condition)
{
Statement;
Statement;
……….;
}

While Loop Example 1: The following java program prints the existing number of students after
checking whether there is enough quorum in bscit class.

When the program runs it prints the following output:

40
While Loop Example 2: The following while statement prints out the numbers 1 to 10.

When the program executes, it prints the following program

b). Do – while statement

In this structure, the body of the loop is executed before the first condition becomes false
The loop is always executed at least once
The statement may be a single statement or a compound statement

Format:

Do
{ statement;
statement;
} while (condition);

Do-while Example1: The above loop produces 1+2+3….+n where a value for n =6 If
the value of n is changed to n= 0 then the value of 1 would be Returned.
This is because the loop is always executed at least once. Therefore, if there is any possibility
that some valid data may require that a loop be executed zero times then a while statement

41
should be used rather than a do while statement.

When the program is executed, it prints the following output:

C) For loop structure


For loop structure is designed for the case where a loop is to be executed starting from an initial
value of some control variable and looping until the control variable satisfies some condition,
meanwhile updating the value of the control variable each time round the loop.

Format:

For(initialise; test condition update control_variable)


{
Statements
}

This statement executes the initialize statement when the for loop is first entered, the test expression
is then evaluated and if true the loop statement is executed followed by the update statement
The cycle of (test;execute-statement;update) is then continued until the test expression evaluates to
false, control then passes to the next statement in the program

Example:

For (i=1; i<10; i++) {


[Link](i);
}

This initialize sets index to 1, index is then compared with 10, if it is less than or equal to 10 then
the statement to output index is executed, index is then incremented by 1 and the condition I <10
is again tested.

Eventually index reaches the value 9, this value is printed and index is incremented to 10.
Consequently on the next test of the condition, the condition evaluates to false and hence exit is
made from the loop.
42
43
7 .5. Self Assessment Questions
i. Explain the following java code and determin e expected output.
ii. Write and run the program.
iii. Check the output to confirm you r answer.

7.6 Suggestion for further reading

Java Loops - for, while and do...while


[Link]

44
LECTURE EIGHT: JAVA IO SYSTEM

8.1 Introduction
Welcome to lecture eight of Java programming module. In this lecture we will learn how to make
use of streams in Java IO system.

8.2 Specific Objectives:


By the end of this lesson you should be able to:
i).Understand streams. ii).Understand
input and output classes
iii).Demonstrate how input and output classes can be applied in Java programming

8.3 Lecture outline


8.3.1. Java IO System Terminology
8.3.2. Streams
8.3.3 Types of Streams

8.3.1. Java IO System Terminology


Java IO system is concerned with getting Input from the Keyboard and its objective of this system
is to make a java program an interactive program. Terminology used in Java IO system can be
explained as follows:

Token: String of characters separated by delimiting character


A token can be a block of text or a single symbol e.g a reserved word (such as int or while), an
identifier (such as b or sum), a constant (such as 25 or "Alice in Wonderland"), a delimiter (such
as {or ;) or an operator (such as + or =).

Parsing the string refers to division of text into a set of discrete parts or tokens, which in a certain
sequence can convey a semantic meaning. The Class StringTokenizer is used to parse strings

A Delimiter is a character used to separate items of data stored on a computer. It is used to tell
computers to finish processing one piece of data and move on to the next one. Most delimiters are
characters that will not be used in the data, such as spaces or commas. Java use Whitespace by
default space. Examples of white space characters include: tab, newline and space.

8.3.2. Streams
Stream is a sequence of characters or bytes that have no fixed length. It provides a connection
between the process that initializes it and an object such as a file which may be viewed as a
sequence of data stream connects a program to an I/O object. Figure 8.1 one illustrates how data
streams can be used to provide a link between a process and input file.

45
Figure 8.1: Stream
Stream class is a class that either delivers data to its destination (screen, file, etc.) or that takes data
from a source (keyboard, file, etc.). It acts as a buffer between the data source and destination Java
has classes InputStream and OutputStream to represent a common super class with the same
methods to read/write data to many different sources console, file, network connection, web page.
Figure 8.2 illustrates how stream class is used to deliver byte stream (data) between sources and
destinations.

Figure 8.2 Stream class

8.3.3 Types of Streams

i) Output stream accepts output from a program and its destination is typically the monitor or a
file.

Figure 8.3 Output stream writing information from a program.

‘out ’ is name of the object for instantiating printStream class which is a sub class of System class
Example of ‗out‘ object: [Link] is the object that displays on the screen and it consists print
and println methods.

ii) Input stream: a stream that provides input to a program which originates at the keyboard or
at a file.

46
Figure 8.4: Input stream Reading information into a program.

Examples of Input stream classes:


i. BufferedReader class gets input from the keyboard using a console.
ii. JOptionPane class gets input from the keyboard using a graphical user interface.
iii. System class provides methods and objects that get input from the keyboard, print text on
the screen, and do file input and output (I/O).
‘in‘ is the name of the object for instantiating inputstream class which is a sub class of System
class.
„[Link]‟ is an object that makes it possible to get input from the keyboard.
‗[Link]‟ has no methods for reading single characters, strings, or numbers at a time. It
has a read method to read a single byte at a time. To be able to read characters, strings, or
numbers, ‗[Link]‟ must be wrapped in other objects.
To turn ‗[Link]‟ into an object that is capable of reading one character at a time, wrap
[Link] in a scanner object:

Format:
Scanner <object_indentifier> = new Scanner([Link]);

iv. Scanner class reads input from the console that is entered by through keyboard
Scanner class accepts data in terms of tokens and it allows a user to enter input values of various
types.
It is defined within a package known as [Link].
The [Link] has to be imported in order to avail the scanner class in the program.
Scanner object is an instance of scanner class and it can be created using the following statement
Scanner sc= new scanner([Link]);

Where:
Sc- The identifier of the object (i.e it can be any name).
Scanner- Class that describes data type of the object.
Scanner()- Constructor for creating the object.
New- Operator for creating objects.
[Link] - Object for accepting inputs.

Need not to mention set of data being input from the console string manipulation is easier Program
logic is simple.

47
Methods defined in Scanner class are:
i. Nextint() method receives the next token from scanner object which can be expressed as an
integer

Format:
Int<variable> = <scanner object>.nextInt();

Example:
Scanner sc = new Scanner ([Link]);
Int a;
a=[Link](); // assign integer to ‗a‘ through scanner object

ii. NextFloat() method receives the next token from scanner object which can be expressed as
float

Format:
Float <variable> = <scanner object>. nextFloat( );

Example:
Scanner sc = new Scanner([Link]); float
a;

a=sc. nextFloat( ); // assign float to ‗a‘ through scanner object

iii. NextLong() method receives the next token from scanner object which can be expressed as a
long data type.

Format:
Long <variable> = <scanner object>. nextlong( );

Example:
Scanner sc = new Scanner ([Link]); long
a;
a=sc. nextlong( ); // assign long to ‗a‘ through scanner object

iv. NextDouble() method This method receives the next token from scanner object which can
be expressed as a Double.

Format:
Double <variable> = <scanner object>. nextDouble( );

48
Example:
Scanner in = new Scanner ([Link]);
Double a; a=in.
nextDouble( );
// this statement assign Double value to ‗a‘ through scanner object

v. Next() method receives the next token from scanner object which can be expressed as a
string

Format:
String <variable> = <scanner object>. next( );

Example:
Scanner in = new Scanner([Link]);
String a; a=in. next( );
// this statement assign string value to ‗a‘ through scanner object

8.4 End of lecture activities

8.4.1 Activity 1 : Exercise


Write and run the following java program

8.4.1 Activity1: Solution

49
8.5.1 Self Assessment Questions

50
8.6 Suggestion for further reading
[Link]

51
LECTURE NINE: ARRAYS IN JAVA

9.1 Introduction
Welcome to lecture nine of Java programming module. In this lecture we will learn arrays in java.

9.2 Specific Objectives:


By the end of this lesson you should be able to:
i).Understand arrays. ii).Describe
dimensions of Arrays
iii).Demonstrate application of arrays in Java programming

9.3 Lecture outline


9.3.1. Arrays
9.3.2. Dimensions of arrays

9.3.1. Arrays
Arrays terminology
Array is a variable that stores many values of the same type and it isdrawn as a row or column of
boxes.
Element: a value in an array.
Index: an integer used to access an element from an array. An index start at zero

Characteristics of array
i. Identifier: the name of the array ii. Elements have the same data type iii. Fixed
length: Arrays sizes cannot be changed during the execution of the code.

Array example: Figure 9.1 illustrates an array that consists of 10 elements


The first element is 12, which is located in index 0 and the last element is 3 which is located in
index 9.

Figure 9.1: Array with 10 elements.

Example2: Figure 9.2 illustrates an array called myarray, which has 8 elements
The data type for these elements is integer
The elements are accessed by their respective index.
Indices of the array start at 0.
In this array, the first element is 3 and it is located in index 0 and the last element is 1 which is in
index 7.

52
Using arrays
The process of using arrays Need to follow 3 steps.
1. Declare the array: specify data type and the identifier
2. Create the array: specify the length of the array 3.
Assigning objects to array: putting data (i.e element).

Declare the array:


Declaring an array involves specifying its data type and the identifier (name). There
are two methods of declaring arrays:
i. Declaration Using Array Literals
ii. Declaration without initialization

i. Declaration Using Array Literals


It is Used when exact size and initial values of an array are known in advance
array-literal is a list of values enclosed in curly braces { }
It is used to initialize the array handle

Example1:
int [] count = { 0,0,0,0}

Results of the above statement can be illustrated using the following figure:

Example2:
Where :

A final means that the variable can only be initialized once, and cannot re-assigned another
value.

Results of the above statement can be illustrated using the following figure:

ii) Declaring Array without initializing


53
This declaration only specifies the data type and name of the array

Example1: The following statement declares myArray to be an array of integers.

int myArray[];

Example2: The following statement declares studentList array to be an array of student data type.

Private Student studentList[];

2. Creating an Array
Creating an array means setting up memory for the already declared array.

Example: The following statement sets up 8 integer-sized spaces in memory,

myArray = new int[8];

Example2: The following statement sets up 10 spaces in memory that can hold references to
student objects

studentList = new Student[10];

An array can be declared and created at once using new operator.

Format :

ElementType [] arrayName = new ElementType [size];

Example:
The following statement assigns and creates an int array known as num which has a space for 5
elements.

Int[] num = new int[5];

The following diagram illustrates the block of memory created by the above statement.

3. Creating and assigning objects to array


54
This involves creating objects and adds them to array:

Example1: The following statements will help to create Student objects and add them to
studentslist [ ] array:

studentList[0] = new Student("Cathy‖); studentList[]


= new Student("Cathy‖, "Computing‖););

Example2: The following statements refer to the array elements by index to store values in them.
myArray[0] = 3; myArray[1] = 6; myArray[2] = 3;

The following figure illustrates the results of the above three statements:
3 6 3 myArray[]=

9.3.2. Dimensions of arrays


The dimension of an array is the number of indices needed to select an element. Arrays
can be classified according to dimensions as follows:

1. One-dimensional array: a list of data (or linear array) whose elements can be accessed
using a single subscript which can either represent a row or column index.

Example: int ArrayName[];

2. Multidimensional arrays: A multidimensional array is an array of arrays. It is an array


with multiples lists of data Examples include:
1. Two-dimensional array 2.
Three-dimensional array.

Two-dimensional array
This is an array whose elements can be accessed using a 2 subscripts.

Two-Dimension array can be declared and created using the following format:

Type array_name = new type[rows][cols];

Example: The following statement declares 2 dimensional array with 10 rows and 5 columns

Double [][]sales = new Double[10][5];

The following figure illustrates the block of memory created by the above statement
55
that can either rep resent a row or column index.

Three-dimension array

This is an array whose elements can be accessed using a 3 subscripts.


It can be declared and created using the following format:

Type array_name = new type[rows][cols][Depth];;

Example1 : This statements declares 3D array of integers with 3 rows and 5 columns multiplied
by 2 . i.e it creates 3*5* 2 matrix

int[][][] matrix1 = new int[3][5][2];

56
57
58
9.5.1 Self-Assessment Questions

i. Explain the code the following program including expected results.

ii. Write and run the program to confirm your answer.

9.6 Suggestion for further reading

Java arrays tutorial:


[Link]

59
LECTURE TEN: JAVA METHODS

10.1 Introduction
Welcome to lecture Ten of Java programming module. In this lecture we will learn how to use
methods when writing java programs.

10.2 Specific Objectives:


By the end of this lesson you should be able to:
i).Understand methods as used in Java programming.
ii).Describe types of methods

10.3 Lecture outline


10.3.1. Methods in Java programming
10.3.2. Using Methods
10.3.3 Types of Methods

10.3.1. Methods in Java programming


A method is a named sequence of code that can be invoked by other Java code. Methods
are composed of statements; either declarations of local variables or executable
statements.
Methods define the kinds of messages (and parameters) which objects of a particular class may
receive.
All object-oriented behavior is implemented through methods.
Methods are used to substantially improve the modularity and maintainability of code.

Example: Rectangle class


Property names Method Names width
calculate_perimeter() length
calculate_area() area
Display_Results()

Structure of a method
A method is made up of two sections. These are

1. Header : Consists of method qualifiers, return type ,name and parameters


2. Body: Consists a block of statements that will be executed to perform an action
The structure of a method is organized as follows:

Qualifiers return-type method-name (parameters) // header

//start of the body {


Statements;
}

60
Example: The following figu re shows the structure of main method.
It is the first method to execu te in a program.

Body starts with ‗{‗ curl


bracket and ends with ‗}‘
curl brackets

„Return‟ key wo rd
So a return statement performs two functions:

i. Quiting a method:As soon return statement is executed, the method stops.


Executing and control returns to the code that just called the method.
Any code that exists after the return statement has been executed will be unreachable and never
executed
Java will provide a compile-time error when this is the case

Example:

public void calculate_area( )


{
Int width;
Int length;
Int area;
Area=width*length; return;
}

ii. Returning a value: is the type of information that comes out of a method may only return one
type of data, but they can take any number of parameters.

Example:

public int calculate_area (int width, int length)


{ int
area;
area = width + length; return
area;

61
}

In the above example, calculate_area() method that takes two integer parameters and returns the
product of the two. The return value of the method is assigned to area variable of int data type (in
this case, an int).

„void‟ key word


‗void‘ key word is used to specify that a method that does not return a value,

Example: main method is void because it has no return any value.


public static void main (String[] args) // header

{ //start body statements;

} // end main method

Parameters
A parameter is a variable declared in the prototype or declaration of a function:

Example: The following statement illustrates a prototype with parameters ‗width‟ and „length‟
void rectangle(int width, int length);

Arguments
An argument is the value that is passed to the function in place of a parameter: It
refers to the actual input being passed.

Example: The following statement shows that value 6 and 8 are arguments passed to parameters
‗width‘ and „length‟ in rectangle (int width, int length);

Rectangle (6,8);

10.3.2. Using Methods


There are two steps of using a methods:
Step1: Design the algorithm

Step2: Declare (write down) the method signature .


• Arrange statements into groups and give each group a name.
Step3: Call (run) the methods.
• The program's main method executes the other methods to perform the overall task.

Step1. Design the algorithm

62
This step involves specifying the procedure for executing a method.
An algorithm is the procedure followed during executing methods It
is an outline of how tasks will be performed in a logical order.

Example: The following list of steps specifies an algorithm for ‗Compute area’ program
1. Start
2. Input width and length
3. Compute area.
4. Display results
5. End

Step 2: Declaring method


This involves specifying method signature.
A method signature is a statement that is used to define name of the method, the type and order of
parameters in a method before that method is used. It is also known as method prototype Within
any class definition, the signature must be unique

Format: Method signature has the following format:


modifiers type_name ( parameter list )

Example:
public int calculate_Area(int width, int length);

Step3: Calling a method


Calling a method refers to invoking a method or passing a message to a certain method.
A method is called by its name when execution of the method is needed.
When calling a method with parameters, the order in which parameters are passed into the method
determines the value of the parameters in the method:

Example : Consider the following method

public int calculate_Area(int width, int length);

{
int area;
area=width*length;
return area;
}

The following statement can be used to call the above method:

63
calculate_Area(5,3);

In this statement argument, ‗5‘ will instantiate ‗width‘ parameter while argument ‗3‘ instantiates
‗length‟ parameter.

10.3.3 Types of Methods

There are different types of methods:

i. Static methods
ii. Non static
methods
iii. Constructors
iv. Accessors
v. Modifiers

i. Static methods
Static method is method that can be invoked when no object exist
Static method can only access and manipulate a class‘s static fields.
It is also known as class method

Example

qa

64
In th is example,
instVar is non static variable.
and therefore it canno t be accessed by
sta tmethod(),wh ich is a static method

Example 2: Main method is a static method and therefore it cannot access non-static members. The
following java code will generate a syntax error since main method is calling test () method, which
is a non-static method.

Calling static methods


Static methods are called using the following format:

[Link]( )

Example: The following statement calls exit() method which belong to System class

[Link]();

ii. Non static methods


These methods are called „non-static‟ because local variables and the parameters are
dynamically allocated to memory, usually on the system stack .When the method is exited, the
stack space(allocated memory) is released.
Non-Static method is method that can be invoked using an object. Therefore, it is also known
as instance method.
Non-static methods can access all variables and call all methods of their class(both static and
non-static).
A non-static method is called for a particular object using ―dot notation‖:

65
[Link]-static Method(...);

Example: The following code create an object known as ‗h‘ and then calls test() method using
‗dot ‗ notation

public static void main(String[] args)


{
Hello h = new Hello(); [Link]();
}

Constructor method

Constructor is a method that is used to create an object The


name of a constructor is identical to that of the class.

Format:

public ClassName(anyParameters)

{
statements;
}

Example : The following java code defines rectangle class that has two global variables (width and
length) and a constructor known as rectangle,which will be used to create an object of two
properties(Wand L).

public class Rectangle


{ int width; int
length;
public Rectangle (int W, int L) //constructor with parameters
{ width = W;
length = L; }
};

It is called when an object of the class is created using new operator


The name of the constructor and its parenthesized list of arguments (if any) must follow the ‗new’
operator
If a constructor is invoked again (using ‗new’ operator), the first object is discarded and an entirely
new object is created.

66
Format:
ClassName objectName = new constructor Name(anyArgs);

Example: The following java code uses rectangle(int W,int L ) constructor to create two objects.
The first object is a rectangle whose width= 5 and L=9. The second object is a rectangle whose W=7
and L=3

Rectangle object1=new Rectangle(5,9);

Rectangle object2=new Rectangle(7,3);

67
Modifier method:
Modifier method is a method that inserts information into an object (instance) It
is also known as mutator or setter.
Modifier method sets values of private variables.
Names of modifier methods often start with prefix set.
The same method can modify several fields and also return its old or new value.

Accessor Method
Accessor method is a method that extracts information from an object (instance).
It is also known as getter method.
It returns values of private variables.
Names of accessor methods often start with prefix get.
Its benefit is that you can include additional computation in a getter.

10.4 End of lecture activities

10.4.1 Activity 1: Exercise


The following java code implements a program a class known as
ExampleMinNumber, which has two methods i.e Main method and
minFunction.
The minFunction method takes two parameters num1 and num2 and
returns the minimum of the two.
i. What is the expected out put of the program?
ii. Write and run the program to confirm your answer.
public class ExampleMinNumber{

public static void main(String[] args) {


int a = 11; int b = 6; int c =
minFunction(a, b);
[Link]("Minimum Value = " + c);

/** returns the minimum of two numbers */ public


static int minFunction(int n1, int n2) { int
min; if (n1 > n2) min = n2;
else min =
n1;

return min;
}
}
10.4.1 Activity1: Solution

i. When executed, the program prints the following output:


Minimum value = 6

70
10.5.1 Self Assessment Questions

1. Modify the program such that it takes two parameters (num1 and num2) and determines the
maximum number of the two.

10 .6 Suggestion fo r further reading


Java Methods tutorial: [Link] [Link] m/java/java_ method [Link]

71
LECTURE ELEVEN: MODULAR PROGRAMMING USING JAVA

11.1 Introduction
Welcome to lecture Eleven of Java programming module. In this lecture we will learn modular
programming methodology using java.

11.2 Specific Objectives:


By the end of this lesson you should be able to:
i).Understand modular programming methodology. ii).Demonstrate
implementation of modular programming using java

11.3 Lecture outline


11.3.1. Modular programming methodology
11.3.2. Implementation of modular programming in Java
11.4.3 Using inheritance property to implement multi-modular programs

11.3.1. Modular programming methodology


Programming methodology of subdividing a program into separate subprograms known as modules
which interact through message passing.
Procedures or functions of a common functionality are grouped together into one module such that
each module several procedures within it that have common functionality.
Each module can have its own data to allow managing an internal state which is modified by calls to
procedures of this module. Figure11.1 illustrates how one module that consists 2 procedures and
data manipulated by each procedure.

Fig11.1: module

11.3.2. Implementation of modular programming in Java


In Java, Modular Programming methodology is implemented by use of classes and objects to
represent modules while methods are used represent Procedures.

i. Objects
An object is a data structure which can be distinctly identified as a single entity. It
is referred to as an instance of a class that contains state and operations.

Elements of an object An
object has three elements:
i. A unique identity: The name of the object ii. State: set of data fields with their current values.
The state is also known as properties of an object

72
iii. Behaviors: Operations that are performed by a set of methods

Figure 11.2 illustrates an object with data that defines its state and method for performing operation
on that data.

Figure 11.2: Object.

An object has the ability to produce program modules that perform a specific task.
Items are represented using self-contained objects.
Figure 11.3 illustrates a modular program that consists 6 objects that instantiate existing classes, for
instance, Object1(O1) and object 6(O6) instantiate class one(C1) while object2(O2) and
object3(O3) instantiate class 3(C3). All the methods interacts using message passing as shown by
arrows.
o1: C1 o3:C3 o4: C4
state o1 state o3 state o4
ops1() ops3 () ops4 ()

o2: C3 o6: C1 o5:C5


state o2 state o6 state o5
ops3 () ops1 () ops5 ()

Figure 11.3: Modular program with objects

Example: Figure 11.4 illustrates an example of circle object that consists findArea() method( for
implementing object behavior) and Radius data field(for defining the state)

r adiu s = 5

f ind Area()

Data field, State


Proper tie s

M ethod, Behavior

73
Figure11.4: An example of circle object

Classes
Class is a program construct that defines properties of an object.
It is the data type that defines properties of an object
All the objects described the class have same characteristics.

Class Example: The following java code defines a class known as rectangle that consists one
method known as main [Link] method has two properties. These are: width length The
behavior of the method is to calculate area of the rectangle

public class rectangle // starts a class


{ public int findarea () // method

{ Int width;
Int length; Int
area;
Area=width*length;
Return area;
}

Package
A collection of classes is known as package Examples
of packages:
Swing class: a GUI (graphical user interface) package AWT
class : Application Window Toolkit (more GUI)
Util class: utility data structures.

Importing packages
To use a package in a program, it must first be imported.
This involves add the import declaration at the beginning of a program, after the package statement
and before any other executable code.
Import statement tells java compiler to provide classes and methods of another package so that they
can add certain functionalities to the current program code.

Format:
To import all classes from a package, the following format is used.

Import packageName.*;

To import one class from packageName , the following format is used

import [Link];

74
Example1: The following statement imports all classes in javax package import
[Link].*;

Example2: The following statement imports only the DecimalFormat class from the [Link]
package.
import [Link];

11.4.3 Using inheritance property to implement multi-modular programs Programs


consisting multiple modules are implemented using inheritance property.
Inheritance is the property of extending or deriving data members and methods from another class
The class that derives data members and methods is known as Sub class or derived class The sub
class can redefine some members and methods by and/or adding its own.
The class from which data members and methods are derived is known as super class or base class

The following figure shows relationship between super class or base class is inherited by sub class
or derived class:

supe r cl ass
subcla ss
or
or exte nd s
ba se class
deri ved class
Figure11.5 inheritance property

Format: Inheritance can be expressed using the following format:

public class <sub class> extends <super class>


{
...
}

Main class in multi-modular programs


To implement multiple modules, the main class(also known as main program) is used for
coordinating calls to procedures (messages) in separate modules and hands over appropriate data
as parameters.
Figure 11.6 illustrates a Modular program with three classes that represent three modules.
One of the classes is referred to as main program (or main class) and its purpose is to facilitate
communication between super class and subclasses.

75
Figure 11.6: multi-Modular program

Type qualifiers

A type qualifier is a keyword that modify (specify) the existing type of a class or its respective
members by provide more restrictive types that consist extra properties or specifications about the
class or its members. Type qualifiers allow adding of new properties to an entity without the need to
reinvent a new type. Examples of type qualifiers include the following:
i. Final qualifier: Specifies that variable, class or method cannot be defined again.
ii. Scope qualifiers: Used to specify visibility of method, class or member data. They
include: public, protected, private iii. Abstract qualifier: specifies that an entity cannot be
instantiated.(object of the class cannot be created). iv. Static qualifier: specifies that the method
is usable by any method and the class without creation of object.

Example:

76
11.4 End of lecture activities

11.4.1 Activity 1: Exercise


i. Identify a super class and sub classes in the following figure

ii. Write a java code that implemen ts the three classes

11.4.1 Activity1: Solution: person is the super class while lecturer


and student are subclasses

77
10.5 .1 Self Assessment Questio ns

Wh en the program is executed it prints output similar to the following

78
79
When the program is executed, it prints the fo llowing output

11.5.1 Self Assessment Questions

i. Identify a super class and sub classes in the following figure ii.
Write a java code that implements the three classes

11.6 Suggestion for further reading


Java Programming Tutorial: Object-oriented Programming (OOP) Basics
[Link]

LECTURE TWELVE: GRAPHICAL USER INTERFACE APPLICATIONS

12.1 Introduction
Welcome to lecture twelve of Java programming module. In this lecture we will learn how to
develop graphical user interface using java.

12.2 Specific Objectives:

80
By the end of this lesson you should be able to:
i).Understand basic concepts of graphical use interface. ii).Demonstrate
implementation of Gui applications using java

12.3 Lecture outline


12.3.1. Components and containers
12.3.2. Layout Classes
A graphical user interface of a java program consists of Components and Containers

[Link]
A component is an object having a graphical representation that can be components can be displayed
on the screen. GUI components are also called controls (Microsoft ActiveX Control), widgets
(Eclipse's Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with the
application via mouse, keyboard, and other forms of inputs such as [Link] are many
components enable a programmer to customise an existing component , instead of having to start
from scratch
The following figure shows examples of Gui components.

Figure1: Examples of Gui components

81
Component contributes several public methods to all its subclasses.
Examples of methods include:
public void setSize(int width, int height); //set size in pixels
public void setBackground(Color c); //see class Color for colors
public void setVisible(boolean b); //Display on screen
//creates peer

Containers
Containers are components that can contain (hold) and manage other components.
There are two main categories of containers
1. Top level containers
2. Secondary containers

Top Level Containers


A Top level container is the root container that hold other containers. Every
GUI program contains at least one top-level container.

Examples:

1. Frame: Main window which has a title bar (containing an icon, a title, the minimize,
maximize/restore-down and close buttons), an optional menu bar, and the content display area.

Figure 2: Frame

2. Dialog: Secondary "pop-up window" used for interacting with the users. It has a title-bar
(containing an icon, a title and a close button) and a content display area,

80
Figure3: Dialog.

3. Applet: a Java program that provides a display area inside a browser

Figure4: Applet.

Secondary containers
Secondary containers are placed inside a top-level container or another secondary container.
Examples are :
• A Panel is a rectangular area (partition) under a higher -level container, that has a set of
related GUI components.

Figure 5: A panel

• Tabbed pane: A rectangular area (partition) that allows user to choose which component to
see

81
Figure 6: Tabbed pane

• Scroll pane: A rectangular area (partition) that provides automatic horizontal and/or vertical
scrolling for a single child component).

Containers and Components


In a GUI program, containers are used to hold the components The following example, has 3
containers and 5 components containers: a Frame and two Panels. components: a Label
(providing description), a TextField (for users to enter text), and three Buttons (for user to
trigger certain programmed actions).

Figure 7: Containers and components

To appear on screen, every component must be part of a containment hierarchy, with a top-level
container. Usually, components are added to the content pane layer as its root as shown in Figure 8

82
Figure 8: Containment hierarchy

Swing components vs AWT components


· Each AWT component has its own opaque native display, and always displays on top of the
lightweight components. As a rule, do not mix heavyweight AWT components and lightweight
Swing components in the same program, as the heavyweight components will always be painted on
top of the lightweight components.

· AWT components rely heavily on the underlying windowing subsystem of the native operating
system,for example, an AWT button ties to an actual button in the underlying native windowing
subsystem, and relies on the native windowing subsystem for their rendering and processing. On the
other hand, Swing components (JComponents) are written in Java. They are generally not "weight-
down" by complex GUI considerations imposed by the underlying windowing subsystem.

· Compared with the AWT classes (in package [Link]), Swing component classes (in package
[Link]) begin with a prefix "J", e.g., JButton, JTextField, JLabel, JPanel, JFrame, or JApplet.

Constructing and Adding Component into a Container


Components are added to a container using add methods found in containers. This
can be done using the following format:
[Link] (component);
There are three steps are necessary to create and place a GUI
component:
1. Declare the component with an identifier;
2. Construct the component by invoking an appropriate constructor via the new operator;
3. Identify the container (such as Frame or Panel) designed to hold this component and
container can then add this component onto itself via [Link](aComponent) method.
Take note that it is the container that actively and explicitly adds a component onto itself,
instead of the other way.

Add component to content-pane

83
Swing components should not be added onto the top-level container directly because they are
lightweight components. i.e utilize less system resources.
Swing components must be added onto content-pane which is secondary level container. that
is used to group and layout components. Figure 9 shows an image of content pane

Figure9: content pane


To components on content pane, get the content-pane via getContentPane() method from a top-
level container, and add components.

Example:

public class TestGetContentPane extends JFrame


{
public TestGetContentPane()
{ Container cp = [Link](); // identify container [Link](new
FlowLayout()); // set layout
[Link](new JLabel("Hello, world!")); // add label comp
[Link](new JButton("Button")); // add a button comp ......
} .......}

Setting the content pane


Panel is the main container that is used to hold all GUI Components in the application.
setContentPane() method is used to set the content-pane to become a Panel
The following sample code creates a new panel known as 'mainpanel', then it adds a label
component on the panel and finally sets content panel to become the mainpanel.

public class TestSetContentPane extends JFrame {


public TestSetContentPane() {
JPanel mainPanel = new JPanel(new FlowLayout()); // new panel [Link](new
JLabel("Hello, world!")); //add label component
[Link](new JButton("Button")); // add button component
[Link](mainPanel); //set content pane to become a panel
...... } .......}

84
12.3.2. Layout Classes

Layout manager.
Layout manager is used to determine position and size of the components contained in a
container.
Each container has a layout manager which arranges components in a container. Examples of
layout classes that are implemented by layout Manager include :

1. Border layout 2. Box layout

3. Flow layout

[Link]

85
Setting layout of container

A container has a setLayout() method to set its layout manager:


Setting up the layout of a Container involves the following

steps:
1. Construct an instance of the chosen layout object, via new and constructor, e.g., new
FlowLayout())
2. Invoke the setLayout() method of the Container, with the layout object created as the
argument;
3. Add the GUI components into the Container using the add() method in the correct order; or
into the correct zones

Example:

Panel p = new Panel();


// create Panel container
[Link](new FlowLayout());
// Allocate a new Layout object.
// and set the Panel container sets to this layout.
[Link](new JLabel("One"));
[Link](new JLabel("Two"));
[Link](new JLabel("Three"));......
// add three label components to // the
Panel container in the proper order.

The current layout is obtained via getLayout() method


Example
Panel awtPanel = new Panel(); [Link]([Link]());

86
Flow layout
In the [Link], components are arranged from left-to-right inside the container in the
order that they are added (via method [Link](aComponent)).
When one row is filled, a new row will be started.
The actual appearance depends on the width of the display window.

Constructors of flow layout

Constructors for flowlayout include the following: public


FlowLayout(); public FlowLayout(int align); public
FlowLayout(int align, int hgap, int vgap); // align:
[Link] (or LEADING), [Link] (or TRAILING), or
[Link]
// hgap, vgap: horizontal/vertical gap between the components
// By default: hgap=5, vgap=5, align=CENTER

Panel is a secondary container, which is added into a top-level container (such as Frame), or another
Panel. The primary function of Panel is to layout a group of component in a particular layout.
By default, Panel (and JPanel) has FlowLayout .
Example: The following program implements flow layout:

87
When executed, the program prints the following output:

2. Border Layout
In [Link], the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH,
and CENTER. Components are added using method aContainer. add(acomponent, aZone), where
azone is either [Link] (or PAGE_START), [Link] (or
PAGE_END), [Link] (or LINE_START), [Link] (or LINE_END), or
[Link]. The method [Link](aComponent) without specifying the zone
adds the component to the CENTER .

88
Example:

You need not add components to all the 5 zones.


The NORTH and SOUTH components may be stretched horizontally;
The EAST and WEST components may be stretched vertically;
The CENTER component may stretch both horizontally and vertically to fill any space left over.

Constructors for border layout


There are two Constructors for border layout .They include:

public BorderLayout();
public BorderLayout(int hgap, int vgap); // By default hgap=0, vgap=0

89
Example: the fo llowing program implements Border layou t

When executed the program prints the following output:

4 .Grid Layout
In [Link], components are arranged in a grid (matrix) of rows and columns inside the
Container. New components are added in a left-to-right, top-to-bottom manner in the order they
are added (via method [Link](aComponent)).

Example:

90
Constructors
Constructors for grid layout include the following:
public GridLayout(int rows, int columns);
public GridLayout(int rows, int columns, int hgap, int vgap); Defaults
are : rows=1, cols=0, hgap=0, vgap=0

Example: The following program implements grid layout

91
When executed, the program prints the following output

92
12.4 End of lecture activ ities

12 .4.1 Activity 1: Exercise


Use eclip se to write and run the following program

93
2.4.2 Activity1: Solution:
When executed, the program prints the following output:

94
12 .4.2 Activity 2: Exercise

95
12.4.2 Activity 2: Solution

When the program is executed, the following form is displayed

12.5.1 Self Assessment Questions


i. Modify the code in activity 1 exercise and replace flow layout with grid
layout to display the same information.

ii. Modify the code in activity2 exercise to create a form for registering degree
course s offered by Kca University.

12.6 Suggestion for further reading.

[Link]
[Link]
References
Oracle Java tutorials, which an be accessed on [Link]

Liang. D.(2008), Introduction to Java programming,(6th ed),which can be accessed on

[Link]

Holzner Steven (2005), JAVA2 Programming Black Book. DreamTech

Wigglesworth & Lumby(2002), JAVA [Link]

Joyce Farrel (2004) Java Programming, 2 [Link] Course Technology.

96
97
98
99
100
101

You might also like