You are on page 1of 99

Chapter One: Methods, Arrays

Introducing Methods
 A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method

modifier return value type method name formal parameters

method
public static int max(int num1, int num2) { int z = max(x, y);
header

int result;
method actual parameters
body parameter list (arguments)
if (num1 > num2)
result = num1;
else
result = num2;
return value
return result;
}
Introducing Methods……
• Method signature is the combination of the method
name and the parameter list.
• The variables defined in the method header are known
as formal parameters or simply parameter.
• You need to declare a separate data type for each
parameter. For instance, int num1,num2 should be
replaced by int num1, int num2.
• When a method is invoked, you pass a value to the
parameter. This value is referred to as actual parameter
or argument.
Introducing Methods……

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.
Calling a method
 This program demonstrates calling a method max to return
the largest of the int values
Calling a method…..
 public class TestMax {
 /** Main method */
 public static void main(String[] args) {
 int i = 5;
 int j = 2;
 int k = max(i, j);
 System.out.println("The maximum between " + i + “
 and " + j + " is " + k);
 }
 /** Return the max between two numbers */
 public static int max(int num1, int num2) {
 int result;
 if (num1 > num2)
 result = num1;
 else
 result = num2;
 return result;
 }
Calling a method…..

pass the value of i


pass the value of

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

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

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

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

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

12
animation
Trace Method Invocation….
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;
}

13
animation
Trace Method Invocation….
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;
}

14
animation
Trace Method Invocation….
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;
}

15
animation
Trace Method Invocation….
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;
}

16
animation
Trace Method Invocation….
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;
}

17
Reuse Methods from Other Classes
 One of the benefits of methods is for reuse.

 The max method can be invoked from any (as it is


declared public) class besides TestMax.

If you create a new class Test, you can invoke the
max method using ClassName.methodName(…)
(because it is declared static).
Example:
• Math.sqrt(900.0)
• TestMax.max
Reuse Methods from Other Classes

 If it were not declared static the method is


accessed using instance of the class, object.

ClassName cn = new ClassName(…);


cn.methodName(…);
Call Stacks

Space required for the


max method
result: 5
num2: 2
num1: 5
Space required for the Space required for the Space required for the
main method main method main method
k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2
i: 5 i: 5 i: 5

The main method The max method is The max method is The main method
is invoked. invoked. finished and the return is finished.
value is sent to k.

20
animation

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);
System.out.println(
"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;
}

21
animation

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);
System.out.println(
"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;
}

22
animation

Trace Call Stack

Declare k

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"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;
}

23
animation

Trace Call Stack

Invoke max(i, j)

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"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;
}

