You are on page 1of 40

COMPUTER STUDIES/ICT

SSS 2

SECOND TERM

SCHEME OF WORK

WEEKS TOPICS
1. Introduction to Computer Data Conversion I
2. Computer Data Conversion II
3. Security and Ethics
4. Concept of Computer files
5. Concept of Computer file
6. Handling Computer Files
7. Handling Computer Files
8. Handling Computer Files
9. Java Console Input 1
10. Java Console Input 11
11. Java Control Statement 1&2
12. Revision
13. Examination
WEEK: 1
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: INTRODUCTION TO COMPUTER DATA CONVERSION

COMPUTER DATA CONVERSION


Data conversion is the conversion (changing) of computer data from one format
to another.
Examples of data conversion are changing of bits from one format to another,
conversion of a text file from one character encoding to another or more complex
, such as the conversion of office file format or the conversion of image and
audio file formats.

REGISTER
Definition of register

Register is one of a small set of data holding places that are part of a computer
processor

Register are small storage locations located directly on the processor of a


computer that are typically used for storage of values used in calculations.

A register may hold a computer instruction, a storage address, or any kind of


data (such as a bit sequence or individual characters).

Almost all computer load data from a larger memory into registers where it is
used for arithmetic, manipulated or tested by some machine instruction

Address

Address is a location of data usually in main memory or on a disk.

Memory addresses are fixed-length sequences of bit conventionally displayed


and manipulated as integers.

Bus

A bus is a collection of parallel electrical conductors called “lines’’ through


which a number of components may be connected.

A bus, in computing is a set of physical connections (cables, printed circuits, etc)


which can be shared by multiple hardware components in order to communicate
with one another.
A bus is a sub system that transfers data between components inside a
computer, or between computers.

It is also a collection of wires/parts through which data is transmitted from one


part of a computer to another.

MAIN PROCESSOR
MEMORY BUS
BUS

Types of Bus

There are two main buses in a computer.

(i) The Internal (or System) Bus


(ii) The External (or Expansion) Bus

1. The Internal Bus

The Internal (or System) Bus resides on the mother board and connects the CPU
to other devices that resides on the motherboard. Examples are :

a. The data bus


b. The address bus
c. The control bus

(a) The Data Bus


The data bus is an electrical path that connects the CPU memory and the other
hardware devices on the motherboard.

(b) The address Bus


The address bus (sometimes called the memory bus) transports
memory addresses which the processor wants to access in order to
read or write data.

(c) The Control Bus


The control bus (or command bus) transports orders and synchronization
signals coming from the Control Unit and traveling to all other hardware
components.

2. The External Bus


The External (or Expansion) bus connects external devices such as the keyboard,
mouse, modem, printer, USB etc. to the CPU.

WEEK: 2
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: COMPUTER DATA CONVERSION II
COMPUTER DATA CONVERSION

Types of register

Register are normally measured by the number of bits they can hold, e.g. an 8-bit
register, or a 32-bit register.

A processor often contains several kinds of register that can be classified


according to their content or instructions that operate on them.

There are various types of register those that are used for various purposes.

Among of some mostly used registers are:

i. Memory Data Register (MDR)


ii. Computer instruction register (CIR)
iii. Data Register (DR)
iv. Memory Address Register (MAR)
v. Conditional Register (CR)
vi. General Purpose Register (GPR)
vii. Floating Point Register (FPR)
viii. Constant Register(CR)
ix. Special Purpose Register (SPR)

The functions of each Register.

i. Memory Data Register (MDR)


The Memory Data Register is the register of a computer control unit that
contains the data to be stored in the computer storage (E.g. RAM) or the data
after a fetch from computer memory.

ii. Computer Instruction Register (CIR)


Computer Instruction Register (CIR) most time referred to as Instruction
Register (IR) the part of a CPUs control unit that stores the instruction currently
being executed or decoded.

iii. Data Registers (DR)


It holds numeric values such as integers and floating point values as well as
character, small bit arrays and other data

iv. Memory Address Register (MAR)

This register holds the memory address of data and instructions.


