Jp1 Mar2023 Lecture Notes
Jp1 Mar2023 Lecture Notes
Java Programming 1
(CTD 1201)
1
COURSE OUTLINE
Acknowledgement
No part of this guide can be reproduced without written permission of the college
2
TABLE OF CONTENTS
Chapter 7: Iteration/Repetition
7.1 while loop 40
7.2 do-while loop 41
7.3 for loop 42
References 45
3
Chapter 1: Introduction to Programming and Java
A Programming language is a set of rules that provides a way of telling a computer what
operations to perform. Computers are designed to follow these instructions to perform task or
solve a problem. These instructions are called an algorithm.
Programming languages are written in English, which use words, symbols and rules of
grammar. The grammatical rules are called syntax. Each programming language has a different
set of syntax rules.
Machine Language
All programs are converted into machine language before they can be executed. It consists of
combination of 0’s and 1’s that represent high and low electrical voltage. Machine language
programs are executable, meaning that they can be run directly. Programming in machine
language requires memorization of the binary codes and can be difficult for the human
programmer. For example, to add two numbers, you might have to write an instruction in binary
code, like this:
BINARY : 1101101010011010
Assembly Language
Assembly language was created in the early days of computing as an alternative to machine
languages. It uses a short descriptive word, known as a mnemonic, to represent each of the
machine-language instructions. For example, the mnemonic add typically means to add
numbers and sub means to subtract numbers. For example, to add the numbers 2 and 3 and
get the result:
add 2, 3, result
4
High Level Language
New generation of programming languages known as high-level languages. They are platform
independent, which means that you can write a program in a high level language and run it in
different types of machines. High-level languages are English-like and easy to learn and use.
For example, is a high-level language statement that computes the area of a circle with a radius
of 5:
area = 5 * 5 * 3.14159;
Popular High-Level Programming Languages: C, C++, Java, Visual Basic, Pascal, Fortran and
…....
Pseudocode is a natural language mixed with some programming code. It uses English words
and has no formal syntactical rules.
Example:
Determine the average grade of a class:
Once your pseudocode ready, you translate them into a high-level language called source
program or source code. Because a computer cannot execute a source program, a source
program must be translated into machine code for execution. The translation can be done using
another programming tool called an interpreter or a compiler.
An interpreter reads one statement from the source code, translates it to the machine
code or virtual machine code, and then executes it right away
A compiler translates the entire source code into a machine-code file, and the
machine-code file is then executed
Was developed by a team led by James Gosling at Sun Microsystems in year 1991.
Originally called “Oak” but was renamed as JAVA in year 1995. Is based on C and C++. Often
described as Web programming language.
Today, it is used not only for Web programming, but also for developing standalone applications
across platforms on servers, desktops, and mobile devices (Palm PDA).
5
The primary authoring language is for the Web is HTML
(……………………………………………..) . Is a simple language for laying out documents,
linking documents on the Internet, and bringing images, sound, and video alive on the Web.
However, it cannot interact with the user except through simple forms. Web pages in HTML are
essentially static and flat.
Java initially became attractive because Java programs can be run from a Web browser. Java
programs uses modern graphical user interface with buttons, text fields, text areas, radio
buttons, and so on.
1. Java Is Simple
Java is easier than the popular object-oriented language C++, which was dominant
software-development language before Java. The clean syntax makes Java programs
easy to write and read.
2. Java Is Object-Oriented
OOP …………………………………….. is a popular programming approach that is
replacing traditional procedural programming techniques. OOP provides great flexibility,
modularity, clarity, and reusability of the code.
3. Java Is Distributed
Distributed computing involves several computers working together on network. Java is
designed to make distributed computing easy.
4. Java Is Interpreted
You need an interpreter to run Java programs. The programs are compiled into Java
Virtual Machine code called bytecode. Most compilers, translate program in high-level
language to machine code. Java interpreter translates the bytecode into the machine
language of the target machine.
5. Java Is Robust
Robust means reliable. Java puts a lot of emphasis on early checking for possible errors,
because Java compilers can detect many problems that would first show up at execution
time.
6. Java Is Secure
If you download a Java applet (a web program) and run it on your computer, it will not
damage your system because Java implements several security mechanisms to protect
your system.
7. Java Is Architectural-Neutral
Java is an architectural-neutral or platform-independent. Using Java, developers need to
write only one version that can run on every platform (Windows, OS/2, Macintosh, and
various UNIX).
8. Java Is Portable
They can be run on any platforms without being recompiled. Moreover, there are no
6
platform-specific features. It is portable to new hardware and operating system.
9. Java’s Performance
The new JVM is significantly faster. The new JVM uses the technology known as just-in-
compilation.
Java syntax is defined in the Java language specification, and the Java library is defined in the
Java API. The application program interface (API), also known as library, contains predefined
classes and interfaces for developing Java programs.
Java Development Toolkit (JDK) is the software for developing and running Java programs. An
IDE is an integrated development environment for rapidly developing programs. Java
development tool (e.g., NetBeans, Eclipse, and TextPad) software that provides an integrated
development environment (IDE) for developing Java programs quickly. Editing, compiling,
building, debugging, and online help are integrated in one graphical user interface.
The Java programming files which consist of source code, are known as source file. Java
source files end with .java extension.
A compiler is a program that translates source code into an executable form. The Java compiler,
however, translates a Java source file into a file that contains byte code instructions. Byte code
instructions are not machine language, and therefore cannot be directly executed by the CPU.
Instead, they are executed by the Java Virtual Machine. The bytecode is similar to machine
instructions but is architecture neutral and can run on any platform that has a JVM.
The Java Virtual Machine(JVM) is a program that reads Java byte code instructions and
executes them as they read. For this reason, the JVM is often called an interpreter, and Java is
often referred to as an interpreted language.
7
1.8 A Simple Java Program
Problem:
Write a program that displays the message “Welcome to Java!” on the console.
Solution:
//this application program prints Welcome to Java
Example:
package welcome;
public class Welcome //class name
{
public static void main(String[ ] args)
{
System.out.println("Welcome to Java!");
}
}
Output:
______________________________________________________________________
Review:
Every Java program must have at least one class. In this example, the class name is welcome.
The class contains a method named main.
1. Comments
Comments help programmers and user to communicate and understand the program.
Comments are not programming statements and are ignored by the compiler.
Comments preceded by two slashes // on a line, called a line comment, or enclosed
between /* and */ one or several lines, called paragraph comment.
2. Reserved Words
Reserved words, keywords, are words that have a specific meaning to the compiler and
cannot be used for other purposes in the program. When the compiler sees the word
8
after the class, it will understand that it is the name of the class. Other reserved words
are public, static, and void.
3. Modifiers
Java uses modifiers that specify the properties of the data, methods, and classes and
how they can be used. Examples of modifiers are public, static, and private,
4. Statements
A statement represents an action that sequence of actions. The statement
System.out.println(“Welcome to Java!”) in the program above is a statement to display
the greeting “Welcome to Java!” Every statement in Java ends with a semicolon(;).
5. Blocks
The braces in the program form a block that groups the components of the program. In
Java, block begins with an opening braces, { and ends with a closing braces, }.
6. Classes
A program is identified by using one or more classes.
7. Methods
System.out is known as the standard output object. println is a method in the object,
which consists of a collection of statements that perform a sequence of operations to
display a message to the standard output device.
Example:
package welcome1;
//Welcome1.java
//printing a line of text with multiple statements
public class Welcome1
{
//main method begins execution of java application
public static void main(String args[])
{
System.out.print("Welcome to ");
System.out.print("\nJava\nPrograming!");// \n to start into a newline
1. Syntax Errors
9
It occurs during compilation. Syntax errors result from errors in code construction, such
as mistyping a keyword, omitting some necessary punctuation, or using an opening
braces without a corresponding closing braces.
2. Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. It occurs when
an application impossible to carry out the certain operation. An input error occurs when
the user enters an unexpected input value that the program cannot handle. For instance,
instead of a number, the user enters a string.
3. Logic Errors
It occurs when a program does not perform the way it was intended to.
Debugging
Logic errors are called bugs. The process of finding and correcting errors is called debugging.
10
Chapter 2: Java Fundamentals
These words that have a special meaning in the programming language. They may be used for
their intended purpose only. Keywords are also known as reserved words. Keywords are
reserved, and cannot be used for anything other than their designated purpose.
Java Keywords
A data type is defined by a set of values and the operators you can perform on them. Each
value stored in memory is associated with a particular data type. The Java language has
several predefined types, called primitive data types.
11
long 64 bits -9223372036854775808 9223372036854775807
byte(s)
float 32 bits -3.4 * 10-38 3.4 * 1038
byte(s)
double 64 bits -1.7 * 10-308 1.7 * 10308
byte(s)
2.3 Characters
A char value stores a single character from the Unicode character set. A character set is an
ordered list of characters. The Unicode character set uses sixteen bits per character, allowing
for 65,536 unique characters. It is an international character set, containing symbols and
characters from many world languages.
Example:
package letters;
//This program demonstrate the char data type
letter = 'A';
System.out.println(letter);
letter = 'B';
System.out.println(letter);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
2.4 Boolean
12
A boolean value represents a true or false condition. They can also be used to represent any
two states, such as a light bulb being on or off. The reserved words true and false are the only
valid values for a boolean type.
Example:
package truefalse;
//A program for demonstrating boolean variables
2.5 Variables
Example:
package computearea;
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
//assign a radius
radius=20;
//compute area
area=radius*radius*3.14159;
//display results
System.out.println("The area for the circle of radius "+radius + " is " +area);
13
/*(+) is called a string concatenation operator. Is used
concatenate strings into a longer string.*/
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Declaring a Variable
If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2,….. ;
The equal sign (=) is used as the assignment operator. The syntax is as follows:
variable = expression;
You can also use a shorthand form to declare and initialize variables of the same type together
as:
int i = 1, j = 2;
2.6 Constants
Constants represent a permanent data that never changes. You can define …. as a constant.
The syntax :
final datatype CONSTANTNAME = VALUE;
You could define ……… as a constant and rewrite the program as follows:
14
Example:
package computearea;
// computeArea.java
public class ComputeArea
{
//assign a radius
double radius=20;
//compute area
double area=radius*radius*PI;
//display results
System.out.println("The area for the circle of radius "+radius + " is " +area);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
Example:
package eg;
//the program shows that how to read the different type of data types
public class eg
{
public static void main(String[] args)
{
int myInteger = 5;
String myString = "Hello";
System.out.println(myInteger);
System.out.println(myString);
}
15
}
Output:
____________________________________________________________________________
____________________________________________________________________________
Example:
package escsequence;
public class EscSequence {
public static void main(String args[]) {
System.out.println(“He said \”Hello!\” to me”);
System.out.print(“and I said \nHello \nHow are you \t Fine thank you \\”);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
16
If the operands of the / operator are both integers, the result is an integer (the fractional
part is truncated)
If one or more operands to the / operator are floating point values, the result is a floating
point value
The remainder operator (%) returns the integer remainder after dividing the first operand
by the second
Expression Result
17 / 5 3
17.0 / 5 3.4
17 / 5.0 3.4
9 / 12 0
9.0 / 12.0 0.75
6%2 0
14 % 5 4
-14 % 5 -4
Example:
package modulusdemo;
//Demostrate the % operator
public class ModulusDemo{
public static void main(String args[ ])
{
int iresult,irem;
double dresult,drem;
iresult = 10/3;
irem = 10%3;
dresult = 10.0/3.0;
drem = 10.0 % 3.0;
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
17
____________________________________________________________________________
____________________________________________________________________________
Shortcut Operators
Comparison Operators
Operator Name
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to
Boolean Operators
Operator Name
! Not
&& And
|| Or
^ Exclusive or
Example:
package comparison;
public class Comparison {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
____________________________________________________________________________
18
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Example:
package logicaloperator;
public class LogicalOperator {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b) );
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b) );
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
You already know how to display console output using the print or println methods. A new printf
method enables you to format output. The syntax to invoke this method is:
System.out.printf (format, items)
where format is a string that may consist of substrings and format specifiers. A format specifier
specifies how an item should be displayed.
Example:
int count = 5;
double amount = 45.56;
System.out.printf (“count is %d and amount is %f”, count, amount);
The display:
count is 5 and amount is 45.560000
19
By default, a floating-point value is displayed with six digits after the decimal point.
Example:
package addition;
//displays the sum of two numbers.
import java.util.Scanner;
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Increment Operator: used to increment the value of a variable by 1. This is denoted by the
symbol “++”. This can be used in two ways.
Pre-increment, e.g. ++x;
Post-increment, e.g. x++;
20
Decrement Operator: used to decrement the value of a variable by 1. This is denoted by the
symbol “--”. This can be used in two ways.
Pre-decrement, e.g. - - x;
Post-decrement, e.g. x - -;
Example:
package incredecre
public class IncreDecre {
public static void main(String args[]) {
int a = 5;
System.out.println(a);
System.out.println(++a);
System.out.println(a++);
System.out.println(a--);
System.out.println(--a);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Below are the conventions for naming variables, methods, and classes:
Use lowercase for variables and methods. If a name consists of several words,
concatenate them into one, making the first word lowercase and capitalizing the first
letter of each subsequent word; for example, the variables radius and area and the
method showInputDialog.
Capitalize the first letter of each word in a class name; for example, the Addition.
Capitalize every letter in a constant, and use underscores between words, for example,
the constant PI and MAX_VALUE.
21
Chapter 3: Keyboard Input
First you create a Scanner object and connect it to the System.in object.
Example:
Scanner keyboard = new Scanner (System.in);
Scanner keyboard
Declares a variable named keyboard. The data type of the variable is Scanner. Because
Scanner is a class, the keyboard variable is a class type variable.
22
name = keyboard.nextLine( );
Returns input as a string.
nextLong long number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a long value:”);
number = keyboard.nextLong( );
Returns input as a long.
nextShort short number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a short value: “);
number = keyboard.nextShort( );
Returns input as a short.
Any program that uses the Scanner class should have the following statement:
import java.util.Scanner;
OR
import java.util.*;
It tells the Java compiler where in the Java library to find the Scanner class, and makes it
available to your program.
package payroll;
//This program demonstrates the Scanner class
import java.util.Scanner;
public class Payroll
{
public static void main(String[] args)
{
String name; //to hold name
int hours; //hours worked
double payRate; //hourly pay rate
double grossPay; //Gross pay
23
//calculate the gross pay
grossPay = hours * payRate;
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
24
Chapter 4: Java Classes
The String class allows you to create objects for holding strings. It also has various methods
that allow you to work with strings.
The String class is provided by the JAVA API for handling strings is named String.
The following program shows String variables being declared, initialized, and then used in a
println statement.
package stringdemo;
// A simple program demonstrating string objects
public class StringDemo
{
public static void main(String[] args)
{
//The greeting & name variable holds the address of a String object
//A String object here is "Good day" & "John"
String greeting = "Good day ";
String name = "John";
System.out.println(greeting + name);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
Because the String type is a class instead of a primitive data type, it provides numerous
methods for working with strings. For example, the String class has a method named length that
returns the length of the string stored in an object.
package stringlength;
// This program demonsrates the String class's length method
25
stringSize = name.length();
System.out.println(name + " has " + stringSize + " characters.");
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
26
The following program demonstrates these methods:
package stringmethods;
//This program demonstrates a few of the String methods
System.out.println(message);
System.out.println(upper);
System.out.println(lower);
System.out.println(letter);
System.out.println(stringSize);
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
Comparing Strings
27
Output:
____________________________________________________________________________
____________________________________________________________________________
Example 2
package equalsignorecase;
public class EqualsIgnoreCase {
public static void main(String args []) {
String m1 = “Bye”;
String m2 = “bye”;
if(m1.equalsIgnoreCase(m2)) {
System.out.print(“They are equal”);
}
else {
System.out.print(“They are not equal”);
}
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
2. Use = = operator
Compares 2 object references to see if they refer to the same object
package comparison;
public class Comparison {
public static void main ( String args [ ] ) {
String code1 = “Joker”;
String code2 = new String(code1);
System.out.println(code1.equals(code2));
System.out.println(code1 == code2 );
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
A Random object generates pseudo-random numbers. Random Class is found in the java.util
package.
import java.util.*;
28
Example:
Random rand = new Random ( );
int randomNumber = rand.nextInt(10); // 0 to 9
Random Questions:
Write a program that simulates rolling of two 6-sided dice until their combined result comes up
as 7.
package dice;
// Rolls two dice until a sum of 7 is reached.
import java.util.*;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int tries = 0;
int sum = 0;
while (sum != 7) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);
29
tries++;
}
System.out.println("You won after " + tries + " tries!");
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
Java provides many useful methods in the Math class for performing common mathematical
functions. Here are some examples:
Example:
package power;
public class Power{
public static void main (String[ ] args) {
int base = 3, exponent = -4;
double result = Math.pow (base, exponent);
System.out.println (“Answer =” +result);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
30
Chapter 5: Date & Decimal Format
If you do not pass any string when creating a new SimpleDateFormat object, the default
formatting is used.
Example :
package datedisplay1;
/* To display the month, day and year in the MM/dd/yy
shorthand format, such as 07/04/03*/
import java.util.*; // for date
import java.text.*; // for SimpleDateFormat
public class DateDisplay1 {
public static void main (String[] args) {
Date today;
SimpleDateFormat sdf;
today = new Date();
sdf = new SimpleDateFormat ("MM/dd/yy");
System.out.println( sdf.format(today));
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
package datedisplay2;
31
package datedisplay2;
//To display which day of the week today is, we can use the letter E.
import java.util.*; // for date
import java.text.*; // for SimpleDateFormat
package datedisplay;
import java.util.*; // for date
import java.text.*; // for SimpleDateFormat
This code allows you to round a double value to 2 decimal places using DecimalFormat.
You can increase the decimal places by adding an extra #. For example
DecimalFormat("#.###"); rounds to 3 decimal places.
32
package decimalplaces;
import java.text.*;
public class DecimalPlaces {
public static void main (String [] args) {
double d = 1.234567;
DecimalFormat df = new DecimalFormat (“#.##”);
System.out.print (df.format (d));
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
package radius;
import java.text.*; //for the decimal format
import java.util.*; //for the keyboard input
area = radius*radius*PI;
volume = area*length;
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
33
Chapter 6: Control Structures
6.1 if Statement
If the boolean condition is true, the statement is executed; if it is false, the statement is
skipped
Two-way Decisions
The windshield wipers are controlled with an ON-OFF switch. The flowchart below shows how
this decision is made.
Start at the top of the chart then follow the line to the question:
is it raining?
34
o perform the instructions in the box "wipers off",
o follow the line to "continue".
Decisions
The windshield wiper decision is a two-way decision (sometimes called a binary decision). The
decision seems small, but in programming, complicated decisions are made of many small
decisions. Here is a program that implements the wiper decision:
package raintester;
import java.util.Scanner;
public class RainTesterb {
public static void main (String [ ] args) {
Scanner scan = new Scanner (System.in);
String answer;
System.out.print (“Is it raining? (Y or No): ”);
answer=scan.nextLine( );
if (answer.equals (“Y”))
System.out.println(“Wipers ON”);
else
System.out.println(“Wipers OFF”);
}
}
Examples:
package guess;
//demonstrate the if ...else statement
public class Guess {
public static void main(String args [ ])
/*must specify the throws java.io.IOException because the program using the System.in.read( ).
It necessary to handle input error*/
throws java.io.IOException
{
char ch, answer;
answer = 'K';//character and string are not same
35
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");
//get a char
ch=(char) System.in.read( );
if
(ch==answer) System.out.println("***Right***");
else
System.out.println("....Sorry, you're wrong." );
}
}
package division;
import java.util.Scanner; //this program demonstrates the if-else statement
public class Division
{
public static void main(String[] args)
{
double number1, number2; // division operands
double quotient; //result of division
if(number2 == 0)
{
System.out.println("Division by zero is not possible.");
System.out.println("Please run the program again and ");
System.out.println("enter a number other than zero.");
}
else
{
quotient = number1 / number2;
System.out.println("The quotient of " +number1);
System.out.println("divided by " +number2);
System.out.println(" is " +quotient);
}
}
}
36
The if-else-if Statement
package ladder;
//Demonstrate an if-else-if ladder.
public class Ladder {
public static void main(String args[]) {
int month =4;//April
String season;
if
(month == 12 || month == 1 || month == 2)
season = "Winter";
else if
(month == 3 || month == 4 || month == 5)
season = "Spring";
else if
(month == 6 || month == 7 || month == 8)
season = "Summer";
else if
(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus month";
package multipleif;
import java.util.Scanner ;
public class MultipleIf {
public static void main(String args[ ]) {
int x, y;
Scanner key = new Scanner(System.in);
System.out.println(“Enter first value:”);
x = key.nextInt();
System.out.println(“Enter second value:”);
y = key.nextInt();
if (x>y) {
System.out.print(“First value is bigger than second value”);
} else if (x<y) {
System.out.print(“First value is smaller than second vavlue”);
} else {
System.out.print(“Both values are equal”);
}
}
}
37
6.2 Switch…Case
In addition to the nested if statement, Java provides a second method for choosing from many
alternative actions. Compare the following code, each of which accomplishes the same task.
The default case, at the end of the switch statement, acts similarly to the else at the end of the
nested if. It will catch any value that doesn't have an exact match in the cases. Although it is not
necessary to include the default case (just as it is not necessary to include the else), it is good
programming practice to account for any unexpected values.
Example – This switch statement assigns a grade based on a quiz that was scored out of five.
38
package switchcase;
import java.util.Scanner;
public class SwitchCase {
public static void main (String args[]) {
char ch;
String s;
Scanner key = new Scanner(System.in);
System.out.print(“Select [F]oods [D]rinks [S]leeping : “);
s = key.nextLine();
ch = s.charAt(0);
switch (ch) {
case 'F' : System.out.println("Eating... ");
break;
case 'D' : System.out.println("Drinking...");
break;
case 'S' : System.out.println("Sleeping...");
break;
default : System.out.println("No such option!" );
break;
}
}
}
39
Chapter 7: Iteration/Repetition
A loop is part of a program that repeats. It is a control structure that causes a statement or
group of statements to repeat. Java has three looping control structures:
while loop
do-while loop
for loop
If the condition is true, the statement is executed; then the condition is evaluated again.
The statement is executed over and over until the condition becomes false.
If the condition of a while statement is false initially, the statement is never executed.
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
ackage summing;
//While Loop statements executes the condition first then the loop body
import java.util.Scanner;
public class Summing {
public static void main(String[] args) {
int data;
//read an initail data
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter an integer value, \nThe program exits if the input is 0");
data = keyboard.nextInt();
int sum = 0;
//while (loop-continuation-condition)
40
while (data != 0)
{
//loop body
sum += data; //equivalent to sum = sum + data;
data = keyboard.nextInt();
}
System.out.println( "The sum is " +sum);
}
}
This loop will execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Example:
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
package testaverage;
import java.util.Scanner;
//this program demonstrates a user controlled loop.
public class TestAverage {
public static void main(String[] args) {
int score1, score2, score3; //three test scores
double average; //average test score
char repeat; //to hold 'y' or 'n'
String input;
41
Scanner keyboard = new Scanner(System.in);
The purpose of the for statement is to repeat Java statements many times. It is similar to the
while statement, but it is often easier to use if you are counting or indexing because it combines
three elements of many loops: initialization, testing, and incrementing.
42
There are three parts in the for statement
The initialization statement is done before the loop is started, usually to initial a
variable.
The Boolean expression is tested at the beginning of each time the loop is done. The
loop is stopped when this Boolean expression is false (the same as the while loop)
The update statement is done at the end of every time through the loop, and usually
increments a variable.
Example1:
Example2:
package squares;
public class Squares {
public static void main(String[] args) {
int number; //loopcontrol variables
package testsum;
// computes the sum of the first 100 positive integers
public class TestSum {
public static void main(String[ ] args) {
//initialize sum
int i, sum = 0;
43
// loop body
sum += i; //equivalent to sum = sum + i;
}
// display result
System.out.println("The sum is " +sum);
}
}
44
References
Gaddis, T., (2019), Starting out with Java: from control structures through objects, 7th Edition,
Pearson Addison
45