24
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);
System.out.println(
"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.

25
animation
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);
System.out.println(
"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.

26
animation
Trace Call Stack

(num1 > num2) is true

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"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.

27
animation
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
System.out.println( 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.

28
animation
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
System.out.println( 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.

29
animation

Trace Call Stack

Execute print statement

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
System.out.println(
"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;
}

30
Passing Parameters
 There are two ways to pass a variable to the called
function: Pass by value and pass by reference
 Example (C++ code)
Passing Parameters…
Pass by value (how it
works)
•The contents of
memory of   i  and j
 don't change

•Pass by reference (how it


works)
The contents of memory of   i  
and  j   change

Java is strictly pass by value


Overloading Methods
 Defining more than one methods with the same
name but different parameter lists within one class.

 The Java compiler determines which method is used


based on the method signature.
Overloading Methods……
Ambiguous Invocation
 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.


Example: max(1,2);

 Ambiguous invocation is a compilation error.


35
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
 public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
36
Benefits of Methods
• Write a method once and reuse it anywhere.
• Avoids “reinventing a wheel”
• Information hiding. Hide the implementation from the
user.
• You can think of the method body as a black box
that contains the detailed implementation for the
method.
• Reduce complexity.
Methods defined in the Math Class

 Class constants:
• PI
• E (base of natural
logarithm)
 Class methods:
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods
Trigonometric Methods
 public static double sin(double redians)
 public static double cos(double redians)
 public static double tan(double redians)
 public static double asin(double redians)
 public static double acos(double redians)
 public static double atan(double redians)
 public static double toRadians(double degree)
 public static double toDegrees(double degree)
Trigonometric Methods …….
Examples:

Math.sin(0) returns 0.0


Math.sin(Math.PI / 6) returns 0.5
Math.sin(Math.PI / 2) returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6) returns 0.866
Math.cos(Math.PI / 2) returns 0
Exponent Methods
 public static double exp(double a)
Returns e raised to the power of a.
 public static double log(double a)
Returns the natural logarithm of a. (ln(x) = loge(x))
 public static double log10(double a)
Returns the 10-based logarithm of a.
 public static double pow(double a, double b)
Returns a raised to the power of b.
 public static double sqrt(double a)
Returns the square root of a.
Exponent Methods
Examples:

Math.exp(1) returns 2.71


Math.log(2.71) returns 1.0
Math.pow(2, 3) returns 8.0
Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns 22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5) returns 3.24
Rounding Methods
 public static double ceil(double x)
x rounded up to its nearest integer. This integer is returned
as a double value.
 public static double floor(double x)
x is rounded down to its nearest integer. This integer is
returned as a double value.
 public static 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.
 public static int round(float x)
Return (int)Math.floor(x+0.5).
 public static long round(double x)
Return (long)Math.floor(x+0.5).
Rounding Methods, example
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.rint(2.1) returns 2.0
Math.rint(2.0) returns 2.0
Math.rint(-2.0) returns –2.0
Math.rint(-2.1) returns -2.0
Math.rint(2.5) returns 2.0
Math.rint(-2.5) returns -2.0
Math.round(2.6) returns 3
Math.round(2.0) returns 2
Math.round(-2.0) returns -2
Math.round(-2.6) returns -3
min, max, and abs
 max(a, b)and min(a, b) Examples:
Returns the maximum or minimum
of two parameters.
Math.max(2, 3) returns 3
 abs(a) Math.max(2.5, 3) returns
Returns the absolute value of the 3.0
parameter. Math.min(2.5, 3.6) returns
 random() 2.5
Returns a random double value Math.abs(-2) returns 2
in the range [0.0, 1.0). Math.abs(-2.1) returns 2.1
The random Method
Generates a random double value greater than or equal to 0.0 and
less than 1.0 (0.0 <= Math.random() < 1.0).

Examples:

Returns a random integer


(int)(Math.random() * 10)
between 0 and 9.

50 + (int)(Math.random() * 50) Returns a random integer


between 50 and 99.

In general,

a + Math.random() * b Returns a random number between


a and a + b, excluding a + b.
Arrays
 In Java and other programming languages, there is one
capability wherein we can use one variable to store a
list of data and manipulate them more efficiently.

 This type of variable is called an array.


 Array is a data structure that represents a collection of
the same types of data, but it is often more useful to
think of an array as a collection of variables of the same
type.
Arrays…..
 Instead of declaring individual variables, such as
number0,number1,….., and number99, you declare one
array variable such as numbers and use numbers[0],
numbers[1],…., and numbers[99] to represent
individual variables.

 An array stores multiple data items of the same data


type, in a contiguous block of memory, divided into a
number of slots.
Declaring Arrays
 To use an array in a program, you must declare a variable
to reference the array.
 To declare an array, write the data type, followed by a set
of square brackets[], followed by the identifier name.
dataType[] arrayRefVar ; //preferred
or
dataType arrayRefVar[];
Where:
• dataType specifies the kind of values the array stores
• the brackets [] indicate this is an array
• arrayRefVar is the handle to access the array
Creating Arrays
 Unlike declaration for primitive data type variables, the
declaration of an array variable does not allocate any space
in memory for the array. Only a storage location for the
reference to an array is created.

 We can not assign a elements to an array unless it has


already been created.

 There are two different ways to create an array:


• Using array literals
• Using new operator
Creating Arrays….
 Array instantiation using literals
 We can declare an array, creating an array, and initializing
in one statement.

int[] Id = {100, 101, 102, 103, 104, 105};


final String[] names = {“Tom”, “John”, “Ann”};

 We 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};