This register is used to access data and information from memory during
the execution phase on an instruction

v. Conditional Registers (CR)

Holds truth values often used to determine whether some instruction should or
should not be executed

vi. General Purpose Register (GPR)

can store both data and addresses , i.e. They are combined Data / Address
register

vii. Floating Point Register (FPR)

S Store floating point numbers in much architecture

viii. Constant Register (CR)

Hold read-only value such as zero, one etc

ix. Special Purpose Register (SPR)

Hold program state; they usually include the program counter and status
register. Differences between register and main memory

REGISTER MAIN MEMORY

1. Located inside the processor 1. Location is outside the processor


2. Operation with register is fast since
2. Operation is slow since there is no
it is directly accessed by the CPU direct access to the CPU
3. Registers are set aside for certain3. Main memory are basically for
task holding the job currently being worked
upon
4. Register are temporary storage in 4. Main memory holds the program
the CPU that holds the data the instructions and the data the program
processor is currently working on require
5. CPU instructions operates on those 5. Instructions are not access directly
value in the register directly by the CPU
The Data - Fetch – Execute Cycle.

The Data - Fetch – Execute Cycle is the process, by which a computer retrieves
a program instruction from its memory, determines what actions the
instructions require and carries out those actions.

Circuits used during fetch – execute cycle

The Circuits used in the CPU during the fetch execute cycle are:
a) Program counter (PC)
b) Memory Address Register (MAR)
c) Memory Data Register (MDR)
d) Current Instruction Register(CIR)
e) Control Unit (CU)
f) Arithmetic Logic Unit (ALU)

Stages in a fetch – execute cycle


There are several stages in the Fetch Execute cycle that are executed in order.

i. Fetch the instruction


ii. Decode the instruction
iii. Execute the instructions
iv. Store the results
Diagram of the fetch execute cycle

Start

Load address to PC

Load PC contents to MAR

Update PC to next address

Load data required to MDR

MAR content to CIR

Decode CIR content

Set PC to
Jump YES
value from
?
NO jump
Execute instruction

NO YES
Interrupt Service
? interrupt

FACTOR AFFECTING SPEED OF DATA TRANFER


Some of the Factor that can affect the speed of a computer system is:
1. Bus Speed.
2. Bus Width.
3. Network latency
4. Network Congestion
Note:
Network congestion refers to the saturation of a path used by packets to flow between the source and the
destination.
Network Latency refers to the time needed to send a packet from the source to the destination. This time
varies depending:

 on the physical distance


 the number of network devices which have to be crossed (also referred to as the number of hops)
 and to a lesser extent, to the performance of each of the device
WEEK: 3
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: SECURITY AND ETHICS

SECURITY AND ETHICS

SECURITY BREACHES

Security breaches in computer refer to a situation whereby there is unauthorized


acquisition of computerized data or information of a person, or group of persons,
thereby gaining access to their secrets or security issues.

COMPUTER SECURITY

Computer security is the protection of computer components such as hardware,


software and data from unauthorized access.

SOURCES OF SECURITY BREACHES

1. Virus ,Worms, and Trojan horse (these are examples of malware)


2. Poorly implemented network
3. Poorly implemented or lack of ICT policy
4. Careless handling of information on the network
5. Hackers

1. VIRUS: is an executable program that is capable of replicating itself


thereby causing great harm to file or other programs on the computer it
infects.
WORMS: Worm is a virus program that copies and multiplies itself by using
computer networks and security flaws.
TROJAN HORSE: is a computer program or file on the computer of a user
that makes the computer susceptible to malicious intruders by allowing
them to access and read user’s file.
Malware is intrusive software that is designed to damage and destroy
computers and computer systems. Malware is a contraction for “malicious
software.” Examples of common malware includes viruses, worms, Trojan
viruses, spyware, adware, and ransomware.
2. POORLY IMPLEMENTED COMPUTER NETWORK: Poorly implementation
and management of network in turn may give room to unauthorized users
to invade the network to steal password, confidential files or even infects
all the network files. Network invaders also launches Denial-of- Service
Attack ( DOS) which may deny legitimate users ability to get on the network
and may even cause the network to crash.
3. POORLY IMPLEMENTED OR LACK OF ICT POLICY : When ICT policy is not
in place or poorly implemented ( policy guiding the use of ICT facilities) ,
lawlessness will be in place and this can lead to security breach.
4. CARELESSNESS: These include carelessness with information, storage
devices, password, movement of people, etc.
5. HACKERS: A hacker is a clever programmer who tries to break into
computer systems. A hacker understands the weak points in a security
system and writes a program that will utilize and break into the system.

