0% found this document useful (0 votes)
32 views

00review Java Basics

This document outlines the contents of an object-oriented programming course taught using Java. The course will cover 10 chapters on Java basics, methods, arrays, objects, inheritance, exceptions, and GUIs. It lists the textbook that will be used - Introduction to Java Programming by Y. Daniel Liang - and provides sample code for a simple Java program that prints "Welcome to Java!".

Uploaded by

Shehab magdy
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

00review Java Basics

This document outlines the contents of an object-oriented programming course taught using Java. The course will cover 10 chapters on Java basics, methods, arrays, objects, inheritance, exceptions, and GUIs. It lists the textbook that will be used - Introduction to Java Programming by Y. Daniel Liang - and provides sample code for a simple Java program that prints "Welcome to Java!".

Uploaded by

Shehab magdy
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 102

Programming II

(Object Oriented Programming)


Dr. Nader Mahmoud
Lecturer at Computer Science department

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
1
Course Content
 Chapter 1: Java basics syntax
 Chapter 2: Java Methods
 Chapter 3: Single-Dimensional Arrays
 Chapter 4: Multidimensional Arrays
 Chapter 5: Objects and Classes
 Chapter 6: Thinking in Objects & Array of objects
 Chapter 7: Inheritance and Polymorphism
 Chapter 8: Abstract Classes and Interfaces
 Chapter 9: Exception Handling
 Chapter 10: GUI

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
Chapter 1
Introduction to Computers,
Programs, and Java

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
3
What is a Computer?
A computer consists of a CPU, memory, hard disk, floppy disk,
monitor, printer, and communication devices.

Bus

Storage Communication Input Output


Memory CPU Devices Devices Devices
Devices
e.g., Disk, CD, e.g., Modem, e.g., Keyboard, e.g., Monitor,
and Tape and NIC Mouse Printer

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
4
Programming Languages
Machine Language Assembly Language High-Level Language

Machine language is a set of primitive instructions


built into every computer. The instructions are in the
form of binary code, so you have to enter binary
codes for various instructions. Program with native
machine language is a tedious process. Moreover
the programs are highly difficult to read and modify.
For example, to add two numbers, you might write
an instruction in binary like this:
 
1101101010011010
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
5
Programming Languages
Machine Language Assembly Language High-Level Language

Assembly languages were developed to make


programming easy. Since the computer cannot understand
assembly language, however, a program called assembler is
used to convert assembly language programs into machine
code. For example, to add two numbers, you might write an
instruction in assembly code like this:
ADDF3 R1, R2, R3

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
6
Programming Languages
Machine Language Assembly Language High-Level Language

The high-level languages are English-like and easy to learn


and program. For example, the following is a high-level
language statement that computes the area of a circle with
radius 5:
area = 5 * 5 * 3.1415;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
7
Popular High-Level Languages
Language Description

Ada Named for Ada Lovelace, who worked on mechanical general-purpose computers. The Ada
language was developed for the Department of Defense and is used mainly in defense projects.
BASIC Beginner’s All-purpose Symbolic Instruction Code. It was designed to be learned and used easily
by beginners.
C Developed at Bell Laboratories. C combines the power of an assembly language with the ease of
use and portability of a high-level language.
C++ C++ is an object-oriented language, based on C.
C# Pronounced “C Sharp.” It is a hybrid of Java and C++ and was developed by Microsoft.
COBOL COmmon Business Oriented Language. Used for business applications.
FORTRAN FORmula TRANslation. Popular for scientific and mathematical applications.
Java Developed by Sun Microsystems, now part of Oracle. It is widely used for developing platform-
independent Internet applications.
Pascal Named for Blaise Pascal, who pioneered calculating machines in the seventeenth century. It is a
simple, structured, general-purpose language primarily for teaching programming.
Python A simple general-purpose scripting language good for writing short programs.
Visual Visual Basic was developed by Microsoft and it enables the programmers to rapidly develop
Basic graphical user interfaces.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
8
Compiling Source Code
A compiler translates the entire source code into a
machine-code file, and the machine-code file is
then executed, as shown in the following figure.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
9
Companion
Website
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture-Neutral
 Java Is Portable
 Java's Performance
 Java Is Multithreaded
 Java Is Dynamic
