0% found this document useful (0 votes)
11 views560 pages

Java Programming Fundamentals Overview

The document provides an introduction to computer data storage, programming languages, and specifically focuses on Java programming. It explains how data is encoded in binary, the differences between machine, assembly, and high-level languages, and the characteristics that make Java a versatile programming language. Additionally, it covers the compilation and execution process of Java programs, highlighting its portability and object-oriented nature.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views560 pages

Java Programming Fundamentals Overview

The document provides an introduction to computer data storage, programming languages, and specifically focuses on Java programming. It explains how data is encoded in binary, the differences between machine, assembly, and high-level languages, and the characteristics that make Java a versatile programming language. Additionally, it covers the compilation and execution process of Java programs, highlighting its portability and object-oriented nature.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to Computers,

Programs, Object Oriented


Programming and Java

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
1
How Data is Stored?
Data of various kinds, such as numbers, characters, and
strings, are encoded as a series of bits (zeros and ones).
Computers use zeros and ones because digital devices
have two stable states, which are referred to as zero and Memory address Memory content
one by convention.
The programmers need not to be concerned about the . .
encoding and decoding of data, which is performed . .
automatically by the system based on the encoding . .
scheme. 2000 01001010 Encoding for character ‘J’
The encoding scheme varies. 2001 01100001 Encoding for character ‘a’
For example, character ‘J’ is represented by 01001010 in one byte. 2002 01110110 Encoding for character ‘v’
A small number such as three can be stored in a single byte. 2003 01100001 Encoding for character ‘a’
2004 00000011
If computer needs to store a large number that cannot fit Encoding for number 3
into a single byte, it uses a number of adjacent bytes. No
two data can share or split a same byte. A byte is the
minimum storage unit.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
2
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
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
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;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
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.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
Compiling Source Code in C

 A program written in a high-level language is


called a source program or source code. Because
a computer cannot understand a source program,
a source program must be translated into machine
code for execution.
 To run the source code of a C program, we need a
C compiler. The C compiler generates assembly
code (.s file) first. The assembler produces the
machine code (.obj file). Finally, the linker
produces the executable machine code (.exe file)
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
Compiling/Interpreting Source Code in Java

 To run the source code of a Java program, we


need a Java compiler and a Java interpreter. The
Java compiler compiles source files (.java) to
generate bytecode (.class) files. We can use the
javac command provided by Sun in the terminal
window.
 Note that a statement from the source code may
be translated into several instructions in .class
file.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Interpreting Source Code
 Although the bytecode is similar to machine level codes,
it is not directly executable.
 The Java Virtual Machine (JVM) is used to load .class
files into the memory and interpret the code. The
Execution Engine or Just-In-Time compiler (JIT)
(executable name: java) reads one statement from the
bytecode in memory, translates it to the machine code of
the target platform, and then executes it right away.
 JVM helps to avoid the need to recompile the source
code for every specific platform.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
Why Java?
The answer is that Java enables users to develop and
deploy applications on the Internet for servers, desktop
computers, and small hand-held devices. The future of
computing is being profoundly influenced by the Internet,
and Java promises to remain a big part of that future.

Java is a general purpose programming language.


Java is an internet programming language.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
Java, Web, and Beyond
 Java can be used to develop standalone
applications.
 Java can be used to develop applications
running from a browser.
 Java can also be used to develop applications
for hand-held devices.
 Java can be used to develop applications for
Web servers.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Characteristics of Java
 Java Is Simple Java is partially modeled on C++, but greatly
simplified and improved. Some people refer to
 Java Is Object-Oriented Java as "C++--" because it is like C++ but
 Java Is Distributed with more functionality and fewer negative
aspects.
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture-Neutral
 Java Is Portable
 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
Characteristics of Java
 Java Is Simple Java is inherently object-oriented.
Although many object-oriented languages
 Java Is Object-Oriented began strictly as procedural languages,
 Java Is Distributed Java was designed from the start to be
object-oriented. Object-oriented
 Java Is Interpreted
programming (OOP) is a popular
 Java Is Robust programming approach that is replacing
 Java Is Secure traditional procedural programming
techniques.
 Java Is Architecture-Neutral
 Java Is Portable One of the central issues in software
development is how to reuse code. Object-
 Java Is Multithreaded oriented programming provides great
 Java Is Dynamic flexibility, modularity, clarity, and
reusability through encapsulation,
inheritance, and polymorphism.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Characteristics of Java
 Java Is Simple Distributed computing involves several
computers working together on a network.
 Java Is Object-Oriented Java is designed to make distributed
 Java Is Distributed computing easy. Since networking
capability is inherently integrated into
 Java Is Interpreted
Java, writing network programs is like
 Java Is Robust sending and receiving data to and from a
file.
 Java Is Secure
 Java Is Architecture-Neutral
 Java Is Portable
 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Characteristics of Java
 Java Is Simple You need an interpreter to run Java
programs. The programs are compiled into
 Java Is Object-Oriented the Java Virtual Machine code called
 Java Is Distributed bytecode. The bytecode is machine-
independent and can run on any machine
 Java Is Interpreted
that has a Java interpreter, which is part of
 Java Is Robust the Java Virtual Machine (JVM).
 Java Is Secure
 Java Is Architecture-Neutral
 Java Is Portable
 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Characteristics of Java
 Java Is Simple Java compilers can detect many problems
that would first show up at execution time
 Java Is Object-Oriented in other languages.
 Java Is Distributed
Java has eliminated certain types of error-
 Java Is Interpreted
prone programming constructs found in
 Java Is Robust other languages.
 Java Is Secure
Java has a runtime exception-handling
 Java Is Architecture-Neutral feature to provide programming support
 Java Is Portable for robustness.

 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
Java implements several security
 Java Is Robust mechanisms to protect your system against
 Java Is Secure harm caused by stray programs.
 Java Is Architecture-Neutral
 Java Is Portable
 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust Write once, run anywhere
 Java Is Secure
With a Java Virtual Machine (JVM),
 Java Is Architecture-Neutral you can write one program that will
 Java Is Portable run on any platform.

 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
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 Because Java is architecture neutral,
Java programs are portable. They can
 Java Is Multithreaded
be run on any platform without being
 Java Is Dynamic recompiled.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted Multithread programming is smoothly
 Java Is Robust integrated in Java, whereas in other
 Java Is Secure languages you have to call procedures
specific to the operating system to enable
 Java Is Architecture-Neutral multithreading.
 Java Is Portable
 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted Java was designed to adapt to an evolving
environment. New code can be loaded on the
 Java Is Robust
fly without recompilation. There is no need for
 Java Is Secure developers to create, and for users to install,
major new software versions. New features can
 Java Is Architecture-Neutral be incorporated transparently as needed.
 Java Is Portable
 Java Is Multithreaded
 Java Is Dynamic

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
Application Interface
 The application program interface (API), also known
as library, contains predefined classes and interfaces
for developing Java programs
 The Java Development Toolkit (JDK) consists of a set
of separate programs, each invoked from a command
line, for developing and testing Java programs.
Instead of using the JDK, you can use a Java
development tool (e.g., NetBeans, Eclipse, and
TextPad)—software that provides an integrated
development environment (IDE) for developing Java
programs quickly

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
22
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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
23
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 .

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
24
Popular Java IDEs
 NetBeans
 Eclipse

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
25
A Simple Java Program
 Every Java program must have at least one class. Each class
has a name. By convention, class names start with an uppercase
letter.
 In a program, multiple classes may cooperate with each other.
 Each program needs an entry point to start execution.
 The program is executed from the main method that is defined
in one of the classes.
 A class may contain several methods.
 The main method is the entry point where the program begins
execution.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
26
Creating, Compiling, and
Running Programs

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson


nd Education, Ltd.
Fundamentals of Programming II, IT, 2 Batch
All rights reserved.
27
Compiling Java Source Code
 The Java language is a high-level language, but Java bytecode is a
low-level language. The bytecode is similar to machine instructions
but is architecture neutral and can run on any platform that has a
Java Virtual Machine (JVM).
 The virtual machine is a program that interprets Java bytecode. This
is one of Java’s primary advantages: Java bytecode can run on a
variety of hardware platforms and operating systems.
 Java source code is compiled into Java bytecode (.class file) and
Java bytecode is interpreted by the JVM. Your Java code may use
the code in the Java library. To execute a Java program is to run the
program’s bytecode.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
28
Compiling Java Source Code
 You can execute the bytecode on any platform with a JVM, which is
an interpreter and resides in RAM. It translates the individual
instructions in the bytecode into the target machine (i.e. the machine
on which it is working at) language code one at a time rather than
the whole program as a single unit.

 Each step is executed immediately after it is translated.

 The bytecode can then run on any computer with a Java Virtual
Machine, as shown below. In fact, Java Virtual Machine is a
software that interprets Java bytecode.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
29
Compiling Java Source Code

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
30
Procedural versus Object-Oriented
Programming
 The procedural programming aims at solving problems using a
collection of variables and functions. This approach is not
manageable as the size of the code gets large.
 Object-oriented programming (OOP) is an alternative approach
where variables and functions are combined to form classes.
 The procedural paradigm focuses on designing methods. The
object-oriented paradigm couples data and methods together
into objects. Software design using the object-oriented
paradigm focuses on objects and operations on objects.
 Classes provide more flexibility and modularity for building
reusable software.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
31
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
32
Procedural versus Object-Oriented
Programming
 In procedural programming, data and operations on the data are
separate, and this methodology requires passing data to
methods.
 Object-oriented programming places data and the operations
that pertain to them in an object. The object-oriented
programming approach organizes programs in a way that
mirrors the real world, in which all objects are associated with
both attributes and activities.
 Using objects improves software reusability and makes
programs easier to develop and easier to maintain.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
33
Object-Oriented Programming Paradigm
 There are many different types of objects like trees, cars,
animals etc. around us
 These objects have different characteristics even if they belong
to the same type. For instance, different animals may have
different numbers of legs, height, size, color etc. Similarly,
different cars may have different sizes, colors, brand names etc.
 In object oriented programming, objects of the same type are
said to belong to the same class. In technical terms, a class is a
blueprint or template or structure that can be used to create
objects.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
34
Abdalla

Abdalla

Amro
ID
Amro

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
35
Object-Oriented Programming Paradigm
 All objects have two basic characteristics:
 Properties OR states
 Behavior
 Example:
 Each car has a state or a set of properties such as model, color, year,
price etc. (i.e. what each object has)
 Each car has a set of behaviors such as start, move, stop, turn, accelerate,
park etc. (i.e. what each object does)
 Conceptually, software objects are similar to the real world ones
 A software object has a set of properties represented using data
fields/variables. The behaviors of the objects are represented in
terms of methods.
 In OOP, objects are instances of a predefined class.
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
36
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
37
Trace a Program Execution
Enter main method

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
38
Trace a Program Execution
Execute statement

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
39
Trace a Program Execution

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

print a message to the


console

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
40
Anatomy of a Java Program
 Class name
 Main method
 Statements
 Statement terminator
 Reserved words
 Comments
 Blocks

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
41
Class Name
Every Java program must have at least one class.
Each class has a name. By convention, class names
start with an uppercase letter. In this example, the
class name is Welcome.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
42
Main Method
Line 2 defines the main method. In order to run a
class, the class must contain a method named main.
The program is executed from the main method.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
43
Statement
A statement represents an action or a sequence of actions.
The statement [Link]("Welcome to Java!") in
the program below is a statement to display the greeting
"Welcome to Java!”.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
44
Statement Terminator
Every statement in Java ends with a semicolon (;).

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
45
Reserved words
Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used for
other purposes in the program. For example, when the
compiler sees the word class, it understands that the word
after class is the name for the class.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
46
Blocks
A pair of braces in a program forms a block that groups
components of a program.