PREVENTIVE MEASURES

1. USE OF ANTI-VIRUS SOFTWARE: is used to prevent, detect, and remove


malwares, including but not limited to computer virus, computer worm,
Trojan horses, spyware and adware.
2. USE OF FIREWALL: is a program or hardware device that filters, permit or
deny network transmission (or information), base upon a set of rules, and
is frequently used to protect networks from unauthorized access, while
permitting legitimate communication to pass.
3. EXERCISING CARE IN GIVING OUT PERSONAL AND VITAL INFORMATION:
such as password, e-mail address, user names, etc.
4. ENCRYPTION (CRYPTOGRAPHY): is the process of converting or
transforming information using an algorithm called (Cipher) to make it
unreadable or not understandable by unauthorized users. DECRYPTION:
makes encrypted information readable again.
5. PROPER NETWORK IMPLEMENTATION AND MANAGEMENT POLICY.
6. USE OF WEBSITES WITH SECURITY CERTIFICATES BECAUSE THEY ARE
SECURED.
7. DO NOT DOWNLOAD E-MAIL FILE ATTACHMENTS FROM UNKNOWN
SOURCES.

LEGAL ISSUES

The following are legal issues related to the use and misuse of ICT

1. COPYRIGHT: Copyright give the creator of an original work exclusive right


for a certain time period in relation to that work, including its publication,
distribution and adaptation, after which time the work is said to enter the
public domain.
2. OWNERSHIP RIGHT: refers to legal ownership of a property and has the
right to use it and has full control over it unless prevented by some
agreement. Ownership rights include right to text, image, logo, audio,
video, etc
3. PIRACY: is the unauthorized duplication of an original recording for
commercial gain without the consent of the rights owner. Piracy is the
unauthorized reproduction and use of copyright software, audio, video, etc.
4. CYBER CRIMES: is described as the crime committed by the means of the
internet and computer.
5. HACKING: gaining unauthorized access to resources on a computer or
network.
6. IDENTITY THEFT: is a cyber-crime that involves stealing of someone else’s
identity by pretending to be the actual person.
7. INTERNET FRAUD: refers to the use of internet to conduct fraudulent
transact ions. E.g., Credit card, postal money orders, money transfer, etc.
WEEK: 4
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: CONCEPT OF COMPUTER FILES

CONCEPT OF COMPUTER FILES


CONCEPT OF COMPUTER FILES
- COMPUTER FILES
A computer file is a block of arbitrary information, or resource for storing
information which is available to a computer program and is usually based on
kind of durable storage.

A file holds data which is required for providing information. It resides on the
secondary (auxiliary backing) storage such as magnetic disk

RECORD

A record is a collection of related fields that represent one transaction or one


individual.
All data about each student is a record.

FIELD

A field is made up of characters like: letters, numbers, and special character.


Each unit of data is stored in a field; students’ record will have a separate field for
students like: Name, Number, Address etc.

DATA ITEM

A data item is a single unit of data in a storage record.


It is the smallest possible unit or field.

Types of Data Item


i. Numeric
ii. Alphabetic
iii. Alphanumeric

i. Numeric data item.


They are data items that contain only figures e.g. phone numbers, dates, age.

ii. Alphabetic Data Item.


They are data items that contain only alphabets e.g. names of school, individual
name and product name.
iii. Alpha-numeric Data Item
They contain figures, alphabets and special characters e.g. e-mail addresses,
passwords, vehicle number.

File structure and organization.

