Uploaded by Nouran Issam Mohammed

Java Objects and Classes: Basic Concepts Presentation

advertisement
Objects and Classes in Java
(Revision of Basic Concepts)
June 2022
Muhammad Nasir Mumtaz Bhutta
College of Engineering
Abu Dhabi University, Al Ain Campus,
Al Ain, United Arab Emirates
Email: Muhammad.bhutta@adu.ac.ae,
Tel: Ext: 2849
Office: L-385, 3rd floor
www.adu.edu.ae
Objectives – I
 To describe objects and classes, and use classes to model objects
 To use UML graphical notation to describe classes and objects.
• A Simple Java Program.
– Interpreter / Compiler
– Programming Errors
• Elementary Programming.
– Trace a program execution
– Reading Input From Console
– Variables and Data types
• Selection
– Relational Operator
– Logical Operator
– Conditional Statement
2
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Objectives – II
• Loops
– For Loop
– While loop
– Do-while loop
• Methods.
–
–
–
–
Defining Methods / Parameters
Method Invocations
Method Overload
Scope of variables
• Arrays .
– Single Dimensional Array
– Multidimensional Array
3
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Objects and Classes,
Object Oriented Programming In
Java Basics
4
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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.

•
5
For example, a student, a desk, a circle, a button, and even a loan
can all be viewed as objects.
An object has a unique identity, state, and behaviors.

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.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Classes
 Classes are constructs that define objects of the same
type.
6
•
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.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Representing Classes and
Objects
A class template
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Circle Object 2
Circle Object 3
Data Fields:
radius is 10
Data Fields:
radius is 25
Data Fields:
radius is 125
Three objects of
the Circle class
A class and an object has both a state and behavior:
The state defines the object, and
The behavior defines what the object does.
7
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Class Discussion
 How can we differentiate between classes and
objects?
•
Class is a logical entity.
•
Object is a physical entity.
 Each group are required to do the followings:
8
•
Think of an object around you.
•
Think of properties of the object
•
Think of behavior of the objects
•
Now think, how can you create class for these objects ?
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Writing, Compiling and Executing Java Programs
WORKING WITH JAVA TOOLS
9
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Interpreting/Compiling Source Code
 A program written in a high-level language is called a
source program or source code.
•
In Java source program is written in a file with .java
extension.
 Because a computer cannot understand a source
program, a source program must be translated into
machine code for execution.
 The translation can be done using another programming
tool called an interpreter or a compiler.
•
10
.java files are compiled into .class files.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Interpreting Source Code
 An interpreter:
•
Reads one statement from the source code,
•
Translates it to the machine code or virtual machine code,
and then
•
Executes it right away, as shown in the following figure.
 Note that a statement from the source code may be
translated into several machine instructions.
11
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Compiling Source Code
 A compiler:
12
•
translates the entire source code into a machine-code file
(all at once), and
•
the machine-code file is then executed, as shown in the
following figure.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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.
13
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Popular Java IDEs
• Eclipse
• NetBeans (To Be Used in the Labs)
• Let’s search on internet “What is IDE?” and
discuss.
Start the NetBeans to see the components.
The NetBeans practice session will be held in the lab!
14
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Java Program Structure
Understanding Basic Components Of
A Java Program
15
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
A Simple Java Program
Listing 1.1
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
What will be the extension of the file in
which this Java source code will be
written?
16
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Compiling Java Source Code

Java was designed to run object programs on any platform.

With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
(What will be the extension of the bytecode file?)

The bytecode can then run on any computer with a Java Virtual
Machine (JVM), as shown below.
•
17
Java Virtual Machine is a software that interprets Java bytecode.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Programming Errors
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result
18
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Anatomy of a Java Program
• Class name
• Main method
• Statements
• Statement terminator
• Reserved words
• Comments
• Blocks
19
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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) {
System.out.println("Welcome to Java!");
}
}
20
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Identifiers: Naming Classes and
Variables and Methods
 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 in book, “Java Keywords,” for a list of reserved
words).
 An identifier cannot be true, false, or null.
 An identifier can be of any length.
21
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Reserved words
 Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used
for other purposes (e.g. names) 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) {
System.out.println("Welcome to Java!");
}
}
22
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Naming Conventions – I
• 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.
23
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Naming Conventions – II
• Class names:
– Capitalize the first letter of each word
in the name. For example, the class
name Circle.
• Constants:
– Capitalize all letters in constants, and
use underscores to connect words.
For example, the constant PI and
MAX_VALUE
24
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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) {
System.out.println("Welcome to Java!");
}
}
25
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Statement

A statement represents an action or a sequence of actions.

The statement
System.out.println("Welcome to Java!")

