Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 39
IP Delivery Team
Year 01 and Semester 01 2 / 39
IP Delivery Team
Year 01 and Semester 01 3 / 39
IP Module Outline
Modes of Delivery
Lectures – 2 hours per week
Tutorials – 1 hour per week
Labs – 2 hours per week
Assessments
Weekly Lab Submissions - 10%
Mid Exam – 20% (1 Hour)
Practical Test – 20% (1 Hour)
Final Exam – 50% (2 Hours)
Module Pass Requirement
To pass this module, students need to obtain a
50% in all ’Continuous Assessments’ and an overall mark that would
qualify for a ’C’ grade or above.
Year 01 and Semester 01 4 / 39
Recommended Books
K. Sierra, B. Bates, T. Gee, Head First Java, 3rd edition, O’Reilly
Media, Inc., 2022, ISBN: 9781491910771
L.A. Robertson, Simple Program Design, A Step-by-Step Approach,
5th edition, Cengage Learning, 2006, ISBN: 9781423901327
H. Schildt, Java: The Complete Reference, 12th edition, 2021,
McGraw Hill, ISBN: 1260463419
Year 01 and Semester 01 5 / 39
Lecture 1
Introduction
Basic operations of a computer, Evolvement of Programming Languages,
Translators, First Java Program
Year 01 and Semester 01 6 / 39
What is a computer?
A computer is a machine for processing data to produce information.
What does the computer do?
Store large amounts of data.
Process large amount of data quickly.
Protects data and resources.
Data Analysis.
Enables communication
Networking
How do you instruct the computers to do these tasks?
Computers perform all these tasks through a combination of hardware and
software working together in a systematic way.
Year 01 and Semester 01 7 / 39
What is a software?
A set of instructions used to operate a computer to produce a specific
result.
A software acts as a bridge between the user and the computer’s
hardware, allowing us to perform tasks, solve problems, and create or
manage data.
The process of writing software / computer programs is called
programming
These software / computer programs are written by a programmer
A set of rules that tell a computer what operations to perform are
called programming language
Year 01 and Semester 01 8 / 39
Software Development Life Cycle
Software development is the process of creating computer programs. It
involves several key steps.
Analysis - Understand/Define the problem
Design -
Plan the solution
Test the solution - Does the design works (In theory)
Fix the solution - Correct the design where it failed
Implement - Write and document the code
Test - Compile, Debug and test
Deploy - Release the software for users to install and use
Maintain - Address user feedback and make enhancements
Year 01 and Semester 01 9 / 39
Analysis - Understand/Define the problem
Understanding what issue or need the software will solve.
Start with a ‘top level’ general English description of the problem;
State what data is required to solve the problem: The input data.
State what results will be calculated: The output data.
What actions need to be taken to generate the results : The
processes/tasks
Year 01 and Semester 01 10 / 39
Exercise 1
Analyze the following problem:
Write a program to find the summation of two integers input from
the keyboard.
Output the result to the screen.
Input : Two integers
Task/Process : Find the sum of two integers
Output : The sum
Year 01 and Semester 01 11 / 39
Exercise 2
Analyze the following problem:
Write a program to find the area of a circle when the radius is entered
from the keyboard.
Output the result to the screen.
Input :
Task/Process :
Output :
Year 01 and Semester 01 12 / 39
Exercise 3
Analyze the following problem:
In an experiment, the heights of 5 people were recorded and the
average height was computed. Due to negligence the height of two
people has been lost. The lab assistant distinctly remembers that the
two missing heights were almost the same. You are required to input
the heights of the known three people and the calculated average.
Find and print the missing height.
Input :
Task/Process :
Output :
Year 01 and Semester 01 13 / 39
Design – Plan the solution
Use algorithms to prepare a solution
Algorithm: A step-by-step set of instructions designed to solve a
particular problem.
The key characteristics of an algorithm
State instructions precisely, without ambiguity
State instructions in order
Algorithms are represented by flowcharts and pseudocodes.
Year 01 and Semester 01 14 / 39
Pseudocodes
Pseudocode is a simplified, informal way of writing algorithms in a
form that resembles programming language, but without the strict
syntax and semantics of a real programming language.
Using pseudocode, you can explain how a program would work in
plain English, instead of using a specified programming language.
Pseudocodes are written in a way that anyone can understand, even if
they don’t know how to code.
Year 01 and Semester 01 15 / 39
Pseudocodes
Year 01 and Semester 01 16 / 39
Pseudocode
Year 01 and Semester 01 17 / 39
The Logical Constructs / Control structures
Three basic constructs that controls the flow of an algorithm;
Sequence
Selection
Iteration
Sequence Control Structure
Sequence is a linear progression where one task is performed
sequentially after another.
Solution steps must follow each other in a logical sequence
Statements are executed in the same order as they are written.
Year 01 and Semester 01 18 / 39
Exercise
Write pseudocodes for the following problems:
1 Print “Hello world!” to the screen.
2 Find the summation of two integers input from the keyboard. Output
the result to the screen.
3 Find the area of a circle when the radius is entered from the keyboard.
Year 01 and Semester 01 19 / 39
Exercise
Write pseudocodes for the following problems:
1 Print “Hello world!” to the screen.
2 Find the summation of two integers input from the keyboard. Output
the result to the screen.
Year 01 and Semester 01 20 / 39
1 Find the area of a circle when the radius is entered from the keyboard.
Year 01 and Semester 01 21 / 39
Design - Test the solution
Review the requirements and understand what the software is
supposed to do.
Perform the desk check – Use some known input values and check
whether algorithm produce the desired output
Do not rely on just one test case. Test the algorithm for all the
possible cases
Identifying errors and bugs at early stage will save the time
Design - Fix the solution
Read the problem definition again to identify missing points
Refine the algorithm to accommodate the changes
Perform the desk check again
Repeat these steps until the desk check is passed
Year 01 and Semester 01 22 / 39
Implement – Write and document the code
Convert the algorithm description into implementation of
programming language Ex. Java , C
Programmers need to know the semantics and syntax of the selected
programming language.
Programmers write the code according to the design specifications,
following coding standards and best practices.
The code can be easily maintained by writing a documentation.
Year 01 and Semester 01 23 / 39
Evolution of Programming languages
Programming languages can be mainly divided into two categories.
Low-level programming languages
Machine Language
Assembly Language
High-level programming languages
Year 01 and Semester 01 24 / 39
Machine Language
Consist of 1 s and 0 s
Machine dependent
Computer can directly understand its own machine language
Year 01 and Semester 01 25 / 39
Assembly Languages
English-like abbreviations called mnemonics formed the basis
Clearer to humans but incomprehensible to computers
Need to translate to machine language using translator programs
called assemblers
Example :
load salary
add bonus
store total
Year 01 and Semester 01 26 / 39
High Level Programming Languages
Instructions look almost like English and mathematical notations
Substantial tasks can be accomplished from a single statement
Easy for humans to understand
Translator programs convert high-level programming languages into
machine language
C, C++, Python, Visual Basic and Java are some of the high level
programming languages.
Example:
total = salary + bonus;
Year 01 and Semester 01 27 / 39
Program Code Translation
Translator
Assemblers (convert assembly language programs to machine
language)
Compilers (convert high-level language programs to machine
language)
Interpreters (convert high-level language programs to machine
language)
Year 01 and Semester 01 28 / 39
Compiling
Compilation is the process whereby the source code file is translated
into machine code at once as a complete unit.
If no syntax errors found in the source code, then machine code file is
created for execution.
With just one error the machine code file is not created.
Interpreting
Interpreting is the process whereby the source code file is translated
line by line into machine code.
If syntax errors exist, the program partially executes since the
execution halts as soon as a syntax error is encountered.
Year 01 and Semester 01 29 / 39
Traditional Methods : Compile → Execute
Year 01 and Semester 01 30 / 39
History of Java
The early 1990s, Sun Microsystems engineers (including James
Gosling) wanted a new programming language.
They designed Java to be simple, secure, and flexible. They wanted it
to work on any computer, not just one kind.
In 1995, Java was released to the public.
By the late 1990s, Java became popular because it could run on
different computers and was good for web development.
In the 2000s, Java became widely used for big business applications,
web apps, and even Android phone apps.
Today, Java is still a popular choice for programmers, especially for
large projects.
Year 01 and Semester 01 31 / 39
How Java works...
How Java becomes platform independent. . .
Here’s the process:
1 Java source code: You write your program instructions in Java
programming language.
2 Translation to bytecode: A java compiler translates your source
code into a special machine code called bytecode.
3 Enter into the JVM: The bytecode goes into the JVM, a program
on your computer that acts like a special translator machine.
4 Interpret the Bytecode: The JVM interprets the bytecode and turn
it into native machine language code that your specific computer can
follow.
5 Running the Program: The computer follows the native machine
code running your Java program.
Since JVM produces the native machine code, the same Java program can run on
different computers as long as they have a JVM. This makes Java very versatile.
Year 01 and Semester 01 32 / 39
Pseudocode to Java code
Year 01 and Semester 01 33 / 39
Creating a JAVA program
Analyze the given problem, design and write your algorithm first.
(Pseudocode)
A text file with the extension of .java must be created. This file
stores the human readable java program. (Source code)
The .java file / source code name must be the same as the
class name.
Ex. MyFirstProgram.java
Year 01 and Semester 01 34 / 39
The Java compiler (known as javac) is used to compile the source
code into the bytecode.
The command : javac MyFirstProgram.java
If the source code contains errors, they’re displayed, no bytecode
created.
If no errors, the bytecode is created as MyFirstProgram.class
The Java interpreter (known as java) translate the bytecode and
executes the resulting native machine code.
The command: : java MyFirstProgram
Year 01 and Semester 01 35 / 39
Java Architecture
Year 01 and Semester 01 36 / 39
More examples
Year 01 and Semester 01 37 / 39
Exercise
1 Write a pseudocode to display your name and your school. Convert it
to a java program.
2 What is the output of the below pseudocode?
MAIN
DEFINE age AS INTEGER
age = 18
PRINT age
ENDMAIN
3 Convert the above pseudocode to a Java program.
Year 01 and Semester 01 38 / 39
Thank You!
Year 01 and Semester 01 39 / 39
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 26
Lecture 2
Basic Java Program, Variables, Operators in Java
Year 01 and Semester 01 2 / 26
Steps to execute a Java program
Write the pseudocode for the given problem.
Convert it to Java code.
Write the java code in a text file and rename it as
<class name>.java
Example: MyFirstProgram.java
Year 01 and Semester 01 3 / 26
Compile the java code into bytecode using the following command.
javac MyFirstProgram.java
If no errors, the bytecode is created as MyFirstProgram.class
Execute the bytecode using the following command and see the result.
java MyFirstProgram
Year 01 and Semester 01 4 / 26
Comments in Java
These are comments.
Comments are used to document programs and it improves the
program readability.
Using comments to improve the readability is a best practice in
software development.
Java compiler ignores comments.
Single line comments begin with // and continue for the rest of the
line.
Multi-line comments (or Block comments) can also be used.
Multi-line comments are indicated using /* . . . */
Everything from /* to */ is a comment.
Year 01 and Semester 01 5 / 26
Variables
A variable is a storage location in memory which can be used to store
a value
A variable has a
- Name (Identifier)
- Data type
A variable must be declared before it is used.
The variable declaration allocates the storage location of the
appropriate size and associates the name and data type with that
location.
Year 01 and Semester 01 6 / 26
Year 01 and Semester 01 7 / 26
Variable declaration
The format for the declaration of a variable
<Data type> <Name of the variable> ;
Examples:
int number;
char grade;
double price;
Year 01 and Semester 01 8 / 26
Variable Name
Variable name/ identifier
can be a series of characters consisting of letters, digits and
underscores ( )
does not begin with a digit
may not contain embedded blank spaces
may not be a keyword or a reserved word (ex: int, return, if, while,
for. . . .)
Java is case sensitive (Uppercase and lowercase letters are different
in Java)
Ex. grade, Grade and GRADE are three different variable names
Variable names must be meaningful.
Variable name reflects the nature of the value it holds.
studentNum is different to numOfStudents
Year 01 and Semester 01 9 / 26
Exercise
Which of the following can be considered as valid variable names?
name
Number Of Values
Tax Rate
DistanceInFeet
2BeOrNot2Be
Number3
Tax%
for
Year 01 and Semester 01 10 / 26
Data Types
The type of data to be stored in the variable is called as the data type.
Year 01 and Semester 01 11 / 26
Data Types - Examples
The type of data to be stored in the variable is called as the data type.
Year 01 and Semester 01 12 / 26
In Java, the data type should be specified when declaring the variable.
The variable declaration is easy. The challenge is identifying the type.
Year 01 and Semester 01 13 / 26
Assigning a value to a variable
After variable declaration, a value can be assigned to a variable
The assignment operator ’=’ can be used to assign/store a value in a
variable or to change the value stored in a variable
An assignment expression has the form
variable(lvalue) = expression(rvalue)
It stores the value of the expression (rvalue) into the memory location
of the variable (lvalue)
Year 01 and Semester 01 14 / 26
Operators in Java
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operator
Increment and decrement operators
Casting
Year 01 and Semester 01 15 / 26
Arithmetic Operators
Year 01 and Semester 01 16 / 26
Operator precedence of arithmetic operators
Year 01 and Semester 01 17 / 26
Relational Operators
Year 01 and Semester 01 18 / 26
Logical Operators
Year 01 and Semester 01 19 / 26
Assignment Operator
It is used to assign values to variables.
There are several assignment operators for abbreviating assignment
expressions.
variable = variable operator expression;
can be written as
variable operator = expression;
where operator is one of the arithmetic operators +, -, *, / or %
Year 01 and Semester 01 20 / 26
Increment/Decrement Operators
Year 01 and Semester 01 21 / 26
Year 01 and Semester 01 22 / 26
Operator precedence revisited
Year 01 and Semester 01 23 / 26
Casting
Cast operator is used to convert from one data type to another;
The syntax is: <NewDataType> <expression>;
Example
Year 01 and Semester 01 24 / 26
More examples
Converting from a real data type to an integer data type involves
truncating the real value (i.e., not rounding).
Year 01 and Semester 01 25 / 26
Thank You!
Year 01 and Semester 01 26 / 26
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 15
Lecture 3
Java Constants, Char Data Type, User Input Handling
Year 01 and Semester 01 2 / 15
Java Constants
In Java, a constant refers to a variable that holds a fixed value
throughout the program’s execution.
Using final and static keyword, we can declare a constant.
Here’re few examples of creating constants
Year 01 and Semester 01 3 / 15
Char Data Type
Characters are normally stored in variable type char
Characters can be stored in any integer type variable too
Characters can be treated as either an integer or a character
Many computers today use ASCII (American Standard Code for
Information Interchange) character set
Year 01 and Semester 01 4 / 15
Relational Operator (== , !=) with Decimal values
When a decimal number is storing as a float or double data type
value, sometimes the computer round off the excess digits. This is
called truncation.
Due to the truncation error inherent in storing float and double
values, these values should never be compared using == or !=
relational operators.
Year 01 and Semester 01 5 / 15
Java Libraries
Java libraries are collections of pre-written code that add functionality
to your java programs.
Think of them as tools that you can use to save time and effort when
building your Java programs.
There are two main types of libraries:
1 Standard libraries
2 External libraries
Year 01 and Semester 01 6 / 15
1 Standard libraries / Java class libraries
These come with Java by default. They provide a bunch of useful
classes and methods.
Like:
Reading user input
Working with files
Making calculations
2 External libraries
These are like extra libraries that provide specialized functionality for
specific tasks.
Graphics for games
Connecting to databases
Working with the internet
User-written libraries
Year 01 and Semester 01 7 / 15
Using libraries in Java program
By including import statements in your Java code, we can use
standard libraries.
java.util is a standard library in Java.
Let’s see, how java.util is used in your Java code.
Year 01 and Semester 01 8 / 15
How to take user inputs from the keyboard
In Java, the Scanner class is used to capture user input from the
keyboard.
Let’s see how it can be done. . .
1 First, you need to tell your program that you want to use Scanner
class in java.util standard library. You do this with an import
statement:
import java.util.Scanner;
2 Next, you create a Scanner object.
Scanner input = new Scanner(System.in);
Year 01 and Semester 01 9 / 15
3. Now it’s time to capture the user input. Here comes the magic!
You need to use appropriate function from the Scanner class to
capture the user input and store it in a variable. It depends on the
data type of the user input.
Year 01 and Semester 01 10 / 15
For Strings:
Year 01 and Semester 01 11 / 15
Exercises
Enter the radius of a circle from the keyboard and display the
circumference and the area.
1 Write the relevant pseudocode.
2 Convert it to Java program.
Year 01 and Semester 01 12 / 15
Pseudocode
Year 01 and Semester 01 13 / 15
Java Code
Year 01 and Semester 01 14 / 15
Thank You!
Year 01 and Semester 01 15 / 15
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 26
Lecture 4
Sequence , Selection Statements
Year 01 and Semester 01 2 / 26
Selection Statements
Obviously in the real world we make choices
Year 01 and Semester 01 3 / 26
Selection
In solving a problem, we can make different choices depending on
certain conditions - i.e. we make decisions
The same can be done in programming as a part of decision making
Note: though selection is a separate construct to sequence, the two
are combined in the overall solution and does not replace each other
Year 01 and Semester 01 4 / 26
Selection
There may be alternative steps that could be taken subject to a
particular condition
Year 01 and Semester 01 5 / 26
Types of Selection Statements
IF statement
This is the basic selection statement to check a condition when making
a decision
If the condition is true, the code block following the IF statement gets
executed
If the condition is false, the code block is skipped
Exercise
Input two integers from the keyboard. Display whether the two integers
are equal.
Write a pseudocode to the above scenario.
Draw the flow chart to the above scenario.
Write a Java program to the above scenario.
Year 01 and Semester 01 6 / 26
Write a pseudocode to the above scenario
Year 01 and Semester 01 7 / 26
Draw the flow chart to the above scenario
Year 01 and Semester 01 8 / 26
Syntax of IF statement
To include several statements in the body of an if, enclose the set of
statements in braces { }
A left brace { begins the body of each if statement
A corresponding right brace } ends each if statement body
Any number of statements can be placed in the body of an if
statement
A set of statements contained within a pair of braces is called a
compound or a block
Year 01 and Semester 01 9 / 26
Write a Java program to the above scenario
Year 01 and Semester 01 10 / 26
IF ELSE statement
This builds upon the IF statement. It checks a condition and then
provides two options:
If the condition is true, one block of code runs
If the condition is false, a different block of code runs
Year 01 and Semester 01 11 / 26
Syntax of IF ELSE statement
Year 01 and Semester 01 12 / 26
Exercise
Input two integers from the keyboard. Display whether the two integers
are equal or not.
Write a pseudocode to the above scenario
Draw the flow chart to the above scenario
Write a Java program to the above scenario
Year 01 and Semester 01 13 / 26
Write a pseudocode to the above scenario
Year 01 and Semester 01 14 / 26
Draw the flow chart to the above scenario
Year 01 and Semester 01 15 / 26
Write a java program to the above scenario
Year 01 and Semester 01 16 / 26
ELSE IF statement
Multiple ELSE IF statements are used to check multiple cases or
conditions.
Exercise
In an ice cream shop, the customer can input the ice cream flavour type
(C, S, V) that he/she needs to purchase. Display the flavour of the ice
cream that the customer purchases.
Write a pseudocode to the above scenario.
Draw the flow chart to the above scenario.
Convert the above pseudocode to a Java program.
Year 01 and Semester 01 17 / 26
Write a pseudocode to the above scenario
Year 01 and Semester 01 18 / 26
Draw the flow chart to the above scenario
Year 01 and Semester 01 19 / 26
Write a java program to the above scenario
Year 01 and Semester 01 20 / 26
Switch statement
It compares a value (usually an integer or character) to a set of
constant expressions (cases). If there’s a match, the code associated
with that case is executed. A break statement is typically used to exit
the switch after the matching case is executed.
Exercise
In an ice cream shop, the customer can input the ice cream flavour type
(C, S, V) that he/she needs to purchase. Display the flavour of the ice
cream that the customer purchases.
Write a pseudocode to the above scenario.
Convert the above pseudocode to a Java program.
Year 01 and Semester 01 21 / 26
Write a pseudocode to the above scenario
Year 01 and Semester 01 22 / 26
Year 01 and Semester 01 23 / 26
Write a Java program to the above scenario
Year 01 and Semester 01 24 / 26
Ternary Operator ( ? : )
The ternary operator, also known as the conditional operator, is a
short way to write if-else statement in a single line of code in Java.
It’s a compact way to express a simple condition and choose a value
based on whether the condition is true or false.
The below images show you how conditional operator and if-else
statement are used to write same code segment.
Year 01 and Semester 01 25 / 26
Thank You!
Year 01 and Semester 01 26 / 26
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 17
Lecture 5
Repetition Statements in Java (Part 1)
Year 01 and Semester 01 2 / 17
Repetition Statements
Java provides several repetition statements, also known as looping
statements or iteration statements, that allow to execute a block of code
repeatedly until a certain condition is met.
Types of Repetition Statements
While Loop
Do While Loop
For Loop
Year 01 and Semester 01 3 / 17
Counter-Controlled Repetition
Number of repetitions is known before the loop begins execution
A control variable is used to count the number of repetitions
The control variable is incremented/decremented on each loop round
The loop terminates when the counter exceeds specified number of
repetitions
Counter-controlled repetition requires:
A name for the control variable
An initial value to the control variable
The increment (or decrement) statement which updates the control
variable in each loop round
The condition that evaluates the final value of the control variable
Year 01 and Semester 01 4 / 17
Counter-Controlled Repetition with the while statement
Exercise
Display the numbers 1, 2, 3, 4, 5
Write a pseudocode to the above scenario
Convert the above pseudocode to a Java program
Pseudocode to the above scenario
Year 01 and Semester 01 5 / 17
Draw a flow chart to the above scenario
Year 01 and Semester 01 6 / 17
Syntax of while loop
Condition: This is a logical expression that controls the loop’s
execution. The loop continues to execute as long as the condition
evaluates to true.
The code block within the curly braces { } is executed repeatedly
until the condition becomes false.
This code block contains the statements you want to execute
repeatedly. These statements can involve variable assignments,
calculations, input/output operations and etc.
Year 01 and Semester 01 7 / 17
Convert the above pseudocode to a Java program
Year 01 and Semester 01 8 / 17
Counter-Controlled Repetition with the while statement
Exercise
Find the summation and average of five numbers entered through the
keyboard
Write a pseudocode to the above scenario
Convert the above pseudocode to a Java program
Year 01 and Semester 01 9 / 17
Write a pseudocode to the above scenario
Year 01 and Semester 01 10 / 17
Draw a flow chart to the above scenario
Year 01 and Semester 01 11 / 17
Convert the above pseudocode to a Java program
Year 01 and Semester 01 12 / 17
Sentinel - Controlled Repetition
Sentinel-controlled repetition in Java refers to a looping technique
where the number of iterations is not predetermined.
The loop continues to execute until a specific value (sentinel value) is
encountered as input or calculated within the loop itself.
Need to define a specific condition with a sentinel value that will
signal the end of the loop.
Year 01 and Semester 01 13 / 17
Sentinel - Controlled Repetition with the while statement
Exercise
Prompt the user to enter a series of integers from the keyboard. If the user
enters -1, the program should display ”End of Program” and terminate.
Write a pseudocode to the above scenario
Convert the above pseudocode to a Java program
Year 01 and Semester 01 14 / 17
Write a pseudocode to the above scenario
Year 01 and Semester 01 15 / 17
Convert the above pseudocode to a Java program
Year 01 and Semester 01 16 / 17
Thank You!
Year 01 and Semester 01 17 / 17
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 22
Lecture 6
Repetition Statements in Java (Part 2)
Year 01 and Semester 01 2 / 22
Counter-Controlled Repetition with the while statement
Exercise
Display the numbers 1, 2, 3, 4, 5
Write a pseudocode to the above scenario
Convert the above pseudocode to a Java program
Write a pseudocode to the above scenario
Year 01 and Semester 01 3 / 22
Convert the above pseudocode to a Java program
Year 01 and Semester 01 4 / 22
Counter-Controlled Repetition with the do while statement
Exercise
Display the numbers 1, 2, 3, 4, 5
Write a pseudocode to the above scenario
Convert the above pseudocode to a Java program
Write a pseudocode to the above scenario
Year 01 and Semester 01 5 / 22
Syntax of do while loop
In a do-while loop, the code block inside the curly braces { } will
execute at least once, even if the condition is initially false.
The condition is checked after executing the code block.
If the condition is true, the loop repeats, and the code block executes
again.
If the condition is false, the loop terminates.
It’s suitable for situations where you want to ensure the code block
executes at least once, even if the initial condition might not be
met.
Year 01 and Semester 01 6 / 22
Year 01 and Semester 01 7 / 22
Year 01 and Semester 01 8 / 22
Java Program
Year 01 and Semester 01 9 / 22
Counter-Controlled Repetition with the for statement
Exercise
Display the numbers 1, 2, 3, 4, 5
Write a pseudocode to the above scenario
Convert the above pseudocode to a Java program
Write a pseudocode to the above scenario
Year 01 and Semester 01 10 / 22
Syntax of for loop
Initialization: This is an optional expression that’s executed once at the
start of the loop. It’s commonly used to initialize a loop counter variable.
Condition: This is an essential expression that controls the loop’s execution.
The loop continues to execute as long as the condition evaluates to true.
Increment / decrement statement: This is an optional expression that’s
executed at the end of each loop iteration. It’s commonly used to
update the loop counter variable.
The code block within the curly braces { } is executed repeatedly until the
condition becomes false.
This code block contains the statements you want to execute repeatedly.
These statements can involve variable assignments, calculations,
input/output operations and etc.
Year 01 and Semester 01 11 / 22
Convert the above pseudocode to a Java program
Year 01 and Semester 01 12 / 22
Break statement
We discussed the break keyword in Switch statement.
Inside a switch statement, the break statement helps you exit the case
block after a matching case is executed.
When you encounter a break keyword within a loop, it causes
immediate exit from the loop, regardless of the loop’s condition.
Common uses of the break statement are to escape early from a loop.
Year 01 and Semester 01 13 / 22
Java Program
Year 01 and Semester 01 14 / 22
Continue statement
The continue keyword in Java is another control flow statement used
within loops.
It’s like a ‘skip button’ for loops, allowing you to jump to the next
iteration without executing the remaining statements in the current
iteration.
Year 01 and Semester 01 15 / 22
Java Program
Year 01 and Semester 01 16 / 22
Nested Loop / Nested Iteration
Nested loops in Java
involve placing a loop inside the body of another loop statement.
This creates a hierarchy of loops, allowing you to iterate through data
in a more complex way.
Year 01 and Semester 01 17 / 22
Display the following pattern using Nested Loop
Year 01 and Semester 01 18 / 22
Modify above Java program to get the following pattern
Year 01 and Semester 01 19 / 22
Modify above Java program to get the following pattern
Year 01 and Semester 01 20 / 22
Exercise
1 Write a program that will print the following sequence of values using
for loop.
3, 8, 13, 18, 23
2 What does the following code segment print?
3 What does the following code segment print?
Year 01 and Semester 01 21 / 22
Thank You!
Year 01 and Semester 01 22 / 22
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 18
Lecture 7
Arrays
Year 01 and Semester 01 2 / 18
Arrays
Array is a data structure which store data items of the same data type
Array store all the data items in a continuous memory location
Arrays can be initialized to any size
Once initialized, the size of an array is fixed and cannot be changed
If need to change the size of an array, you must create a new array
with the desired size and copy the elements from old array to the new
one
Year 01 and Semester 01 3 / 18
Declaring and Allocating Arrays
Year 01 and Semester 01 4 / 18
Accessing elements in an array
To refer to a specific element in an array, we need to specify array
name followed by the index (subscript) of the array element location
in square brackets
Array index always starts with Zero, hence first element in the array
is the zeroth index [0]
The last array element index always equal to: Array Size – 1
Year 01 and Semester 01 5 / 18
Using arrays
Print the first element in the array:
Print the sum of first three elements in the array:
Add number 2 to the fourth element:
Year 01 and Semester 01 6 / 18
Declare and Initialize an Array
Year 01 and Semester 01 7 / 18
Initialize an Array (1D) using an Initializer List
Year 01 and Semester 01 8 / 18
Summing the elements of a Number Array (Integer / Whole
Numbers)
Year 01 and Semester 01 9 / 18
Example of a Float Array (Real Numbers / Decimals)
Year 01 and Semester 01 10 / 18
Example of a Char Array (Characters)
Year 01 and Semester 01 11 / 18
Exercises
1 Write a Java program to do the following:
Declare an integer array called counts with 10 elements
Initialize all elements to -1
Read and store 10 numbers each of which is between 10 to 100
Find the maximum number from the stored numbers.
2 Write a Java program to do the following:
Declare a double array called salary of size 8
Prompt the user to input ten salaries of employees from the keyboard
and store in the array
Display the salaries stored in the array
Count and display the number of employees in the following three
salary ranges
Year 01 and Semester 01 12 / 18
Exercises
3 Write a Java program to do the following:
Declare a character array called shirts of size 10
Prompt the user to input the sizes of the t-shirts that ten customers
need to purchase and store in the array
The t-shirt sizes are small(S), medium(M) and large(L). Assume that
the customer will purchase one t-shirt at a time
Display the quantity of each t-shirt sizes that need to be arranged
Year 01 and Semester 01 13 / 18
Multidimensional Arrays
Java language has arrays with multiple indexes (subscripts)
These arrays are referred as multidimensional arrays
An array with two subscripts is called double-subscripted or
Two-Dimensional (2D) array
Two-Dimensional Arrays
Two-dimensional arrays represent values in a tabular format arranged
into rows and columns
Year 01 and Semester 01 14 / 18
Initialize a 2D Array using an Initializer List
Year 01 and Semester 01 15 / 18
Initialize a 2D Array using User Inputs via Keyboard
Year 01 and Semester 01 16 / 18
Summing the elements of a 2D Number Array (Integer / Whole
Numbers)
Year 01 and Semester 01 17 / 18
Thank You!
Year 01 and Semester 01 18 / 18
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 11
Lecture 8
Java Methods
Year 01 and Semester 01 2 / 11
Introduction to Java Methods
A method is used to break algorithms into smaller parts
A method is also known as a function in programming
It allows the modularity in programming
Generally, a method is designed to perform one task
Benefits of using methods:
Ease of Design
Code Readability
Code Re-usability
Code Debugging
There are two types of methods:
Predefined Methods
User Defined Methods
Year 01 and Semester 01 3 / 11
Java Predefined Methods
Year 01 and Semester 01 4 / 11
Using Math Class Methods in java
Year 01 and Semester 01 5 / 11
Using Math class methods in java
Year 01 and Semester 01 6 / 11
Exercises
Write the value of x after each of the following statements is performed:
a x = floor (7.5)
b x = abs(-3.6)
c x = floor (0.0)
d x = ceil (-6.4)
e x = pow (5, 2)
f x = round (2.7)
g x = abs(2.5)
Year 01 and Semester 01 7 / 11
Java String Class Methods
Year 01 and Semester 01 8 / 11
Using String class methods in java
Year 01 and Semester 01 9 / 11
Exercises
a Given a string ”Hello, World!”, how can you determine the number of
characters in the string using an predefined method?
b Given a string ” Hello, World! ”, how can you remove the leading and
trailing whitespace using the trim() method?
c Given a string ”Hello, World!”, how can you access the character at
index 7 (where ‘W’ is located) using the charAt() method?
d Given a string ”HELLO, WORLD!”, how can you convert it to
lowercase using the toLowerCase() method?
Year 01 and Semester 01 10 / 11
Thank You!
Year 01 and Semester 01 11 / 11
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 16
Lecture 9
Java Methods : User-Defined Methods
Year 01 and Semester 01 2 / 16
Calculate Area of 3 Rectangles
Year 01 and Semester 01 3 / 16
Calculate Area of 3 Rectangles using a Method
Year 01 and Semester 01 4 / 16
Calculate Area of 3 Rectangles using a Method
Year 01 and Semester 01 5 / 16
User-Defined Method
Implement a method
Example : Implement a method called calculateArea() to calculate and
return the are of a rectangle.
Year 01 and Semester 01 6 / 16
Calculate Area of 3 Rectangles using a Method
Year 01 and Semester 01 7 / 16
Java Method Syntax
public: Defines the access modifier and makes the method accessible
from anywhere within the program.
static: Defines the modifier and makes the method belong to the
class itself, rather than to an instance of the class.
Return Type: This specifies the data type of the value that method
returns. If the method doesn’t return a value, use void as the return
type.
Year 01 and Semester 01 8 / 16
Year 01 and Semester 01 9 / 16
Exercises
1 Write a method that displays a square of asterisks where the side is
specified as an integer parameter.
For example: if side is 4, the method displays:
****
****
****
****
2 Write a method called max to determine and return the largest of
two integers. The integers should be input from the keyboard in the
main program and pass to max method.
Year 01 and Semester 01 10 / 16
Passing Arguments/Parameters By Value
When arguments are passed by value, a copy of the argument’s value
is made and passed to the called method.
Changes to the copy do not affect an original variable’s value in the
caller.
Passing Arguments By Value - Example
Year 01 and Semester 01 11 / 16
Passing Arguments/Parameters By Value - Example
Year 01 and Semester 01 12 / 16
Passing Arguments/Parameters By Value - Example
Year 01 and Semester 01 13 / 16
Passing Arguments/Parameters By Value - Example
Year 01 and Semester 01 14 / 16
Passing Arguments/Parameters By Value - Example
Year 01 and Semester 01 15 / 16
Thank You!
Year 01 and Semester 01 16 / 16
Sri Lanka Institute of Information Technology
Faculty of Computing
IT1120 - Introduction to Programming
Dr.Junius Anjana
Year 01 and Semester 01
Year 01 and Semester 01 1 / 21
Lecture 10
Testing
Year 01 and Semester 01 2 / 21
Introduction to Testing
Testing is a crucial aspect of software development that ensures the
quality and correctness of the code.
It involves writing and executing tests to verify that the code behaves
as expected under various conditions.
Why we need to test?
Early bug detection: Tests can identify and fix bugs early in the
development process, saving time and effort.
Improved code quality: Writing tests forces the programmers to
think about the code from a user’s perspective, leading to
better-designed and more maintainable code.
Increased confidence: Tests provide confidence that the code works
as intended, making it easier to make changes and refactor.
Year 01 and Semester 01 3 / 21
Year 01 and Semester 01 4 / 21
BlackBox Testing vs WhiteBox Testing
BlackBox testing and WhiteBox testing are two fundamental
approaches to software testing
They differ in their focus and methodologies, but both are essential
for ensuring the quality and reliability of software applications
BlackBox Testing
BlackBox testing focuses on the external behavior of the software,
without considering its internal structure or implementation
The software testers with less knowledge about the code/software can
involve in black box testing since it can be done without knowing the
actual structure of the code
WhiteBox Testing
WhiteBox testing focuses on the internal structure of the code
implementation of the software
Year 01 and Semester 01 5 / 21
Year 01 and Semester 01 6 / 21
Unit Testing using assertions
Assertions can be used to conduct Unit Testing in Java
Assert is a keyword in Java that allows you to verify conditions at the
time of code execution
It’s used to check if certain conditions are true during program
execution.
If a condition evaluates to false, an AssertionError is given which is
generally considered as a sign of a problem in your code
Year 01 and Semester 01 7 / 21
Assert – Example 01
Year 01 and Semester 01 8 / 21
Assert – Example 02
Write a method called calculateGrade( ) which takes a mark as a
parameter and return the grade according to the following table.
Write another method called testCalculateGrade( ) which contains test
cases to test the calculateGrade( ) method.
Year 01 and Semester 01 9 / 21
Assert – Example 02
Year 01 and Semester 01 10 / 21
Assert – Example 02
Year 01 and Semester 01 11 / 21
Assert – Example 02
Year 01 and Semester 01 12 / 21
When we write an equality condition in assert statement:
Year 01 and Semester 01 13 / 21
Assert - Example 03
Define a method called calcHypotenuse( ) that calculates the length
of the hypotenuse of a right triangle when the other two sides are
given. The method should take two parameters of type double and
return the hypotenuse length as a double.
Modify the above program to have another method called
testCalcHypotenuse() which contains the three assert statements you
wrote. Call testCalcHypotenuse() method in your main program.
Year 01 and Semester 01 14 / 21
Assert - Example 03
Year 01 and Semester 01 15 / 21
Assert – Example 03
Year 01 and Semester 01 16 / 21
Few More Concepts in Java
Year 01 and Semester 01 17 / 21
Data Types and Sizes
Year 01 and Semester 01 18 / 21
Command Line Arguments
Command-line argument is an argument that is passed at the time of
running the java program using the console
These arguments passed from the console can be received to the
program and used as an input
With the Java run command, these arguments need to be passed as
space-separated values
Both strings and primitive data types (int, double, float, char, etc..)
can be passed as command-line arguments
Internally, JVM wraps up these command-line arguments into the
args[] array that we declare in the main() function
Year 01 and Semester 01 19 / 21
Year 01 and Semester 01 20 / 21
Thank You!
Year 01 and Semester 01 21 / 21