slide1 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Chapter One: Methods, Arrays PowerPoint Presentation
Download Presentation
Chapter One: Methods, Arrays

Loading in 2 Seconds...

play fullscreen
1 / 99

Chapter One: Methods, Arrays - PowerPoint PPT Presentation


  • 57 Views
  • Uploaded on

Chapter One: Methods, Arrays. Introducing Methods. A method is a collection of statements that are grouped together to perform an operation. Introducing Methods……. Method signature is the combination of the method name and the parameter list.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Chapter One: Methods, Arrays' - licia


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
slide2

Introducing Methods

  • A method is a collection of statements that are grouped together to perform an operation.
slide3

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 asactual parameter or argument.
introducing methods
Introducing Methods……

A method may return a value.

  • ThereturnValueTypeis the data type of the value the method returns.
  • If the method does not return a value, the returnValueTypeis the keyword void.
  • For example, the returnValueTypein themainmethod is void.
slide5

Calling a method

  • This program demonstrates calling a method max to return the largest of theintvalues
calling a method
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;
  • }
  • }
slide11

Trace Method Invocation….

invoke max(i, j)

Pass the value of i to num1

Pass the value of j to num2

slide12

Trace Method Invocation….

declare variable result

trace method invocation

animation

Trace Method Invocation….

Trace Method Invocation

(num1 > num2) is true since num1 is 5 and num2 is 2

trace method invocation1

animation

Trace Method Invocation….

Trace Method Invocation

result is now 5

trace method invocation2

animation

Trace Method Invocation….

Trace Method Invocation

return result, which is 5

trace method invocation3

animation

Trace Method Invocation….

Trace Method Invocation

return max(i, j) and assign the return value to k

trace method invocation4

animation

Trace Method Invocation….

Trace Method Invocation

Execute the print statement

slide18

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
slide19

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(…);

trace call stack

animation

Trace Call Stack

i is declared and initialized

trace call stack1

animation

Trace Call Stack

j is declared and initialized

trace call stack4
Trace Call Stack

pass the values of i and j to num1 and num2

trace call stack5

animation

Trace Call Stack

pass the values of i and j to num1 and num2

trace call stack6

animation

Trace Call Stack

(num1 > num2) is true

trace call stack7

animation

Trace Call Stack

Assign num1 to result

trace call stack8

animation

Trace Call Stack

Return result and assign it to k

trace call stack9

animation

Trace Call Stack

Execute print statement

slide31

Passing Parameters

  • There are two ways to pass a variable to the called function: Pass by value and pass by reference
  • Example (C++ code)
slide32

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   don't change

Java is strictly pass by value

slide33

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

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

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;

}

}

slide37

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

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
slide39

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

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

slide41

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.

slide42

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

slide43

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

slide44

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.6f) returns 3

Math.round(2.0) returns 2

Math.round(-2.0f) returns -2

Math.round(-2.6) returns -3

slide45

min, max, and abs

Examples:

Math.max(2, 3) returns 3

Math.max(2.5, 3) returns 3.0

Math.min(2.5, 3.6) returns 2.5

Math.abs(-2) returns 2

Math.abs(-2.1) returns 2.1

  • max(a, b)and min(a, b)

Returns the maximum or minimum of two parameters.

  • abs(a)

Returns the absolute value of the parameter.

  • random()

Returns a random double value in the range [0.0, 1.0).

slide46

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:

In general,

slide47

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

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

dataTypearrayRefVar[];

Where:

    • dataTypespecifies the kind of values the array stores
    • the brackets []indicate this is an array
    • arrayRefVar is the handle to access the array
slide50

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
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 arrays1
Creating Arrays….
  • We can create an array by using the new operator with the following syntax:

dataType[] arrayRefVar = newdataType[arraySize];

OR

dataType[] arrayRefVar

arrayRefVar = newdataType[arraySize];

  • Here is an example of such a statement:

double[] myList = new double[10];

int[] num;

num = new int[10];

creating arrays2
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.
slide54

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).
slide55

Accessing Array Element…

Note:

myList[2] = 3.3

myList[5] = 34.33

myList[6] = 34

myList[8] = 99.993

slide56

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 thelengthfield/attribute of an array.