in the program 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) {
System.out.println("Welcome to Java!");
}
}
26
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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) {
System.out.println("Welcome to Java!");
}
}
What about brackets { } ?
27
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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) {
System.out.println("Welcome to Java!"); Method block
}
}
28
Dr M Nasir Mumtaz Bhutta
Class block
www.adu.ac.ae
Special Symbols
Character Name
Description
{}
Opening and closing
braces
Opening and closing
parentheses
Opening and closing
brackets
Double slashes
Denotes a block to enclose statements.
Opening and closing
quotation marks
Semicolon
Enclosing a string (i.e., sequence of characters).
()
[]
//
" "
;
29
Used with methods.
Denotes an array.
Precedes a comment line.
Marks the end of a statement.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
JAVA PROGRAM EXECUTION
30
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace a Program Execution
Enter main method
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
31
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace a Program Execution
Execute statement
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
32
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace a Program Execution
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
print a message to the
console
33
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Operands and Operations
VARIABLES
34
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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;
35
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Assignment Statements
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
36
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Declaring and Initializing
in One Step
• int x = 1;
• double d = 1.4;
37
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Named Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
38
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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
(i.e., -9223372036854775808 to 9223372036854775807)
64-bit signed
float
Negative range:
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
32-bit IEEE 754
double
Negative range:
-1.7976931348623157E+308 to -4.9E-324
64-bit IEEE 754
Positive range:
4.9E-324 to 1.7976931348623157E+308
39
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Reading Numbers from the Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();
Method
Description
nextByte()
reads an integer of the byte type.
nextShort()
reads an integer of the short type.
nextInt()
reads an integer of the int type.
nextLong()
reads an integer of the long type.
nextFloat()
reads a number of the float type.
nextDouble() reads a number of the double type.
40
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Numeric Operators
41
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
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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)
42
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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 6 th 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
43
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Exponent Operations
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16
44
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Relational Operators
Java
Operator
Mathematics
Symbol
Name
Example
(radius is 5)
Result
<
<
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
45
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Reading and Writing to the Computer Screen
Basic Input And Output In Java
46
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use the method nextDouble() to obtain to a double
value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
3. Let’s try other methods in Scanner class.
47
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Writing Output to the Console

The statement
System.out.println("Welcome to Java!")

in the program is a statement to display the messages on the
monitor screen "Welcome to Java!“.

Let’s try different options in print and println methods.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
48
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
If – else statement, switch statement
CONDITIONAL STATEMENTS
49
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Logical Operators
Operator
Name
Description
!
not
logical negation
&&
and
logical conjunction
||
or
logical disjunction
^
exclusive or
logical exclusion
50
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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
51
!(weight == 150) is true, because (weight == 150) is false.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Truth Table for Operator &&
p1
p2
p1 && p2 Example (assume age = 24, weight = 140)
false
false false
(age <= 18) && (weight < 140) is false, because (age >
18) and (weight <= 140) are both false.
false
true
false
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.
52
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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
false
true
(age > 14) || (weight >= 150) is false, because
(age > 14) is true.
true
53
true
true
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Truth Table for Operator ^
p1
p2
p1 ^ p2 Example (assume age = 24, weight = 140)
false
false
false
(age > 34) ^ (weight > 140) is true, because (age > 34) is false
and (weight > 140) is false.
false
true
true
(age > 34) ^ (weight >= 140) is true, because (age > 34) is false
but (weight >= 140) is true.
true
false
true
(age > 14) ^ (weight > 140) is true, because (age > 14) is
true and (weight > 140) is false.
true
54
true
false
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
One-way if Statements
if (boolean-expression) {
statement(s);
}
55
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area"
+ " for the circle of radius "
+ radius + " is " + area);
}
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Note
if i > 0 {
System.out.println("i is positive");
}
if (i > 0) {
System.out.println("i is positive");
}
(a) Wrong
(b) Correct
if (i > 0) {
System.out.println("i is positive");
}
Equivalent
if (i > 0)
System.out.println("i is positive");
(b)
(a)
56
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
57
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
58
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Multiple Alternative if Statements
if (score >= 90.0)
System.out.print("A");
else
if (score >= 80.0)
System.out.print("B");
else
if (score >= 70.0)
System.out.print("C");
else
if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Equivalent
This is better
(a)
59
if (score >= 90.0)
System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
(b)
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}
60
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
switch Statement Flow Chart
61
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
switch Statement Rules
The switch-expression
must yield a value of char,
byte, short, or int type and
must always be enclosed in
parentheses.
The value1, ..., and valueN must
have the same data type as the
value of the switch-expression.
The resulting statements in the
case statement are executed when
the value in the case statement
matches the value of the switchexpression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
62
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
switch Statement Rules
The keyword break is optional,
but it should be used at the
end of each case in order to
terminate the remainder of the
switch statement. If the break
statement is not present, the
next case statement will be
executed.
The default case, which is
optional, can be used to perform
actions when none of the
specified cases matches the
switch-expression.
63
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
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.
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Loops (For, While, Do-While)
REPETITIVE STATEMENTS
64
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
Statement(s);
}
65
count++;
}
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcom
e to Java!");
count++;
}
66
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuationcondition);
67
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
for Loops
for (initial-action; loopcontinuation-condition;
action-after-each-iteration) {
// loop body;
Statement(s);
}
68
int i;
for (i = 0; i < 100; i++) {
System.out.println(
"Welcome to Java!");
}
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace for Loop, cont.
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
69
Dr M Nasir Mumtaz Bhutta
Execute initializer
i is now 0
www.adu.ac.ae
Note
 The initial-action in a for loop can be a list of zero or more