public class Test {


public static void main(String[] args) { Class block
[Link]("Welcome to Java!"); Method block
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
47
Special Symbols

Character Name Description

{} Opening and closing Denotes a block to enclose statements.


braces
() Opening and closing Used with methods.
parentheses
[] Opening and closing Denotes an array.
brackets
// Double slashes Precedes a comment line.

" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
48
{ …}

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
49
( … )

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
50
;

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
51
// …

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
52
"…"

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
[Link]("Welcome to Java!");
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
53
Programming Style and
Documentation
 Appropriate Comments
 Naming Conventions
 Proper Indentation and Spacing Lines
 Block Styles

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
54
Appropriate Comments
 Include a summary at the beginning of the program to
explain what the program does, its key features, its
supporting data structures, and any unique techniques it
uses.
 In addition to line comments (beginning with //) and
block comments (beginning with /*), Java supports
comments of a special type, referred to as javadoc
comment (begin with /** and end with */). They can be
extracted into an HTML file using the JDK’s javadoc
command. Use javadoc comments (/** ... */) for
commenting on an entire class or an entire method.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
55
Naming Conventions
 Choose meaningful and descriptive names.
 Class names:
Capitalize the first letter of each word in the
name. For example, the class name
ComputeExpression.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
56
Proper Indentation and Spacing
 A consistent indentation style makes
programs clear and easy to read, debug, and
maintain. Indentation is used to illustrate the
structural relationships between a program’s
components or statements.
 Spacing
Use blank line to separate segments of the code.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
57
Block Styles
 There are two popular styles, next-line style
and end-of-line style, as shown below.
Next-line public class Test
style {
public static void main(String[] args)
{
[Link]("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
[Link]("Block Styles");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
58
Programming Errors
 Syntax Errors
Detected by the compiler
 Runtime Errors
Causes the program to abort
 Logic Errors
Produces incorrect result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
59
Syntax Errors
public class ShowSyntaxErrors {
public static main(String[] args) {
[Link]("Welcome to Java);
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
60
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
[Link](1 / 0);
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
61
Logic Errors
public class ShowLogicErrors {
public static void main(String[] args) {
[Link]("Celsius 35 is Fahrenheit degree
");
[Link]((9 / 5) * 35 + 32);
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
62
Elementary Programming

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
1
Motivations
In the preceding chapter, you learned how to create,
compile, and run a Java program.
Starting from this chapter, you will learn how to solve
practical problems programmatically.
Through these problems, you will learn Java primitive
data types and related subjects, such as variables,
constants, data types, operators, expressions, and input
and output.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
2
Objectives
 To write Java programs to perform simple computations.
 To obtain input from the console using the Scanner class.
 To use identifiers to name variables, constants, methods, and
classes.
 To use variables to store data.
 To program with assignment statements and assignment
expressions.
 To use constants to store permanent data.
 To name classes, methods, variables, and constants by following
their naming conventions.
 To explore Java numeric primitive data types: byte, short, int,
long, float, and double.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
Objectives
 To read a byte, short, int, long, float, or double value from the
keyboard.
 To perform operations using operators +, -, *, /, and %.
 To perform exponent operations using [Link](a, b).
 To write integer literals, floating-point literals, and literals in
scientific notation.
 To write and evaluate numeric expressions.
 To use augmented assignment operators.
 To distinguish between postincrement and preincrement and
between postdecrement and predecrement.
 To cast the value of one type to another type.
 To avoid common errors and pitfalls in elementary programming.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
Trace a Program Execution
allocate memory
public class ComputeArea { for radius
/** Main method */
public static void main(String[] args) {
radius no value
double radius;
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
[Link]("The area for the circle of
radius " +
radius + " is " + area);
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Trace a Program Execution
public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) { radius no value
double radius;
area no value
double area;

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

// Display results
[Link]("The area for the circle of
radius " +
radius + " is " + area);
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
Trace a Program Execution
public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) { radius 20
double radius;
double area; area no value

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
[Link]("The area for the circle of
radius " +
radius + " is " + area);
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
Trace a Program Execution
public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) { radius 20
double radius;
double area; area 1256.636

// Assign a radius
radius = 20;
compute area and assign it
to variable area
// Compute area
area = radius * radius * 3.14159;

// Display results
[Link]("The area for the circle of
radius " +
radius + " is " + area);
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Trace a Program Execution
public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) { radius 20
double radius;
double area; area 1256.636

print a message to the console


// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
[Link]("The area for the circle of
radius " +
radius + " is " + area);
}
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
Reading Input from the Console
• Java uses [Link] to refer to the standard output device and
[Link] to the standard input device.
• By default, the output device is the display monitor and the
input device is the keyboard.

• To perform console output, you simply use the println method to


display a primitive value or a string to the console.
• Console input is not directly supported in Java, but you can use
the Scanner class to create an object to read input from
[Link], as follows:
Scanner input = new Scanner([Link]);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
Reading Input from the Console

Use the method nextDouble() to obtain to a double


value.
Example:
[Link]("Enter a double value: ");
Scanner input = new Scanner([Link]);
double d = [Link]();

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Reading Input from the Console
import [Link]; // Scanner is in the [Link] package

public class ComputeAreaWithConsoleInput {


public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner([Link]);

// Prompt the user to enter a radius


[Link]("Enter a number for radius: ");
double radius = [Link](); //method in Scanner class

// Compute area
double area = radius * radius * 3.14159;

// Display results
[Link]("The area for the circle of radius " + radius + " is " + area);
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
Implicit Import and Explicit Import
 There are two types of import statements: specific import and wildcard
import.
 The specific import specifies a single class in the import statement. For
example, the following statement imports Scanner from the package
[Link].
import [Link];

 The wildcard import imports all the classes in a package by using the
asterisk as the wildcard. For example, the following statement imports all
the classes from the package [Link].
import [Link].*;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Implicit Import and Explicit Import
 The information for the classes in an imported package is not read at
compile time or runtime unless the class is used in the program. The
import statement simply tells the compiler where to locate the classes.

 There is no performance difference between a specific import and a


wildcard import declaration.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
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.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
[Link]("The area is ” + area + " for
radius ” + radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
[Link]("The area is ” + area + " for
radius ” + radius);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
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;

Remark: A compilation error occurs if you display the


value of an uninitialized variable or use it in any
expression.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.0; // Assign 1.0 to radius;


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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
Declaring and Initializing
in One Step
 int x = 1;
 double d = 1.4;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Named Constants
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Naming Conventions
 Choose meaningful and descriptive names.
 Variables and method names:
 Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word,
and capitalize the first letter of each subsequent word
in the name.
 For example,
 the variables radius and area,
 and the method computeArea.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
Naming Conventions, cont.
 Class names:
 Capitalize the first letter of each word in
the name.
 For example, the class name
ComputeArea.

 Constants:
 Capitalize all letters in constants, and use
underscores to connect words.
 For example, the constant PI and
MAX_VALUE

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
23
Reading Numbers from the Keyboard
Scanner input = new Scanner([Link]);
int value = [Link]();

Methods for Scanner Objects:


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.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
24
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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
25
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)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
26
Remainder Operator
Remainder is very useful in programming.
For example, an even number % 2 is always 0 and an odd number
% 2 is always 1.
So you can use this property to determine whether a number is even
or odd.
Suppose today is Saturday and you and your friends are going to
meet in 10 days.
What day is in 10 days? You can find that day is Tuesday using the
following expression:
Saturday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
27
Exponent Operations
[Link]([Link](2, 3));
// Displays 8.0
[Link]([Link](4, 0.5));
// Displays 2.0
[Link]([Link](2.5, 2));
// Displays 6.25
[Link]([Link](2.5, -2));
// Displays 0.16

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
28
Number Literals
A literal is a constant value that appears directly
in the program. For example, 34, 1,000,000, and
5.0 are literals in the following statements:

int i = 34;
long x = 1000000;
double d = 5.0;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
29
Integer Literals
An integer literal can be assigned to an integer variable
as long as it can fit into the variable.
A compilation error would occur if the literal were too large for
the variable to hold.
For example, the statement byte b = 1000 would cause a
compilation error, because 1000 cannot be stored in a variable of
the byte type.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
30
Integer Literals
An integer literal is assumed to be of the int type, whose value is
between -231 (-2147483648) to 231–1 (2147483647).
To denote an integer literal of the long type, append it with the letter
L or l. L is preferred because l (lowercase L) can easily be confused
with 1 (the digit one).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
31
Floating-Point Literals
Floating-point literals are written with a decimal point.
By default, a floating-point literal is treated as a double type value.
For example, 5.0 is considered a double value, not a float value.
You can make a number a float by appending the letter f or F, and
make a number a double by appending the letter d or D.
For example, you can use 100.2f or 100.2F for a float number, and
100.2d or 100.2D for a double number.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
32
double vs. float
The double type values are more accurate than the float
type values. For example,

[Link]("1.0 / 3.0 is " + 1.0 / 3.0);

displays 1.0 / 3.0 is 0.3333333333333333

16 digits

[Link]("1.0F / 3.0F is " + 1.0F / 3.0F);

displays 1.0F / 3.0F is 0.33333334


7 digits

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
33
Scientific Notation
Floating-point literals can also be specified in scientific notation,
for example, 1.23456e+2, same as 1.23456e2, is equivalent to
123.456, and 1.23456e-2 is equivalent to 0.0123456.
E (or e) represents an exponent and it can be either in lowercase or
uppercase.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
34
Arithmetic Expressions
3  4 x 10( y  5)( a  b  c) 4 9 x
  9(  )
5 x x y

is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
35
How to Evaluate an Expression
Though Java has its own way to evaluate an expression behind the
scene, the result of a Java expression and its corresponding arithmetic
expression are the same.
Therefore, you can safely apply the arithmetic rule for evaluating a
Java expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
36
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree to
Celsius using the formula:

celsius  ( 95 )( fahrenheit  32)

Note: you have to write


celsius = (5.0 / 9) * (fahrenheit – 32)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
37
Augmented Assignment Operators

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
38
Increment and
Decrement Operators

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
39
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;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
40
Increment and
Decrement Operators, cont.
Using increment and decrement operators makes
expressions short, but it also makes them complex and
difficult to read.
Avoid using these operators in expressions that modify
multiple variables, or the same variable for multiple times
such as this:
int k = ++i + i.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
41
Assignment Expressions and
Assignment Statements
variable op= expression; // Where op is +, -, *, /, or %
++variable;
variable++;
--variable;
variable--;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
42
Numeric Type Conversion
 Can you perform binary operations with two operands of
different types? Yes.
 If an integer and a floating-point number are involved in a
binary operation, Java automatically converts the integer
to a floating-point value. So,

3 * 4.5 is same as 3.0 * 4.5.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
43
Numeric Type Conversion
 You can always assign a value to a numeric variable
whose type supports a larger range of values; thus, for
instance, you can assign a long value to a float variable.
 You cannot, however, assign a value to a variable of a
type with a smaller range unless you use type casting.
int i = 1;
byte b = i; // Error because explicit casting is required
int j = 0.5; // Error because explicit casting is required
float x = 0.5; // Error because casting from double to float is required

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
44
Numeric Type Conversion
 Casting is an operation that converts a value of one data
type into a value of another data type.
 Casting a type with a small range to a type with a larger
range is known as widening a type.
 Casting a type with a large range to a type with a smaller
range is known as narrowing a type.
 Java will automatically widen a type, but you must narrow
a type explicitly.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
45
Numeric Type Conversion
 The syntax for casting a type is to specify the target type in
parentheses, followed by the variable’s name or the value
to be cast.
 For example, the following statement

[Link]((int)1.7);
displays 1.
 When a double value is cast into an int value, the fractional
part is truncated.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
46
Numeric Type Conversion
 The following statement
[Link]((double)1 / 2);
displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided
by 2.
 The statement
[Link](1 / 2);
displays 0, because 1 and 2 are both integers and the
resulting value should also be an integer.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
47
Numeric Type Conversion
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

[Link](d);

Result????

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
48
Conversion Rules
When performing a binary operation involving two operands
of different types, Java automatically converts the operand
based on the following rules:

1. If one of the operands is double, the other is converted into


double.
2. Otherwise, if one of the operands is float, the other is converted
into float.
3. Otherwise, if one of the operands is long, the other is converted
into long.
4. Otherwise, both operands are converted into int.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
49
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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
50
Casting in an Augmented Expression
In Java, an augmented expression of the form x1 op= x2 is
implemented as x1 = (T)(x1 op x2), where T is the type for x1.
Therefore, the following code is correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement

sum += 4.5 is equivalent to sum = (int)(sum + 4.5).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
51
Common Errors and Pitfalls
 Common Error 1: Undeclared/Uninitialized Variables and Unused
Variables
 Common Error 2: Integer Overflow
 Common Error 3: Round-off Errors
 Common Error 4: Unintended Integer Division
 Common Error 5: Redundant Input Objects

 Common Pitfall 1: Redundant Input Objects

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
52
Common Error 1: Undeclared/Uninitialized
Variables and Unused Variables

double interestRate = 0.05;


double interest = interestrate * 45;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
53
Common Error 2: Integer Overflow

int value = 2147483647 + 1;


// value will actually be -2147483648

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
54
Common Error 3: Round-off Errors
Calculations involving floating-point numbers are
approximated because these numbers are not stored with
complete accuracy.

[Link](1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);


0.5000000000000001 is displayed
[Link](1.0 - 0.9);
0.09999999999999998 is displayed

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
55
Common Error 4: Unintended Integer
Division
int number1 = 1; int number1 = 1;
int number2 = 2; int number2 = 2;
double average = (number1 + number2) / 2; double average = (number1 + number2) / 2.0;
[Link](average); [Link](average);

(a) (b)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
56
Common Pitfall 1: Redundant Input Objects

Scanner input = new Scanner([Link]);


[Link]("Enter an integer: ");
int v1 = [Link]();

Scanner input1 = new Scanner([Link]);


[Link]("Enter a double value: ");
double v2 = [Link](); (use input instead)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
57
Selections

Fundamentals of Programming II, IT, 2nd Batch 1


Objectives
 To declare boolean variables and write Boolean expressions using relational
operators (§3.2).
 To implement selection control using one-way if statements (§3.3).
 To implement selection control using two-way if-else statements (§3.4).
 To implement selection control using nested if and multi-way if statements
(§3.5).
 To avoid common errors and pitfalls in if statements (§3.6).
 To generate random numbers using the [Link]() method (§3.7).
 To program using selection statements for a variety of examples
(SubtractionQuiz, BMI, ComputeTax) (§§3.7–3.9).
 To combine conditions using logical operators (&&, ||, and !) (§3.10).
 To program using selection statements with combined conditions (LeapYear,
Lottery) (§§3.11–3.12).
 To implement selection control using switch statements (§3.13).
 To write expressions using the conditional expression (§3.14).
 To examine the rules governing operator precedence and associativity (§3.15).
 To apply common techniques to debug errors (§3.16).

Fundamentals of Programming II, IT, nd


2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
2
The boolean Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j. Java
provides six comparison operators (also known
as relational operators) that can be used to
compare two values. The result of the
comparison is a Boolean value: true or false.

boolean b = (1 > 2);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { [Link]("The area"
statement(s); + " for the circle of radius "
}
+ radius + " is " + area);
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Note
if i > 0 { if (i > 0) {
[Link]("i is positive"); [Link]("i is positive");
} }
(a) Wrong (b) Correct

if (i > 0) { if (i > 0)
[Link]("i is positive"); Equivalent [Link]("i is positive");
}

(a) (b)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;

[Link]("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
[Link]("Negative input");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Multiple Alternative if Statements

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


[Link]("A"); [Link]("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent [Link]("B");
[Link]("B"); else if (score >= 70.0)
else [Link]("C");
if (score >= 70.0) else if (score >= 60.0)
[Link]("C"); [Link]("D");
else else
if (score >= 60.0) [Link]("F");
[Link]("D"); This is better
else
[Link]("F");

(a) (b)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
Multi-Way if-else Statements

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Note
The else clause matches the most recent if clause in the
same block.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
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)
[Link]("A");
}
else
[Link]("B");

This statement prints B.


Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
[Link](
"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.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
CAUTION
if (even == true) Equivalent if (even)
[Link]( [Link](
"It is even."); "It is even.");
(a) (b)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Logical Operators
Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
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.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
22
Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

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

conditions are both false.

false true false

true false 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.


Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
23
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
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
24
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)

false false false (age > 34) ^ (weight > 140) is false, 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 false true (age > 14) ^ (weight > 140) is true, because (age > 14) is

true and (weight > 140) is false.

true true false

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
25
Examples
[Link]("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));

[Link]("Is " + number + " divisible by 2 or 3? " +


((number % 2 == 0) || (number % 3 == 0)));

[Link]("Is " + number +


" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
26
Example

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
27
Example

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
28
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
29
Example

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
30
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
31
switch Statements

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
32
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed in case value1: statement(s)1;
parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
The resulting statements in the case valueN: statement(s)N;
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch-
}
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
33
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end of
case value1: statement(s)1;
each case in order to terminate the
remainder of the switch break;
statement. If the break statement case value2: statement(s)2;
is not present, the next case
statement will be executed. break;

case valueN: statement(s)N;
The default case, which is break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the
specified cases matches the
}
switch-expression.
When the value in a case statement matches the value
of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
34
Trace switch statement
Suppose day is 2:

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
35
Trace switch statement
Match case 2

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
36
Trace switch statement
Fall through case 3

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
37
Trace switch statement
Fall through case 4

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
38
Trace switch statement
Fall through case 5

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
39
Trace switch statement
Encounter break

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
40
Trace switch statement
Exit the statement

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
41
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year
and displays the animal for the year.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
42
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
43
Conditional Operators

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
44
Conditional Operator
if (num % 2 == 0)
[Link](num + “is even”);
else
[Link](num + “is odd”);

[Link](
(num % 2 == 0)? num + “is even” :
num + “is odd”);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
45
Operator Precedence

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
46
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When
evaluating an expression without parentheses, the
operators are applied according to the precedence rule and
the associativity rule.

If operators with the same precedence are next to each


other, their associativity determines the order of
evaluation. All binary operators except assignment
operators are left-associative.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
47
Operator Associativity
When two operators with the same precedence
are evaluated, the associativity of the operators
determines the order of evaluation. All binary
operators except assignment operators are left-
associative.
a – b + c – d is equivalent to ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
48
Example
Applying the operator precedence and associativity rule,
the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as
follows:

3 + 4 * 4 > 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
49
Mathematical Functions,
Characters, and Strings

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
1
Objectives
F To solve mathematics problems by using the methods in the Math class (§4.2).
F To represent characters using the char type (§4.3).
F To encode characters using ASCII and Unicode (§4.3.1).
F To represent special characters using the escape sequences (§4.4.2).
F To cast a numeric value to a character and cast a character to an integer (§4.3.3).
F To compare and test characters using the static methods in the Character class (§4.3.4).
F To introduce objects and instance methods (§4.4).
F To represent strings using the String objects (§4.4).
F To return the string length using the length() method (§4.4.1).
F To return a character in the string using the charAt(i) method (§4.4.2).
F To use the + operator to concatenate strings (§4.4.3).
F To read strings from the console (§4.4.4).
F To read a character from the console (§4.4.5).
F To compare strings using the equals method and the compareTo methods (§4.4.6).
F To obtain substrings (§4.4.7).
F To find a character or a substring in a string using the indexOf method (§4.4.8).
F To program using characters and strings (GuessBirthday) (§4.5.1).
F To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.5.2).
F To revise the lottery program using strings (LotteryUsingStrings) (§4.5.3).
F To format output using the [Link] method (§4.6).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
2
Mathematical Functions
Java provides many useful methods in the Math
class for performing common mathematical
functions.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
The Math Class
 A method is a group of statements that performs a specific
task.
 You have already used the pow(a, b) method to compute ab and the
random() method for generating a random number.
 There are many other useful methods in the Math class.
 They can be categorized as trigonometric methods, exponent
methods, rounding methods and service methods.
 Service methods include the min, max, absolute, and random
methods.
 In addition to methods, the Math class provides two useful
double constants, PI and E (the base of natural logarithms).
You can use these constants as [Link] and Math.E in any
program.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
The Math Class
 Class constants:
– PI
–E
 Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– min, max, abs, and random Methods

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Trigonometric Methods
 sin(double a) Examples:

 cos(double a) [Link](0) returns 0.0


[Link]([Link] / 6)
 tan(double a) returns 0.5
 acos(double a) [Link]([Link] / 2)
returns 1.0
 asin(double a) [Link](0) returns 1.0
[Link]([Link] / 6)
 atan(double a) returns 0.866
[Link]([Link] / 2)
returns 0

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
Exponent Methods
 exp(double a) Examples:
Returns e raised to the power of a.
 log(double a) [Link](1) returns 2.71
Returns the natural logarithm of a. [Link](2.71) returns
1.0
 log10(double a)
[Link](2, 3) returns
Returns the 10-based logarithm of a. 8.0
 pow(double a, double b) [Link](3, 2) returns
Returns a raised to the power of b. 9.0
[Link](3.5, 2.5)
 sqrt(double a)
returns 22.91765
Returns the square root of a.
[Link](4) returns 2.0
[Link](10.5) returns
3.24

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
Rounding Methods
 double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a double
value.
 double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
 double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
 int round(float x)
Return (int)[Link](x+0.5).
 long round(double x)
Return (long)[Link](x+0.5).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Rounding Methods Examples
[Link](2.1) returns 3.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -2.0
[Link](2.1) returns 2.0
[Link](2.0) returns 2.0
[Link](-2.0) returns –2.0
[Link](-2.1) returns -3.0
[Link](2.1) returns 2.0
[Link](2.0) returns 2.0
[Link](-2.6) returns –3.0
[Link](-2.1) returns -2.0
[Link](2.5) returns 2.0
[Link](2.501) returns 3.0
[Link](-2.5) returns -2.0
[Link](2.5) returns 3
[Link](2.501) returns 3
[Link](2.0) returns 2
[Link](-2.4) returns -2
[Link](-2.6) returns -3
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
min, max, and abs
 max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters. [Link](2, 3) returns 3
 abs(a) [Link](2.5, 3) returns
Returns the absolute value of the 3.0
parameter. [Link](2.5, 3.6)
 random() returns 2.5
Returns a random double value [Link](-2) returns 2
in the range [0.0, 1.0). [Link](-2.1) returns
2.1

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
The random Method
Generates a random double value greater than or equal to 0.0 and less
than 1.0 (0 <= [Link]() < 1.0).

Examples:

Returns a random integer


(int)([Link]() * 10)
between 0 and 9.

50 + (int)([Link]() * 50) Returns a random integer


between 50 and 99.

In general,

a + [Link]() * b Returns a random number between


a and a + b, excluding a + b.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Case Study: Computing Angles
of a Triangle
x2, y2
A = acos((a * a - b * b - c * c) / (-2 * b * c))
a B = acos((b * b - a * a - c * c) / (-2 * a * c))
B
c C = acos((c * c - b * b - a * a) / (-2 * a * b))
C
A x3, y3
b
x1, y1

Write a program that prompts the user to enter the


x- and y-coordinates of the three corner points in a
triangle and then displays the triangle’s angles.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Character Data Type
Four hexadecimal digits.
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)

NOTE: The increment and decrement operators can also be used


on char variables to get the next or preceding Unicode character.
For example, the following statements display character b.
char ch = 'a';
[Link](++ch);
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by \u, expressed in four hexadecimal numbers
that run from '\u0000' to '\uFFFF'.

Unicode \u03b1 \u03b2 \u03b3 for three Greek


letters

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
ASCII Code for Commonly Used
Characters
Characters Code Value in Decimal Unicode Value

'0' to '9' 48 to 57 \u0030 to \u0039


'A' to 'Z' 65 to 90 \u0041 to \u005A
'a' to 'z' 97 to 122 \u0061 to \u007A

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
Escape Sequences for Special Characters

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Casting between char and
Numeric Types
A char can be cast int any numeric type
and vice versa.

int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
Comparing and Testing
Characters
if (ch >= 'A' && ch <= 'Z')
[Link](ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
[Link](ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
[Link](ch + " is a numeric character");

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Methods in the Character Class
Method Description

isDigit(ch) Returns true if the specified character is a digit.


isLetter(ch) Returns true if the specified character is a letter.
r
isLetterOfDigit(ch) Returns true if the specified character is a letter or digit.
isLowerCase(ch) Returns true if the specified character is a lowercase letter.
isUpperCase(ch) Returns true if the specified character is an uppercase letter.
toLowerCase(ch) Returns the lowercase of the specified character.
toUpperCase(ch) Returns the uppercase of the specified character.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Methods in the Character Class

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
The String Type
The char type only represents one character. To represent a string of
characters, use the data type called String. For example,

String message = "Welcome to Java";

String is actually a predefined class in the Java library just like the
System class and Scanner class.

The String type is not a primitive type. It is known as a reference type. Any Java
class can be used as a reference type for a variable. The variable declared by a
reference type is known as a reference variable that references an object. Here,
message is a reference variable that references a string object with contents
Welcome to Java.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
22
Simple Methods for String Objects
Method Description

length() Returns the number of characters in this string.


charAt(index) Returns the character at the specified index from this string.
concat(s1) Returns a new string that concatenates this string with string s1.
toUpperCase() Returns a new string with all letters in uppercase.
toLowerCase() Returns a new string with all letters in lowercase.
trim() Returns a new string with whitespace characters trimmed on both sides.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
23
Simple Methods for String Objects
•Strings are objects in Java.
•The methods in the preceding table can only be invoked
from a specific string instance.
•are called instance methods.
•A non-instance method is called a static method.
•A static method can be invoked without using an object.
• All the methods defined in the Math class are static
methods.
•They are not tied to a specific object instance.
•The syntax to invoke an instance method is
•[Link](arguments).
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
24
Getting String Length
String message = "Welcome to Java";
[Link]("The length of " + message + " is "
+ [Link]());

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
25
Getting Characters from a String

String message = "Welcome to Java";


[Link]("The first character in message is "
+ [Link](0));

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
26
Converting Strings
 "Welcome".toLowerCase() returns a new string,
welcome.

 "Welcome".toUpperCase() returns a new string,


WELCOME.

 " Welcome Home ".trim() returns a new string,


Welcome Home.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
27
String Concatenation
String s3 = [Link](s2); or String s3 = s1 + s2;

// Three strings are concatenated


String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2;
or String s = "Chapter" + "2"; // s becomes Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B';
// s1 becomes SupplementB

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
28
Reading a String from the Console
 To read a string from the console, invoke the next()
method on a Scanner object.

Scanner input = new Scanner([Link]);


[Link]("Enter three words separated by spaces: ");

String s1 = [Link]();
String s2 = [Link]();
String s3 = [Link]();

[Link]("s1 is " + s1);


[Link]("s2 is " + s2);
[Link]("s3 is " + s3);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
29
Reading a String from the Console

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
30
Reading a Character from the Console

Scanner input = new Scanner([Link]);


[Link]("Enter a character: ");
String s = [Link]();
char ch = [Link](0);
[Link]("The character entered is " + ch);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
31
Two Types of String Objects
String objects can be created in following two expressions:

String strObject = new String("Java");


String strLiteral = "Java";

When you create String object using new() operator, it


always create a new object in the heap memory . On the
other hand, if you create object using String literal syntax
e.g. "Java", it may return an existing object from String
pool. Otherwise it will create a new string object and put in
string pool for future re-use.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
32
REMARK:

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
33
Comparing Strings
• The == operator checks only whether two string
variables refer to the same object; it does not
tell you whether they have the same contents.

• You cannot use the == operator to find out


whether two string variables have the same
contents. Instead, you should use the equals
method.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
34
Comparing Strings
The String class contains the methods as shown below for comparing two strings .

Method Description

equals(s1) Returns true if this string is equal to string s1 .


equalsIgnoreCase(s1) Returns true if this string is equal to string s1 ; it is case insensitive.
compareTo(s1) Returns an integer greater than 0 , equal to 0 , or less than 0 to indicate whether
this string is greater than, equal to, or less than s1 .
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case insensitive.
startsWith(prefix) Returns true if this string starts with the specified prefix.
endsWith(suffix) Returns true if this string ends with the specified suffix.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
35
Comparing Strings
The following code, for instance, can be used to compare two strings:

if ([Link](string2))
[Link]("string1 and string2 have the same
contents");
else
[Link]("string1 and string2 are not equal");

For example, the following statements display true and then false.
String s1 = "Welcome to Java";
String s2 = "Welcome to Java";
String s3 = "Welcome to C++";
[Link]([Link](s2)); // true
[Link]([Link](s3)); // false

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
36
Comparing Strings

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
37
Comparing Strings

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
38
Obtaining Substrings
Method Description

substring(beginIndex) Returns this string’s substring that begins with the character at the specified
beginIndex and extends to the end of the string, as shown in Figure 4.2.

substring(beginIndex, Returns this string’s substring that begins at the specified beginIndex and
endIndex) extends to the character at index endIndex – 1, as shown in Figure 9.6.
Note that the character at endIndex is not part of the substring.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
39
Finding a Character or a Substring
in a String
Method Description

indexOf(ch) Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string.
Returns -1 if not matched.
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns -1 if
not matched.
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after
fromIndex. Returns -1 if not matched.
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns -1 if not
matched.
lastIndexOf(ch, Returns the index of the last occurrence of ch before fromIndex in this
fromIndex) string. Returns -1 if not matched.
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns -1 if not matched.
lastIndexOf(s, Returns the index of the last occurrence of string s before fromIndex.
fromIndex) Returns -1 if not matched.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
40
Finding a Character or a Substring
in a String
int k = [Link](' ');
String firstName = [Link](0, k);
String lastName = [Link](k + 1);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
41
Conversion between Strings and Numbers

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
42
Formatting Output
Use the printf statement.
[Link](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. An item may be a numeric value,
character, boolean value, or a string. Each specifier begins
with a percent sign.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
43
Frequently-Used Specifiers
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"

int count = 5;
items
double amount = 45.56;
[Link]("count is %d and amount is %f", count, amount);

display count is 5 and amount is 45.560000

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
44
Examples

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
45
Loops

Fundamentals of Programming II, IT, nd


2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
1
Objectives
 To write programs for executing statements repeatedly using a while loop
(§5.2).
 To follow the loop design strategy to develop loops (§§5.2.1–5.2.3).
 To control a loop with a sentinel value (§5.2.4).
 To obtain large input from a file using input redirection rather than typing
from the keyboard (§5.2.5).
 To write loops using do-while statements (§5.3).
 To write loops using for statements (§5.4).
 To discover the similarities and differences of three types of loop statements
(§5.5).
 To write nested loops (§5.6).
 To learn the techniques for minimizing numerical errors (§5.7).
 To learn loops from a variety of examples (GCD, FutureTuition,
Dec2Hex) (§5.8).
 To implement program control with break and continue (§5.9).
 To write a program that displays prime numbers (§5.11).

Fundamentals of Programming II, IT, nd


2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
2
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
[Link]("Welcome to Java!");
Statement(s); Boolean!
count++;
} }

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to
signify the end of the loop. Such a value is known
as a sentinel value.

Write a program that reads and calculates the sum


of an unspecified number of integers. The input 0
signifies the end of the input.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
Ending a Loop with a Sentinel Value

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Caution
Don’t use floating-point values for equality checking in a
loop control. Since floating-point values are
approximations for some values, using them could result
in imprecise counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8
+ ... + 0.1:
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
[Link](sum);
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
do-while Loop

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

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) { [Link](
// loop body;
Statement(s); "Welcome to Java!");
} }

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
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; [Link](i++));

for (int i = 0, j = 0; (i + j < 10); i++, j++) {


// Do something
}
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
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)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
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++);


{
[Link]("i is " + i);
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
[Link]("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
[Link]("i is " + i);
i++;
} while (i<10); Correct

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
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) { Equivalent for ( ; loop-continuation-condition; ) {
// Loop body // Loop body
} }
(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)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Recommendations
 Use the one that is most intuitive and comfortable for
you.
 In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need
to print a message 100 times.
 A while loop may be used if the number of repetitions
is not known, as in the case of reading the numbers
until the input is 0.
 A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition.
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Nested Loops

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Nested Loops

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
Problem:
Finding the Greatest Common Divisor

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
break and continue
The break and continue keywords provide additional controls in a loop.
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;
}

[Link]("The number is " + number);


[Link]("The sum is " + sum);
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
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;
}

[Link]("The sum is " + sum);


}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Problem:
Checking
Palindrome

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Methods

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
1
Objectives
 To define methods with formal parameters (§6.2).
 To invoke methods with actual parameters (i.e., arguments) (§6.2).
 To define methods with a return value (§6.3).
 To define methods without a return value (§6.4).
 To pass arguments by value (§6.5).
 To develop reusable code that is modular, easy to read, easy to debug, and
easy to maintain (§6.6).
 To write a method that converts hexadecimals to decimals (§6.7).
 To use method overloading and understand ambiguous overloading
(§6.8).
 To determine the scope of variables (§6.9).
 To apply the concept of method abstraction in software development
(§6.10).
 To design and implement methods using stepwise refinement (§6.10).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
2
Defining Methods

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

int z = max(x, y);


public static int max(int num1, int num2) {
actual parameters
int result; (arguments)

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Method Signature
Method signature is the combination of the method name and the
parameter list.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
Formal Parameters
The variables defined in the method header are known as
formal parameters.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.

Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
Calling Methods

pass the value of i


pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
[Link]( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
CAUTION
A return statement is required for a value-returning method. The
method shown below in (a) is logically correct, but it has a
compilation error because the Java compiler thinks it possible that
this method does not return any value.
public static int sign(int n) { public static int sign(int n) {
if (n > 0) Should be if (n > 0)
return 1; return 1;
else if (n == 0) else if (n == 0)
return 0; return 0;
else if (n < 0) else
return –1; return –1;
} }
(a) (b)

To fix this problem, delete if (n < 0) in (a), so that the compiler will
see a return statement to be reached regardless of how the if
statement is evaluated.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the static method
max using [Link] (e.g., [Link]).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
Call Stacks
Each time a method is invoked, the system creates an activation record (also called
an activation frame) that stores parameters and variables for the method and places
the activation record in an area of memory known as a call stack. A call stack is
also known as an execution stack, runtime stack, or machine stack, and it is often
shortened to just “the stack.” When a method calls another method, the caller’s
activation record is kept intact, and a new activation record is created for the new
method called. When a method finishes its work and returns to its caller, its
activation record is removed from the call stack.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Trace Call Stack
i is declared and initialized

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i +
" and " + j + " is " + k);
}

public static int max(int num1, int num2) {


int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Trace Call Stack
j is declared and initialized

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i +
" and " + j + " is " + k);
}

public static int max(int num1, int num2) { j: 2


int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Trace Call Stack
Declare k

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i +
" and " + j + " is " + k);
} Space required for the
main method
k:
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
Trace Call Stack
Invoke max(i, j)

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i +
" and " + j + " is " + k);
} Space required for the
main method
k:
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Trace Call Stack
pass the values of i and j to num1
and num2

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i +
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
Trace Call Stack

Declare result

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i + result:
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Trace Call Stack

(num1 > num2) is true

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i + result:
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Trace Call Stack

Assign num1 to result

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
Space required for the
[Link]( max method
"The maximum between " + i + result: 5
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
Trace Call Stack

Return result and assign it to k

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
Space required for the
[Link]( max method
"The maximum between " + i + result: 5
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) {
int result; main method
k:5
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;
return result; The max method is
} invoked.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
22
Trace Call Stack
Execute print statement

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
[Link](
"The maximum between " + i +
" and " + j + " is " + k);
} Space required for the
main method
k:5
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;
return result;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
23
void Method Example

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
24
Passing Parameters

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
25
Pass by Value
•When you invoke a method with an
argument, the value of the argument is
passed to the parameter.
•This is referred to as pass-by-value.
•If the argument is a variable rather than a
literal value, the value of the variable is
passed to the parameter.
•The variable is not affected, regardless
of the changes made to the parameter
inside the method
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
26
Pass by Value

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
27
Pass by Value

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
28
Pass by Value, cont.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
29
Overloading Methods
F Overloading methods enables you to define the methods with
the same name as long as their signatures are different.
F The method max (int num1, int num2) works only with the int data
type.
F But what if you need to determine which of two floating-point
numbers has the maximum value?
– The solution is to create another method with the same name but
different parameters, as shown in the following code:
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
30
Ambiguous Invocation

F The Java compiler determines which method to


use based on the method signature.
F Sometimes there may be two or more possible
matches for an invocation of a method, but the
compiler cannot determine the most specific
match.
– This is referred to as ambiguous invocation.
– Ambiguous invocation is a compile error.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
31
Ambiguous Invocation

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
32
Scope of Local Variables
F A local variable: a variable defined inside a
method.
F Scope: the part of the program where the
variable can be referenced.
F The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable.
– A local variable must be declared before it can be
used.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
33
Scope of Local Variables, cont.
FYou can declare a local variable with
the same name multiple times in
different non-nesting blocks in a method,
–but you cannot declare a local variable twice in
nested blocks.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
34
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
The scope of i .
int j;
.
The scope of j .
.
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
35
Scope of Local Variables, cont.

It is fine to declare i in two It is wrong to declare i in


non-nesting blocks two nesting blocks

public static void method1() { public static void method2() {


int x = 1;
int y = 1; int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i; for (int i = 1; i < 10; i++) {
} sum += i;
}
for (int i = 1; i < 10; i++) {
y += i; }
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
36
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
} nd
Fundamentals of Programming II, IT, 2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
37
Scope of Local Variables, cont.
// compile time error
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is used again
for ( ; i < 10; i++) {
y += i;
}
} nd
Fundamentals of Programming II, IT, 2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd.
All rights reserved.
38
Scope of Local Variables, cont.
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
39
Method Abstraction
You can think of the method body as a black box
that contains the detailed implementation for the
method.
Optional arguments Optional return
for Input value

Method Header
Black Box
Method body

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
40
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding.
• Hide the implementation from the user.
• Reduce complexity.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
41
Case Study: Generating Random
Characters
Computer programs process numerical data and characters.
You have seen many examples that involve numerical data.
It is also important to understand characters and how to
process them.
As introduced in Section 4.3, each character has a unique
Unicode between 0 and FFFF in hexadecimal (65535 in
decimal). To generate a random character is to generate a
random integer between 0 and 65535 using the following
expression: (note that since 0 <= [Link]() < 1.0, you
have to add 1 to 65535.)
(int)([Link]() * (65535 + 1))

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
42
Case Study: Generating Random
Characters, cont.
Now let us consider how to generate a random
lowercase letter. The Unicode for lowercase letters
are consecutive integers starting from the Unicode
for 'a', then for 'b', 'c', ..., and 'z'. The Unicode for 'a'
is
(int)'a'
So, a random integer between (int)'a' and (int)'z' is
(int)((int)'a' + [Link]() * ((int)'z' - (int)'a' + 1)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
43
Case Study: Generating Random
Characters, cont.
As discussed in Chapter 2, all numeric operators
can be applied to the char operands. The char
operand is cast into a number if the other operand
is a number or a character. So, the preceding
expression can be simplified as follows:
'a' + [Link]() * ('z' - 'a' + 1)

So a random lowercase letter is


(char)('a' + [Link]() * ('z' - 'a' + 1))
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
44
Case Study: Generating Random
Characters, cont.
To generalize the foregoing discussion, a random character
between any two characters ch1 and ch2 with ch1 < ch2
can be generated as follows:

(char)(ch1 + [Link]() * (ch2 – ch1 + 1))

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
45
The RandomCharacter Class
// [Link]: Generate random characters
public class RandomCharacter {
/** Generate a random character between ch1 and ch2 */
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + [Link]() * (ch2 - ch1 + 1));
}

/** Generate a random lowercase letter */


public static char getRandomLowerCaseLetter() {
return getRandomCharacter('a', 'z');
}

/** Generate a random uppercase letter */


public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}