File structure organization is a way of organizing the data or records in a file. It is


also refers to the way data is structured into field and records within a file, i.e. the
relationship between data items

FILE

RECORDS
RECORDS
RECORDS

FIELD FIELD FIELD FIELD

Types of file organization

a) Serial File organization


b) Sequential File organization
c) Indexed File organization
d) Random File organization
e) Index – sequential File organization

(a) Serial file organization

The serial file organization is a collection of record with no particular


sequence. Records in a serial file are inserted as they arrive. That is
records are arranged serially with record 1 being the first and the record 2
being the second record etc. The method of accessing the contents of
serial file is serially

(b) Sequential file organization


A sequential file is organized such that each record in the file except
the first has a unique predecessor record and each record except the last
has a unique successor record.
In a sequential file organization, records are organized in the sequence by
which they were added

(c) Indexed files organization

Indexed file organization contain reference number (keys).


It is organized such that each record is uniquely identified by the value of a
key within the record. E.g. Employee number that identify a record in
relation to other record. These references are called the primary keys that
are unique to a particular record.
Alternate keys can also be defined to allow alternate methods of accessing
the record. For example instead of accessing an employee’s record using
employee numbers you can use an alternate key that reference employee
by department.

(d) Random file organization

In random or direct files organization the records are not stored


sequentially on the storage medium
A relative key is assigned to determine the order of files, and this technique
is called hashing

(e) Index sequential file organization

Index-sequential file organization may be used when both sequential and


random processing are supported
In this kind of a file, records are stored in sequential order according to a key
but file also contains an index.

The key enables user to access specified records without going through the
entire file.

METHODS OF ACCESSING FILES

Data access typically refers to activities related to storing, retrieving, or acting on


data housed in a database or other repository. The following are methods of
accessing files or data.

Methods of Accessing Files are:

a. Sequential Access
b. Serial Access
c. Random Access
d. Indexed Sequential Access

a. Sequential Access

Sequential access means that a group of elements is accessed in a


predetermined ordered sequence.
In a data structure, a data is said to have sequential if one can only visit the
values it contains in one particular order.

b. Serial Access
Serial access means that in order to identify and retrieve a particular record
it is necessary to read all the records which precede it in a relevant file.

c. Random Access
The random access sometimes called direct access is the ability to access
an element at an arbitrary position in a sequence in equal time,
independent of sequence size.

d. Indexed Sequential Access

The main concept is to access a file directly first and then sequentially
from that point onwards.
It is a method of indexing data for fast retrieval. It is in fact a combination
of both the sequential access as well as random access

Assignment
List three types of data item with suitable example

WEEK: 5
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: CONCEPT OF COMPUTER FILES
SUBTOPIC: CLASSIFICATION OF COMPUTER FILES

FILE CLASSIFICATION
Computer files are classified into the following

1. Master file
2. Transaction file
3. Reference file

1. MASTER FILE
It is a computer file containing relatively permanent information, usually updated
periodically, such as payroll data, names, etc.
Master file contains records of permanent records and data.

2. TRANSACTION FILE
It contains data which is used to update the records of master file. E. g.
address of the customer. It is a collection of transaction records e.g sales
transaction file may contain details of all sales made a day, a week, a month or
more . it also serve as audit trail and history.

3. Reference file.
It is a file that is used for reference or look up purpose.

Criteria for classifying files.


i. Nature of content
ii. Organization method
iii. Storage medium.

i. Nature of content: this is based on what it contains, the application it was


developed with and extension it was saved with. E.g. Word File (.docx),
pictures(.jpg or .jpeg), portable document format(.pdf), Excel file(.xls), Amination
files (.wmv)
ii. Organization method: this is based on the manner in which they are
organized or arranged E.g. Random file , Sequential file etc
iii. Storage medium: based on location and mode of storage E.g desktop
file ,Hard disk file , System files, BIOS file, server file etc

Assignment
1. State two limitation of computer filing system
WEEK: 6
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: HANDLING OF COMPUTER FILES

HANDLING OF COMPUTER FILES

BASIC OPERATIONS ON COMPUTER FILE