Creating Arrays….

 We can create an array by using the new operator with the


following syntax:
dataType[] arrayRefVar = new
dataType[arraySize];
OR
dataType[] arrayRefVar
arrayRefVar = new dataType[arraySize];
 Here is an example of such a statement:
double[] myList = new double[10];

int[] num;
num = new int[10];
Creating Arrays….

• Once an array is declared and constructed, the


stored value of each member of the array will be
initialized to zero for number data.

• For reference data types such as Strings, they are


NOT initialized to blanks or an empty string “”.
• Therefore, you must populate the String arrays
explicitly.
Accessing Array Element
 To access an array element, or a part of the array, we use
the name of an array and a number called an index or a
subscript.
 The name of an array is the name we gave to our array
during its declaration.
 index number or subscript
• assigned to each member of the array, to allow the
program to access an individual member of the array.
• begins with zero and progress sequentially by whole
numbers to the end of the array.
• NOTE: Elements inside your array are from 0 to
(sizeOfArray-1).
Accessing Array Element…
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

Note: myList[7] 45.45


myList[2] = 3.3 myList[8] 99.993
myList[5] = 34.33 myList[9] 11123
myList[6] = 34
myList[8] = 99.993
Accessing Array Element…
 Often a for() loop is used to process each of the
elements of the array in turn.
 In order to get the number of elements in an array, you
can use the length field/attribute of an array.

int[] a = new int[100];


for (int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random() * 100);
Example
}

int sum = 0;
for (int i = 0; i < a.length; i++)
sum += a[i];
System.out.println(“ Total = “ + sum);
Accessing Array Element…
 If we only need to reference the value of each of the elements, you
can use the somewhat simpler enhanced for loop (also known as
the foreach loop), which traverse the complete array sequentially
without using an index variable.
 The foreach loop only gets the values, so it couldn't have been
used to set the values in the first loop above.
Example

for(double element: myList)


{
System.out.println(element)
}

 we can read as “for each element in myList do the following”


For-each Loop example
Here is a loop written as both a for-each loop and a
basic for loop to add all elements of an array

double[] ar = {1.2, 3.0, 0.8};


int sum = 0;

for (int i = 0; i < ar.length; i++) {


Sum += ar[i];
}
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;

for (double d : ar)


{
sum += d;
} 58
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;
 
Before the assignment After the assignment
list2 = list1; list2 = list1;

list1 list1
Contents Contents
of list1 of list1

list2 list2
Contents Contents
of list2 of list2
Garbage

59
Copying Arrays …..
 There are three ways to copy arrays:
 Use a loop to copy individual elements on by one
 Use the static arraycopy method in the System class
 Use the clone method to copy arrays
Copying Arrays ….
Using a loop:

int[] sourceArray = {2, 3, 1, 5, 10};


int[] targetArray = new int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];

61
Copying Arrays ….

The arraycopy Utility:

arraycopy(sourceArray, src_pos, targetArray,


tar_pos, length);

 The parameter src_pos and tar_pos indicates the starting


position in sourceArray and targetArray, respectively.

 The number of elements copied from sourceArray to


targetArray is idicated by length.

62
Copying Arrays ….

Example:
System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);

 The arraycopy method does not allocate memory space


for the target array. The target array must have already
been created with its memory space allocated.

 After the copying takes place, targetArray and