/** Generate a random digit character */


public static char getRandomDigitCharacter() {
return getRandomCharacter('0', '9');
}

/** Generate a random character */


public static char getRandomCharacter() {
return getRandomCharacter('\u0000', '\uFFFF');
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
46
The TestRandomCharacter Class

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
47
Single-Dimensional Arrays

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
1
Objectives
 To describe why arrays are necessary in programming (§7.1).
 To declare array reference variables and create arrays (§§7.2.1–7.2.2).
 To obtain array size using [Link] and know default values in an array
(§7.2.3).
 To access array elements using indexes (§7.2.4).
 To declare, create, and initialize an array using an array initializer (§7.2.5).
 To program common array operations (displaying arrays, summing all elements, finding
the minimum and maximum elements, random shuffling, and shifting elements) (§7.2.6).
 To simplify programming using the for each loops (§7.2.7).
 To apply arrays in application development (AnalyzeNumbers) (§§7.3–7.4).
 To copy contents from one array to another (§7.5).
 To develop and invoke methods with array arguments and return values (§§7.6–7.8).
 To define a method with a variable-length argument list (§7.9).
 To sort an array using the selection sort approach (§7.11).
 To use the methods in the [Link] class (§7.12).
 To pass arguments to the main method from the command line (§7.13).

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
2
Introducing Arrays
Array is a data structure that represents a collection
of the same types of data.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
Declaring Array Variables
datatype[] arrayRefVar;

Example:
double[] myList;

datatype arrayRefVar[]; // This style is allowed, but not preferred

Example:
double myList[];

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Declaring and Creating in
One Step
datatype[] arrayRefVar = new datatype[arraySize];
double[] myList = new double[10];

datatype arrayRefVar[] = new datatype[arraySize];


double myList[] = new double[10];

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
The Length of an Array
•Once an array is created, its size is fixed.
•It cannot be changed.
•You can find its size using

[Link]

For example,

[Link] returns 10

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
Default Values
When an array is created, its elements are assigned the
default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Indexed Variables
•The array elements are accessed through the index.
•The array indices are 0-based,
•i.e., it starts from 0 to [Link]-1.
•In the previous example, myList holds ten double values and the
indices are from 0 to 9.
•Each element in the array is represented using the following
syntax, known as an indexed variable:

arrayRefVar[index];
•10

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
Using Indexed Variables
•After an array is created, an indexed variable can be used
in the same way as a regular variable.
•For example, the following code adds the value in
myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
Array Initializers
 Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};

 Thisshorthand syntax must be in one


