Understand Java Programming Notes
Understand Java Programming Notes
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.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.
• 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
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
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:
4
In this course, we will use java2 Standard Edition JDK 1.8, which is the current version of
Java 2 Standard Edition.
A Java distribution typically comes in two flavors, the Java Runtime Environment (JRE) and
the Java Development Kit (JDK).
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.
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
• 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
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
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).
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"); }
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().
13
2.4 End of lecture activities
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.
Downloading steps
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.
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.
Downloading eclipse
16
3.3.2. Writing and Running Java programs using eclipse To
write a program using eclipse, use the following steps:
17
4. In the dialogue box that appears ensure the package name is the name of your project
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".
8. A Java editor for [Link] will open. In the main method enter the following line.
[Link]("Hello World");
[Link]("Welcome to KCA University");
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.
19
3.4 End of lecture activities
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
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
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.
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!")_
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 ...
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
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
[Link]("Hello, world)
[Link]("Hello, world);
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
5.1 Introduction
Welcome to lecture five of Java programming module. In this lecture we will learn basic Java
syntax.
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
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.
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.
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.
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.
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.
28
Example: Boolean >
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.
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:
Examples:
Int sum, position, marks;
Double average,weight,temperature
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“
<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
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> ;
Mathematical operators
Examples
• Sum=0.0
• Perimeter = 2.0 *(length+breadth);
• Ratio =(a+b) /(c+d);
Increment and decrement operators
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)
in
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.
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.
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
// start of class
{
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.
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‖.
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;
37
6.4.1 Activity 1: Exercise
Write and run the following Java program
38
6.5. Self Assessment Questions
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.
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.
a. While loop
b. Do/while loop
c. For loop
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.
40
While Loop Example 2: The following while statement prints out the numbers 1 to 10.
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.
Format:
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:
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.
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.
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.
i) Output stream accepts output from a program and its destination is typically the monitor or a
file.
‘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.
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;
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
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.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.
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).
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:
int myArray[];
Example2: The following statement declares studentList array to be an array of student data type.
2. Creating an Array
Creating an array means setting up memory for the already declared array.
Example2: The following statement sets up 10 spaces in memory that can hold references to
student objects
Format :
Example:
The following statement assigns and creates an int array known as num which has a space for 5
elements.
The following diagram illustrates the block of memory created by the above statement.
Example1: The following statements will help to create Student objects and add them to
studentslist [ ] array:
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[]=
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.
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:
Example: The following statement declares 2 dimensional array with 10 rows and 5 columns
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
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
56
57
58
9.5.1 Self-Assessment Questions
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.
Structure of a method
A method is made up of two sections. These are
60
Example: The following figu re shows the structure of main method.
It is the first method to execu te in a program.
„Return‟ key wo rd
So a return statement performs two functions:
Example:
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:
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).
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);
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
Example:
public int calculate_Area(int width, int length);
{
int area;
area=width*length;
return area;
}
63
calculate_Area(5,3);
In this statement argument, ‗5‘ will instantiate ‗width‘ parameter while argument ‗3‘ instantiates
‗length‟ parameter.
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.
[Link]( )
Example: The following statement calls exit() method which belong to System class
[Link]();
65
[Link]-static Method(...);
Example: The following code create an object known as ‗h‘ and then calls test() method using
‗dot ‗ notation
Constructor method
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).
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
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.
return min;
}
}
10.4.1 Activity1: Solution
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.
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.
Fig11.1: module
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.
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 ()
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()
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
{ 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.*;
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];
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
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
77
10.5 .1 Self Assessment Questio ns
78
79
When the program is executed, it prints the fo llowing output
i. Identify a super class and sub classes in the following figure ii.
Write a java code that implements the three classes
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.
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
[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.
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
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.
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).
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
· 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.
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
Example:
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 :
3. Flow layout
[Link]
85
Setting layout of container
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:
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.
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:
public BorderLayout();
public BorderLayout(int hgap, int vgap); // By default hgap=0, vgap=0
89
Example: the fo llowing program implements Border layou t
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
91
When executed, the program prints the following output
92
12.4 End of lecture activ ities
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
ii. Modify the code in activity2 exercise to create a form for registering degree
course s offered by Kca University.
[Link]
[Link]
References
Oracle Java tutorials, which an be accessed on [Link]
[Link]
96
97
98
99
100
101