www.cs.armstrong.edu/liang/JavaCharacteristics.pdf
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
10
JDK Versions
 JDK 1.02 (1995)
 JDK 1.1 (1996)
 JDK 1.2 (1998)
 JDK 1.3 (2000)
 JDK 1.4 (2002)
 JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
 JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
 JDK 1.7 (2011) a. k. a. JDK 7 or Java 7
 JDK 1.8 (2014) a. k. a. JDK 8 or Java 8

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
11
JDK Editions
 Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
 Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such
as Java servlets, Java ServerPages, and Java ServerFaces.
 Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
This book uses J2SE to introduce Java programming.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
12
Popular Java IDEs
 NetBeans
 Eclipse

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
13
A Simple Java Program
Listing 1.1
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
} Animation

IMPORTANT NOTE: If you cannot run the buttons, see


Welcome www.cs.armstrong.edu/liang/javaslidenote.doc.

Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
14
animation

Trace a Program Execution


Enter main method

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
15
animation

Trace a Program Execution


Execute statement

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
16
Variables and DataTypes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
17
Identifiers
 An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
 An identifier must start with a letter, an underscore (_),
or a dollar sign ($). It cannot start with a digit.
 An identifier cannot be a reserved word. (See Appendix
A, “Java Keywords,” for a list of reserved words).
 An identifier cannot be true, false, or
null.
 An identifier can be of any length.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
18
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
19
Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
20
Declaring and Initializing
in One Step
 int x = 1;
 double d = 1.4;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
21
Named Constants
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
22
Numerical Data Types
Name Range Storage Size

byte –27 to 27 – 1 (-128 to 127) 8-bit signed

short –215 to 215 – 1 (-32768 to 32767) 16-bit signed

int –231 to 231 – 1 (-2147483648 to 2147483647) 32-bit signed

long –263 to 263 – 1 64-bit signed


(i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324

Positive range:
4.9E-324 to 1.7976931348623157E+308

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
23
Numeric Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
24
Integer Division
+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
25
animation

Trace a Program Execution


allocate memory
public class ComputeArea { for radius
/** Main method */
public static void main(String[] args) {
double radius; radius no value
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);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
26
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// Assign a radius
radius = 20;
allocate memory
for area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
27
animation

Trace a Program Execution


public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area; area no value
// 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);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
28
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and assign
// Compute area it to variable area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
29
animation

Trace a Program Execution


public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area; area 1256.636
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
30
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);

2. Use the method nextDouble() to obtain to a double


value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();

Animation
ComputeAreaWithConsoleInput ComputeAverage

Run Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
31
Reading Numbers from the
Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();

Method Description

nextByte() reads an integer of the byte type.


nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
32
Augmented Assignment Operators

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
33
Increment and
Decrement Operators

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
34
Increment and
Decrement Operators, cont.

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
35
Type Casting
Implicit casting
double d = 3; (type widening)

Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)

What is wrong? int x = 5 / 2.0;

range increases

byte, short, int, long, float, double

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
36
Selection Statements

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
37
Relational Operators
Java Mathematics Name Example Result
Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
38
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s); + " for the circle of radius "
}
+ radius + " is " + area);
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
39
Note
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}

(a) (b)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
40
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
41
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;