statement.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
 Thisshorthand notation is equivalent to the
following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
CAUTION
•Using the shorthand notation, you have to declare,
create, and initialize the array all in one statement.
•Splitting it would cause a syntax error.
•For example, the following is wrong:
double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
13
Trace Program with Arrays
Declare array variable values, create
an array, and assign its reference to
values
public class Test {
public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0
2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Trace Program with Arrays
After this, i becomes 1

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0
2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Trace Program with Arrays
i (=1) is less than 5

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0
2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
Trace Program with Arrays
After this line is executed, value[1] is 1

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Trace Program with Arrays
After this, i becomes 2

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
Trace Program with Arrays
i (=2) is still less than 5

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 0
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Trace Program with Arrays
After this line is executed, value[2] is 3 (2+1)

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Trace Program with Arrays
After this, i becomes 3

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
Trace Program with Arrays
i (=3) is still less than 5

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 0
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
22
Trace Program with Arrays
After this line is executed, value[3] is 6 (3+3)

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
23
Trace Program with Arrays
After this, i becomes 4

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
24
Trace Program with Arrays
i (=4) is still less than 5

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 0
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
25
Trace Program with Arrays
After this line is executed, value[4] is 10 (4+6)

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 10
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
26
Trace Program with Arrays
After this, i becomes 5

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 10
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
27
Trace Program with Arrays
i (=5) is equal to 5, and the loop ends

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 10
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
28
Trace Program with Arrays
After this line is executed, value[0] is 11 (1+10)

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 11
values[i] = i + values[i-1]; 1 1
2 3
}
3 6
values[0] = values[1] + values[4];
4 10
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
29
Processing Arrays
1.(Initializing arrays with input values)
2.(Initializing arrays with random values)
3.(Printing arrays)
4.(Summing all elements)
5.(Finding the largest element)
6.(Finding the smallest index of the largest
element)
7.(Random shuffling)
8.(Shifting elements)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
30
Initializing arrays with input
values
[Link] input = new [Link]([Link]);
[Link]("Enter " + [Link] + " values: ");
for (int i = 0; i < [Link]; i++)
myList[i] = [Link]();

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
31
Initializing arrays with random
values
for (int i = 0; i < [Link]; i++) {
myList[i] = [Link]() * 100;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
32
Summing all elements

double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
33
Finding the largest element

double max = myList[0];


for (int i = 1; i < [Link]; i++) {
if (myList[i] > max) max = myList[i];
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
34
Random shuffling
myList
for (int i = 0; i < [Link] - 1; i++) { 0
1
// Generate an index j randomly 2
int j = (int)([Link]()* [Link]); 3
i
// Swap myList[i] with myList[j]
swap
double temp = myList[i]; j

myList[i] = myList[j]; n
myList[j] = temp;
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
35
Shifting Elements

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
36
Enhanced for Loop (for-each
loop)
•JDK 1.5 introduced a new for loop that enables you to traverse
the complete array sequentially without using an index
variable.
•For example, the following code displays all elements in the
array myList:
for (double value: myList) [Link](value);

In general, the syntax is

for (elementType value: arrayRefVar) {


// Process the value
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
37
Lab Activity: Analyze Numbers
Read one hundred numbers, compute their average,
and find out how many numbers are above the
average.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
38
Copying Arrays
Often, in a program, you need to duplicate an array or a
part of an array. In such cases you could attempt to use
the assignment statement (=), as follows:
list2 = list1;

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
39
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[[Link]];

for (int i = 0; i < [Link]; i++)


targetArray[i] = sourceArray[i];

sourceArray sourceArray

targetArray targetArray

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
40
The arraycopy Utility
arraycopy(sourceArray,src_pos,targetArray,tar_pos, length);

Example:

[Link](sourceArray, 0,targetArray, 0,
[Link]);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
41
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < [Link]; i++) {
[Link](array[i] + " ");
}
}

Invoke the method

int[] list = {3, 1, 2, 6, 4, 2};


printArray(list);

Invoke the method


printArray(new int[]{3, 1, 2, 6, 4, 2});

Anonymous array

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
42
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array.
Such array is called an anonymous array.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
43
Ambiguous Invocation

 The Java compiler determines which method to


use based on the method signature.
 Sometimes there may be two or more possible
matches for an invocation of a method, but the
compiler cannot determine the most specific
match.
This is referred to as ambiguous invocation.
Ambiguous invocation is a compile error.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
44
Pass By Value
 Java uses pass by value to pass arguments to a method.
 There are important differences between passing a value
of variables of primitive data types and passing arrays.
 For a parameter of a primitive type value, the actual
value is passed.
Changing the value of the local parameter inside the method
does not affect the value of the variable outside the method.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
45
Pass By Value
 For a parameter of an array type, the value of the
parameter contains a reference to an array; this reference
is passed to the method.
Any changes to the array that occur inside the method body will
affect the original array that was passed as the argument.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
46
Simple Example
public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values
m(x, y); // Invoke m with arguments x and y
[Link]("x is " + x);
[Link]("y[0] is " + y[0]);
}

public static void m(int number, int[] numbers) {


number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
47
Call Stack

When invoking m(x, y), the values of x and y are passed


to number and numbers.
Since y contains the reference value to the array,
numbers now contains the same reference value to the
same array.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
48
Heap
Heap
5555 The arrays
0 are stored
Space required for in a heap.
the main method
int[] y: reference
0
int x: 1

 The JVM stores the array in an area of memory, called


heap, which is used for dynamic memory allocation
 where blocks of memory are allocated and freed in an arbitrary
order.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
49
Passing Arrays as Arguments
Objective: Demonstrate differences of passing
primitive data type variables and array variables.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
50
Call Stack

Invoke swap(int n1, int n2). The arrays Invoke swapFirstTwoInArray(int[]


The primitive type values in are stored array).
a[0] and a[1] are passed to in a heap The reference value in a is passed to
the swap method. the swapFirstTwoInArray method.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
51
Returning an Array from a
Method
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];

for (int i = 0,j = [Link] – 1; i < [Link]; i++, j--){


result[j] = list[i];
}
return result; list
}
result

