Css 121 Lecture1 Kilima
Css 121 Lecture1 Kilima
3 / 178
Course assessment
∗ Course assessment:
• Quiz - Many.
• 2 Assignments @ 10%.
• 2 tests @ 15%.
• University Examination (UE) - 50%.
∗ Marks for assignments, tests or UE cannot
be compromised or negotiated.
∗ Any dissatisfaction with the UE results
should not be directed to the lecturer but
handled in accordance with MU academic
regulations.
∗ Provide prior notice if you feel you
cannot write the test or submit the
assignment as required. 4 / 178
Answering of test & Exam questions
∗ Observe the following;
• Strictly follow the instructions given - List,
explain, tabular form.
• Answer questions sequentially.
• Grammar and spelling mistakes that distort the
meaning will not be tolerated. Eg., crality vs
clarity, collect vs correct, blind vs bind, flesbility vs
flexibility, later vs letter, assess vs access, submission
vs submittion
• Definitions must be logically sound and
coherent.
• Be neat, clear, concise, and legible.
• Cross out/cancel answers explicitly.
• Write question number for each question.
5 / 178
Answering of test & Exam questions
∗ Observe the following;
• For the UE, each new question should start on
a new page.
• Do not write your name anywhere in the answer
paper/booklets.
• Use simple and concise examples when answering
questions.
• Provide the full forms of terms used e.g.
Don’t Repeat Yourself (DRY).
• Provide only the number of items (3, 4, or 5)
asked to be listed or explained.
• Do not provide definitions if not asked.
• I hope to receive your full cooperation.
6 / 178
Prerequisites, requirements &
assumption
∗ Prerequisites
i. Programming skills and concepts from CSS 111
and CSS 112
∗ Requirements
i. Java Development Kit (JDK) - JDK 23 or JDK 21
LTS
ii. Preferred text editor - TextPad text editor
for Windows or vim for Ubuntu Linux
iii. Preferred Java IDE - Apache NetBeans (v23) or
Visual Studio Code
∗ Assumption
i. Novice to Java programming
7 / 178
Principles to consider
∗ Read Read
∗ Practise Practise Practise Practise ......
∗ Get more answers through reading relevant
references such as books and web materials
rather than asking others
∗ Demonstrate what you know to others
8 / 178
Main contents
• Introduction to computer programming
• Computer programming languages
• Java
• Identifiers
• Reserved words
• comments
• Data types
• Variables
• Java classes
• Method main ()
• Arithmetic operators
• Method println()
• Method
• Program errors
9 / 178
Recommended References
10 / 178
Recommended References
11 / 178
Brainstorming
12 / 178
Introduction to computer
programming
∗ Computer program: An ordered set of
stored instructions which control the
operations of computer hardware.
∗ Computer hardware such as CPU, RAM,
keyboard etc. are responsible for
carrying out computer operations.
∗ Computer programs provide instructions to
computer’s CPU, which in turn sends
signals to respective hardware to execute
desired operations.
∗ Programs give computers ability to carry
out all the tasks they perform. 13 / 178
Introduction to computer
programming
∗ Computer programming: A process of
developing computer programs.
∗ It is a multidisciplinary field, which may
combine knowledge, skills and experience
from other fields including;
• Mathematics, computer security, database,
computer networking, statistics, sciences, AI,
communication skill, software engineering etc.
∗ The professional diversity involved in the
development of a computer program depends
on the use of the program being developed.
14 / 178
Computer programming language
15 / 178
Computer programming language
16 / 178
Computer programming languages:
Types
17 / 178
Low level programming languages:
Weaknesses
18 / 178
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 to improve their security,
performance, suitability, usability etc.
19 / 178
High level computer programming
languages
∗ 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 special vocabulary
instead of sequence of binary digits.
∗ They also allow programmers to name
storage locations of the computer rather
than remembering them.
20 / 178
High level computer programming
languages
∗ Each high level programming language has
its own specific and limited set of
vocabulary and rules (syntax).
∗ Mastering a programming language involves
learning;
• A set of vocabulary
• Syntax
• Semantics
• Programming logic
∗ Vocabulary: A set of words, symbols, and
expressions that are valid and meaningful
in that language like keywords, operators,
identifiers, and data types. 21 / 178
High level computer programming
languages
∗ Syntax: A set of rules of a programming
language which tells programmers what is
an acceptable program.
∗ Semantics: Refers to the meaning of the
statements and expressions in a program.
• Correct semantic: x = 5
• Incorrect semantic: "Mzumbe" + 10
∗ Programming logic: Involves writing
program’s statements in the correct order
to produce the desired output (result).
22 / 178
High level computer programming
languages
∗ You may use programming language’s syntax
correctly but fail to observe the logic.
∗ With high level programming language like
Java, programmers write a series of
executable statements for a program to
carry out a specific task.
∗ Special software called compilers and
interpreters translate program’s statements
from high level programming language into
machine code for the CPU’s execution of
the statements.
23 / 178
High level computer programming
languages
∗ Compilers and interpreters generate error
messages each time they encounter an
invalid statement or violation of the
language’s syntax or vocabulary.
∗ Errors resulting from invalid programming
statements or misuse of the language are
called syntax errors.
∗ Locating and fixing these syntax errors
and other types of errors is called
debugging.
24 / 178
High level computer programming
languages
∗ Programs written in compiled languages
like C++ do execute faster, while those
written in interpreted languages like
Visual Basic (VB) are easier to develop.
∗ Java is both a compiled and interpreted
computer programming language.
∗ It uses a compiler to translate the
program into bytecode, and an interpreter
to read the bytecode line by line at
runtime (execution).
25 / 178
High level programming languages:
Strengths
∗ High portability: Largely machine independent
and highly portable.
• A high level program can be run on different
types of OS platforms and CPU architectures
with little or no modifications.
∗ Contains fewer code: Program statements are
fewer than their equivalent machine
language programs.
∗ User friendly: They look very similar to
human (natural) languages like English.
26 / 178
High level programming languages:
Strengths
27 / 178
High level programming languages:
Weaknesses
∗ Less performance: This is because they need
to be translated or/and interpreted into
appropriate machine language for each CPU
platform before they are executed.
∗ Need for translators: Translators
(compilers and interpreters) must be
developed and installed in order to
compile and translate high level programs
into their machine language equivalents.
28 / 178
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).
29 / 178
Java: Brief background
30 / 178
Motives for inventing Java
∗ The primary motivation for its invention
was the development of a cross-independent
language for creating software to be
embedded in consumer electronic devices.
∗ This compelled James Gosling’ team to work
on cross-platform programming language.
∗ At the same time, the World Wide Web
(WWW), which needed platform-independent
applications, was invented.
• Java’s Applets were cross-platform programs
provided features such as interactive forms,
animations, multimedia etc. and were executed
by JVM embedded in web browsers that supported
Java.
31 / 178
Motives for inventing Java
∗ Significance of the WWW to the growth and
popularity of Java;
• Java became a powerful server-side programming
language for backend services to handle web
and database requests for early e-commerce
websites like Amazon and eBay.
• Java Server Page (JSP) became important web
application technology.
∗ Had the WWW not taken shape at the time of
its invention, Java might have remained a
useful but an obscure language.
∗ Cross-independent language is also known
as platform-independent, architectural
neutral or machine-independent language.
32 / 178
Features of Java
∗ A simple programming language whose syntax
is largely based on C and C++ languages.
∗ A software platform which is;
• A multi-platform programming language
• Class-based object-oriented programming (OOP)
• Network centric programming language
• A general-purpose programming language
∗ Capable of developing different types of
robust applications running on billions of
devices including;
• Micro-computers
• Mobile phones
• Servers
• Gaming consoles
• Medical devices etc.
33 / 178
Features of Java
∗ It is a very stable programming language
with;
• Strong memory allocation
• Automatic garbage collection mechanism
• Powerful exception handling
• Type checking
• Checks for compile-time and run-time errors by
compiler and interpreter, respectively.
∗ Contains hundreds of network features to
provide massive support for network and
distributed-based applications.
∗ Supports many character sets including
ASCII and Unicode.
34 / 178
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
like lists, queues and arrays. 35 / 178
Features of Java
∗ It supports multi-threading, allowing a
program to have different threads
executing independently at the same time.
∗ It is a programming language and software
platform available for all major operating
systems including Windows, Linux and MacOS
∗ Available on all major CPU architectures
with little or no modification. These
include;
• CISC (x86, x86-64 (AMD64 Intel64))
• RISC
• ARM architecture
• IBM Power Architecture
• SPARC
• MIPS 36 / 178
Features of Java
∗ The platform-independence nature of Java
enables development of applications which
run unchanged on different CPU platforms.
• It is called ’Write Once Run Anywhere (WORA)’
∗ Platform-independence occurs because Java
programs do not execute directly on CPU,
but on a runtime environment called Java
Virtual Machine.
∗ Java program is first compiled by Java
compiler (javac) into a bytecode, which is
subsequently executed (interpreted) by
Java virtual machine (JVM) for a specific
hardware (CPU) architecture.
• JVM is also known as Java interpreter
37 / 178
Features of Java
∗ 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 OS to provide libraries and resources
needed to execute Java programs.
∗ While compiler and JVM are platform-dependent,
bytecode produced by Java compiler and
executed by JVM is platform-independent.
• Java bytecode can run on any CPU architecture
that runs JVM without need to recompile.
∗ Java is designed to adapt evolving
environment, allowing libraries to easily
add new methods and instance variables.
38 / 178
Features of Java
39 / 178
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 to develop applications
running on network servers and many Internet.
40 / 178
Major applications of Java
∗ It is widely used for development of;
• 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 to
develop of machine learning applications to
solve 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
41 / 178
Java: A compiled and interpreted
language
∗ Source code is a program file made up of
program statements in high-level language.
∗ However, computers do not understand
statements written in high-level language.
∗ A bridge is needed between the high-level
language and the machine language.
• Compiler: It translates program source code
from high-level language to machine language.
• Interpreter: It carries out the instructions
of the program source code directly.
∗ The source code in high-level programming
languages is compiled into object code
compatible with specific CPU. 42 / 178
Java: A compiled and interpreted
language
∗ However, this is not the case with Java as
it involves a combination of both
translation and interpreting.
∗ The translation (compilation) of a Java
program by Java compiler (javac) produces
an output called bytecode which is not a
true machine language (i.e., object code).
∗ Bytecode is designed to be executed by
Java interpreter (JVM).
∗ If the compilation succeeds without any
syntax error, the program can be executed
by the run-time. 43 / 178
Java: A compiled and interpreted
language
∗ Bytecode is a binary representation into
which a program source code is converted
by Java compiler.
∗ Since bytecode file does not contain real
machine machine code, it can not be
directly executed by any CPU.
∗ Bytecode is interpreted by Java
interpreter, specifically Java Virtual
Machine (JVM) into appropriate object code
to be executed by CPU.
44 / 178
Java: A compiled and interpreted
language
∗ Translating Java programs into bytecode
has advantages include;
• The bytecode is not specific to a particular
CPU - instead, it can be executed by any
computer’s CPU.
✓ This makes Java a platform independent language
because its programs are executed on different
CPU platforms with appropriate JVM.
• Since bytecode is less complicated than
equivalent source code, it is easier to write
Java interpreter and embed it in programs such
as web browsers.
✓ It allows Java web-based programs to run on
different web browsers embedded with JVM.
45 / 178
Java: A compiled and interpreted
language
∗ Once appropriate JVM for a given platform
(CPU or web browser) is installed, any
Java program can run on it.
∗ Although details of JVM differ from one
CPU platform and web browser to another,
all JVMs understand the same bytecode.
∗ If Java compiled to native code, a
separate program version would be needed
for each CPU.
• This would make Java a platform-dependent
language, similar to its predecessors like
C++.
46 / 178
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 modeled after C and C++ languages;
• There is close similarity in the syntax and
vocabulary between the two languages.
∗ Despite the similarity, Java eliminates
most complex features and hardware
dependence of C and C++.
47 / 178
A compiled language: E.g. C++
54 / 178
Creating a first Java program: Steps
1. Create a folder, separate from Java
installation folder for storing your
program source code files.
2. Create a program file (source code) using
a text editor.
3. Save your program file in the folder
created in step (1) using a name that;
• Has the same name as the class name.
• Not a reserved word (keyword).
• Observes rules and conventions for naming
classes.
• Has a .java extension, Eg. FirstProgram.java
55 / 178
Compiling Java program: Steps
1. Start up a CMD window (for Windows OS) or
command line interface (for Linux OS).
2. Navigate to the folder with Java files
using CD commands.
CMD commands: cd, \ and dir.
3. Compile a program:
javac program_name
4. As our program is FirstProgram.java, run
this command to compile it into bytecode;
javac FirstProgram.java
5. Ensure that the FirstProgram.java file is
in the current directory or specify its
classpath in the command.
56 / 178
Running Java program: Steps
57 / 178
Things to Note
58 / 178
Computer programming language:
Simple Java program
59 / 178
Computer programming language:
Simple Java program
60 / 178
Identifiers
∗ Identifier: A sequence of characters used
as a name for a program’s construct like
class, method, variable or object.
∗ Rules for naming identifiers differ
depending on the construct for which the
identifier is used.
∗ All identifiers must be declared in the
main class or support class before they
are used.
∗ Any attempt to use undeclared identifier
generates an error.
∗ Java is a case sensitive language, and
therefore R is not the same as r.
61 / 178
Identifiers
∗ Java conventions for identifiers include;
∗ Identifiers for variables, methods and
packages start with lowercase and any new word
begins with an uppercase letter such as sum,
sqFeet, toSqFeet.
∗ Identifiers for class names should start with
uppercase letter for every first letter of
each word in the name such as First_Program,
FirstProgram, _FirstProgram, $FirstProgram
∗ Use meaningful and descriptive identifiers;
• The identifier salary is appropriate for used to
store a person salary
• age for person’s age
• coursework for student’s coursework
• firstName for a person’s first name
• studRegNumber for a student’s registration number
62 / 178
Identifiers
63 / 178
Reserved words (Keywords)
∗ They are special words with predefined
meaning in Java language.
∗ They are used by Java for special purpose
and should not be used by the programmer
for any other use in the program.
∗ If used by a programmer as identifier,
they will confuse Java, and syntax errors
will be generated.
∗ A comprehensive list of Java keywords is
shown in Fig. 5
64 / 178
Reserved words
65 / 178
Reserved words
66 / 178
Comments
∗ Comments are notes put in the program by
the programmer to clarify the code to the
readers.
∗ They are part of program documentation
i.e, information that enhances the program
readability.
∗ Comments are ignored by Java compiler
during compilation and not translated into
machine language during program execution.
∗ Writing useful and good comments in a
program is a good programming practice.
67 / 178
Comments
∗ Comments may be used to;
• Describe the purpose of the program.
• Explain the use of an identifiers.
• 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, method, variable
etc.
∗ Comments are put anywhere in a program.
68 / 178
Comments
∗ Two ways of writing comments in Java are
using:
• Line comments which use double forward slash
(//).
• Bar and star (surrounded) comments which use
/* and */ at the beginning of the first
comment line and end of the last comment line,
respectively.
∗ When using surrounded comments, ensure the
presence of both delimiters at the
beginning and end of the comment.
∗ When using line comments, all text on the
rest of the line is a comment.
69 / 178
Comments
∗ Important conventions (guidelines) when
using comments;
• A comment should precede class definition.
• Comments should not appear in the middle of
the a statement.
• Comments should not describe how Java works,
but give insights not readily apparent from
the code.
∗ Each class should begin with a header
section that consist of comments
specifying;
• The programmer’s name
• The date of the current version
• A brief description of what the class does
70 / 178
Comments: Single line comment
71 / 178
Comments: Surrounded comments
(Multiple line comments)
72 / 178
Program statements and format
∗ Statement: An instruction that causes the
computer to perform an operation.
• In Java, a statement is usually terminated
with a semi colon (;).
• As Java ignores line breaks, a statement can
extend over multiple lines.
• A statement extending over more than one line
can not be split in the middle of an
identifier, a reserved word or a literal.
• Placing one statement on a line improves
readability, specifically when updating or
debugging the program.
• By default, Java’s program statements are
executed one by one in order of appearance
i.e., from top to bottom.
73 / 178
Program statements and format
∗ About Java statement....
• At least one blank space is required between
two adjacent words or keywords in a program
statement to enhance program readability.
• Extra spaces between words are ignored by
compiler, but they may be used to enhance
readability and style of a program.
• To enhance program readability, leave blank
space before and after operators such as
arithmetic operators.
• Do not insert blank space before or after the
dot symbol (.).
• Use Tab key not space bar to indent a
statement.
74 / 178
Statement, expression and statement
block
75 / 178
Data types
∗ Data type: A classification defining a
set of values, permissible operations that
can be performed on them and amount of
memory required to store a single value.
∗ For each data type, Java specifies;
• Range of values (minimum to maximum value)
• Operations to be performed to all values of a
particular type
• Storage mechanism (size) 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 (+, -, *, /, %).
76 / 178
Data types
∗ 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 primitive built-in 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.
∗ Having different data types allows the
compiler to determine valid operations and
memory space for each data value.
77 / 178
Data types
∗ Java compiler generates an error when an
invalid operation is performed to a
particular data value.
• For instance, an attempt to add two boolean
values generates an error.
∗ Similarly, an attempt to store a value
inconsistent to a declared variable type
generates an error.
• For instance, an attempt to store a string
value to a variable of type int generates an
error.
∗ To enhance portability across different
architectures, all primitive data types
have strictly defined range of possible
values. 78 / 178
Data types
∗ For instance, an int is a 32-bit
regardless of the computer architecture.
• This allows Java programs to be written and
run on any platform.
∗ 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
79 / 178
Data types
82 / 178
Non-numeric primitive data types:
Boolean data type
∗ A data type with two values namely true and
false.
∗ It is also known as logical data type
∗ Common operators on boolean values are;
• logical conjunction (AND), represented as & or &&
• disjunction (OR) represented as |
• Exclusive OR (XOR) represented as ∧
• Negation represented as !
• Equality represented as ==
• Inequality represented as !=
∗ Java boolean values must always be written
in lowercase letters, i.e., true and
false. 83 / 178
Non-numeric primitive data types:
Boolean data type
P R P&R P | R P ∧ R !P P==R P != R
true true true true false false true false
true false false true true false false true
false true false true true true false true
false false false false false true true false
84 / 178
Non-numeric primitive data types:
Char data type
∗ Comprises of printable and non-printable
characters.
∗ Represents an individual character value
of a character set such as a letter, digit
or special symbol.
∗ Its storage locations (variable) store
only one character
∗ A char data type has a memory size of 16
bits (2 bytes), allowing characters to be
represented as integers.
∗ Char data type is unsigned, meaning that
it can only store positive values. 85 / 178
Non-numeric primitive data types:
Char data type
• Java uses a coding scheme for characters
called Unicode which has 65,536 unique
characters.
• Unicode has a minimum value of '\u0000'
(or 0) and a maximum value of '\uffff' (or
65,535 inclusive)
• Unicode allows symbols from different
languages such as English, Kiswahili,
Chinese, French, Japanese etc. be
represented in Java programs.
• A character data value must be enclosed in
apostrophes (single quotes) e.g., 'F', '
86 / 178
Non-numeric primitive: Char
• Java uses a special set of symbols called
escape sequences, written as type char, to
represent special characters.
88 / 178
Non-numeric primitive data types:
Char data type
∗ It also contains non-printable characters
which include blank character and line-end
character, commonly used as separators.
• They separate data or split text into lines.
∗ A line-end character signifies the end of
a line in text such as a newline (\\n) or
carriage return (\\r) character.
• A newline character (Line feed) moves the
cursor down to the next line, keeping it at
the same horizontal position.
• A carriage return character moves the cursor
to the beginning of the current line without
advancing to the next line.
89 / 178
Primitive data types: Integer
90 / 178
Primitive data types: Integers
91 / 178
Primitive data types: Integers
∗ byte
• Occupies 8 bits (1 byte) of memory.
• It ranges from -128 to 127 i.e., −27 to 27 − 1
∗ short
• It occupies 16 bits (2 bytes) of memory
• It ranges from -32,768 to 32,767 i.e., −215 to
215 − 1
92 / 178
Primitive data types: Integers
∗ int
• A commonly used integer data type.
• Occupies 32 bits (4 bytes) of memory.
• It ranges from −231 to 232 − 1.
∗ long
• Occupies 64 bits (8 bytes).
• Ranges from −263 to 263 − 1.
93 / 178
Floating-point numbers
∗ Denotes a subset of all real numbers such
as 1.8, -2.0, 3.14 etc.
∗ Permitted to be inaccurate within the
limits of the round-off errors caused by
computations on finite number of digits.
∗ Common operators on floating-point numbers
are addition(+), subtraction (-), division
(/), and multiplication (*).
∗ Integers are considered a subset of
floating-point numbers, and can easily be
promoted into floating-point values.
• The inverse direction is not permissible.
94 / 178
Floating-point numbers
95 / 178
Floating-point numbers
∗ Two major categories of floating-point
numbers are float and double.
∗ Float
• Its values range from -3.4E38 to +3.4E48
• Each float value occupies 32 bits of memory.
• It has 7 significant digits of precision, i.e.
stores exactly only 7 significant digits and
rounds off or truncates the remaining.
∗ Double
• Each value occupies 64 bits of memory.
• They range from -1.7E308 to 1.7E308.
• A default type for floating-point data type.
• It has 17 significant digits of precision.
96 / 178
Non-primitive data type
∗ It is also called reference data type
because it references (stores) a memory
location of an instance (object), rather
than an object itself.
∗ It does not store the actual value of the
object, but rather store memory address
(reference) of an object.
∗ Some of the non-primitive data types are
created by the programming language, while
others are created by the programmer.
∗ m In Java, non-primitive data types are
simply called "objects" because they are
created, rather than predefined.
97 / 178
Non-primitive data type
∗ Examples of non-primitive data types are;
• Arrays, enumerations
• Objects of standard (built-in) classes such as
String, Random, JFrame, Scanner etc.
• Objects of user-defined classes (i.e., classes
created by programmer)
• Interfaces
∗ Everything in Java is object except
primitive data types.
∗ Non-primitive data types are associated
with particular classes.
∗ They represent any instantiable class.
∗ m Non-primitive data types are created by
using the new keyword.
98 / 178
Primitive vs non-primitive data type
99 / 178
Non-primitive data type: Creating
objects
100 / 178
Non-primitive data type: Creating
objects
101 / 178
Non-primitive data type: Creating
objects
∗ Clarifications of the syntax;
• Person :Class name defining the data type of
variable aneth.
• aneth :An instance of an object Person.
✓ It represents a name for a reference (variable)
to store memory address for an object.
• = :The assignment operator which tells the
compiler to assign the created object to the
variable aneth
• new :keyword used to create objects
• Person( ) :A constructor which tells the
compiler;
✓ How much space is needed for an object instance.
✓ Initialize variables of an object to its default
values. 102 / 178
Variables and variable types
∗ Variable: A named storage location in
memory used to store data values during
program execution.
∗ They are called variables because their
contents (values they hold) can change.
∗ Variables store input data, intermediate
results and output data (results).
∗ Data values can be numeric, text, boolean,
strings or characters.
∗ A variable must have a specific name
(identifier) used to refer to it and a
data type describing the category of data
value.
103 / 178
Variables and variable types
∗ Variable declaration is a kind of data
declaration
∗ Data declaration defines the type of an
identifier and that may provide an initial
value and visibility for the identifier.
∗ A variable consists of three major parts:
• Access specifier (modifier): public, private,
protected or default.
• Data type: Any of the data types discussed,
int, float, String, double, char, boolean etc.
• Name (identifier): Any valid identifier. By
convention, variable names begin with
lowercase first alphabetical letters.
104 / 178
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;
105 / 178
Variable declaration
106 / 178
Variable initialization
∗ This is the process of fixing initial
value to a declared variable.
∗ Variables can use the initial values in
the operations or have them changed.
∗ Initialization is done using an assignment
operator (=) in an assignment statement.
• Assignment statement: A statement that stores
a value or a computational result in a
variable.
• In Java, the = operator does not have the
equality meaning it carries in mathematical
calculations.
107 / 178
Variable initialization
108 / 178
Variable initialization
∗ Example of variable initialization is:
total = 2;
boolValue = false;
∗ Variables total and boolValue must have
been declared before as of type int and
boolean, respectively.
∗ Characters and strings must be delimited
by single and double quotes, respectively.
aLetter = 'F';
fullName = “Frank Kilima;”
∗ Variables aLetter and fullName must have
been declared before being assigned.
109 / 178
Variable declaration and initialization
∗ Variable declaration and initialization
can be done in one statement (step) such
as:
int total = 2;
boolean boolValue = false;
instead of doing it in two separate statement
int total;
total = 2;
∗ This makes programs much shorter.
∗ The value of data such as 2 or false
written within a line (in-line) is called
literal.
110 / 178
Types of Variables
111 / 178
Class variables
∗ Class variable: A variable that is shared by
all instances of a class.
∗ They are also called static data fields or
class data fields because they use the
keyword static during their declaration.
∗ Only one copy of each class variable
exists and shared by all class objects no
matter how many objects are created.
• Useful for the information that is always the
same for all objects of the class as it would
be wasteful for each instance to have its own
copy.
∗ They exist even if no objects have been
created.
112 / 178
Class variables
∗ 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.
∗ They are declared using keyword static
with the following syntax:
static data_type variableName;
∗ An example of the class variable
declaration is:
static double pi;
∗ Declaration and initialization in one
statement:
static double pi = 3.14; 113 / 178
Class variables holding constants
∗ Constants do not change throughout program
execution.
∗ They must be protected against both
accidental and intentional changes.
∗ Java provides a way of fixing constants
and prevent them from being changed.
∗ This is done by using keyword final.
static final double pi = 3.14;
∗ The keyword final tells the compiler that
the stored value is a constant that can
only be retrieved but not modified
anywhere in the program.
114 / 178
Class variables holding constants
∗ Any variable declared as final must have
an initial value assigned in the same
statement as it can not be specified
later.
∗ By convention names of class variables
holding constants are written in uppercase
letters.
static final double PI = 3.14;
∗ This improves readability of the constants
within the program.
∗ Any attempt to change a constant value
will generate an error.
115 / 178
Instance variables
∗ They are also called non-static variables
as they do not use keyword static.
∗ They are declared inside the class but
outside any method (i.e., not inside any
method), commonly after class definition
statement
∗ They are associated with each class object
uniquely.
∗ Form the bulk of variables declared in
program.
116 / 178
Instance variables
∗ Each instance (object) of the class has
its own copy of each instance variable,
giving each instance an individuality.
∗ They can not be operated upon by static
methods.
∗ Referencing an instance variable to a
static method generates an syntax error.
∗ It is a good programming practice to
initialize variables to some values.
∗ Initialization of variables can be done in
the variable declaration or in the default
constructor.
117 / 178
Instance variables
118 / 178
Instance variables
Table 6: Default values for Java’s data types
Data type Default value
byte 0
short 0
int 0
long 0L
double 0.0d
float 0.0f
char Null character (NUL), represented as
'\u0000' in Unicode (0 in decimal number),
which means a non-printing character i.e.,
not empty in the sense of having no value
boolean false
String null (no object assigned)
119 / 178
Local variables
∗ Variables declared within the body of the
method.
∗ They exist only within the body of the
method.
∗ They are available only during the
execution of the method.
∗ Their scope (accessibility) is from the
point of declaration to the closing brace
of that particular method.
∗ Unlike instance variables, they are not
automatically initialized to default
values.
∗ They must be initialized to appropriate values
before being used.
120 / 178
Local variables
∗ Any attempt to use uninitialized local
variables generates an error.
∗ Consider the following method:
double getSum(double cw, double fe){
double total = 0.0; //Local variable
total = cw + fe;
return total;
}
∗ total is local variable, of type double.
∗ It must be initialized to any double value
before being used.
121 / 178
Java class definition
∗ A class definition describes the kind of
objects to be defined.
∗ A class, is a set of objects which shares
common behaviors and properties.
∗ 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 non-primitive data type.
∗ Java program is a collection of classes.
∗ However simple a Java program is, it must
be organized into a functional unit called
class.
122 / 178
Java class definition
∗ Even simple programs that add two numbers
(28 + 1), or display messages like ”Hello
students, how are you?” etc. must be
organized into a class.
∗ Program execution is initiated by a class
with the main method.
∗ Other program classes which do not contain
the main method are called supporting
classes.
∗ Methods defined in the supporting classes
are called into execution by the main
method or other methods called by the main
method.
123 / 178
Java class definition
∗ For this reason, the order of method
definitions in the supporting classes is
insignificant.
∗ 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.
∗ A class is therefore used to create
(instantiate) objects (instances) of its
own data type.
124 / 178
Java class definition
∗ 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 start
with an uppercase first letter for every
word in the name.
• It aims at differentiating class names from
variable and method names, and therefore it is
a good programming practice to adhere to it.
125 / 178
Java class definition - General syntax
126 / 178
Java class definition - General syntax
∗ A header declaration contains;
• It tells the compiler of the class definition.
• It contains the reserved word class, followed
by an identifier for the class name.
• It may also declare a class from which this
class extends (i.e., inherits features from)
• Class header is followed by the class body,
which is sorrounded by the delimiters { and }
• The visibility of the class defined by the
access specifier, commonly public
• A public class can be referenced (accessed) by
other classes in the program.
• The general header declaration is
class class_name
127 / 178
Java class definition - General syntax
∗ Variable declarations;
• They provide definitions for variables which
store data values of the program.
∗ Method definitions
• Provide definitions for the methods which
perform certain operations on data values
stored in variables.
∗ Constructor definition
• It initializes variables to some specific or
default values.
• When no user-defined constructor is provided,
a default constructor which initializes
variables to default values (Table 6) is
invoked.
128 / 178
Java class definition - General syntax
129 / 178
Java class definition - General syntax
130 / 178
Java class definition: Clarification of
terms
∗ class keyword
• A reserved word that must precede class_name.
∗ class_name
• Any valid identifier for the class name.
∗ public
• An access specifier signifying that the class
can be accessed by other classes in a program.
∗ extends
• A keyword signifying that the class_name
inherits some features (members) from the
parent_class.
∗ parent_class
• A class from which class_name inherits
features.
131 / 178
Java class definition
132 / 178
Java conventions and Good
programming practices
133 / 178
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.
134 / 178
Method main ( )
135 / 178
Arithmetic operators
∗ To solve most programming problems,
programmer needs to write arithmetic
expressions that manipulate integer or
real numbers.
Table 7: Java’s arithmetic operators
Arithmetic operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder operator
136 / 178
Method println()
137 / 178
Method
∗ Method: A named self-contained block of
code that operates on data values or
perfoms a certain task.
∗ Defines operations that can be performed
on data values (stored in variables).
∗ It is equivalent to a function in C
programming language.
∗ Major advantage of the method is
reusability i.e. ability to be executed
multiple times without rewriting it.
∗ It helps to break a large and complex
problem like calculation into smaller &
more manageable chunks.
138 / 178
Method
∗ A method may receive an input from
external source (keyboard or file) and
store it in the variable.
∗ It may also write information in a file or
display it on the screen.
∗ It may also get input via an argument list
∗ A method is executed by calling its name,
and may or not return a value when its
execution finishes.
∗ Methods that return a value must finish by
executing a return statement.
139 / 178
Method
∗ An access specifier may optionally precede
the return type.
∗ A method’s return type defines the type
for the value that will be returned at the
end of its execution.
∗ A returned value must be consistent with
the data specified in the method
declaration.
∗ Methods that do not return any value have
a return type specified as void.
140 / 178
Method
141 / 178
Method
∗ Java method - Major components;
• 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.
142 / 178
Method definition
143 / 178
Method definition
∗ The general syntax of a method definition
is;
data_type method_name(){
// Body of the method
}
∗ Method name is preceded by return type (or
void) and optionally by access specifier.
∗ Return type specifies the data type
returned by method which can be any of the
primitive data types or reference data
type.
144 / 178
Method
∗ Example of the method definition:
int getSum(){
// Body of the method
}
∗ Body of the method includes the code for
operations to be performed by the method.
int getSum(){
sum = num1 + num2;
return sum;
}
∗ Return type must be consistent with method
type, in this int.
∗ num1, num2 and sum must have been declared
145 / 178
Types of Methods
146 / 178
Instance methods
∗ They are executed only in relation to
particular objects of class rather than to
the class itself.
double getSum(){
double total = 0;
total = cw + fe;
return total;
}
∗ They can only be used after instances of
the class have been created and can not
execute if no object have not been
created.
147 / 178
Instance methods
∗ Variables cw and fe must have been
declared somewhere in the program.
∗ Variable total is a local variable.
∗ They can access class variables, constants
as well as instance variables.
∗ An instance method can not be called with
no reference to any object nor with
reference to the class.
∗ When an instance method is invoked, its
name is tacked next to the instance
(object) name, separated by a period (.)
such as;
circle.findCircleArea();
148 / 178
Class methods
∗ They are also called static methods as
they are declared using keyword static.
∗ They belong to the whole class rather than
to a particular class instance.
∗ The static keyword sticks the method to
the class rather than to the objects of
the class.
∗ They can be executed even if there are no
objects created because they perform tasks
which do not depend on the contents of the
objects.
149 / 178
Class methods
∗ They can manipulate only class (static)
variables i.e., they can not manipulate
instance variables.
• This is because instance variables may not be
created.
• Referencing an instance variable to a static
method generates an error.
∗ Class methods are only referenced to class
variables.
static int countObjects(){
return count;
}
150 / 178
Class methods
∗ The variable count must have been declared
as static variable.
∗ If not static variable, an error will be
generated.
∗ They are useful for creating and operating
on constants and class variables.
∗ When a class method is invoked, its name
is tacked next to the class name,
separated by a period (.) rather than to
any objects of the class.
FindArea.countObjects();
151 / 178
Assignment
1. Write Java program that computes an area
of a triangle with at least two instance
variables and 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 Presidents.
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πr2 ) and volume
2 152 / 178
Assignment
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 (b2 ≥ 4ac). It
should contain;
i. At least three instance variables
ii. At least two instance methods
153 / 178
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.
154 / 178
Parameterized Method
∗ 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.
155 / 178
Parameterized Method
∗ An attempt to call this method without
supplying the values will generate a
compile error.
∗ It is not allowed to declare parameters of
the same type in one statement such as:
int getSum(int a, b, c){
// The rest of the method
}
∗ It is also possible to declare parameters
of different data types such as:
int getSum(int a, double b, float c){
// The rest of the method
}
156 / 178
Parameterized Method
∗ When calling this method, arguments for
variables a, b and c must be of the
appropriate data types and provided in the
same order as specified in the method.
∗ Arguments must match the parameters in
terms of order, number and data type.
∗ This is called parameter order
association.
∗ If the parameter order association is not
observed:
• A syntax error will be generated.
• Incorrect result (logic error) will be
produced.
157 / 178
Calling methods
∗ Method definition (declaration) defines
what the method should perform when
called.
∗ A class method is called using the class
name in which it has been defined.
• A class method called binadamuWalk() defined
in a class Person will be called using this
syntax;
Person.binadamuWalk();
• The . between the class and method is called
a period or dot.
• It is not recommended to call a class method
using an object name.
158 / 178
Calling methods
∗ The syntax for calling the instance method
is objectName.methodName(arguments);
• objetName is the name of the object of the
class in which the instance method methodName
has been declared.
∗ When the method does not have arguments,
the pair of parentheses becomes empty.
∗ Calling an instance method binadamuName()
on an object john of the type Person;
john.binadamuName();
• It is not recommended to call an instance
method using the name of the class.
• When you apply a method to an object instance,
the statements in the method body execute to
process the information stored in that object.
159 / 178
Program errors
∗ Program error: A bad code in a program
that causes it to terminate unexpectedly,
produce an incorrect result, or behave in
unintended ways.
∗ Program errors are commonly referred to as
bugs.
∗ Distinguishing them helps programmers to
track them more quickly.
∗ Most common types of program errors are:
• Compile-time errors (also called syntax
errors)
• Run-time errors
• Logic errors
160 / 178
Compile-time errors
∗ They occur when the code violates the
syntax of the programming language.
∗ Syntax: Refers to the structure or rules
that govern how statements and expressions
are written in a programming language.
∗ Java compiler is not forgiving - it
doesn’t compile code containing any errors
which violate its syntax.
• Java compiler can only translate a program
that is syntactically correct.
• Syntax errors are detected during compilation
(translation) of the program source code.
• If syntax errors are discovered from the code,
the compiler prints them and quits.
• Uncompiled Java program can not be executed.
161 / 178
Compile-time errors
162 / 178
Compile-time errors
163 / 178
Run-time errors
∗ They occur when a program attempts to
perform an invalid operation during
program execution, causing it to stop
executing and terminates.
∗ They are so called because they do not
appear until you run the program.
∗ In Java, they occur when interpreter is
running the bytecode.
∗ In Java, run-time errors are called
exceptions.
∗ Java is a safe language; meaning that it
has few such run-time errors.
164 / 178
Run-time errors
165 / 178
Logic errors
∗ Also called semantics errors.
∗ They are errors in which the program
compiles and runs successfully, but
produces unexpected or incorrect result.
∗ They are caused by following an incorrect
algorithm i.e., the program you wrote is
not what you wanted to write.
∗ Because they do not cause compile-time or
run-time errors and don’t display error
messages, they are difficult to detect.
166 / 178
Logic errors
∗ The only sign of the logic error may be an
incorrect program output.
∗ Identifying logic errors is tricky and may
require a lot of time and effort.
∗ Examples of logic errors are:
• Using a wrong arithmetic operator, for
instance + instead of -.
• Creating an infinity loop or one with off-by
one error.
• Using a data type such as byte in an operation
which produces a value that is outside the
range.
• Calling a different variable but of the same
data type in an operation
167 / 178
Fixing programming errors
∗ The process of identifying and fixing
programming errors from the program code
is called Debugging.
∗ Technique to identify, fix and reduce
program errors include;
• Plan your program design carefully and desk
check them carefully to eliminate the bugs.
• Desk check the algorithm and the program
design before you type it in.
• Desk check the source code before compiling
it.
• Familiarize with different error messages.
168 / 178
Fixing programming errors
169 / 178
Test One - 11 May
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 C+ or C++?
5. List all major categories of primitive
data types in Java. 170 / 178
Individual Drill: ITS I
∗ Write Java program called WeightOfWater
that 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 dimensions are
instance variables whose values are
entered by the user through the keyboard.
The program should also contain two
constants; DENSITY_OF_WATER (1000kg/m3)
and GRAVITY (9.8N/kg) representing density
of water and gravitational force,
respectively.
171 / 178
Individual Drill: ITS I
172 / 178
Individual Drill: ICTB I
∗ Write Java program called WeightOfWater
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 the keyboard
and initialized by an appropriate
constructor at creation of each object.
The program should also contain two
constants DENSITY (1000kg/m3 ) and
GRAV_FORCE (9.81N/kg) for density of water
and gravitational force, respectively.
173 / 178
Individual Drill: ICTB I
174 / 178
Individual Drill: MICT EDU I
∗ Write Java program called
QuadraticEquation which computes two x
values of a quadratic equation expressed
as ax2 +bx+c= 0, using general formula
method, assuming that b2 ≥ 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.
175 / 178
Individual Drill: MICT EDU I
176 / 178
Individual Drill: ICTM I
177 / 178
Individual Drill: ICTM I
• 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.
178 / 178