Basic operations on computer files are;

1. Creation: to make a new blank document

2. Deletion: To remove a file from disk

3. Retrieval: To find a file from the disk and bring it back

4. Copy: To produce, duplicate, or create a new file which has the same content
as an existing file

5. View: To see the content of the file on a disk

6. Update: To add new information to existing information on a file

7. Open: To unveil the content of a file

8. Close: To close, or make the content of a file not available for viewing

Sequential files

In sequential files, to find a particular element, you must first read the whole file
up to that element. It is also a file whose record is organized on the basis of their
successive physical portion.

Sequential file are files which consist of the same record types that are stored on
a secondary storage device.

STEPS IN CREATING A SEQUENTIAL FILE

1. Open the file in sequential output mode: to create a file

In power BASIC, you must use the OPEN statement.


2. Output data to file: Use WRITE # or PRINT # to write data to a sequential file.

3. Close the file: The CLOSE statement closes a file after the program has
completed all I/O operations

BASIC FILE PROCESSING STATEMENT

1. OPEN # : To open the file

2. INPUT# : To read entire document

3. LINE INPUT # :To read the file line by line

4. CLOSE # : To close the file after the process has been completed.

WEEK: 7
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: HANDLING OF COMPUTER FILES
SUBTOPIC: FILE INSECURITY
FILE INSECURITY

File insecurity refers to the concept that computer system file is always
vulnerable to attack

The attack usually is on files personally created by user or files created during
installation of our computer system and other packages we make use of. These
fact create a constant battle between those looking to improve security, and
those looking to circumvent security.

Effects of file insecurity

1. Data/information loss

Data loss is one of the major problems associated with computer files,
coincidentally. It is one of the problems computer system hope to achieve from
the old files storage system.

Therefore, adequate care must be taken to ensure that computer files are well
secured and void of loss or damage.

Causes of data loss

(a) Human Error.

(b) Computer Virus.

(c) Natural Disaster.

(d) Hardware or System Problem.

(e) Software Corruption or Program Problem.

(2) Over Writing of Data \ Information.

It occurs most times when we are careless with naming our document. This
happens when a new file is created. We try to save it but we are not careful
enough to check if such name exists before. If we eventually save with the name,
it overwrites the existing document even though they do not contain information.
3. Data Corruption

4.Data becomes unreliable

Method of File Security

1. Use of back-ups: This is coping or creating the copy of your file in another
storage medium, so that if any damage occurs the file can be replaced from the
backup.

2. Use of Antivirus: Anti-virus are software or programs writing to prevent


unnecessary attack to computer files.

They are mostly refers to as utility programs and they help to block and clean-up
threats to computer files

3. Password: It helps to protect files from unauthorized access. If a file cannot be


accessed, it content cannot be deleted or edited as the case be.

4. Proper labelling of storage devices: Storage device should be well labeled, this
makes it easier to store and locate file, it also prevent accidental and form of
storage devices.

5. Encryption: This is a process of converting information or data into code,


especially to prevent unauthorized access.

WEEK: 8
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: HANDLING OF COMPUTER FILES (cont’d)

DIFFERENCES BETWEEN COMPUTER FILES AND MANUAL FILES

COMPUTER FILE MANUAL FILES

1.Computer files can be considered as Manual file is considered as a local


modern counterpart of paper and old way of storing data or
document. information.

2.Computer file allows operations or Manual file system does not support
transactions like insert, delete, such operation or transaction.
update, etc.

3.Computer file is stored in electronic Manual file tend to be ink printed or


state or digital form and view in a written on paper
comprehensive way

4.Computer file can be sent through Manual file is physically transferred or


electronic means such as E -mail, file transported through courier services
transfer or through portable electronic E.g UPS, Fedex, DHL.
devices

5.Computer file is easily Manual files must be physically


duplicated/copied and maintained on copied either a copier or hand written
the storage/electronic device which copier
they are stored.

ADVANTAGES OF COMPUTER FILES

1.It is neatly modified


2.It is fast to access

3.It is more secured

4.it is more reliable