int[] list1 = {1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
52
Trace the reverse Method

int[] list1 = {1, 2, 3, 4, 5, 6}; Declare result and create array


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
53
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i = 0 and j = 5


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
54
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i (= 0) is less than 6


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
55
Trace the reverse Method, cont.
i = 0 and j = 5
Assign list[0] to result[5]
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
56
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; After this, i becomes 1 and j becomes 4


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
57
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i (= 1) is less than 6


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
58
Trace the reverse Method, cont.
i = 1 and j = 4
Assign list[1] to result[4]
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
59
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1); After this, i becomes 2 and j becomes 3

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
60
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i (= 2) is still less than


int[] list2 = reverse(list1); 6

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
61
Trace the reverse Method, cont.
i = 2 and j = 3
int[] list1 = {1, 2, 3, 4, 5, 6}; Assign list[2] to result[3]
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
62
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1); After this, i becomes 3 and j becomes 2

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
63
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i (= 3) is still less than 6


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
64
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i = 3 and j = 2


int[] list2 = reverse(list1); Assign list[3] to result[2]

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
65
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1); After this, i becomes 4 and j becomes 1

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
66
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i (= 4) is still less than 6


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
67
Trace the reverse Method, cont.

i = 4 and j = 1
int[] list1 = {1, 2, 3, 4, 5, 6};
Assign list[4] to result[1]
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
68
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6};


After this, i becomes 5 and j becomes 0
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
69
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i (= 5) is still less than 6


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
70
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; i = 5 and j = 0


int[] list2 = reverse(list1); Assign list[5] to result[0]

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

6 5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
71
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1); After this, i becomes 6 and j becomes -1

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

6 5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
72
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6};


i (=6) < 6 is false. So exit the loop
int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list

6 5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
73
Trace the reverse Method, cont.

int[] list1 = {1, 2, 3, 4, 5, 6}; Return result


int[] list2 = reverse(list1);

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}

return result;
}
list
list2
6 5 4 3 2 1
result

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
74
Lab Activity: Counting Occurrence of
Each Letter
Generate 100 lowercase letters randomly and assign to an
array of characters.
Count the occurrence of each letter in the array.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
75
The [Link] Method
Since sorting is frequently used in programming, Java
provides several overloaded sort methods for sorting an array
of int, double, char, short, long, and float in the
[Link] class.
For example, the following code sorts an array of numbers
and an array of characters.

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


[Link](numbers);

char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};


[Link](chars);
Java 8 now provides [Link](list) that utilizes
the multicore for fast sorting.
Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
76
Main Method Is Just a Regular Method
You can call a regular method by passing actual parameters.
Can you pass arguments to main?
Of course, yes.
For example, the main method in class B is invoked by a
method in A, as shown below:
public class A { public class B {
public static void main(String[] public static void main(String[]
args) { args) {
String[] strings = {"New for (int i = 0; i < [Link];
York", "Boston", i++) {
"Atlanta"}; [Link](args[i]);
[Link](strings); }
} }
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
77
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}

java TestMain arg0 arg1 arg2 ... argnS

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
78
Processing Command-Line
Parameters
In the main method, get the arguments from
args[0], args[1], ..., args[n],
which corresponds to arg0, arg1, ...,
argn in the command line.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
79
Multidimensional Arrays

Fundamentals of Programming II, IT, nd


2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
1
Objectives
To give examples of representing data using two-dimensional arrays
(§8.1).
To declare variables for two-dimensional arrays, create arrays, and
access array elements in a two-dimensional array using row and column
indexes (§8.2).
To program common operations for two-dimensional arrays (displaying
arrays, summing all elements, finding the minimum and maximum
elements, and random shuffling) (§8.3).
To write a program for grading multiple-choice questions using two-
dimensional arrays (§8.5).
To use multidimensional arrays (§8.8).

Fundamentals of Programming II, IT, nd


2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.
2
Declare/Create Two-dimensional
Arrays
// Declare array ref var
dataType[][] refVar;
// Create array and assign its reference to variable
refVar = new dataType[10][10];
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
3
Declaring Variables of Two-
dimensional Arrays and
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];

matrix[0][0] = 3;
for (int i = 0; i < [Link]; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)([Link]() * 1000);

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
4
Declaring, Creating, and
Initializing Using Shorthand
Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,

