CSS 121 Lecture Notes Combined
CSS 121 Lecture Notes Combined
Programmes: BSc. ITS I, BSc. ICTM I, BSc. ICTB I & BSc. MICT EDU I
Email ID: [email protected]
June 4, 2024
1 / 187
Code of conduct
2 / 187
Code of Conduct - Cont’d
▶ Course assessment:
• Quiz - Many.
• 2 Assignments @ 10%.
• 2 tests @ 15%.
• University Examination (UE) - 50%.
▶ Marks for assignments, tests or UE can not be compromised or
negotiated for.
▶ Hope to enjoy your maximum cooperation.
3 / 187
Brainstorming
4 / 187
Main contents
• Recommended books
• Introduction to computer programming
• Computer programming languages
• Java
• Identifiers
• Reserved words
• comments
• Data types
• Variables
• Java classes
• Method main ()
• Arithmetic operators
• Method println()
• Method
• Programming errors
5 / 187
Recommended References (Books)
1. Ivor Horton, Ivor Horton’s Beginning Java, 7e, John Wiley & Sons
inc., 2011.
2. Herbert Schildt, Java The Complete Reference, 9e, McGraw Hill,
2014.
3. Herbert Schildt, Java A Beginner’s Guide , McGraw Hill, 2018.
4. Y. Daniel Liang, Introduction To Java Programming, 9e, Pearson
Prentice Hall, 2011.
5. Paul Deitel & Harvey Deitel, Java How To Program, 11e,
Pearson, 2017.
6. Rich Raposa, Java in 60 Minutes A Day, 7e, Wiley Publishing
Inc., 2003.
6 / 187
Introduction to computer programming
7 / 187
Introduction to computer programming
8 / 187
Computer programming language
9 / 187
Computer programming languages: Types
10 / 187
High level computer programming languages
▶ They use words and symbols from human languages like English
rather than mnemonic codes.
▶ Computer programs are written using human like languages
which are more convenient to use.
▶ They form the bulk of today's computer programming languages.
▶ They constantly evolve to incorporate new features in order
to improve their security, performance, suitability,
usability etc.
▶ Examples of high level programming languages are BASIC,
COBOL, Pascal, FORTRAN, C, C++, Java, Python and Perl.
▶ High level programming languages allow programmers to use
vocabulary of reasonable terms instead of sequence of binary
digits.
▶ They also allow programmers to name storage locations of the
computer rather than remembering them.
11 / 187
High level computer programming languages
▶ Each high level programming language has its own specific and
limited set of vocabulary and rules (syntax).
▶ A set of rules of a programming language is called syntax.
▶ Learning a programming language means learning a set of
vocabulary, syntax and programming logic of that language.
▶ Programming logic involves writing program's statements in
the correct order to produce the desired output (result).
▶ You may use programming language's syntax correctly but fail
to observe the logic.
▶ Using high level programming language like Java, programmers
write series of executable statements, similar to English
statements for a program to carry out a specific task.
▶ Special computer software called compilers and interpreters
are used to translate program's statements from high level
programming language into machine code for computer's CPU to
execute the instructions specified in statements.
12 / 187
High level computer programming languages
13 / 187
High level computer programming languages:
Strengths
14 / 187
High level computer programming languages:
Weaknesses
15 / 187
Java: Brief background
▶ It was built upon the rich legacy inherited from C and C++.
▶ Invented by James Gosling, Cris Warth, Patrick Naughton, Ed
Frank and Mike Sheridon at Sun Microsystems in 1991.
▶ It was originally known as Oak, but renamed Java and first
released in public in 1995.
▶ Older programming languages like C++ were designed to be
compiled for a specific computer architecture (CPU).
▶ Since its first release, Java has continued to evolve
significantly.
▶ The current Java version is Java 21, which is a Long-term
support (LTS) released in September 2023.
▶ Other Java LTS versions are Java 8, Java 11, Java 17.
16 / 187
Motives for inventing Java
17 / 187
Features of Java
▶ A simple computer programming language whose syntanx is
largely based on C and C++ programming languages.
▶ A multi-platform, class-based, object-oriented programming
(OOP), network centric language, general-purpose programming
language, fully-featured, and software platform.
▶ Capable of developing different types of robust applications
running on billions of devices including micro-computers,
mobile phones, servers, gaming consoles, medical devices etc.
▶ It is a very stable programming language with;
• Strong memory allocation
• Automatic garbage collection mechanism
• Powerful exception handling
• Type checking and checks for compile-time errors and run-time
errors by compiler and interpreter respectively.
▶ Contains hundreds of network features to provide massive
support for network and distributed based applications.
▶ Has a built-in ability to support many character sets e.g.
ASCII and Unicode.
18 / 187
Features of Java
▶ Provides comprehensive tools for developing applications
with;
• An interactive Graphical User Interface (GUI)
• Extensive image processing, graphics programming, access to
relational databases and cryptography to name a few.
▶ It is a fast, highly secure and reliable programming language
with many built-in security features such as;
• Lack of memory pointers
• Sandboxing
• Null checking of references
• Explicit variable declaration
• Bounds checking of arrays
▶ Provides a rich set for data structures including lists,
queues and arrays.
▶ It supports multi-threading; It allows a program to have
different threads executing independently at the same time.
▶ It a programming language and software platform available for
all major operating systems including Windows, Linux and
MacOS, as well as all major hardware architectures.
19 / 187
Features of Java
▶ Computer platform comprises of hardware type (CPU) and system
software (such as OS) of a particular computer.
▶ It is dynamic: Designed to adapt evolving environment,
libraries can add new methods and instance variables without
any problem.
▶ It is free and open source platform - i.e., its software
development kit such as JDK can be obtained freely without
paying for it, and there exist several free source code for
Java stack implementations.
▶ It is a multi-platform (also known as cross platform,
architectural neutral or platform independent) programming
language, enabling it to run on a wide range of computer
architectures with no or little modifications.
▶ The platform independence nature of Java enables development
of applications which are 'Write Once Run Anywhere (WORA)'
▶ Platform independence occurs because Java programs do not
execute directly on CPU, instead they execute on a runtime
environment called Java Virtual Machine.
20 / 187
Features of Java
▶ Java program is first compiled by Java compiler (javac) into
a bytecode, which is subsequently executed (interpreted) by
Java virtual machine (JVM) (also known as Java interpreter)
for a specific hardware architecture.
▶ This means Java is both a compiled and interpreted language.
▶ JVM is part of Java runtime environment (JRE) - a layer of
software running on top of a computer's OS to provide
libraries and resources required to execute Java programs.
▶ While Java compiler and JVM are platform dependant, bytecode
produced by Java compiler and executed by JVM is platform
independent.
▶ Java bytecode can run on any architecture which supports JVM
without need to recompile.
▶ It is architecturally neutral (platform independent): Allows
creation of large scale applications that can run unchanged
on different computer platforms.
▶ The OOP feature allows the development of modular programs
and enhances code reusability, code security, clarity etc.
21 / 187
Major applications of Java
▶ It is widely used for development of;
• Desktop applications: It can be used to write very powerful
standalone or network-based desktop applications
• Mobile operating systems and mobile applications such as
Android operating system and Android mobile applications
• Big data applications: Used for data science applications and
by data processing engines which process complex and massive
amounts of real-time datasets
• Server-side technologies and Internet applications: Used for
developing applications running on network servers and many
Internet/ web-based applications running on Internet
• Cloud computing: Because of its 'WORA' nature, it is highly
used for development of decentralized cloud-based applications
• Game applications: For developing various games including
mobile, computer and video games
• Artificial intelligence applications: Used for development of
machine learning applications to solve various classification,
object detection, natural language processing (NLP) tasks
• Internet of Things (IoT): Used to program sensors and hardware
in edge devices which connect to Internet independently
22 / 187
Java: A compiled and interpreted language
23 / 187
Java: A compiled and interpreted language
24 / 187
Java: A compiled and interpreted language
▶ Because Java programs are isolated from the OS, they are also
insulated from particular hardware on which they run.
▶ This isolation helps to protect Java programs against
malicious programs that access computer hardware through OS.
▶ Java is modelled after C and C++ language, and therefore
there is close similarity in the syntax and vocabulary
between the two languages.
▶ Despite this similarity, Java eliminates most of the
difficult-to-understand features inherent to C and C++, and
with few hardware implementation dependencies.
25 / 187
A compiled language: E.g. C++
26 / 187
Java: A compiled and interpreted language
28 / 187
Major Java Editions
29 / 187
Requirements for writing Java applications
30 / 187
Requirements for writing Java applications
31 / 187
Types of Java Programs
32 / 187
Creating a first Java program: Steps
33 / 187
Creating a first Java program: Steps
34 / 187
Things to Note
35 / 187
Identifiers
36 / 187
Reserved words
▶ It is any word that Java uses for special meaning and should
not be used by the programmer to name anything (i.e. as an
identifier).
▶ They are used by Java programming language itself for some
special purpose
▶ If used by a programmer as identifier, they will confuse
Java, syntax errors will be generated.
▶ Never use reserved words as identifiers in your program.
▶ Examples of reserved words are public, class, static, void.
▶ A comprehensive list of Java keywords is shown in Fig. 3
37 / 187
Reserved words
38 / 187
Comments
▶ Java compilers tend to ignore (do not execute) all comments
contained in the Program.
▶ Comments is a documentation provided by a programmer within a
program used to:
• Clarify some important points in Java programs.
• Emphasize something in a program.
• Change lines of code into comments so that they are not
executed.
• Explain something in the program, such as a function of a
program, class, variable etc.
▶ Two ways of writing comments in Java are using:
• Double forward slash (//) for each comment line.
• Putting /* at the beginning of the first comment line and */ at
the end of the last comment line.
▶ Comments are put anywhere in a program.
▶ Writing useful and good comments in a program is a good
programming practice.
39 / 187
Data types
▶ Data type is a set of values having predefined
characteristics.
▶ For each data type, Java specifies the following;
• Range of values (minimum to maximum value)
• Operations to be performed to all values of a particular type
• Storage mechanism for each data type
▶ For instance, a byte data type has values ranging from -128
to 127, each byte value takes one byte (8 bits) in memory is
manipulated using arithmetic operations (+, -, *, /, %).
▶ Java is a statically typed language i.e., all data storage
locations (variables) must be declared before they are used.
▶ Java is a strongly typed language i.e., has its own
predefined built-in data types (specifically primitive data
types) and does not allow programmers to define their own
data types.
▶ Any data type value is stored in a variable declared to hold
a value of that particular type.
40 / 187
Data types
▶ Assigning a value to a variable that is inconsistent with a
declared type generates a compile time error.
▶ To enhance portability across different architectures
(platforms), all data types in Java have a strictly defined
range of possible values.
▶ Compiler allocates memory space for each variable or constant
according to its data type.
▶ An int is a 32-bit data type regardless of the computer
architecture allows Java programs to be written and run on
any platform without porting on any machine architecture.
▶ Data types play crucial role in defining the kind of
information to be stored or manipulated by program
▶ Choose the most appropriate data types by considering the
range, memory usage and operations to be performed on them.
▶ Two main data types in Java are:
• Primitive data types
• Non-primitive (reference)) data types
41 / 187
Data types
43 / 187
Non-numeric primitive data types
▶ Boolean data type
• Represents only one of two values; true or false which
represent two truth values of logic and Boolean algebra
• The size of the boolean data type is virtual machine-dependent
• It is also known as logical data type
• It has only two values, true and false
• These values must always be written in lowercase.
▶ Character data type
• It is also known as char or single 16-bit Unicode data type
• Represents symbols in character set, like letters and numbers.
• Its storage locations (variable) store only one character
• A character data type has a memory size of 16 bits, which
allows characters to be represented as integers.
• Character data types are unsigned, meaning that they can not
store negative value; i.e., can only hold single positive value
• A character data value must be enclosed with single quotation
marks, like 'F'
• It has a minimum value of '\u0000' (or 0) and a maximum value
of '\uffff' (or 65,535 inclusive)
44 / 187
Numeric primitive data types: Integer
45 / 187
Numeric primitive data types: Integer
• int
♦ It is the most commonly used integer data type in Java.
♦ Provides a range larger than one provided by either byte or
short.
♦ An int value occupies 32 bits (4 bytes) in memory.
♦ int values range from -2147483648 to 2147483647, i.e. −231 to
231 − 1.
♦ It covers most of programmers' needs in calculations, control
loops, indexing arrays.
• long
♦ A long value occupies 64 bits (8 bytes).
♦ Use this data type when you need a range of values wider than
those provided by int data type
♦ Values range from -9223372036854775808 to 9223372036854775807,
i.e., −263 to 263 − 1.
♦ In order to assign to a variable a data value of type long, it
is optionally appended with L (or l).
46 / 187
Numeric primitive data types: Floating point
▶ Floating point
• Non-integral numeric values such as 0.123, 345.678, -3.607 etc.
• Values of this type are called floating numbers.
• Floating point values are signed
▶ Two types of floating point data types are;
• float
♦ Specified as float values by appending an f (or F) to the value.
♦ Float values range from -3.4E38 to +3.4E38 and occupy 32 bits
♦ Use a float (instead of double) if you need to save memory in
large arrays of floating point numbers.
♦ They are represented with approximately 7 decimal digits accuracy.
• double
♦ They occupy 64 bits.
♦ They range from -1.7E308 to +1.7E308
♦ It is a default data type for floating point data values.
♦ They are represented with approximately 17 decimal digits accuracy
i.e., a number of digits to the right of the decimal point.
♦ They are the most commonly used floating point data values.
47 / 187
Non-primitive data type
48 / 187
Non-primitive data type
49 / 187
Primitive vs non-primitive data type
50 / 187
Non-primitive data type
51 / 187
Non-primitive data type: Creating objects
52 / 187
Variables and variable types
53 / 187
Variable declaration
▶ A process of creating a named storage location (variable) for
storing data value or reference of a certain type.
▶ It involves specifying a data type and variable name
(identifier).
▶ A variable stores a value of declared type only, and it can
not change through out its life time.
▶ Examples of variable declarations are:
int total;
boolean boolValue;
char aLetter;
float floatNum;
▶ Multiple variables of the same data type can be declared in
the same statement:
int x, y, z;
float fNum1, fNum2, fNum3;
char aletter1, aletter2, aletter3;
54 / 187
Variable initialization
55 / 187
Variable declaration and initialization
56 / 187
Types of Variables
57 / 187
Class variables
▶ Also called static fields because they use the keyword static
during their declaration.
▶ They are associated with the entire class and shared by all
class objects.
▶ They are declared inside the class but outside any method
(i.e., not inside any method), commonly after class
definition statement
▶ Only one copy of each class variable exists no matter how
many objects are created.
▶ Exists even if no objects have been created.
▶ Class variables are commonly used for:
• Holding constants which are common and required by all class
objects such as PI.
• Tracking data values that are common to all class objects.
58 / 187
Class variables
59 / 187
Class variables holding constants
60 / 187
Class variables holding constants
61 / 187
Instance variables
62 / 187
Instance variables
63 / 187
Local variables
64 / 187
Local variables
65 / 187
Java classes
▶ A class, is a set of objects which shares common behaviors
and properties (attributes).
▶ It is a user-defined blueprint or prototype from which
objects are created.
▶ A class defines its own data type, which is an example of
reference (non-primitive) data type.
▶ However simple a Java program is, it must be organized into a
functional unit called class.
▶ Even simple programs that add two numbers (28 + 1), or
display messages like Hello students, how are you? etc.
must be organized in a class.
▶ No any constructs of Java program will work independently
without being organized into at least one class.
▶ Real world programs contain tens, hundreds or thousands of
classes.
▶ A particular instance of the class takes its attributes from
the general category.
66 / 187
Java classes
▶ A class is therefore used to create (instantiate) objects
(instances) of its own data type.
▶ If a program contains one class, then the source code file
name must match with this class name.
▶ If it contains more than one class, then the source code file
must match the name of the class that contains the method
main().
▶ As a convention, Java class names should start with an
uppercase first letter.
▶ While it is not a strict rule, it aims at differentiating
class names from variable names, and therefore it is a good
programming practice to adhere to it.
▶ To define a class, we use a keyword class, followed by an
identifier (class name), followed by braces, also called
curly brackets, {}.
▶ All other constructs (elements) are placed between braces.
67 / 187
Java class - General syntax (form)
68 / 187
Clarification of terms
▶ class keyword
• It must precede the class_name.
• It is a reserved word (keyword) that must not be used to name
anything else by a programmer.
▶ class_name
• Any valid identifier.
• Must start with the uppercase letter: FindAreas, Mzumbe
• If two or more words are used, capitalize each first letter of
each word, e.g. Big4Cat, MzumbeStudents, FindStudents or use
an underscore to separate word, such as Find_Students etc.
• Can be of any length.
• Must not include blank space or tabs in the middle of the name:
e.g Mzumbe Students not a valid name.
69 / 187
Java classes
70 / 187
Method main ( )
public static void main (String [ ] args)
▶ The keyword public
Makes a method accessible by any code in the program.
▶ The keyword static
Ensures that method main() is executed (accessible) even
if no objects of the class exist.
▶ The keyword void
Indicates that main() does not return a value.
▶ The keyword main
▶ The name (identifier) given to the method
▶ A pair of parentheses i.e., ()
It must follow any method name, and it can be empty or
carry a parameter/argument.
▶ String [ ] args
It is an argument of type array which provides a mechanism
of accessing data passed to the program.
71 / 187
Arithmetic operators
▶ Additive operator: +
▶ Subtraction operator: -
▶ Multiplication operator: ∗
▶ Division operator: /
▶ Modulus operator: %
72 / 187
Method println()
73 / 187
Method
▶ A self contained block of code that operates on data values
of class.
▶ Defines operations that can be performed on fields (data
values stored in fields).
▶ It is equivalent to a function in C programming language.
▶ Major advantage of the method is reusability, can be executed
as many times as required.
▶ Methods help to break a large and complex problem such as
calculation into smaller and more manageable chunks.
▶ A method is executed by calling its name.
▶ A method may or not return a value when its execution
finishes.
▶ Methods that return a value must finish by executing a return
statement.
▶ An access specifier (attribute) may optionally precede the
return type.
74 / 187
Method
▶ Specifying a return type for a method defines the type for
the value that will be returned when the method is executed.
▶ A returned value must be consistent with the data specified
in the method declaration (i.e. return type).
▶ Methods that do not return any value have a return type
specified as void.
▶ Java method consists of the following major components;
• Access specifiers: Define access type to the method.
• The return type: Data type of the value returned by the method
or void if it does not return a value.
• Method name (identifier): A method name that uniquely
identifies it in the program.
• Parameter list:
♦ Comma-separated list of input parameters that are defined,
preceded by their data type within the enclosed parentheses.
♦ If there are no parameters, you must use empty parentheses ()
• Exception list: List of exceptions you expect the method to
throw e.g., ArithmeticException, IOException etc.
• Method body: A block of code enclosed between braces which
execute to perform intended operations.
75 / 187
Method definition
76 / 187
Method
77 / 187
Types of Methods
78 / 187
Instance methods
79 / 187
Instance methods
80 / 187
Class methods
81 / 187
Class methods
82 / 187
Assignment
1. Write Java program that computes an area of a triangle with;
i. At least two instance variables
ii. At least one instance method
2. Write Java program called President which display correct
full name, age, sex (male or female) and date of assuming
office for Tanzanian and Kenyan President.
3. Write Java program with two instance methods, two instance
variables and one constant which receives radius (r) and
height (h) of the cylindrical body from user through keyboard
to compute its surface area (2πrh+2πr 2 ) and volume (2πr 2 ).
4. Write Java program which prompts a user to enter an integer
and displays true if an integer is greater than 0 and false
otherwise. The program should contain one instance method
which return boolean value.
5. Write Java program that prompts user for coefficients of
quadratic equation to compute its two x values using general
formula assuming that (b 2 ≥ 4ac ). It should contain;
i. At least three instance variables
ii. At least two instance methods
83 / 187
Parameterized Method
▶ Both instance and class methods may have optional one or more
values passed to them when they are called.
▶ Values passed to a method are called arguments.
▶ Variables that receive arguments inside a method are called
Parameters.
▶ For a method to have a value passed, you must first declare a
data type and variable name.
▶ Data type and variable name form a parameter.
▶ A parameter is declared inside the method's parentheses.
int getSum(int a, int b, int c){
// The rest of the method
}
▶ The return value of method getSum() is of type int.
▶ int a, int b, int c are the parameters.
▶ This method must be supplied with 3 values of type int for
the three variables when calling it.
84 / 187
Parameterized Method
85 / 187
Parameterized Method
86 / 187
Programming error
87 / 187
Compile-time errors
88 / 187
Compile-time errors
89 / 187
Run-time errors
90 / 187
Logical errors
91 / 187
Test One
1. Define the following terms and give one example for each;
(a). Computer programming language
(b). Data type
(c). Keyword
(d). Access specifier
2. Describe any five weaknesses of machine programming
languages.
3. Mention key components of any programming language like Java
that any programmer needs to learn.
4. Why Java is more portable than other high level programming
languages like C+ or C++?
5. List all major categories of primitive data types in Java.
6. List major parts of a Java method.
92 / 187
Individual Drill: ITS I
93 / 187
Individual Drill: ICTB I
94 / 187
Individual Drill: ICTM I
▶ Write Java program called QuadraticEquation which computes
two x values of a quadratic equation expressed as
ax 2 +bx +c= 0, using general formula method, assuming that
b 2 ≥ 4ac . The program should contain three instance
variables a , b , and c , all of type double, for coefficients
a , b and c , respectively. These coefficients must be
supplied to the program by the user via the keyboard, and get
initialized by an appropriate user-defined constructor at the
time of creating an object. The program should also contain
two instance methods, both returning double values, called
computeFirstX() and computeSecondX() for computing the two x
values.
Deadline and mode of submission: The question be attempted
by only 51 students who attended today's tutorial session.
The source code file, bearing your full name, programme name
and registration number be submitted via email (bearing your
name) to [email protected] not later than 10.00AM, 26
April 2024.
95 / 187
Individual Drill 2: ICTM I
• Write a Java program called BankAccount (containing main( ))
which allows a user to check balance, deposit cash and
withdraw cash from his account by choosing an integer 1, 2 or
3, respectively. If an integer other than 1, 2 and 3 is
entered, the program should display a message No such
service, and terminate. The program should contain relevant
number of instance variables and instance methods. The user
should deposit cash not less than 10,000 and withdraw any
amount such that the balance left is not less than 10,000.
Upon successful completion of any transaction, the program
should display the message Thank you for doing business with
us, and terminate. The program should also include three
well defined packages, balance, deposit and withdraw for
CheckBalance, DepositCash and WithdrawCash classes,
respectively. No constructor is needed, and the initial
deposit amount should be 500,000. Submit the source code by
31st May, 2024 at 3.00PM. Assessment will largely base on
your understanding of the code and ability to answer
questions. Avoid copying of code from anyone.
96 / 187
Part II - Main contents
• Relational operators
• Logical operators
• Order of precedence
• Constructors
• Control structures
• Arrays
• Packages
• Integrated Development Environments (IDEs)Variables
• Basics of Graphical User Interface (GUI)
97 / 187
Relational operators
98 / 187
Relational operators
99 / 187
Logical (boolean) operators
▶ They operate on boolean operands to create a resultant
boolean value which is used to determine whether the combined
statement (expression) is true or not.
▶ These operators are;
• logical NOT
• logical AND
• logical OR
• exlusive OR
▶ The logical AND, logical OR and XOR operate on binary boolean
operands.
▶ The logical NOT (!), is a unary operator, that it operates on
a single boolean operand to invert its state.
▶ The logical NOT (unary operator) is an operator which
operates on a single operand to invert its state.
▶ Represented using symbols, rather than names and that using
names such as NOT instead of ! generates syntax errors.
▶ Binary logical operators operate from left to right order.
100 / 187
Logical (boolean) operators
102 / 187
Constructors
▶ DEMONSTRATION ON HOW to supply instance variables with
values without a constructor.
▶ When you create an object of a class, a special kind of
method called a constructor is always invoked.
▶ If no constructor is defined for your class, the compiler
supplies a default constructor which does nothing.
▶ The default constructor is also described as the no-arg
constructor because it requires no arguments to be specified
when it is called.
▶ The primary purpose of a constructor is to provide programmer
with the means of initializing instance variables uniquely
for each object created.
▶ Constructors ensure that instance variables are initialized
at the time they are created.
▶ However, not all instance variables must be initialized with
the constructor
103 / 187
Constructors
104 / 187
Control structures
105 / 187
Control structures
106 / 187
Sequential control structure
107 / 187
Sequence control structure
108 / 187
Sequence control structure
109 / 187
Selection control structure
110 / 187
Selection control structure: if statement
111 / 187
Selection control structure: if statement
112 / 187
Selection control structure: if statement
113 / 187
Selection control structure: if statement
114 / 187
Selection control structure: if/else
115 / 187
Selection control structure: if/else
116 / 187
Selection control structure: if-else-if ladder
▶ It is a variant of the if/else statement.
▶ Its else statement may contain another if statement,creating
a series of if-else statements in which only one if statement
execute when its condition is true.
▶ The conditional expressions are evaluated from top to bottom,
and at no time will two or more else if statements execute.
▶ As soon as the true condition is found, the statement
associated with it is executed and the rest of the ladder is
bypassed.
▶ If it erroneously happens that two else-if statements contain
the same conditional expression, the first else-if statement
in the order will execute.
▶ If none of the conditions is true, the final (optional) else
statement is executed.
▶ An else clause always associates with the nearest if in the
same block that is not already associated with any else.
117 / 187
Selection control structure: if-else-if ladder
if(boolean_expression){
//statement 1;
} else if (boolean_expression){
//statement 2;
} else if (boolean_expression){
//statement 3;
} else if (boolean_expression){
//statement 4;
}else { // This else clause is optional
//statement 5;
}
118 / 187
Selection control structure: switch statement
119 / 187
Selection control structure: switch statement
▶ Statements to be executed when the case is selected follow
the case label.
▶ All case labels and their associated statements are placed
between braces for switch statement.
▶ Switch statement may contain a special case called default,
which is selected when the value of the switch expression
does not correspond to any of the values for the other cases.
▶ A value of an expression is successively tested against a
list of constant values and when a match is found, the
statement sequence associated with that match is executed.
▶ This means a particular case is selected if its value is the
same (matches) with the value of the switch expression.
▶ Frequently, the expression controlling the switch is simply a
variable and the case constant (value) must be literals of a
data type compatible with the variable (expression).
▶ Statements of each case label may be terminated by an
optional break statement.
120 / 187
Selection control structure: switch statement
121 / 187
Selection control structure: switch statement
122 / 187
Selection control structure
123 / 187
Repetition control structure
124 / 187
Repetition control structure: for loop
125 / 187
Repetition control structure: for loop
▶ The update expression can change by any amount, but usually
it changes by one.
▶ The expression i++ is equivalent to i = i + 1 or i += 1.
▶ If you want it to change by 2, you can write i += 2.
▶ The update expression may also involve -, *, / or any valid
combination as long as it meets your need.
▶ If a loop continuation condition evaluates to false from the
beginning, the for loop body will not execute
▶ The general syntax of the for loop is;
126 / 187
Repetition control structure: for loop
▶ Example of the for loop is;
129 / 187
Repetition control structure: Sentinel
controlled while loop
▶ It is used where the number of repetitions (iterations)is not
known in advance.
▶ In this case, a condition must be set to enable the loop
iterate for any unspecified number of times, and terminate
when required.
▶ It uses a special value called sentinel or signal value which
indicates when a loop should terminate.
▶ Upon entering a sentinel value, the loop will terminate and
the next statement in the order of execution after the while
loop will execute.
▶ While a sentinel value can be any number, it must be careful
chosen so that it can not be confused with any acceptable
values entered by the user.
▶ The sentinel value may vary from program to program depending
on the valid range of the values to be entered by the user.
130 / 187
Repetition control structure: Sentinel
controlled while loop
131 / 187
Repetition control structure: Sentinel
controlled while loop
132 / 187
Repetition control structure: while (true) loop
133 / 187
Repetition control structure: while (true) loop
134 / 187
Repetition control structure: do-while loop
135 / 187
Repetition control structure: do-while loop
136 / 187
Arrays
137 / 187
Declaring arrays
138 / 187
Creating arrays
139 / 187
Declaring and creating an array (combined)
140 / 187
Array initialization
141 / 187
Array initialization
▶ After creation:
• This method initializes an array after its creation and is
commonly used to initialize one element value at a time.
int [ ] intArray = new int[5];
• Then assigning values can be done such as;
intArray[0] = 5;
intArray[1] = 12;
intArray[3] = 45;
• Not necessary to initialize all elements at once and in an
order as elements can be initialized (or accessed) randomly.
• Repetition loops such as for and while can also be used to
initialize larger arrays much easily.
Figure 14: Assigning elements to an array using for loop after creation
142 / 187
Packages
143 / 187
Packages
144 / 187
Packages
145 / 187
Packages
146 / 187
Packages
147 / 187
Creating and using packages
148 / 187
Creating and using packages
149 / 187
Creating and using packages
150 / 187
Packages and access specifiers
▶ They are also called access modifiers or access attributes
▶ They are elements which control accessibility of class
members (data and methods) from other classes in the program
▶ Access to class members from other classes depends on access
specifiers specified for the class members regardless of the
package in which the class belongs
▶ Non-static (instance) members (variables or methods) can not
be referenced (accessed) by static (class) members (i.e.,
instance variables and methods can not be accessed by static
(class) variables and methods.
▶ Static members (variable and methods) can be accessed by both
static and non-static members.
▶ Four access specifiers are public, protected, private and
default.
▶ If no access specifier has been specified for a particular
class member, then the member is said to have a default
access specifier.
▶ Default access specifier is essentially absence of an
explicit access specifier.
151 / 187
Packages and access specifiers
▶ public:
• It is the least restrictive access specifier
• Public members are accessible to all code (methods) in the
program
• A class declared as public in a package can be accessed from a
class within the same package and other packages of the program
• Classes not declared as public can be accessed only by classes
within the same package
▶ protected:
• Accessible in any class in the same package and from any
subclass(es) within and outside the package in which it is
defined.
▶ private:
• It is the most restrictive access specifier
• Private members can only be accessed by code (methods) inside
the class
• Any code that is not a member of the class can not access a
private member.
▶ default:
• It means no access specifier specified
• Accessible to any methods in any class in the same package
152 / 187
Packages and access specifiers
153 / 187
Object oriented programming: Access specifiers
154 / 187
Standard packages and classes
155 / 187
Standard packages and classes
▶ Commonly used Java's packages include;
• java.lang: Contains language support classes (e.g classes
which defines primitive data types, math operations).
✓ This package is automatically imported into any Java program.
• java.util: Contains utility classes which implement data
structures like linked list, dictionary and support for
Date/Time operations.
• java.io: Contains classes for supporting input/output
operations.
• java.awt:Contains classes for developing Graphical User
Interface (GUI) or window-based applications in Java.
• javax.swing:Contains classes for implementing the components
for graphical user interfaces (like button, menus etc.)
• java.awt.event: Defines classes and interfaces used for event
handling in the AWT and Swing.
• java.net: Contains classes for supporting networking
operations.
▶ Each of these packages contains several classes which in turn
contains many methods.
156 / 187
Standard packages and classes
157 / 187
Integrated Development Environment (IDE)
▶ It is a software suite that consolidates tools essential for
software development into a unified platform.
▶ Provides the programmer with centralized tools for authoring,
modifying, testing, debugging, deploying code documentation
and others to streamline the development process.
▶ By integrating multiple tools within cohesive environment,
developers can write, test and debug code more efficiently,
ultimately contributing to increased productivity.
▶ Examples of popular IDE for Java programming include
NetBeans, Eclipse, Visual Studio, IntellJ
▶ Among other things, IDE consists of the following;
• Source code editor (Text editor): For creating and editing
source code.
• Build automation tools: Performs various activities such as
compiling source code, packaging, running tests, deploying
software and creating documentation and release notes.
• Debugger: Used to find and remove bugs (errors) in the program
source code i.,e. debugging.
158 / 187
Integrated Development Environment (IDE)
159 / 187
Integrated Development Environment (IDE)
160 / 187
Integrated Development Environment (IDE)
▶ Advantages (benefits) of using IDE include;
• Framework integration: Provides tools to package applications
and integrate them with frameworks.
• Enforce project, company or language standards:
• Breakpoints and debugging console: Using breakpoints,
developers can pause code execution at specific points to
facilitate step-by-step debugging.
✓ Debugging consoles provide real-time insight into variable values,
function calls and other critical information during debugging
process
• Variable inspection and tracking: Provides tools for inspecting
variables and tracking their values as code runs.
• Code compilation and execution: Provides real-time
compilation, allowing developers to identify syntax errors and
compile their code as they type.
• Immediate feedback on code changes: Developers can observe
the impact of code changes almost immediately.
• Code refactoring tools: Allows developers to restructure,
rename elements such as variables, methods, classes easily and
organize imports with minimal efforts, saving time, and
ensuring code quality.
161 / 187
Integrated Development Environment (IDE)
162 / 187
Integrated Development Environment (IDE)
163 / 187
Integrated Development Environment (IDE)
▶ Disadvantages of using IDE include;
• Initial setup and configuration: IDEs, especially those with
extensive features may have steeper learning curve during
initial setup and configuration.
✓ Setting up of project environment, integrating external tools and
preferences which can be time-consuming for new comers.
• Mastering advanced features: IDEs often come with a wide array
of advanced features which can be powerful but might require
time and effort to master.
• Resource intensive: Some IDEs may demand substantial
computational resources which can pose challenges to developers
using older hardware or working in resource-constrained
environment.
• Impact on system performance: Running IDE alongside other
resource intensive applications can impact overall system
performance.
✓ IDE processes such as compiling or running intensive analysis may
lead to slowdowns especially on less powerful machines.
• Feature overload for simple projects: IDEs may contain
comprehensive features which may create a sense of feature
overload and make the development environment seem overly
complex for the scope of smaller projects.
164 / 187
Basics of Graphical User Interface (GUI)
165 / 187
Basics of GUI
▶ Three major frameworks for GUI development in Java are;
• Abstract Windowing Toolkit (AWT)
• Swing
• JavaFX
▶ AWT and swing reside in the standard packages java.awt and
javax.swing, respectively which both contain many classes for
writing GUI programs.
▶ Most components for creating GUI in Java are members (classes
and methods) of these packages.
▶ The java.awt package has been included in Java since the
earliest versions of Java.
▶ AWT was the first framework for GUI development in Java, but
due to several limitations, more robust and feature rich
frameworks such as swing and JavaFX were developed.
▶ Limitations of AWT include;
• Most of its components are dependent on the OS. This means the
same component such as a button could have different look and
feel depending on the OS the application runs on.
• Many components of this framework provided limited
functionalities.
166 / 187
Basics of GUI
167 / 187
Console VS Windowed applications
168 / 187
Console VS Windowed applications
▶ Events performed by user on GUI include;
• Clicking of the mouse button.
• Pressing of the window components including button, radio
button, check box etc.
• Entering the text on a text field.
• Pressing a key on the keyboard.
• Selecting an item such as text, color etc.
• Pointing of the window component.
• Resizing the window etc.
• Displaying message (text) on the label
▶ Statements of the GUI programs which execute at any time
depend on the event that takes place.
▶ If a user presses a button or clicks a mouse, then the code
that is associated with this event (pressing of a button or
clicking of a mouse) will execute.
▶ For each type of an event, the program could do an event
(action) associated with that event.
169 / 187
Basics of GUI
170 / 187
Basics of GUI
171 / 187
Creating GUI-based Java application - Steps
172 / 187
Creating GUI window
173 / 187
Creating a window - Extending a JFrame class
174 / 187
Creating a window - Extending a JFrame class
176 / 187
Creating a window - Creating a JFrame class
180 / 187
Adding smaller components to a window
▶ After the window has been created, you can add other
components on it.
▶ To do this, there are two methods to use, add() and
getContentPane() methods.
▶ When adding any component directly to the window, use the
getContentPane() method and not add().
▶ The add() is used when adding a component to another
component, which is then added to the content pane using the
getContentPane() method.
181 / 187
Adding smaller components to a window
182 / 187
Event handling
183 / 187
Event handling
▶ The methods (actual code to respond to an event) that a
listener class must have are defined in the interface.
▶ Common listener method we will use is actionPerformed( ) that
belongs to class ActionEvent.
▶ It responds to pressing of buttons, changing of text on
textfields, selection of choices.
▶ However, there are other methods for different classes and
interfaces which can be used to handle different events.
▶ A listener method always get an object of type of class to
which the interface belongs, for instance, ActionPerformed()
must have a parameter of type ActionEvent.
▶ After implementing the listener method, you must register the
listener. This is done by calling the the appropriate method
to the component the listener is connected to.
▶ For button presses we use the method AddActionListener to
register the listner.
184 / 187
Customizing behaviors of components
185 / 187
Group Assignment
▶ Write GUI-based Java program called WeightOfWaterGUI which
computes weight of water contained in a rectangular container
of dimensions; height, length and width, representing the
container's height, length and width, respectively. All
these inputs should be entered by the user through three
textfields for height, width and length of the aplication
window. The program should also contain two constants
DENSITY (1000kg/m 3 ) and GRAV_FORCE (9.81N/kg) for density of
water and gravitational force, respectively. Further, it
should contain three instance methods (all returning double
values) called computeVolume(), computeMass() and
computeWeight() for computing volume, mass and weight of
water, respectively. The program should finally print, on
the window, the volume, mass and weight of water. All group
members must appear in person for the presentation of their
program in my office (Fundikira (block B) 207) by Friday,
14th June 2024 at 6.00PM. The program should have a look
similar to one shown in Figure 20.
186 / 187
Figure 20: WeightOfWaterGUI window
187 / 187