5.it is sless laborious

DISADVANTAGES OF COMPUTERIZED FILES

1. It can be affected by virus

2. It can be affected by irregular power supply

3. It is expensive to set up

4. It can be lost or damaged

WEEK: 9
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: JAVA CONSOLE INPUT 1(USING KEYBOARD CLASS)

9.1 Simple Input Command


A program that accepts values at run times is interactive because it exchanges
communications, or interacts with user. In order to provide values during the execution
of a program requires input, and the form of input that is used is keyboard entry from the
user. Here, we shall be looking at some standard input commands that are used in Java
programming language.

9.2 Character Input Command


In Java programming language, the character are read from the keyboard by calling the
System.in.read() method. This is one of Java’s console functions. This method accepts
input from the keyboard. The in object has access to the method named read() that
retrieves data from the keyboard. The example below shows a program that accepts
simple user input.

public class CharacterInput

public static void main(String[] args) throws Exception

char charInput

System.out.print(“Enter a character :”);

In the above example, the string “enter a character” prints on the screen. A message
charInput=(char)System.in.read():
requesting user input is commonly known as a prompt because it prompts or coaches
System.in.read();System.inread();//absorbs the enter key.
the user to enter an appropriate response. The System.in.read() is used to obtain a
character

Input entered by the user the keyboard. The read() method accepts the returned integer
into a character. The cast(char) converts the returned integer into a character.

By default, the standard input is line buffered, so the Enter key must be pressed before
any characters that we type will be sent to the our program.

There is however, a problem when we use read() to accept a character from the
keyboard, every key we press – including the Enter key – is accepted, one at a time.
Thus, we can absorb the Enter key after each input by reading in with two read()
method cells.

Since we are using the System.in.read() method, in the main() method header, a phrase
throws Exception must be added at the end of the line. It is necessary to handle input
errors. An exception is an error situation. Because errors should be infrequent, and all
sorts of errors can arise, thus, we can let the compiler handle the problem by throwing
the exception, or passing the error to the operating system. By placing throws Exception
after the main() header accomplishes this and a program, which reads keyboard input
will not be able to compile successfully without this phrase.

The output of the above program is shown below:


The output of the above program is shown below:

9.3 Simple Output Command

In Java programming language, the terminal window is used as the standard output.
System.out is a PrintStream object that allows us to write to “standard output” there are
two methods used in Java programming language that allows the users to display the
input that had been entered to the screen, which include the print() and printIn() method.
The difference between the two methods was mentioned in the earlier chapters. By
using the printIn() method, after a statement is displayed, the cursor will be position on
the next line. If the print() method is used, the cursor will be position on the next
available position but on the same line.
WEEK: 10
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: JAVA CONSOLE INPUT II

JAVA CONSOLE INPUT USING SCANNER CLASS

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation. In our example, we will use
the nextLine() method, which is used to read Strings:

Example

import java.util.Scanner; // Import the Scanner class

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input

System.out.println("Username is: " + userName); // Output user input

}
Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user


nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various types:

Example
import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input

String name = myObj.nextLine();


// Numerical input

int age = myObj.nextInt();

double salary = myObj.nextDouble();

// Output input by user

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Salary: " + salary);

Run Example »

Note: If you enter wrong input (e.g. text in a numerical input), you will get an
exception/error message (like "InputMismatchException").

You can read more about exceptions and how to handle errors in the Exceptions
chapter.

WEEK: 11
DATE: ………………………………………………………….
CLASS: SS2
TOPIC: JAVA CONTROL STATEMENTS 1&11

JAVA CONTROL STATEMENT 1- THE IF STATEMENT


The statements that control the execution flow of the program are known as control statements.
In a program, we modify and repeat the data several times. We need some tools for these
modifications that will control the flow of the program, and to perform this type of tasks Java
Provides control statements.
There are four types of control statements:

1. Sequence Control Statement


2. Selection or Decision Control Statement
3. Repetition or Loop Control Statement
4. Case Control Statement

We shall dwell on Selection or Decision Control Statement