int[][] array = { int[][] array = new int[4][3];


{1, 2, 3}, Same as array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
5
Lengths of Two-dimensional
Arrays
int[][] x = new int[3][4];

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
6
Lengths of Two-dimensional
Arrays, cont.

int[][] array = { [Link]


{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};

array[4].length ArrayIndexOutOfBoundsException

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
7
Two-dimensional Array
Illustration

[Link]? 5 [Link]? 4
matrix[0].length? 5 array[0].lengt

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
8
Ragged Arrays
•Each row in a two-dimensional array is itself an array.
•So, the rows can have different lengths.
•Such an array is known as a ragged array.
•For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, [Link] is 5
matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
{4, 5}, matrix[2].length is 3
{5} matrix[3].length is 2
}; matrix[4].length is 1

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
9
Ragged Arrays, cont.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
10
Multidimensional Arrays
Part II

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
11
Processing Two-Dimensional
Arrays
See the examples in the text.
1. (Initializingarrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
12
Initializing arrays with input values

int[][] matrix = new int [10][5];


[Link] input = new Scanner([Link]);
[Link]("Enter " + [Link] + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = [Link]();
}
} Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
13
All rights reserved.
Initializing arrays with random
values
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)([Link]() * 100);
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
14
Printing arrays

for (int row = 0; row < [Link]; row++) {


for (int column = 0; column < matrix[row].length; column++) {
[Link](matrix[row][column] + " ");
}
[Link]();
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
15
Summing all elements

int total = 0;
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
16
Summing elements by column

for (int column = 0; column < matrix[0].length; column++) {


int total = 0;
for (int row = 0; row < [Link]; row++)
total += matrix[row][column];
[Link]("Sum for column " + column + " is " + total);
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
17
Random shuffling

for (int i = 0; i < [Link]; i++) {


for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)([Link]() * [Link]);
int j1 = (int)([Link]() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
18
Multidimensional Arrays

• Occasionally, you will need to represent n-dimensional


data structures.
• In Java, you can create n-dimensional arrays for any
integer n.
• The way to declare two-dimensional array variables and
create two-dimensional arrays can be generalized to
declare n-dimensional array variables and create n-
dimensional arrays for n >= 3.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
19
Multidimensional Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}
};

Which student Which exam Multiple-choice or essay

scores[ i ] [ j ] [ k ]

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
20
Problem: Calculating Total Scores
Objective: write a program that calculates the total score for
students in a class. Suppose the scores are stored in a three-
dimensional array named scores. The first index in scores refers to
a student, the second refers to an exam, and the third refers to the
part of the exam. Suppose there are 7 students, 5 exams, and each
exam has two parts--the multiple-choice part and the programming
part. So, scores[i][j][0] represents the score on the multiple-choice
part for the i’s student on the j’s exam. Your program displays the
total score for each student.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
21
Problem: Weather Information
Suppose a meteorology station records the temperature
and humidity at each hour of every day and stores the data
for the past ten days in a text file named [Link]. Each
line of the file consists of four numbers that indicate the
day, hour, temperature, and humidity. Your task is to write
a program that calculates the average daily temperature
and humidity for the 10 days.

Fundamentals of Programming II, IT, 2 Batch nd Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson
All rights reserved.
22
Objects and Classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
1
Motivations
Suppose you want to develop a graphical user interface as
shown below. How do you program it?

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
2
OO Programming Concepts
Object-oriented programming (OOP) involves
programming using objects.

An object represents an entity in the real world that


can be distinctly identified.

For example, a student, a desk, a circle, a button,


and even a loan can all be viewed as objects.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
3
Classes (Cookie Cutters)
Classes are constructs that define objects of the
same type.
A Java class uses variables to define data fields
and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are invoked
to construct objects from the class.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
4
Classes

Data Field

Constructors

Methods

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
5
UML Class Diagram

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
6
Objects (Cookies)
An object has a unique identity, state, and
behavior.

The state of an object consists of a set of data


fields (also known as properties) with their
current values.

The behavior of an object is defined by a set


of methods.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
7
Objects

An object has both a state and behavior. The state


defines the object, and the behavior defines what
the object does.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
8
Example: Defining Classes and Creating Objects

Let’s go look . . .

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
9
Constructors, cont.
•A constructor with no parameters is referred to as
a no-arg constructor or default constructor.
• Constructors must have the same name as the
class itself.
• Constructors do not have a return type—not even
void.
• Constructors are invoked using the new operator
when an object is created.
•Constructors play the role of initializing objects.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd
Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
10
Constructors
Constructors are a special
Circle() { kind of methods that are
} invoked to construct objects.

Circle(double newRadius) {
radius = newRadius;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
11
Default Constructor
•A class may be defined without constructors.
•In this case, a no-arg constructor with an empty
body is implicitly defined in the class.
•This constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly defined in the class.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
12
Creating Objects Using
Constructors
new ClassName();

Example:
new Circle();

new Circle(5.0);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
13
Declaring Object Reference Variables
To reference an object, assign the object to a reference
variable.

To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
14
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();

Assign object reference Create an object


Example:
Circle myCircle = new Circle();

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
15
Accessing Object’s Members
❑ Referencing the object’s data:
[Link]
e.g., [Link]

❑ Invoking the object’s method:


[Link](arguments)
e.g., [Link]()

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
16
Trace Code
Declare myCircle

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

[Link] = 100;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
17
Trace Code, cont.

Circle myCircle = new Circle(5.0); no value


myCircle
Circle yourCircle = new Circle();

[Link] = 100;

Create a circle

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
18
Trace Code, cont.

Circle myCircle = new Circle(5.0); reference value


myCircle
Circle yourCircle = new Circle();

[Link] = 100; Assign object reference


to myCircle

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
19
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

[Link] = 100;

yourCircle no value

Declare yourCircle

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
20
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

[Link] = 100;

yourCircle no value

Create a new
Circle object

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
21
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

[Link] = 100;

yourCircle reference value

Assign object reference


to yourCircle

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
22
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();

[Link] = 100;

yourCircle reference value

Change radius in
yourCircle

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
23
END OF PART I

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
24
PART II

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
25
Reference Data Fields
The data fields can be of reference types. For example,
the following Student class contains a data field name of
the String type.
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
26
The null Value
If a data field of a reference type does not
reference any object, the data field holds a
special literal value, null.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
27
Default Value for a Data Field
The default value of a data field is null for a
reference type, 0 for a numeric type, false for a
boolean type, and '\u0000' for a char type.

public class Test {


public static void main(String[] args) {
Student student = new Student();
[Link]("name? " + [Link]);
[Link]("age? " + [Link]);
[Link]("isScienceMajor? " + [Link]);
[Link]("gender? " + [Link]);
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
28
Example
Java assigns no default value to a local variable
inside a method body.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
[Link]("x is " + x);
[Link]("y is " + y);
}
}

Compile error: variable not


initialized
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd
Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
29
Differences between Variables of
Primitive Data Types and Object Types

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
30
Copying Variables of Primitive
Data Types and Object Types

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
31
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2, c1 points to
the same object referenced by c2.
The object previously referenced by c1 is no
longer referenced.
This object is known as garbage.

Garbage is automatically collected by JVM.


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd
Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
32
Caution
Recall that you use [Link](arguments) (e.g., [Link](3, 2.5))
to invoke a method in the Math class.

Can you invoke getArea() using [Link]()? NO!

All the methods used before this chapter are static methods,
which are defined using the static keyword, and not associated
with objects.

However, getArea() is non-static, and associated with a


particular object and invoked using
[Link](arguments) (e.g., [Link]()).

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
33
Static
●A way of sharing variables, constants, and
methods. We use ONE static Math class, like a
library.
●Static variables are shared by all the instances
of the class.
●Static methods are not tied to a specific
object.
●Static constants are final variables shared by
all the instances of the class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd
Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
34
Static Variables, Constants,
and Methods, cont.

To declare static variables, constants, and methods,


use the static modifier.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
35
Objects: Instance
Variables, and Methods

•Instance variables belong to a specific object.

Instance methods are invoked by an instance of the


class.

•Instance variables and methods are specified by


omitting the static keyword.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
36
Static Variables, Constants,
and Methods, cont.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
37
Static
numberOfObjects is shared by ALL
objects because it is specified as static;
whereas, radius is an instance variable that
is only used in the instance of an object to
store the value for that object.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
38
END OF PART II

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
39
PART III

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
40
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
❑ public
The class, data, or method is visible to any class in any
package.

❑ private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd
Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
41
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
42
The default modifier on a class restricts access to within a package,
and the public modifier enables unrestricted access.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
43
NOTE
•An object cannot access its private members, as shown in (b).
•It is OK, however, if the object is declared in its own class, as
shown in (a).

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
44
Why Data Fields Should Be
private?
●To protect data.

●To make code easy to maintain.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
45
Passing Objects to Methods

❑ Passing by value for primitive type value


(the value is passed to the parameter)
❑ Passing by value for reference type value
(the value is the reference to the object)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
46
Passing Objects to Methods, cont.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
47
Array of Objects
Circle[] circleArray = new Circle[10];

● An array of objects is actually an array of


reference variables.
● So invoking circleArray[1].getArea()
involves two levels of referencing as
shown in the next figure.
– circleArray references to the entire array.
– circleArray[1] references to a Circle object.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd
Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
48
Array of Objects, cont.
Circle[] circleArray = new Circle[10];

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
49
Mutator Methods
setters and getters

/** Return numberOfObjects */


static int getNumberOfObjects() {
return numberOfObjects;
}

/** Return the area of this circle */


double getArea() {
return radius * radius * [Link];
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
50
Immutable Objects and Classes
•If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class.
•If you delete the set method in the Circle class in Listing 8.10,
the class would be immutable because radius is private and
cannot be changed without a set method.

•A class with all private data fields and without mutators is not
necessarily immutable.
•For example, the following class Student has all private data
fields and no mutators, but it is mutable.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
51
Example
public class Student {
public class BirthDate {
private int year;
private int id; private int month;
private BirthDate birthDate; private int day;
public Student(int ssn,
public BirthDate(int newYear,
int year, int month, int day) {
id = ssn;
int newMonth, int newDay) {
birthDate = new BirthDate(year, year = newYear;
month, day); month = newMonth;
} day = newDay;
}
public int getId() {
return id; public void setYear(int newYear) {
} year = newYear;
}
public BirthDate getBirthDate() { }
return birthDate;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = [Link]();
[Link](2010); // Now the student birth year is changed!
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
52
What Class is Immutable?
For a class to be immutable, it must mark all data fields private
and provide no mutator methods and no accessor methods that
would return a reference to a mutable data field object.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
53
Scope of Variables
❑ The scope of instance and static variables is the
entire class. They can be declared anywhere inside
a class.
❑ The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
initialized explicitly before it can be used.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
54
The this Keyword
❑ The this keyword is the name of a reference that
refers to an object itself. One common use of the
this keyword is to reference a class’s hidden
data fields.
❑ Another common use of the this keyword to
enable a constructor to invoke another
constructor of the same class.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch Education, Inc. All
rights reserved.
55
Reference the Hidden Data Fields

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
56
Calling Overloaded Constructor

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
57
END OF LECTURE

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearsonnd


Fundamentals of Programming II, IT, 2 Batch
Education, Inc. All
rights reserved.
58
Inheritance and Polymorphism

Fundamentals of Programming II, IT, 2nd Batch 1


Motivations
Suppose you will define classes to model circles,
rectangles, and triangles. These classes have many
common features. What is the best way to design
these classes so to avoid redundancy? The answer
is to use inheritance.

Fundamentals of Programming II, IT, 2nd Batch 2


Objectives
◆To define a subclass from a superclass through inheritance (§11.2).
◆To invoke the superclass’s constructors and methods using the super
keyword (§11.3).
◆To override instance methods in the subclass (§11.4).
◆To distinguish differences between overriding and overloading (§11.5).
◆To explore the toString() method in the Object class (§11.6).
◆To discover polymorphism and dynamic binding (§§11.7–11.8).
◆To describe casting and explain why explicit downcasting is necessary
(§11.9).
◆To explore the equals method in the Object class (§11.10).
◆To store, retrieve, and manipulate objects in an ArrayList (§11.11).
◆To enable data and methods in a superclass accessible from subclasses
using the protected visibility modifier (§11.13).
◆To prevent class extending and method overriding using the final
modifier (§11.14).

Fundamentals of Programming II, IT, 2nd Batch 3


Superclasses and Subclasses
GeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: [Link] The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, filled: Creates a GeometricObject with the specified color and filled values.
boolean)
+getColor(): String Returns the color.
+setColor(color: String): void Sets a new color.
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property.
+getDateCreated(): [Link] Returns the dateCreated.
+toString(): String Returns a string representation of this object.

Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String, filled: +Rectangle(width: double, height: double)
boolean) +Rectangle(width: double, height: double color: String,
+getRadius(): double filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd
Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
4
Are superclass’s Constructor
Inherited?
 No. They are not inherited.
 They are invoked explicitly or implicitly.

 Explicitly using the super keyword.


 A constructor is used to construct an instance of a class.
 Unlike properties and methods, a superclass's constructors are not
inherited in the subclass.
 They can only be invoked from the subclasses' constructors, using the
keyword super.
 If the keyword super is not explicitly used, the superclass's no-arg constructor
is automatically invoked.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd


Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
5
Superclass’s Constructor Is
Always Invoked
A constructor may invoke an overloaded constructor or
its superclass’s constructor.
If none of them is invoked explicitly, the compiler puts
super() as the first statement in the constructor.
For example,
is equivalent to public A() { super();
public A() {
}
}

public A(double d) { public A(double d) {


// some statements is equivalent to super();
} // some statements
}

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
6
Using the Keyword super

The keyword super refers to the superclass of the


class in which super appears.
This keyword can be used in two ways:
 To call a superclass constructor
 To call a superclass method

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd


Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
7
CAUTION

You must use the keyword super to call the superclass


constructor.
Invoking a superclass constructor’s name in a subclass
causes a syntax error.
Java requires that the statement that uses the keyword
super appear first in the constructor.

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
8
Constructor Chaining
•Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain.
This is known as constructor chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");

}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}

public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is
invoked");
}
} ndPearson Education, Ltd.
Fundamentals of Programming II, IT, 2 Batch
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
9
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
1. Start from the main method
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
10
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) { 2. Invoke faculty constructor
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
11
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person { 3. Invoke Employee’s no-
public Employee() { arg constructor
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
12
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person { 4. Invoke Employee(String)
public Employee() { constructor
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
13
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
5. Invoke Person constructor
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
14
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
6. Execute println
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
15
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) { 7. Execute println
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals ofProgramming,
Liang, Introduction to Java Programming II, IT,
Eleventh Edition, (c)2 nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
16
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
} 8. Execute println
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
17
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
} 9. Execute println
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
18
Example on the Impact of a Superclass
without no-arg Constructor

Find out the errors in the program:


public class Apple extends Fruit {
}

class Fruit {
public Fruit(String name) {
[Link]("Fruit's constructor is invoked");
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
19
Defining a Subclass

A subclass inherits from a superclass.


You can also:
Add new properties
Add new methods
Override the methods of the superclass

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
20
Calling Superclass Methods

You could rewrite the printCircle() method in the Circle class as


follows:

public void printCircle() {


[Link]("The circle is created " +
[Link]() + " and the radius is " + radius);
}

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
21
Overriding Methods in the
Superclass
A subclass inherits methods from a superclass.
Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
This is referred to as method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted

/** Override the toString method defined in GeometricObject */


public String toString() {
return [Link]() + "\nradius is " + radius;
}
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
22
NOTE

An instance method can be overridden only if it is


accessible. Thus a private method cannot be
overridden, because it is not accessible outside its
own class. If a method defined in a subclass is
private in its superclass, the two methods are
completely unrelated.

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
23
NOTE

Like an instance method, a static method can be


inherited. However, a static method cannot be
overridden. If a static method defined in the
superclass is redefined in a subclass, the method
defined in the superclass is hidden.

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
24
Overriding vs. Overloading

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
25
The Object Class and Its Methods

Every class in Java is descended from the [Link]


class.
If no inheritance is specified when a class is defined, the
superclass of the class is Object.

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
26
The toString() method in Object
•The toString() method returns a string representation of the
object.
•The default implementation returns a string consisting of a
class name of which the object is an instance, the at sign
(@), and a number representing this object.

Loan loan = new Loan(); [Link]([Link]());

oThe code displays something like Loan@15037e5.


oThis message is not very helpful or informative.
oUsually you should override the toString method so that it
returns a digestible string representation of the object.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd


Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
27
Polymorphism
oPolymorphism means that a variable of a supertype can refer
to a subtype object.
oA class defines a type.
oA type defined by a subclass is called a subtype, and a
type defined by its superclass is called a supertype.
oTherefore, you can say that Circle is a subtype of
GeometricObject and GeometricObject is a supertype for
Circle.

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
28
Polymorphism, Dynamic Binding
and Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) { Method m takes a parameter of the
m(new GraduateStudent()); Object type. You can invoke it with
m(new Student());
m(new Person());
any object.
m(new Object()); An object of a subtype can be used
} wherever its supertype value is
public static void m(Object x) {
required. This feature is known as
[Link]([Link]());
} polymorphism.
}
class GraduateStudent extends Student {
} When the method m(Object x) is executed,
the argument x’s toString method is invoked.
class Student extends Person { x may be an instance of GraduateStudent,
public String toString() { Student, Person, or Object. Classes
return "Student"; GraduateStudent, Student, Person, and Object
} have their own implementation of the toString
} method. Which implementation is used will
class Person extends Object { be determined dynamically by the Java
public String toString() {
Virtual Machine at runtime. This capability
return "Person";
}
known as dynamic binding.
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd
Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
29
Dynamic Binding
•Dynamic binding works as follows: Suppose an object o is an
instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a
subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a subclass
of Cn.
•That is, Cn is the most general class, and C1 is the most
specific class.
•In Java, Cn is the Object class.
•If o invokes a method p, the JVM searches the implementation
for the method p in C1, C2, ..., Cn-1 and Cn, in this order, until it
is found.
•Once an implementation is found, the search stops and the
first-found implementation is invoked.

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
30
Method Matching vs. Binding
•Matching a method signature and binding a method
implementation are two issues.
•The compiler finds a matching method according to parameter
type, number of parameters, and order of the parameters at
compilation time.
•A method may be implemented in several subclasses. The Java
Virtual Machine dynamically binds the implementation of the
method at runtime.

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
31
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) { Polymorphism allows methods to be
m(new GraduateStudent()); used generically for a wide range of
m(new Student()); object arguments.
m(new Person()); This is known as generic programming.
m(new Object());
} If a method’s parameter type is a
public static void m(Object x) { superclass (e.g., Object), you may pass
[Link]([Link]()); an object to this method of any of the
} parameter’s subclasses (e.g., Student or
}
String).
class GraduateStudent extends Student { When an object (e.g., a Student object or
} a String object) is used in the method,
the particular implementation of the
class Student extends Person { method of the object that is invoked
public String toString() {
(e.g., toString) is determined
return "Student";
} dynamically.
}
class Person extends Object {
public String toString() {
return "Person";
}
}
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd
Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
32
Casting Objects
•You have already used the casting operator to convert variables of one
primitive type to another.
•Casting can also be used to convert an object of one class type to another
within an inheritance hierarchy.
•In the preceding section, the statement
m(new Student());

assigns the object new Student() to a parameter of the Object type.


•This statement is equivalent to:

Object o = new Student(); // Implicit casting


m(o);

•The statement Object o = new Student (), as implicit casting, is legal because an
instance of Student is automatically an instance of Object.

Fundamentals of Programming
Liang, Introduction to Java Programming, EleventhII, IT,
Edition, 2
(c) nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
33
Why Casting Is Necessary?
•Suppose you want to assign the object reference o to a variable of the
Student type using the following statement:

Student b = o;
A compile error would occur.

•Why does the statement Object o = new Student() work and the statement
Student b = o doesn’t?
•This is because a Student object is always an instance of Object, but an
Object is not necessarily an instance of Student.
•Even though you can see that o is really a Student object, the compiler is
not so clever to know it. To tell the compiler that o is a Student object, use
an explicit casting. The syntax is similar to the one used for casting among
primitive data types. Enclose the target object type in parentheses and place
it before the object to be cast, as follows:

Student b = (Student)o; // Explicit casting


Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.
Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
34
Casting from Superclass to
Subclass
•Explicit casting must be used when casting an object from a
superclass to a subclass.
•This type of casting may not always succeed.

Apple x = (Apple)fruit;
Orange x = (Orange)fruit;

Fundamentals of Programming,
Liang, Introduction to Java Programming Eleventh II, IT,
Edition, nd Batch
(c)22018 Pearson Education, Ltd.
All rights reserved.
35
The instanceof Operator
•Use the instanceof operator to test whether an object is an
instance of a class:
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of Circle */
if (myObject instanceof Circle) {
[Link]("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
36
TIP
To help understand casting, you may also consider
the analogy of fruit, apple, and orange with the Fruit
class as the superclass for Apple and Orange.
An apple is a fruit, so you can always safely assign an
instance of Apple to a variable for Fruit. However, a
fruit is not necessarily an apple, so you have to use
explicit casting to assign an instance of Fruit to a
variable of Apple.

Fundamentals of Programming,
Liang, Introduction to Java Programming Eleventh II, IT,
Edition, nd Batch
(c)22018 Pearson Education, Ltd.
All rights reserved.
37
The equals Method
•The equals() method compares the contents of two objects.
• The default implementation of the equals method in the Object
class is as follows:
public boolean equals(Object obj) {
return this == obj;
}

public boolean equals(Object o) {


For example, the equals if (o instanceof Circle) {
method is overridden in return radius ==
the Circle class. ((Circle)o).radius;
}
else
return false;
}

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd


Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
38
NOTE

The == comparison operator is used for comparing


two primitive data type values or for determining
whether two objects have the same references.
The equals method is intended to test whether two
objects have the same contents, provided that the
method is modified in the defining class of the
objects. The == operator is stronger than the equals
method, in that the == operator checks whether the
two reference variables refer to the same object

Fundamentals of Programming II, IT, 2 Batch ndPearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
39
The ArrayList Class
You can create an array to store objects. But the array’s size is
fixed once the array is created. Java provides the ArrayList class
that can be used to store an unlimited number of objects.
[Link]<E>

+Arra yList( ) Creates an empty list.


+add( o: E) : voi d Appends a new element o at the end of this list.
+add( index: int, o: E) : v oid Adds a ne w element o at the specified index in this list.
+clea r(): v oid Removes all the elements from this list.
Returns true if this list contains the element o.
+cont ains(o : Obj ect): bool ean
Re turns the element from this list at the specified index.
+get( index: int) : E
Returns the index of the first matching element in this list.
+inde xOf(o: Obje ct) : int Returns true if this list contains no elements.
+isEm pty(): bool ean Returns the index of the last matching element in this list.
+last IndexO f(o: Objec t) : int Re moves the element o from this list.
+remo ve(o: Objec t): b oolea n Returns the number of elements in this list.
+size (): in t Re moves the element at the specified index.
+remo ve(ind ex: i nt) : bool ean Sets the e lement at the specified index.
+set( index: int, o: E) : E

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
40
Generic Type

•ArrayList is known as a generic class with a generic


type E.
•You can specify a concrete type to replace E when creating
an ArrayList.
•For example, the following statement creates an
ArrayList and assigns its reference to variable cities.
•This ArrayList object can be used to store strings.
•ArrayList<String> cities = new ArrayList<String>();
•ArrayList<String> cities = new ArrayList<>();

Fundamentals ofProgramming,
Liang, Introduction to Java Programming II, IT,
Eleventh Edition, (c)2 nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
41
Differences and Similarities between
Arrays and ArrayList

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
42
Array Lists from/to Arrays
1. Creating an ArrayList from an array of objects:

String[] array = {"red", "green", "blue"};


ArrayList<String> list = new
ArrayList<>([Link](array));

2. Creating an array of objects from an ArrayList:

String[] array1 = new String[[Link]()];


[Link](array1);

Fundamentals ofProgramming,
Liang, Introduction to Java Programming II, IT,
Eleventh Edition, (c)2 nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
43
max and min in an Array List
String[] array = {"red", "green", "blue"};
[Link]([Link](
new ArrayList<String>([Link](array)));

String[] array = {"red", "green", "blue"};


[Link]([Link]( new
ArrayList<String>([Link](array)));

Fundamentals ofProgramming,
Liang, Introduction to Java Programming II, IT,
Eleventh Edition, (c)2 nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
44
Shuffling an Array List

Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5};


ArrayList<Integer> list = new ArrayList<>([Link](array));
[Link](list);
[Link](list);

Fundamentals of Programming II, IT, 2 Batch nd Pearson Education, Ltd.


Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018
All rights reserved.
45
The protected Modifier

• The protected modifier can be applied on data and


methods in a class.
• A protected data or a protected method in a public class can
be accessed by any class in the same package or its
subclasses, even if the subclasses are in a different package.
• private, default, protected, public

Visibility increases

private, none (if no modifier is used), protected, public

Fundamentals ofProgramming,
Liang, Introduction to Java Programming II, IT,
Eleventh Edition, (c)2 nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
46
Visibility Modifiers

Fundamentals of Programming,
Liang, Introduction to Java Programming Eleventh II, IT,
Edition, nd Batch
(c)22018 Pearson Education, Ltd.
All rights reserved.
47
A Subclass Cannot Weaken the
Accessibility
•A subclass may override a protected method in its
superclass and change its visibility to public.
•However, a subclass cannot weaken the
accessibility of a method defined in the superclass.
•For example, if a method is defined as public in the
superclass, it must be defined as public in the
subclass.

Fundamentals of Programming
Liang, Introduction to Java Programming, EleventhII, IT,
Edition, 2
(c) nd Batch
2018 Pearson Education, Ltd.
All rights reserved.
48
NOTE

•The modifiers are used on classes and class


members (data and methods), except that the final
modifier can also be used on local variables in a
method.
•final local variable is a constant inside a method.

Fundamentals
Liang, Introduction toof Programming
Java Programming, EleventhII, IT,
Edition, (c)nd2018
2 Batch
Pearson Education, Ltd.
All rights reserved.
49
The final Modifier

✦ The final class cannot be extended:


final class Math {
...
}

✦ The final variable is a constant:

final static double PI = 3.14159;

✦ The final method cannot be overridden by its


subclasses.

Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018nd


Fundamentals of Programming II, IT, 2 Batch Pearson Education, Ltd.
All rights reserved.
50
Recursion

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
1
Motivations
Suppose you want to find all the files under a
directory that contains a particular word. How do
you solve this problem? There are several ways to
solve this problem. An intuitive solution is to use
recursion by searching the files in the
subdirectories recursively.

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
2
Objectives
 To describe what a recursive method is and the benefits of using recursion
(§18.1).
 To develop recursive methods for recursive mathematical functions (§§18.2–
18.3).
 To explain how recursive method calls are handled in a call stack (§§18.2–18.3).
 To solve problems using recursion (§18.4).
 To use an overloaded helper method to derive a recursive method (§18.5).
 To get the directory size using recursion (§18.6).
 To discover the relationship and difference between recursion and iteration
(§18.9).

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
3
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);

n! = n * (n-1)!
0! = 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
4
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4)

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
5
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
6
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
7
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
8
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
9
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
10
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
11
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * 3 * factorial(2)
= 4 * 3 * (2 * factorial(1))
= 4 * 3 * ( 2 * (1 * factorial(0)))
= 4 * 3 * ( 2 * ( 1 * 1)))
= 4 * 3 * ( 2 * 1)
=4*3*2

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
12
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * ( 2 * (1 * factorial(0))))
= 4 * (3 * ( 2 * ( 1 * 1))))
= 4 * (3 * ( 2 * 1))
= 4 * (3 * 2)
= 4 * (6)

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
13
Computing Factorial
factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * ( 2 * (1 * factorial(0))))
= 4 * (3 * ( 2 * ( 1 * 1))))
= 4 * (3 * ( 2 * 1))
= 4 * (3 * 2)
= 4 * (6)
= 24
Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
14
Trace Recursive factorial
Executes factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6 Stack

