Ict SS2
Ict SS2
E- LEARNING NOTE
INFORMATION
COMMUNICATION
TECHNOLOGY
SS2
SECOND TERM
2024/2025 SESSION
WEEK 1
Data conversion is the transformation of computer data from one format to another.
Registers
Address
A memory address is an identifier for a memory location at which a computer program or a hardware
device can store data and later receive it.
Bus
A bus is a set of physical connections (cables, printed circuits, etc.) which can be shared by multiple
hardware components to communicate with one another. The purpose of buses is to reduce the number of
"pathways" needed for communication between components, by carrying out all communications over a
single data channel. This is why the metaphor of a "data highway" is sometimes used. If only two
hardware components communicate over the line, it is called a hardware port (such as a serial port or
parallel port).
A bus is characterized by the amount of information that can be transmitted at once. This amount,
expressed in bits, corresponds to the number of physical lines over which data are sent simultaneously. A
32-wire ribbon cable can transmit 32 bits in parallel. The term, "width" refers to the number of bits a bus
can transmit at once. In addition, the bus speed is also defined by its frequency (expressed in Hertz), the
number of data packets sent or received per second. Each time that data is sent or received is called a
cycle. This way, it is possible to find the maximum transfer speed of the bus, the amount of data which it
can transport per unit of time, by multiplying its width by its frequency.
Functions of Registers
Functions of the registers are:
i.Registers hold the address of memory where the CPU wants to read or write data
ii. They hold the contents of data instruction read from or written in memory
iii.They are used to specify the address of a particular I/O device
iv. Registers are used for exchanging data between the I/O module and the processor
v. They store current instructions being executed or coded
vi. Registers allow the bits of its content to be moved to left or right (shift register)
vii.They hold the memory addresses of data and instructions during the execution phase
viii. Registers store the result produced by the system
Fetch-Execute Cycle
The fetch-execute cycle is the sequence the computer follows to transform data from one format to
another.
The steps in the processing cycle are as follows:
Fetch the next instruction: The program counter contains the address of the next instruction to be
executed; the control unit goes to the address in the memory specified in the program counter, makes a
copy of the contents and places the copy in the instruction register.
Decode the Instruction: To execute the instruction in the instruction register, the control unit has to
determine what the instruction is.
Get Data If Needed: It may be that the instruction to be executed requires additional memory accesses to
complete its task. If this is the case, the control unit must get the content of the memory location.
Execute the Instruction: Once an instruction has been decoded and any data fetched, the control unit is
ready to execute the instruction. Execution involves sending signals to the arithmetic/logic unit to carry
out the processing. When the execution is complete, the cycle begins again.
2. CPU Speed and Generation: The speed of a computer is measured in Hertz (Hz), which is the number
of tasks it can process per second. A faster CPU can process more tasks per second, improving data
transfer speed.
3. Register Size: Larger registers can hold more data at once, potentially accelerating data transfer.
4. Bus Width: A wider bus, measured in bits, can transmit more data bits simultaneously. This increased
data transmission capacity directly translates to faster transfer rates.
5. Bus Speed: A higher bus speed enables data to be transferred more quickly.
6. Cache Memory: Cache memory is a temporary memory that holds frequently accessed data and
instructions for faster and more efficient processing by the CPU. The higher the size of cache memory the
faster the speed of data transfer. The downside of the cache memory is that it trades off capacity for speed.
The types of registers are Memory data register (MDR) and Current instruction Register (CIR).
1. MDR
The memory data register is used to hold data or the memory address that contains either the next
piece of data or an instruction that is to be used.
The memory data register acts like a buffer and holds data that is transferred from the memory to
the processor.
The memory data register is used whenever data is being transferred between central processing
unit and main memory.
2. CIR
Current instruction register is the register, usually in the control unit, that contains the instruction
that is being executed by the CPU.
The CIR stores the instruction currently being executed. In simple processors each instruction to be
executed is loaded into the instruction register which holds it while it is decoded, prepared and
ultimately executed.
DATA-FETCH-EXECUTE CYCLE
Fetch execute cycle is the very basic way a computer works. All commands are executed through the
running of this cycle. The cycle itself has very few commands, however when linked up together it is
possible to create a large program, or even an operating system.
WEEK 3:
In today’s class, we will be talking about security and ethics. Enjoy the class!
Computer ethics
Computer Ethics can be defined as a set of moral principle that requires the use of the computer. It deals
with how computer professional should decide on professionals and social conduct.
Computer ethics are rules that govern the use of a computer system. Ethics deals with placing a “value”
on acts according to whether they are “good” or “bad”. Every society has its rules about whether certain
acts are ethical or not. These rules have been established as a result of consensus in society and are often
written into laws. Computer ethics are increasingly becoming important because of the rising number of
cybercrime issues, including software piracy, unauthorized access, pornography, spamming, and target
marketing, and hacking.
The widespread popularity and use of the Internet have given rise to many cybercrime issues and concerns
about user privacy. Various computing applications are tampered with to invade into other’s privacy.
Malware, spyware, freeware, and browser cookie exploits are some of the notorious computing
applications that have spurred the debate on the importance of ethical behaviour in technology.
Some of the rules you should follow while using a computer are:
Basic rules
General rules
Security breaches
1. Unintentional intrusions
2. Intentional attacks
3. Denial of services attacks
4. Making services not available (e.g. over the Internet)
5. Browsing
6. Directory or data in memory
7. Disk from previous process file
8. Wiretapping
9. Listening and collecting information (e.g. passwords for later access) bypassing
authentication
10. Repeated trials (guessing authentic passwords)
11. Trap doors (including backdoor passwords)
12. Unspecified and undocumented entry points to systems
13.Trash collection/dumpster diving
a small program that alters the way a computer operates without the permission or
knowledge of the user
Self-executing – often placing its own code in the path of another
Self-replicating – accomplished by copying itself from an infected file to a clean file
Targeting certain OS exploiting a known vulnerability in the system software – hence
important to correctly update the OS with patches Security and Viruses and worms
Types of virus
1. File infector Normally resident in memory and infect executive files in the OS
2. Boot sector Infect the boot sector (disks and hard drives) when the computer is
booted up (powered on)
3. Master boot record Infect the boot record of a disk saving a legitimate copy of the
master boot record in a different location on the volume
4. Multipartite Infect both boot record and program files making especially difficult to
repair
5. Macro Infect data files such as word processing and spreadsheet Security and Viruses
and worms
1. A logic bomb is a destructive program with a fuse – triggering event (e.g. keystroke
or Internet connection).
2. A logic bomb often spreads unnoticed throughout a network until a predetermined
event when it goes off and does the damage.
3. A time bomb is triggered by a specific time such as a day of the year. Example –
Michaelangelo discovered in 1991 was designed to execute on the birthday of
Michaelangelo (6 March 1475) when a computer is booted up. It overwrote the first 17
sectors on heads 0-3 of the first 256 tracks of the disk making subsequent boot
difficult.
Antivirus software is capable of repairing files infected with a virus but it is generally unable to repair
worms.
WEEK 4:
Concept of Computer Files
Welcome to class!
In today’s class, we will be talking about the concept of computer files. Enjoy the class!
Computer files: Computer files are the most basic unit of data that users can store on a disk. Every
program, image, video, song employee numbers, a 3-digit, and the document is stored as a file
Record: A record is a collection of related data items or fields. Each record normally corresponds to a
specific unit of information. For example, employee number, employee’s name, basic salary and house
rent allowance.
Field: Data items are physically arranged as fields in a computer file. Their length may be fixed or
variable. Since all individuals have 3 digits field is required to store the particular data. Hence, it is a fixed
field. In contrast, since a customer’s name varies considerably from one customer to another, a variable
amount of space must be available to store this element. This can be called a variable field.
Data item: Data item is the smallest unit of information stored in a computer file. It is a single element
used to represent a fact such as an employee’s name, item price and so on.
File structure:
Data: a data item is the smallest unit of information stored in a computer file.
1. Serial: A serial file is one which the records have been stored in the order in which
they have arisen. They have not been sorted into any particular order. An example of
a serial file is an unsorted transaction file. A shopping list is an example of a non-
computerized serial file. Serial files can be stored on tape, disc or in memory.
Sequential: in sequential file organization, records are organized in the sequence by
which they were added. A sequential file contains records organized in the order they
were entered. The order of the records is fixed. The records are stored and sorted in
physical, contiguous blocks within each block the records are in sequence. Records in
these files can only be read or written sequentially.
2. Indexed: An indexed file organization contains reference numbers, like employee
numbers, that identify a record in relation to other records. 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 employees by departments. This allows greater flexibility
for users to randomly search through thousands of records in a file. However, it
employs complex programming to be implemented.
3. Random file: This is the file organized via an index. Also called a “direct file” or
“direct access file,’’ it enables quick access to specific records or other elements
within the file rather than having to read the file sequentially. The index points to a
specific location within the file, and the file is read from that point.
1. Master file: there are files of a fairly permanent nature, e.g. customer ledger,
payroll, inventory, and so on. A feature to know is the regular updating of these files
to show a current position. For example, a customer’s order will be processed,
increasing the “balance owing “figure on a customer ledger record. It is seen
therefore that master records will contain both data of a static nature, e.g. a
customer name, address, and data that, by its nature will change each time a
transaction occurs, e.g. the” balance” figure already mentioned.
2. Transaction file: This is also known as movement file. This is made up of various
transactions created from the source documents. In a sales ledger application the file
will contain all the orders received at a particular time. This file will be used to update
the master file. As soon as it had been used for this purpose it is no longer required. It
will therefore have a very short life, because it will be replace by a file containing the
next batch of orders.
3. Reference files: A file with a reasonable amount of permanency. Examples of data
used for reference purposes are price lists, tables of rates of pay, names and
addresses.
Criteria for classifying computer files: Criteria for classifying computer files are:
General evaluation
Computer files
Record
Field
Data Item
WEEK 5:
File Contents
On the atomic level, all the information in a file is binary, or just a series of ones and zeros. A computer
file may contain;
i. Document: A document includes any file created by a user.
ii. Program: Program files contain instructions for the computer’s microprocessor.
iii. Data: Data files include all other files that aren’t programs or documents.
File Functions
Files are used to do one or more of the following functions:
a. They provide machine-executable code
b. They store application programs or operating system configuration
c. They store data used by the users such as Microsoft Word files.
a. Block: A block is the physical unit of transfer between the backing store and the main memory.
b. Bucket: A bucket is the logical unit of transfer between the backing store and the main memory.
c. Hit: A hit is the number of times a program or item of data has been accessed.
Welcome to Class !!
In today’s Computer Science class, We will be learning about Handling Files. We hope you enjoy the
class!
A file is abstract; to define a file properly we need to consider the operation that can be performed on the
files. There are six basic file operations that can be performed by the OS. The OS can provide system calls
to create, write, read, re-position, delete and truncate files. All information in a file is always in binary
form or a series of ones and zeros. A document includes any file you have created. It can be a true text
document, sound file, graphics, images, or any other type of information the computer can create, store, or
size from the internet.
Files: As we know that Computers are used for storing the information for a Permanent Time or the Files
are used for storing the Data of the users for a Long time Period. And the files can contain any type of
information means they can Store the text, any Images or Pictures or any data in any Format. So that there
must be Some Mechanism those are used for Storing the information, Accessing the information and also
Performing Some Operations on the files.
o
Space in the file system must be found for the file.
An entry for the new file must be made in the directory.
2. Writing a file: To write a file, we make a system call specifying both the name of the file and the
information to be written in the file. The system must keep a write pointer to the location in the file where
the next write is to take place.
3. Deleting a file: To delete a file, we search the directory for the named file. Having found the associated
directory entry, we release all file spaces so that it can be re-used by other files and erase the directory
entry.
File Operations
We can Also Link a File with any other File. These are also called as the Symbolic Links, in the Symbolic
Links all the files are linked by using Some Text or Some Alias.
When a user clicks on the Special text or on the Alias then this will open that Linked File. So that we can
say that the Files are linked With each other by using Some Names and by using Some Locations.
These are Also Called as the Symbolic Links and always remember that when we remove the Link from
the System then this will not an effect on the Actual file Means the Original File will be Kept Save into
the Locations.
WEEK 8
COMPUTER STUDIES
HANDLING COMPUTER FILES
Basic File Operations
Following are some of the basic file operations:
1. Create: To make a new file
2. Delete: To remove a file from disk
3. Retrieve: To find a file and bring it back
4. Copy: To produce file so that it is the same as the original piece of work
5. View: To see the files in a folder
6. Update: A manipulation involving adding, modifying, or deleting data to bring a file up to-
date
7. Open: Open a file for editing
8. Close: To exit the edited file.
Sequential File Creation
There are many ways to organize data in a sequential file. One of such ways is by using
BASIC
Programming.
1. Choose a DOS file name. A DOS file name is a string consisting of a base name of at most
eight
characters followed by an optional extension consisting of a period and at most three
characters. Blank
spaces are not allowed. Some examples of DOS file names are INCOME.86, CUSTOMER.DAT.
And
FORT500.
2. Choose a number from 1 through 255 to be the reference number of the file. While the
file is used, it
Will be identified by this number.
3. Execute the statement. OPEN file name FOR OUTPUT AS #n. Where n is the reference
number.
4. Place data into the file with the WRITE statement.
5. After all the data have been recorded in the file, execute CLOSE #n
Example 1: A program to demonstrate the use of WRITE statement
REM Demonstrate use of WRITE statement
CLS
WRITE “ENIAC”
WRITE 1946
WRITE “ENIAC, 1946
LET a$ = “Eckert”
LET b$ = “Mauchly”
WRITE 14*139, “J.P. “ , a$, b$, “John”
END
[run]
ENIAC
1946
ENIAC 1946
1946, J.P. Eckert, Mauchly, John
Example 2: Write a program to create a file EXAMFILE.DAT with marks of English and
Mathematics.
REM a program to create a file EXAMFILE.DAT and record data into it
OPEN “EXAMFILE.DAT” FOR OUTPUT AS #1
READ Maths$, Eng$
DO WHILE names$ “EOD”
WRITE #1, names$, Maths$, Eng$
READ names$, Maths$, Eng$
LOOP
CLOSE #1
DATA Joy, 87, 75
DATA Gbenda, 88, 67
DATA Viola 77, 70
DATA EOD, 0, 0
END
Accessing a Sequential File
Data stored in a sequential file can be read in order and assigned to variables with the
following steps:
1. Choose a number from 1 to 255 to be the reference number for the file
2. Execute the statement. OPEN filename FOR INPUT AS n. where n is the reference number
3. Read data from the file with the INPUT statement.
4. After the desired items have been found close the file with the statement CLOSE #n.
Example: 3 write a program to display the contents of EXAMFILE.DAT
Solution
REM Read data from EXAMFILE.DAT file
OPEN “EXAMFILE.DAT” FOR INPUT AS #1
PRINT “Name”, English”, Mathematics”
DO WHILE NOT EOF (1)
REM process the entire file
INPUT name$, Maths$, Eng$
LOOP
CLOSE #1
END
BASIC FILE PROCESSING
File processing is a method of storing, retrieving, and manipulating data in computer files. It
involves
reading data from a file, processing it in some way, and then writing the processed data
back to the
same or a different file. This process allows data to be stored and retrieved in a persistent
manner, so
that it can be used again in the future.
File processing is a fundamental aspect of computer programming and is used in many
applications, such
as database management, data analysis, and other data-intensive tasks. In file processing,
data is stored
in a file, which is a collection of related data stored on a computer system. Files can be in
various
formats, such as text files, binary files, and more.
The basic file processing operations include creating a file, reading the contents of a file,
updating the
contents of a file, and deleting a file. In addition, file processing also includes manipulating
data in a file,
such as sorting, searching, and updating specific elements in the file.
FILE INSECURITY
File insecurity refers to the lack of proper measures taken to protect digital files from
unauthorized
access, modification, or destruction. When files are insecure, they can be vulnerable to a
variety of
threats
EFFECTS OF FILE INSECURITY
- Unauthorized access: This occurs when someone gains access to a file without permission,
either
by stealing login credentials or exploiting a vulnerability in the system.
- Malware: Malicious software such as viruses, worms, and Trojans can infect files and
compromise their security. Malware can be spread through email attachments, downloaded
files,
or other means, and can cause significant harm to the file and the system.
- Data breaches: A data breach occurs when sensitive information is exposed to
unauthorized
parties. This can happen when files are not properly secured, either through a cyber attack
or
through human error such as accidentally sending an email to the wrong recipient.
- Data loss: Data loss can occur when files are accidentally deleted, corrupted, or lost due to
hardware or software failures. Without proper backups or data recovery procedures, data
loss
can result in permanent damage to the file and the organization.
- Decreased productivity: Insecure files can lead to decreased productivity as employees
may
spend more time dealing with security issues, such as trying to recover lost files or clean up
malware infections. This can result in lost work hours and decreased efficiency.
- Legal and regulatory consequences: Insecure files can result in legal and regulatory
consequences, particularly for organizations that handle sensitive information. Failure to
properly secure files can result in fines, legal liabilities, and reputational damage
- Corrupt data: Corrupt data refers to any data that is damaged, incomplete, or inaccurate,
making
it unusable or unreliable. Data corruption can occur due to a variety of reasons, including
hardware or software failures, power outages, viruses or malware, or human error
- Hacking: Hacking is the unauthorized access to a computer system or file, usually with the
intention of stealing or destroying data.
- Phishing: Phishing is a method of tricking individuals into revealing sensitive information,
such as
passwords or financial details, by posing as a trustworthy entity.
FILE SECURITY METHODS
File security refers to the measures taken to protect digital files, such as documents,
images, videos, and
other types of data, from unauthorized access, modification, or destruction. Ensuring file
security is
essential for protecting sensitive information, such as personal and financial data,
intellectual property,
and confidential business information.
There are several ways to improve file security, including:
- Use of backups: This is refers to making copies of data so that these additional copies are
used to
restore the original after loss event. It is also a method of making copies of the file in a
separate
location so that they can be restored if something happen to the computer. This can be
done by
using removable media such as rewritable CD, memory card, flash etc.
- The use of antivirus . A virus is a self – replicating program that copies itself and that can
infect
other programs by modifying them or their environment such that a call to an infected
program
implies a call to a virus. An anti-virus is a software designed to detect and destroy computer
viruses.
- The use of password: A password is a string of characters used for authenticating a user on
a
computer system. It can prevent people accessing computer system, account files or parts
of files
by requiring a user to enter password. It is important to use strong passwords that are
difficult to
guess and to avoid reusing passwords across different accounts.
- Encryption: Encryption involves converting the data in a file into a code that can only be
decrypted with a key or password. This can help protect the file in case it falls into the
wrong
hands.
- Proper label of storage device: You should label your storage devices like floppies, CDs,
DVDs,
Pen drivers etc. So that you know what is exactly stored in them and so as not to
accidentally
delete of format them.
- File management: file management is the process of maintaining folders, documents and
multimedia into categories and subcategories as desired by a user.
- Access controls: Access controls allow administrators to set permissions for who can
access,
modify, or delete a file. This can help ensure that only authorized users can access sensitive
files.
- Firewalls: Firewalls are network security systems that monitor and control incoming and
outgoing network traffic based on predetermined security rules. They can help prevent
unauthorized access to files by blocking incoming traffic from untrusted sources.
DIFFERENCE BETWEEN COMPUTER FILE AND MANUAL FILE
Manual File
These files are hand-written and are always present in an intangible form. Moreover, they
can be stored
in different areas like shelves, cupboards and in a file room, etc. if a person wants to
transfer them then
he has to carry them along his way which is quite difficult. Also, they are always present in
hardcopy. The
maintenance of the manual files is also an issue and they can be destroyed easily as well.
Similarly,
chances of making errors are quite a lot in manual files as we are human beings and we
tend to make
many mistakes. Even when we do mistakes erasing them is not done that neatly, so the
overall look of
the formal document is affected. Moreover, the gathering of information is quite difficult and
time-
consuming. Additionally, when it comes to the accessibility factor they can be accessed
quite easily by
the people who are allowed to see them and also by the people who are not which is a
threat. So they
are not that safe.
Computer File
Computer files are the type of files that are made on a computer and are stored in the form
of a soft
copy. These types of files have a lot of protection as they are secured by different passwords
and codes.
Moreover, while making these files one can get automatic error-correction facilities. And
while writing
something whether it’s a research paper or anything which requires information from
multiple sources
than work is done quite easily here as the information can be gathered by varies websites in
less time.
Destroying computer files is not that easy. Such types of files can be transferred in no time
through
emails etc. and a large amount of information can be transferred as well as sent.
Furthermore,
computers have multiple file systems like MS windows computer, MS-DOS, and NTFS file
system, etc.
COMPUTER FILE MANUAL FILE
Computer files are transferred electronically. Manual files can be transported through
physical means
Computer files are difficult to destroy and can last
for a long time.
Manual files can warn off and can be
depleted easily by hand
Difficult to access at all times Easy to access whenever required
A large amount of information can be stored and
transferred
It is difficult to store a hefty amount of
information manually.
ADVANTAGES OF COMPUTERIZED FILES
(i) Computer can perform calculations quickly and efficiently.
(ii) Data can be retrieved quickly and easily.
(iii) Documents that are lost can often be retrieved.
(iv) Security is tight and hard to break into.
(v) Makes work easier.
(vi) Quicker to find things and sort things.
(vii) Transactions, accounts can be handled more properly by computers than manually.
LIMITATIONS OF COMPUTERIZED FILES
(i) Computerized filing system is expensive to set up.
(ii) Not effective where there is irregular electric supply.
(iii) Skilled labor with proficiency in computers is required.
WEEK 9
In Java, there are four different ways to read input from the user in the command line
environment(console).
This is the Java classical method to take input, Introduced in JDK 1.0. This method is used by wrapping
the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we
can read input from the user in the command line.
Implementation:
13
// Reading data using readLine
14
String name = reader.readLine();
15
16
// Printing the read line
17
System.out.println(name);
18
}
19
}
Input:
Geek
Output:
Geek
Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read
multiple values, we use split().
This is probably the most preferred method to take input, Introduced in JDK 1.5. The main purpose of the
Scanner class is to parse primitive types and strings using regular expressions; however, it is also can be
used to read input from the user in the command line.
WEEK 11:
Integrative Programming Selection Statements
Chapter 3: Java Control Statements
In java, the default execution flow of a program is a sequential order. But the
sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to skip
a part of the program, or sometimes we may want to execute a part of the program
again and again. To solve this problem, java provides control statements.
1. Selection Statement
Like all high-level programming languages, Java provides selection statements:
statements that let you choose actions with alternative courses. The program can
decide which statements to execute based on a condition. Selection statements
use conditions that are Boolean expressions. A Boolean expression is an
expression that evaluates to a Boolean value: true or false.
Integrative Programming Selection Statements
2. boolean Data Type
The boolean data type declares a variable with the value either true or false.
How do you compare two values, such as whether a radius is greater than 0,
equal to 0, or less than 0? Java provides six relational operators (also known as
comparison operators), shown in Table 3.1, which can be used to compare two
values (assume radius is 5 in the table).
3. if Statement
Java has several types of selection statements: one-way if statements, two-
way if-else statements, nested if statements, multi-way if-else statements,
switch statements, and conditional operators.
In java, we use the if statement to test a condition and decide the execution
of a block of statements based on that condition result. The if statement
checks, the given condition then decides the execution of a block of
statements. If the condition is True, then the block of statements is executed
and if it is False, then the block of statements is ignored. The syntax and
execution flow of if the statement is as follows.
Let's look at the following example java code.
Integrative Programming Selection Statements
Let's look at the following example java code.
When we run this code, it produces the following output.
Integrative Programming Selection Statements
In the above execution, the number 12 is not divisible by 5. So, the condition
becomes False and the condition is evaluated as False. Then the if statement
ignores the execution of its block of statements.
When we enter a number, which is divisible by 5, then it produces the output as
follows.
A one-way if statement executes an action if and only if the condition is true.
The syntax for a one-way if statement is as follows:
if (boolean-expression) {
statement(s);
}
Integrative Programming Selection Statements
The flowchart in Figure 3.1a illustrates how Java executes the syntax of an if
statement.
If the boolean-expression evaluates to true, the statements in the block are
executed.
As an example, see the following code:
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
The flowchart of the preceding statement is shown in Figure 3.1b. If the value
of radius is greater than or equal to 0, then the area is computed and the result
is displayed; otherwise, the two statements in the block will not be executed.
The boolean-expression is enclosed in parentheses. For example, the code in
(a) is wrong. It should be corrected, as shown in (b).
Integrative Programming Selection Statements
The block braces can be omitted if they enclose a single statement. For
example, the following statements are equivalent:
Listing 3.2 gives a program that prompts the user to enter an integer. If the
number is a multiple of 5, the program displays HiFive. If the number is
divisible by 2, it displays HiEven.
The program prompts the user to enter an integer (lines 6–7) and displays
HiFive if it is divisible by 5 (lines 9–10) and HiEven if it is divisible by 2 (lines
12–13).
Integrative Programming Selection Statements
3.1 Two-Way if-else Statements
An if-else statement decides the execution path based on whether the condition is
true or false. A one-way if statement performs an action if the specified condition
is true. If the condition is false, nothing is done. But what if you want to take
alternative actions when the condition is false? You can use a two-way if-else
Let's look at the following example java code.
When we run this code, it produces the following output.
Integrative Programming Selection Statements
3.2 Nested if and Multi-Way if-else Statements
An if statement can be inside another if statement to form a nested if statement.
The statement in an if or if-else statement can be any legal Java statement,
including another if or if-else statement. The inner if statement is said to be nested
inside the outer if statement. The inner if statement can contain another if
statement; in fact, there is no limit to the depth of the nesting. For example, the
following is a nested if statement:
if (i > k) {
if (j > k)
System.out.println("i and j are greater than k");
}
else
System.out.println("i is less than or equal to k");
The if (j > k) statement is nested inside the if (i > k) statement.
The nested if statement can be used to implement multiple alternatives. The
statement given in Figure 3.3a, for instance, prints a letter grade according to the
score, with multiple alternatives.
Integrative Programming Selection Statements
The if statement in Figure 3.3a is equivalent to the if statement in Figure 3.3b. In
fact, Figure 3.3b is the preferred coding style for multiple alternative if
statements. This style, called multi-way if-else statements, avoids deep
indentation and makes the program easy to read.
The execution of this if statement proceeds as shown in Figure 3.4. The first
condition (score >= 90) is tested. If it is true, the grade is A. If it is false, the
second condition (score >= 80) is tested. If the second condition is true, the grade
is B. If that condition is false, the third condition and the rest of the conditions (if
necessary) are tested until a condition is met or all of the conditions prove to be
false. If all of the conditions are false, the grade is F. Note a condition is tested
only when all of the conditions that come before it are false.
Integrative Programming Selection Statements
4. Logical Operators
Sometimes, whether a statement is executed is determined by a combination of
several conditions. You can use logical operators to combine these conditions
to form a compound Boolean expression. Logical operators, also known as
Boolean operators, operate on Boolean values to create a new Boolean value.
Listing 3.6 gives a program that checks whether a number is divisible by 2 and
3, by 2 or 3, and by 2 or 3 but not both.
Integrative Programming Selection Statements
(number % 2 == 0 && number % 3 == 0) (line 12) checks whether the number
is divisible by both 2 and 3. (number % 2 == 0 || number % 3 == 0) (line 15)
checks whether the number is divisible by 2 or by 3. (number % 2 == 0 ^
number % 3 == 0) (line 18) checks whether the number is divisible by 2 or 3,
but not both.
Integrative Programming Selection Statements
5. switch Statements
Using the switch statement, one can select only one option from more number of
options very easily. In the switch statement, we provide a value that is to be
compared with a value associated with each option. Whenever the given value
matches the value associated with an option, the execution starts from that option.
In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Let's look at the following example java code.
Integrative Programming Selection Statements
When we run this code, it produces the following output.
Integrative Programming Selection Statements
6. Conditional Operators
You might want to assign a value to a variable that is restricted by certain
conditions. For example, the following statement assigns 1 to y if x is greater than
0 and -1 to y if x is less than or equal to 0:
if (x > 0)
y = 1;
else
y = −1;
Alternatively, as in the following example, you can use a conditional operator to
achieve the same result.
y = (x > 0) ? 1 : −1;
The symbols ? and : appearing together is called a conditional operator (also
known as a ternary operator because it uses three operands. It is the only ternary
operator in Java. The conditional operator is in a completely different style, with
no explicit if in the statement. The syntax to use the operator is as follows:
boolean-expression ? expression1 : expression2
The result of this expression is expression1 if boolean-expression is true;
otherwise, the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to
max. You can simply write a statement using the conditional operator:
max = (num1 > num2) ? num1 : num2;
For another example, the following statement displays the message “num is even”
if num is even, and otherwise displays “num is odd.”
System.out.println((num % 2 == 0) ? "num is even" : "num is odd");
As you can see from these examples, the conditional operator enables you to write
short and concise code.