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

08Chapters 1 - 8_Java Basics Revision

The document provides an overview of objects and classes in Java, focusing on object-oriented programming concepts, class definitions, and the structure of Java programs. It covers essential programming elements such as methods, loops, arrays, and the process of compiling and executing Java code. Additionally, it discusses naming conventions, variable declarations, and basic data types in Java.

Uploaded by

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

08Chapters 1 - 8_Java Basics Revision

The document provides an overview of objects and classes in Java, focusing on object-oriented programming concepts, class definitions, and the structure of Java programs. It covers essential programming elements such as methods, loops, arrays, and the process of compiling and executing Java code. Additionally, it discusses naming conventions, variable declarations, and basic data types in Java.

Uploaded by

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

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: [email protected],
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.
 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.

5 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


Classes

 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.

6 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


Representing Classes and
Objects
Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

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:
• 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 ?

8 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.
• .java files are compiled into .class files.

10 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:
• 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.

12 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.
• Java Virtual Machine is a software that interprets Java bytecode.

17 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 {


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

28 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


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.

29 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 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

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

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

41 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 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

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 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

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 !(weight == 150) is true, because (weight == 150) is false.

51 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

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

> 140) is false.


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

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


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
true false (age > 14) || (weight >= 150) is false, because

(age > 14) is true.


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

true and (weight > 140) is false.

false
true true
54 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s); + " for the circle of radius "
}
+ radius + " is " + area);
}

55 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


Note

if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

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

(a) (b)

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) if (score >= 90.0)


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

(a) (b)

59 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, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in 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.

62 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the
end of each case in order to case value1: statement(s)1;
terminate the remainder of
break;
the switch statement. If the
break statement is not case value2: statement(s)2;
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.

63 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
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s);
count++;
} }

65 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {

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

66 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


do-while Loop

do {
// Loop body;
Statement(s);
} while (loop-continuation-
condition);
67 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae
for Loops
for (initial-action; loop- int i;
continuation-condition;
action-after-each-iteration) { for (i = 0; i < 100; i++) {
// loop body; System.out.println(
Statement(s); "Welcome to Java!");
} }

68 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0

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

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

69 Dr M Nasir Mumtaz Bhutta 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) { 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

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)
73 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
int result; (arguments)

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 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


}

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 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


}

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 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


}

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 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


}

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 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
81 return result; Dr M Nasir
returnMumtaz
value Bhutta www.adu.ac.ae
}
animation

Calling Methods, cont.

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

82 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


i is now 5

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

83 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


j is now 2

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

84 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


invoke max(i, 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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

85 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) { 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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

86 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


declare variable result

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

87 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) { 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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

88 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


result is now 5

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

89 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


return result, which is 5

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

90 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) { 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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

91 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


animation

Trace Method Invocation


Execute the print statement

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;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

92 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.

public static void method1() {


.
.
for (int i = 1; i < 10; i++) {
.
The scope of i .
int j;
.
The scope of j .
.
}
}

98 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


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; }
}
}

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;
}
100 } Dr M Nasir Mumtaz Bhutta www.adu.ac.ae
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 Optional return
for Input 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;

115 myList = {1.9, 2.9, 3.4,


Dr M Nasir 3.5};
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[] After the array is created
args) {
int[] values = new int[5]; 0 0

for (int i = 1; i < 5; i++) { 1 0

values[i] = i + values[i-1]; 2 0

} 3 0

values[0] = values[1] + 4 0

values[4];
}
}

116 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae


Thanks for listening !

»Questions ?

117 Dr M Nasir Mumtaz Bhutta www.adu.ac.ae

You might also like