1. Selection Statements
In the previous chapter, we have learned how to write program that can accept inputs, we can
therefore, alter the events that occur within the program based on the user’s input allowing decision
making to take place. To make a decision, it involves choosing between two alternative courses of
action based some value within a program.

Selection statement allows our program to choose different paths of execution based on the outcome
of an expression or the state of the variable. The expression or value upon which a decision is made is
always a boolean value, which is always one of two values – true or false. Java supports two kind of
selection statements: if or if..else statement and the switch statement.

THE IF-STATEMENT

If statements in Java is used to control the program flow based on some


condition, it's used to execute some statement code block if the expression
evaluated to true; otherwise, it will get skipped. This statement is the
simplest way to modify the control flow of the program.

The basic format of if statement is:


Syntax:
if(test_expression)

statement 1;

statement 2;

...

'Statement n' can be a statement or a set of statements, and if the test expression evaluated
to true, the statement block will get executed, or it will get skipped.

Example of a Java Program to Demonstrate If statements


Example:

public class Sample{

public static void main(String args[]){

int a=20, b=30;

if(b>a)

System.out.println("b is greater");

Program Output:
Java Switch Statements
Use the switch statement to select one of many code blocks to be executed.

Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later
in this chapter
The example below uses the weekday number to calculate the weekday name:

Example
int day = 4;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

case 4:

System.out.println("Thursday");

break;

case 5:

System.out.println("Friday");

break;

case 6:

System.out.println("Saturday");

break;

case 7:

System.out.println("Sunday");

break;
}

// Outputs "Thursday" (day 4)

Try it Yourself »

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

Example
int day = 4;

switch (day) {

case 6:

System.out.println("Today is Saturday");

break;

case 7:

System.out.println("Today is Sunday");

break;

default:
System.out.println("Looking forward to the Weekend");

// Outputs "Looking forward to the Weekend"

Try it Yourself »

Note that if the default statement is used as the last statement in a switch
block, it does not need a break.

Test Yourself With Exercises


Exercise:
Insert the missing parts to complete the following switch statement.

int day = 2;
switch ( ) {
1:
System.out.println("Saturday");
break;
2:
System.out.println("Sunday");
;
}
Nest if and Nested if…else Structure.

We can code as many dependent statements as we need within an if or an else statement. Such
statements with an if inside another if are commonly called nested if statements. Nested if statements
are particularly useful when two conditions must be met before some action is taken.

Syntax: nested if structure


If (condition 1)

If (condition 2)

Statement;

Syntax: nested if…else structure.

If(condition 1)

If(condition 2)

Statement 1:

Else

Statement 2:
The example below shows a segment of a program using the nested if statement.

If ( itemSold > 3)

If (total > 1000)

The next example below shows a segment of a program using the nested if…else statement.

If (itemSold >3)

If (total > 1000)

Bonus = 50;

Note: There can be sometimes when there will be more than one action taken place (compound
statements) following by the evaluation of a Boolean expression within an ifstatement. To execute more
than one statement that depends on the evaluation of a Boolean expression, we will have to place these
compound statements within a pair of curly brackets.

EXAMPLE 4:WORKING WITH if …else statement


class example3
{
public static void main(String [] args)
{
int a = 5;
if (a>=4)
{
System.out.println( "a is greater than 4");
}
else
{
System.out.println( "a is less than 4");
}
}
}

EXAMPLE 5:working with switch…case statement


class example4
{
public static void main(String [] args)
{
int a = 5;
switch(a)
{
case 1:
System.out.println("a is 1");
break;
case 3:
System.out.println("a is 3");
break;
case 5:
System.out.println("a is 5");
break;
default:
System.out.println("Wrong input");
}
}
}

Example 6:working with nested if…else statement


class example5
{
public static void main(String [] args)
{
int a = 5,b = 9;
if (a>=4)
{
if(b<8)
{
System.out.println("a is greater than 4 and b is less than 8");
}
else
{
System.out.println("a is greater than 4 and b is greater than 8");
}
}
else
{
System.out.println("a is less than 4");
}
}

You might also like