comma-separated expressions.
 The action-after-each-iteration in a for loop can be a list of zero or
more comma-separated statements.
 Therefore, the following two for loops are correct. They are rarely
used in practice, however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
70
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Caution
 Adding a semicolon at the end of the for clause before the loop
body is a common mistake, as shown below:
Logic
Error
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
71
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Caution, cont.
 Similarly, the following loop is also wrong:
int i=0;
while (i < 10);
Logic Error
{
System.out.println("i is " + i);
i++;
}
 In the case of the do loop, the following semicolon is needed to end
the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10);
Correct
72
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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) {
// Loop body
}
Equivalent
for ( ; loop-continuation-condition; )
// 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
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(a)
73
(b)
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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.
• 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.
74
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Modules in a Java Class
METHODS
75
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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
(arguments)
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
76
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
77
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Method Signature
Method signature is the combination of the method name and the
parameter list.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
78
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Formal Parameters
The variables defined in the method header are known as
formal parameters.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
79
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
80
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Return Value Type
 A method may return a value.
 The return ValueType 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 return ValueType in the main method is void.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
81
return result;
}
parameter list
method
signature
Dr M Nasir
Bhutta
returnMumtaz
value
www.adu.ac.ae
animation
Calling Methods, cont.
pass the value of i
pass the value of j
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
82
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
i is now 5
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
83
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
j is now 2
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
84
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
invoke max(i, j)
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
85
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
86
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
declare variable result
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
87
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
(num1 > num2) is true since num1
is 5 and num2 is 2
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
88
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
result is now 5
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
89
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
return result, which is 5
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
90
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
return max(i, j) and assign the
return value to k
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
91
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
Trace Method Invocation
Execute the print statement
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}
92
return result;
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
void Method Example
This type of method does not return a value. The method
performs some actions.
93
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Can you invoke the method using
nPrintln(15, “Computer Science”);
94
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Overloading Methods
Overloading the max Method
public static double max(double num1, double
num2) {
if (num1 > num2)
return num1;
else
return num2;
}
95
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Scope of Local Variables
A local variable: a variable defined inside
a method.
Scope: the part of the program where the
variable can be referenced.
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.
96
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Scope of Local Variables, cont.
You 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.
97
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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.
The scope of i
The scope of j
98
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Scope of Local Variables, cont.
It is fine to declare i in two
non-nesting blocks
public static void method1() {
int x = 1;
int y = 1;
It is wrong to declare i in
two nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
for (int i = 1; i < 10; i++) {
sum += i;
}
}
}
99
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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;
}
}
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
100
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;
}
}
101
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Method Abstraction
You can think of the method body as a black
box that contains the detailed
implementation for the method.
Optional arguments
for Input
Optional return
value
Method Header
Black Box
Method body
102
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Benefits of Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
103
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Multiple Variables of Same Type
WORKING WITH ARRAYS
104
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Introducing One Dimensional Arrays
Array is a data structure that represents a collection of the
same types of data.
105
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
• datatype arrayRefVar[]; // This style is
allowed, but not preferred
Example:
double myList[];
106
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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.
107
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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];
108
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
The Length of an Array
Once an array is created, its size is fixed. It
cannot be changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
109
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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.
110
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Indexed Variables
The array elements are accessed through the
index. The array indices are 0-based, i.e., it starts
from 0 to arrayRefVar.length-1. In the example in
Figure 6.1, 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];
111
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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];
112
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Array Initializers
• Declaring, creating, initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one
statement.
113
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand 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;
114
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
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};
115
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
animation
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)
{
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
116
Dr M Nasir Mumtaz Bhutta
After the array is created
0
0
1
0
2
0
3
0
4
0
www.adu.ac.ae
Thanks for listening !
»Questions ?
117
Dr M Nasir Mumtaz Bhutta
www.adu.ac.ae
Download