Example

  • int[] a = new int[100];
  • for (int i = 0; i < a.length; i++) {
  • a[i] = (int)(Math.random() * 100);
  • }
  • int sum = 0;
  • for (int i = 0; i < a.length; i++)
  • sum += a[i];
  • System.out.println(“ Total = “ + sum);
slide57

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

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

for(double element: myList)

{

System.out.println(element)

}

slide58

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;

}

slide59

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;

copying arrays
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
slide61

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

slide62

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

Copying Arrays ….

Example:

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

  • Thearraycopymethod 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,targetArrayand sourceArray have the same content but independent memory location.
passing arrays to methods
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

anonymous array
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.

pass by value
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.

pass by value1
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.

simple example
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]

}

}

slide69

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.

returning an array from a method
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;

}

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

int[] list2 = reverse(list1);

list

result

trace the reverse method

animation

Trace the reverse Method

Declare result and create array

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

0

0

trace the reverse method cont

animation

Trace the reverse Method, cont.

i = 0 and j = 5

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

0

0

trace the reverse method cont1

animation

Trace the reverse Method, cont.

i (= 0) is less than 6

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

0

0

trace the reverse method cont2

animation

Trace the reverse Method, cont.

i = 0 and j = 5

Assign list[0] to result[5]

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

0

1

trace the reverse method cont3

animation

Trace the reverse Method, cont.

After this, i becomes 1 and j becomes 4

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

0

1

trace the reverse method cont4

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

trace the reverse method cont5

animation

Trace the reverse Method, cont.

i = 1 and j = 4

Assign list[1] to result[4]

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

2

1

trace the reverse method cont6

animation

Trace the reverse Method, cont.

After this, i becomes 2 and j becomes 3

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

2

1

trace the reverse method cont7

animation

Trace the reverse Method, cont.

i (=2) is still less than 6

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

0

2

1

trace the reverse method cont8

animation

Trace the reverse Method, cont.

i = 2 and j = 3

Assign list[i] to result[j]

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

trace the reverse method cont9

animation

Trace the reverse Method, cont.

After this, i becomes 3 and j becomes 2

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

trace the reverse method cont10

animation

Trace the reverse Method, cont.

i (=3) is still less than 6

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

trace the reverse method cont11

animation

Trace the reverse Method, cont.

i = 3 and j = 2

Assign list[i] to result[j]

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

4

3

2

1

trace the reverse method cont12

animation

Trace the reverse Method, cont.

After this, i becomes 4 and j becomes 1

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

4

3

2

1

trace the reverse method cont13

animation

Trace the reverse Method, cont.

i (=4) is still less than 6

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

4

3

2

1

trace the reverse method cont14

animation

Trace the reverse Method, cont.

i = 4 and j = 1

Assign list[i] to result[j]

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

5

4

3

2

1

trace the reverse method cont15

animation

Trace the reverse Method, cont.

After this, i becomes 5 and j becomes 0

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

5

4

3

2

1

trace the reverse method cont16

animation

Trace the reverse Method, cont.

i (=5) is still less than 6

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

5

4

3

2

1

trace the reverse method cont17

animation

Trace the reverse Method, cont.

i = 5 and j = 0

Assign list[i] to result[j]

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

6

5

4

3

2

1

trace the reverse method cont18

animation

Trace the reverse Method, cont.

After this, i becomes 6 and j becomes -1

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

6

5

4

3

2

1

trace the reverse method cont19

animation

Trace the reverse Method, cont.

i (=6) < 6 is false. So exit the loop.

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

6

5

4

3

2

1

trace the reverse method cont20

animation

Trace the reverse Method, cont.

Return result

int[] list1 = new int[]{1, 2, 3, 4, 5, 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

list2

result

6

5

4

3

2

1

slide93

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

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
slide96

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

Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as a ragged array. For example,

int[][] matrix = {

{1, 2, 3, 4, 5},

{2, 3, 4, 5},

{3, 4, 5},

{4, 5},

{5}

};

matrix.length is 5

matrix[0].length is 5

matrix[1].length is 4

matrix[2].length is 3

matrix[3].length is 2

matrix[4].length is 1

slide99

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

}