return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Space Required
Step 4: executes factorial(0) for factorial(4)
Step 5: return 1
Main method
return 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
15
Trace Recursive factorial

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24 Executes factorial(3)
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6 Stack

return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
Space Required
return 1 * factorial(0) for factorial(3)
Step 4: executes factorial(0) Space Required
Step 5: return 1
for factorial(4)
return 1
Main method

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
16
Trace Recursive factorial

factorial(4) Executes factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3) Stack
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1) Space Required
for factorial(2)
Step 3: executes factorial(1)
Step 6: return 1 Space Required
for factorial(3)
return 1 * factorial(0)
Space Required
Step 4: executes factorial(0) for factorial(4)
Step 5: return 1
Main method
return 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
17
Trace Recursive factorial

factorial(4) Executes factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3) Stack
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2) Space Required
Step 7: return 2 for factorial(1)

return 2 * factorial(1) Space Required


for factorial(2)
Step 3: executes factorial(1)
Step 6: return 1 Space Required
for factorial(3)
return 1 * factorial(0)
Space Required
Step 4: executes factorial(0) for factorial(4)
Step 5: return 1
Main method
return 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
18
Trace Recursive factorial

factorial(4) Executes factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Stack
Step 1: executes factorial(3)
Step 8: return 6
Space Required
return 3 * factorial(2) for factorial(0)
Space Required
Step 2: executes factorial(2) for factorial(1)
Step 7: return 2
Space Required
return 2 * factorial(1) for factorial(2)
Step 3: executes factorial(1) Space Required
Step 6: return 1
for factorial(3)
return 1 * factorial(0) Space Required
Step 4: executes factorial(0) for factorial(4)
Step 5: return 1
Main method
return 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
19
Trace Recursive factorial