System.out.println("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
42
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


System.out.print("A"); System.out.print("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent System.out.print("B");
System.out.print("B"); else if (score >= 70.0)
else System.out.print("C");
if (score >= 70.0) else if (score >= 60.0)
System.out.print("C"); System.out.print("D");
else else
if (score >= 60.0) System.out.print("F");
System.out.print("D"); This is better
else
System.out.print("F");

(a) (b)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
43
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
44
animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
45
animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
46
animation
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
47
animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
48
Note
The else clause matches the most recent if clause in the
same block.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
49
Note, cont.
Nothing is printed from the preceding statement. To force
the else clause to match the first if clause, you must add a
pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
50
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error
or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
51
Problem:

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
52
Logical Operators

Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
53
Truth Table for Operator !

p !p Example (assume age = 24, weight = 140)

true false !(age > 18) is false, because (age > 18) is true.

false true !(weight == 150) is true, because (weight == 150) is false.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
54
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

false false false (age <= 18) && (weight < 140) is false, because (age >

18) and (weight <= 140) are both false.

false true false  

false
true false (age > 18) && (weight > 140) is false, because (weight

> 140) is false.


true
true true  (age > 18) && (weight >= 140) is true, because both

(age > 18) and (weight >= 140) are true.


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
55
Truth Table for Operator ||

p1 p2 p1 || p2 Example (assume age = 24, weihgt = 140)

false false false

false true true  (age > 34) || (weight <= 140) is true, because (age > 34)

is false, but (weight <= 140) is true.

true
true false (age > 14) || (weight >= 150) is false, because

(age > 14) is true.

true
true true  
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
56
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)

false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false

and (weight > 140) is false.

false true true  (age > 34) ^ (weight >= 140) is true, because (age > 34) is false

but (weight >= 140) is true.

true
true false (age > 14) ^ (weight > 140) is true, because (age > 14) is

true and (weight > 140) is false.

false
true true  
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
57
Companion
Website

The & and | Operators


If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)

If x is 1, what is x after this


expression?
(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?


(1 == x) || (10 > x++)?
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
58
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
59
animation

Trace switch statement


Suppose day is 2:

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
60
animation

Trace switch statement


Match case 2

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
61
animation

Trace switch statement


Fall through case 3

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
62
animation

Trace switch statement


Fall through case 4

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
63
animation

Trace switch statement


Fall through case 5

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
64
animation

Trace switch statement


Encounter break

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
65
animation

Trace switch statement


Exit the statement

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
66
Conditional Expressions
if (x > 0)
y=1
else
y = -1;

is equivalent to

y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2

Ternary operator
Binary operator
Unary operator
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
67
Conditional Operator, cont.
boolean-expression ? exp1 : exp2

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
68
Loops

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
69
Opening Problem
Problem:

System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times …


System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
70
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s);
count++;
} }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
71
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
72
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
73
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
74
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
75
animation

Trace while Loop, cont.


(count < 2) is still true since count is
int count = 0; 1

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
76
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
77
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
78
animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
79
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2) {


System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
80
do-while Loop

do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
81
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) { System.out.println(
// loop body;
Statement(s); "Welcome to Java!");
} }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
82
animation

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
83
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0

for (i = 0; i < 2; i++) {


System.out.println(
"Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
84
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
85
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
86
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
87
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
88
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
89
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
90
animation

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
91
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
92
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));
 
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something

}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
93
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
94
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
95
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error

for (int i=0; i<10; i++);


{
System.out.println("i is " + i);
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
96
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
97
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure
can always be converted into the following for loop in (b):
while (loop-continuation-condition) { Equival for ( ; loop-continuation-condition; )
// Loop body // Loop body
ent
} }
(a) (b)

A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
98
Using break and continue
Examples for using the break and continue
keywords:

 TestBreak.java

TestBreak Run

 TestContinue.java

TestContinue Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
99
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
sum += number;
if (sum >= 100)
break;
}

System.out.println("The number is " + number);


System.out.println("The sum is " + sum);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
100
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
if (number == 10 || number == 11)
continue;
sum += number;
}

System.out.println("The sum is " + sum);


}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
101
End of Lecture

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved.
102

You might also like