sourceArray have the same content but independent
memory location.
63
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(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

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

65
Pass By Value

Java uses pass by value to pass parameters 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.

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

67
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
 
System.out.println("x is " + x);
System.out.println("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]
}
}
68
Pass By Value

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

69
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list

result

int[] list1 = new int[]{1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1);

70
animation

Trace the reverse Method


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Declare result and create array
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0

71
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0

72
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (= 0) is less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1; i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 0

73
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; i = 0 and j = 5
int[] list2 = reverse(list1); Assign list[0] to result[5]

public static int[] reverse(int[] list) {


int[] result = new int[list.length];
 
for (int i = 0, j = result.length – 1;i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1

74
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1); After this, i becomes 1
and j becomes 4
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length – 1;i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1

75
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

i (=1) is less than 6


public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 0 1

76
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6}; i = 1 and j = 4
int[] list2 = reverse(list1); Assign list[1] to result[4]

public static int[] reverse(int[] list) {


int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1

77
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{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[list.length];
 
for (int i = 0, j = result.length – 1;i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1

78
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=2) is still less than
public static int[] reverse(int[] list) { 6
int[] result = new int[list.length];
 
for (int i = 0, j = result.length – 1;i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 0 2 1

79
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 2 and j = 3
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length – 1;i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1

80
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 3
public static int[] reverse(int[] list) { and j becomes 2
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1; i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1

81
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{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[list.length];
 
for (int i = 0, j = result.length - 1; i < list.length; i++, j--){
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 0 3 2 1

82
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 3 and j = 2
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1

83
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 4
public static int[] reverse(int[] list) { and j becomes 1
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1

84
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=4) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 0 4 3 2 1

85
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 4 and j = 1
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1

86
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 5
public static int[] reverse(int[] list) { and j becomes 0
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1

87
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=5) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 0 5 4 3 2 1

88
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 5 and j = 0
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1

89
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 6
public static int[] reverse(int[] list) { and j becomes -1
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1

90
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=6) < 6 is false. So exit
public static int[] reverse(int[] list) { the loop.
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

result 6 5 4 3 2 1

91
animation

Trace the reverse Method, cont.


int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Return result
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
 
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
 
return result;
}

list 1 2 3 4 5 6

list2
result 6 5 4 3 2 1

92
Multi-Dimensional Array
 Multidimensional arrays are implemented as arrays of arrays.
 Multidimensional arrays are declared by appending the
appropriate number of bracket pairs after the array name.
 Example

int[][] twoD = new int[512][128];


char[][][] threeD = new char[8][16][24];
String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
{ "fido", "black“}};
Multi-Dimensional Array…

0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3

1 1 1 4 5 6

2 2 7 2 7 8 9

3 3 3 10 11 12

4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
Multi-Dimensional Array…
 To access an element in a multidimensional array is
just the same as accessing the elements in a one
dimensional array.
 For example, to access the first element in the first row
of the array dogs, we write,
System.out.print( dogs[0][0] );
 This will print the String "terry" on the screen.
 Use nested loops to access each and every element of
multidimensional arrays
Jagged/Ragged Arrays
 Multidimensional arrays with equal number of row
slots are called rectangular arrays

 Jagged arrays are two-dimensional Arrays with row


slots of different Lengths.
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}, matrix.length is 5
{2, 3, 4, 5}, matrix[0].length is 5
matrix[1].length is 4
{3, 4, 5}, matrix[2].length is 3
{4, 5}, matrix[3].length is 2
matrix[4].length is 1
{5}
};
97
Ragged Arrays, cont.

int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 1 2 3 4
{3, 4, 5},
{4, 5}, 1 2 3
{5}
}; 1 2

1 2

98
Ragged Arrays, cont.
 What is the output of the following code?

for ( int row = 0; row < jagged.length; row++ ) {


for ( int col = 0; col <jagged [ row ].length; col++ )
System.out.printf( "%c ", jagged[ row ][ col ] );
System.out.println(); // start new line of output
}

You might also like