factorial(4) returns 1
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1) Space Required


for factorial(0)
Space Required
Step 3: executes factorial(1) for factorial(1)
Step 6: return 1
Space Required
for factorial(2)
return 1 * factorial(0)
Space Required
for factorial(3)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
20
Trace Recursive factorial

factorial(4) returns factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6 Stack

return 3 * factorial(2) Space Required


for factorial(0)
Step 2: executes factorial(2) Space Required
Step 7: return 2 for factorial(1)
return 2 * factorial(1) Space Required
for factorial(2)
Step 3: executes factorial(1)
Step 6: return 1 Space Required
for factorial(3)
return 1 * factorial(0)
Space Required
Step 4: executes factorial(0) for factorial(4)
Step 5: return 1
Main method
return 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
21
Trace Recursive factorial

factorial(4) returns factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3) Stack
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2) Space Required
Step 7: return 2 for factorial(1)
return 2 * factorial(1) Space Required
for factorial(2)
Step 3: executes factorial(1)
Step 6: return 1
Space Required
return 1 * factorial(0) for factorial(3)

Step 4: executes factorial(0) Space Required


Step 5: return 1 for factorial(4)
return 1 Main method

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
22
Trace Recursive factorial

factorial(4) returns factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3) Stack
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1) Space Required
for factorial(2)
Step 3: executes factorial(1)
Step 6: return 1 Space Required
return 1 * factorial(0) for factorial(3)

Step 4: executes factorial(0) Space Required


Step 5: return 1 for factorial(4)
return 1 Main method

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
23
Trace Recursive factorial

factorial(4) returns factorial(3)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0) Space Required
Step 5: return 1 for factorial(3)
Space Required
return 1 for factorial(4)
Main method

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
24
Trace Recursive factorial
returns factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6 Stack

return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0) Space Required
Step 5: return 1 for factorial(4)

return 1 Main method

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
25
factorial(4) Stack Trace
5 Space Required
for factorial(0)

4 Space Required
for factorial(1)
Space Required
for factorial(1)

3 Space Required
for factorial(2)
Space Required
for factorial(2)
Space Required
for factorial(2)

2 Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)

1 Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)

6 Space Required
for factorial(1)
Space Required 7 Space Required
for factorial(2) for factorial(2)
Space Required Space Required 8 Space Required
for factorial(3) for factorial(3) for factorial(3)
Space Required Space Required Space Required 9 Space Required
for factorial(4) for factorial(4) for factorial(4) for factorial(4)

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
26
Other Examples
f(0) = 0;
f(n) = n + f(n-1);

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
27
Fibonacci Numbers
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89…
indices: 0 1 2 3 4 5 6 7 8 9 10 11

fib(0) = 0;
fib(1) = 1;
fib(index) = fib(index -1) + fib(index -2); index >=2

fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0)


+fib(1) = 1 + fib(1) = 1 + 1 = 2

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
28
Fibonnaci Numbers, cont.
fib(4)
17: return fib(4) 0: call fib(4)

return fib(3) + fib(2)


11: call fib(2)
10: return fib(3)

1: call fib(3) 16: return fib(2)

return fib(2) + fib(1) return fib(1) + fib(0)


7: return fib(2) 8: call fib(1) 14: return fib(0)
2: call fib(2) 13: return fib(1) 12: call fib(1)

9: return fib(1) 15: return fib(0)


return fib(1) + fib(0) return 1 return 1 return 0
4: return fib(1) 5: call fib(0)

3: call fib(1)

return 1 6: return fib(0) return 0

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
29
Characteristics of Recursion
All recursive methods have the following characteristics:
– One or more base cases (the simplest case) are used to stop
recursion.
– Every recursive call reduces the original problem, bringing it
increasingly closer to a base case until it becomes that case.
In general, to solve a problem using recursion, you break it
into subproblems.
–If a subproblem resembles the original problem, you can apply
the same approach to solve the subproblem recursively.
This subproblem is almost the same as the original problem
in nature with a smaller size.

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
30
Directory Size
This section presents a problem that is difficult to solve
without using recursion. The problem is to find the size
of a directory. The size of a directory is the sum of the
sizes of all files in the directory. A directory may contain
subdirectories. Suppose a directory contains files , , ..., ,
and subdirectories , , ..., , as shown below.

directory

f1 f2 ... fm d1 d2 ... dn
1 1 1 1 1 1

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
31
Directory Size
The size of the directory can be defined recursively as
follows:
size (d )  size ( f1 )  size ( f 2 )  ...  size ( f m )  size (d1 )  size (d 2 )  ...  size (d n )

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
32
Recursion vs. Iteration
Recursion is an alternative form of program
control. It is essentially repetition without a loop.

Recursion bears substantial overhead. Each time the


program calls a method, the system must assign
space for all of the method’s local variables and
parameters. This can consume considerable
memory and requires extra time to manage the
additional space.

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
33
Advantages of Using Recursion
Recursion is good for solving the problems that are
inherently recursive.

Fundamentals of Programming II, IT, 2 Batch ndEducation, Inc. All


Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson
rights reserved.
34
Exception Handling

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
1
Motivations
When a program runs into a runtime error, the
program terminates abnormally. How can you
handle the runtime error so that the program can
continue to run or terminate gracefully? This is the
subject we will introduce in this chapter.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
2
Objectives
 To get an overview of exceptions and exception handling (§12.2).
 To explore the advantages of using exception handling (§12.2).
 To distinguish exception types: Error (fatal) vs. Exception (nonfatal) and checked vs.
unchecked (§12.3).
 To declare exceptions in a method header (§12.4.1).
 To throw exceptions in a method (§12.4.2).
 To write a try-catch block to handle exceptions (§12.4.3).
 To explain how an exception is propagated (§12.4.3).
 To obtain information from an exception object (§12.4.4).
 To develop applications with exception handling (§12.4.5).
 To use the finally clause in a try-catch block (§12.5).
 To use exceptions only for unexpected errors (§12.6).
 To rethrow exceptions in a catch block (§12.7).
 To create chained exceptions (§12.8).
 To define custom exception classes (§12.9).

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
3
Exception Advantages

•The advantages of using exception handling.


•It enables a method to throw an exception to its caller.
•Without this capability, a method must handle the
exception or terminate the program.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
4
Exception Types
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
5
System Errors
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError
System errors are thrown by
JVM and represented in the Error VirtualMachineError
Error class. The Error class
describes internal system errors.
Many more classes
Such errors rarely occur. If one
does, there is little you can do
beyond notifying the user and
trying to terminate the program
gracefully.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson
nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
6
Exceptions
Exception describes errors
caused by your program ClassNotFoundException
and external ArithmeticException
circumstances. These IOException
errors can be caught and Exception NullPointerException
handled by your program.
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
7
Runtime Exceptions
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError
RuntimeException is caused
Error VirtualMachineError
by programming errors, such
as bad casting, accessing an
out-of-bounds array, and
Many more classes
numeric errors.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
8
Checked Exceptions vs.
Unchecked Exceptions

•RuntimeException, Error and their subclasses are


known as unchecked exceptions.
•All other exceptions are known as checked
exceptions,
•meaning that the compiler forces the programmer to
check and deal with the exceptions.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
9
Unchecked Exceptions
In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable.
For example, a NullPointerException is thrown if you access an
object through a reference variable before an object is assigned to it;
an IndexOutOfBoundsException is thrown if you access an element
in an array outside the bounds of the array.
These are the logic errors that should be corrected in the program.
Unchecked exceptions can occur anywhere in the program.
To avoid cumbersome overuse of try-catch blocks, Java does not
mandate you to write code to catch unchecked exceptions.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
10
Unchecked Exceptions
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError Unchecked


exception.

Many more classes

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
11
Declaring, Throwing, and
Catching Exceptions

method1() { declare exception


method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
12
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as
declaring exceptions.

public void myMethod()


throws IOException

public void myMethod()


throws IOException, OtherException

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
13
Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate exception
type and throw it. This is known as throwing an
exception. Here is an example,

throw new TheException();

TheException ex = new TheException();


throw ex;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
14
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
15
Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
16
Catching Exceptions
An exception
is thrown in
try try try method3

catch catch catch

Call Stack
method3

method2 method2

method1 method1 method1

main method main method main method main method

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
17
Catch or Declare Checked Exceptions
Suppose p2 is defined as follows:

void p2() throws IOException {


if (a file does not exist) {
throw new IOException("File does not exist");
}

...
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
18
Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).

void p1() { void p1() throws IOException {


try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}

(a) (b)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
19
Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
20
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
21
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
22
Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
23
Trace a Program Execution
Next statement in the
try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
24
Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
25
Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
26
Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
27
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
28
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
29
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
30
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
31
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}

Next statement;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
32
Cautions When Using Exceptions
 Exceptionhandling separates error-handling
code from normal programming tasks, thus
making programs easier to read and to modify.
 Beaware, however, that exception handling
usually requires more time and resources
because it requires instantiating a new exception
object, rolling back the call stack, and
propagating the errors to the calling methods.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
33
When to Throw Exceptions
 An exception occurs in a method.
– If you want the exception to be processed by its
caller, you should create an exception object and
throw it.
– If you can handle the exception in the method where
it occurs, there is no need to throw it.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
34
When to Use Exceptions
When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
[Link]([Link]());
}
catch (NullPointerException ex) {
[Link]("refVar is null");
}
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson
nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
35
When to Use Exceptions
is better to be replaced by
if (refVar != null)
[Link]([Link]());
else
[Link]("refVar is null");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
36
Defining Custom Exception Classes
 Use the exception classes in the API whenever possible.
 Define custom exception classes if the predefined
classes are not sufficient.
 Define custom exception classes by extending
Exception or a subclass of Exception.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson


nd Education, Inc. All
Fundamentals of Programming II, IT, 2 Batch
rights reserved.
37

You might also like