1 of 140

UNIT-3 METHODS

Defining and calling method, Passing argument by values, Overloading methods and scope

of variables, Method abstraction and stepwise refinement, Single Dimensional arrays,

copying arrays ,Passing and returning array from method, Searching and sorting arrays

and the Array class, Two-Dimensional array and its processing, Passing Two-dimensional

Array to methods, Multidimensional Arrays.

2 of 140

Problem

  • Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

int sum = 0;

for (int i = 1; i <= 10; i++)

sum += i;

System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;

for (int i = 20; i <= 30; i++)

sum += i;

System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;

for (int i = 35; i <= 45; i++)

sum += i;

System.out.println("Sum from 35 to 45 is " + sum);

3 of 140

Solution

public static int sum(int i1, int i2) {

int sum = 0;

for (int i = i1; i <= i2; i++)

sum += i;

return sum;

}

public static void main(String[] args) {

System.out.println("Sum from 1 to 10 is " + sum(1, 10));

System.out.println("Sum from 20 to 30 is " + sum(20, 30));

System.out.println("Sum from 35 to 45 is " + sum(35, 45));

}

4 of 140

Defining Methods

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

public static int

max(

int

num1,

int

num2) {

int

result;

if

(num1 > num2)

result = num1;

else

result = num2;

return

result;

}

modifier

return value

type

method

name

formal

parameters

return value

me

thod

body

method

header

parameter list

Define a method

Invoke a method

int

z = max(x, y);

actual parameters

(arguments)

method

signature

5 of 140

Program

  • This program demonstrates calling a method max to return the largest of the int values.

public class Method_first {

// Method to find the maximum of two integers

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

if (num1 > num2) {

return num1;

} else {

return num2;

}

}

// Main method

public static void main(String[] args) {

// Declare some integer values to find the maximum

int a = 10;

int b = 20;

int c = 30;

int d = 5;

// Call the max method to find the largest value between pairs

int maxAB = max(a, b); // Find the max between a and b

int maxCD = max(c, d); // Find the max between c and d

int finalMax = max(maxAB, maxCD); // Find the max between the previous results

// Display the largest value

System.out.println("The largest value among the four numbers is: " + finalMax);

}

}

6 of 140

Calling Methods

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;

if (num1 > num2)

result = num1;

else

result = num2;

return result;

}

pass the value of i

pass the value of j

7 of 140

Trace Method Invocation

7

i is now 5

8 of 140

Trace Method Invocation

8

j is now 2

9 of 140

Trace Method Invocation

9

invoke max(i, j)

10 of 140

Trace Method Invocation

10

invoke max(i, j)

Pass the value of i to num1

Pass the value of j to num2

11 of 140

Trace Method Invocation

11

declare variable result

12 of 140

Trace Method Invocation

12

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

13 of 140

Trace Method Invocation

13

result is now 5

14 of 140

Trace Method Invocation

14

return result, which is 5

15 of 140

Trace Method Invocation

15

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

16 of 140

Trace Method Invocation

16

Execute the print statement

17 of 140

CAUTION (Method_demo.java )

  • A return statement is required for a value-returning method.
  • The method shown below in (a) is logically correct, but it has a compilation error because the Java compiler thinks it possible that this method does not return any value.

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

public static int sign(int n) {

if (n > 0)

return 1;

else if (n == 0)

return 0;

else if (n < 0)

return –1;

}

Should be

public static int sign(int n) {

if (n > 0)

return 1;

else if (n == 0)

return 0;

else

return –1;

}

18 of 140

Reuse Methods from Other Classes

  • If you create a new class Test, you can invoke the max method using ClassName.methodName (e.g., TestMax.max).

  • Example:: Method_demo2.java

  • Example:: Method_demo1.java(example of non static method)

19 of 140

Call Stacks

20 of 140

Trace Call Stack

20

i is declared and initialized

21 of 140

Trace Call Stack

21

j is declared and initialized

22 of 140

Trace Call Stack

22

Declare k

23 of 140

Trace Call Stack

23

Invoke max(i, j)

24 of 140

Trace Call Stack

24

pass the values of i and j to num1 and num2

25 of 140

Trace Call Stack

25

Declare result

26 of 140

Trace Call Stack

26

(num1 > num2) is true

27 of 140

Trace Call Stack

27

Assign num1 to result

28 of 140

Trace Call Stack

28

Return result and assign it to k

29 of 140

Trace Call Stack

29

Execute print statement

30 of 140

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”);

Example:: Metod_demo3.java

31 of 140

Pass by Value

  • Testing Pass by value

  • Example:: TestPassByValue.java

32 of 140

Pass by Value, cont.

33 of 140

Overloading Methods

  • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
  • Method overloading is an example of Static Polymorphism(Compile Time Polymorphism).
  • Static Polymorphism is also known as compile time binding or early binding.
  •  Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.

34 of 140

Overloading Methods

  • Method overloading is done by declaring same method with different parameters. 
  • The parameters must be different in either of these:
    • Number
    • sequence or
    • types of parameters (or arguments).
  • It is not method overloading if we only change the return type of methods. There must be differences in the number of parameters.

35 of 140

Overloading by changing the number of arguments

public class MethodOverloadingExample {

// Method with one argument

public void display(int number) {

System.out.println("Display method with one argument: " + number);

}

// Overloaded method with two arguments

public void display(int number1, int number2) {

System.out.println("Display method with two arguments: " + number1 + " and " + number2);

}

public static void main(String[] args) {

// Creating an object of the class

MethodOverloadingExample example = new MethodOverloadingExample();

// Calling the method with one argument

example.display(10);

// Calling the overloaded method with two arguments

example.display(20, 30);

}

}

36 of 140

Output:

Display method with one argument: 10

Display method with two arguments: 20 and 30

Explanation:

  1. Overloading is done by defining multiple methods with the same name but different numbers of arguments.
  2. The method to be called is determined at compile time based on the number of arguments passed.
  3. In the example above:
    • display(int number) takes one argument.
    • display(int number1, int number2) takes two arguments.

37 of 140

By changing the data type of parameters

public class MethodOverloadingByDataType {

// Method with an int parameter

public void display(int number) {

System.out.println("Display method with int parameter: " + number);

}

// Overloaded method with a double parameter

public void display(double number) {

System.out.println("Display method with double parameter: " + number);

}

public static void main(String[] args) {

// Creating an object of the class

MethodOverloadingByDataType example = new MethodOverloadingByDataType();

// Calling the method with an int parameter

example.display(10);

// Calling the overloaded method with a double parameter

example.display(15.5);

}

}

38 of 140

Output:

Display method with int parameter: 10

Display method with double parameter: 15.5

Explanation:

  1. Overloading by data type is achieved by defining methods with the same name but different parameter data types.
  2. In this example:
    • display(int number) is called when an integer is passed.
    • display(double number) is called when a double is passed.
  3. The compiler determines which method to call based on the type of the argument at compile time.

39 of 140

By changing the sequence of parameters

public class MethodOverloadingBySequence {

// Method with int followed by String

public void display(int number, String text) {

System.out.println("Display method with int and String: " + number + ", " + text);

}

// Overloaded method with String followed by int

public void display(String text, int number) {

System.out.println("Display method with String and int: " + text + ", " + number);

}

public static void main(String[] args) {

// Creating an object of the class

MethodOverloadingBySequence example = new MethodOverloadingBySequence();

// Calling the method with int followed by String

example.display(10, "Hello");

// Calling the overloaded method with String followed by int

example.display("World", 20);

}

}

40 of 140

Output:

Display method with int and String: 10, Hello

Display method with String and int: World, 20

Explanation:

  1. Overloading by sequence of parameters works by defining methods with the same name but different orders of parameter types.
  2. In this example:
    • display(int number, String text) expects an integer first and then a string.
    • display(String text, int number) expects a string first and then an integer.
  3. The compiler determines the appropriate method to call based on the order of arguments at compile time.

41 of 140

Method Overloading and

Type Promotion

  • When a data type of smaller size is promoted to the data type of bigger size than this is called type promotion.
  • for example: byte data type can be promoted to short, a short data type can be promoted to int, long, double etc.
  • What it has to do with method overloading?
  • it is very important to understand type promotion else you will think that the program will throw compilation error but in fact that program will run fine because of type promotion.
  • Example::
  •  I have passed the float value while calling the disp() method but it got promoted to the double type as there wasn’t any method with argument list as (int, float).

42 of 140

class Demo

{

void disp(int a, double b)

{

System.out.println("Method A");

}

void disp(int a, double b, double c)

{

System.out.println("Method B");

}

public static void main(String args[])

{

Demo obj = new Demo();

/* I am passing float value as a second argument but

* it got promoted to the type double, because there

* wasn't any method having arg list as (int, float)

*/

obj.disp(100, 20.67f);

}

}

43 of 140

Type Promotion table:

  • The data type on the left side can be promoted to the any of the data type present in the right side of it.

byteshortintlong

shortintlong

intlongfloatdouble

floatdouble

longfloatdouble

44 of 140

Can we overload java main() method?

  • Yes, we can overload the main() method in Java.
  • However, the JVM always calls the standard public static void main(String[] args) method as the entry point of the program.
  • Any overloaded versions of main() will not be invoked automatically.
  • They act like normal methods and can be called explicitly within the program.

45 of 140

public class MainOverloadingExample {

// Standard main method called by JVM

public static void main(String[] args) {

System.out.println("Standard main() method called by JVM");

// Explicitly calling overloaded main methods

main(10);

main("Hello, Java!");

}

// Overloaded main method with an int parameter

public static void main(int number) {

System.out.println("Overloaded main() with int parameter: " + number);

}

// Overloaded main method with a String parameter

public static void main(String message) {

System.out.println("Overloaded main() with String parameter: " + message);

}

}

Standard main() method called by JVM

Overloaded main() with int parameter: 10

Overloaded main() with String parameter: Hello, Java!

46 of 140

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.
  • Ambiguous invocation is a compile error.

47 of 140

public class AmbiguousInvocationExample {

// Overloaded method with float parameter

public void display(float number) {

System.out.println("Display method with float: " + number);

}

// Overloaded method with double parameter

public void display(double number) {

System.out.println("Display method with double: " + number);

}

public static void main(String[] args) {

AmbiguousInvocationExample example = new AmbiguousInvocationExample();

// Explicit call with a float value (no ambiguity)

example.display(10.5f); // Calls the method with float parameter

// Explicit call with a double value (no ambiguity)

example.display(10.5); // Calls the method with double parameter

// Ambiguous call

// example.display(10); // Compilation error: ambiguous invocation

}

}

Display method with float: 10.5

Display method with double: 10.5

48 of 140

Explanation:

  1. Float and Double Overloading:
    • The method display(float) is for float arguments.
    • The method display(double) is for double arguments.
  2. Ambiguous Call with Integer Literal:
    • The integer literal 10 can be implicitly converted to either float or double.
    • The compiler cannot decide whether to call display(float) or display(double), leading to a compilation error.

—--------------------------------------------------------------------------------------------------------------------------

How to Resolve Ambiguity:

Explicit Casting: Specify the argument's type explicitly to resolve ambiguity:��example.display((float) 10); // Calls the method with float parameter

example.display((double) 10); // Calls the method with double parameter

Avoid Ambiguous Overloads: Avoid creating overloaded methods with closely related types, especially where implicit conversions can occur (e.g., int, float, double).

Ambiguity is a common issue in method overloading, and resolving it requires careful design or explicit type specification.

49 of 140

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

50 of 140

Scope of Local Variables

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

51 of 140

Scope of Local Variables

52 of 140

UNIT-3 SINGLE-DIMENSIONAL ARRAYS

53 of 140

Problem

  • Read one hundred numbers, compute their average, and find out how many numbers are above the average.

54 of 140

Introducing Arrays

  • Array is a data structure that represents a collection of the same types of data.

55 of 140

Declaring Array Variables

  • datatype[] arrayRefVar;

Example:

double[] myList;

  • Datatype arrayRefVar[];

Example:

double myList[];

56 of 140

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.

57 of 140

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

58 of 140

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

59 of 140

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
    • false for boolean types.

60 of 140

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.
  • Each element in the array is represented using the following syntax, known as an indexed variable:

arrayRefVar[index];

61 of 140

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

62 of 140

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.

63 of 140

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;

64 of 140

CAUTION

  • Using the shorthand notation, you have to declare, create, and initialize the array all in one statement.

  • Splitting it would cause a syntax error. For example, the following is wrong:

double[] myList;

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

  • Example:: Test.java

65 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

65

Declare array variable values, create an array, and assign its reference to values

66 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

66

i becomes 1

67 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

67

i (=1) is less than 5

68 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

68

After this line is executed, value[1] is 1

69 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

69

After i++, i becomes 2

animation

70 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

70

i (= 2) is less than 5

71 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

71

After this line is executed,

values[2] is 3 (2 + 1)

72 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

72

After this, i becomes 3.

73 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

73

i (=3) is still less than 5.

74 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

74

After this line, values[3] becomes 6 (3 + 3)

75 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

75

After this, i becomes 4

76 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

76

i (=4) is still less than 5

animation

77 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

77

After this, values[4] becomes 10 (4 + 6)

78 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

78

After i++, i becomes 5

79 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

79

i ( =5) < 5 is false. Exit the loop

80 of 140

Trace Program with Arrays

public class Test {

public static void main(String[] args) {

int[] values = new int[5];

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

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

}

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

}

}

80

After this line, values[0] is 11 (1 + 10)

81 of 140

  • Read one hundred numbers, compute their average, and find out how many numbers are above the average.

import java.util.Scanner;

public class NumbersAboveAverage {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Array to store 100 numbers

double[] numbers = new double[100];

double sum = 0;

// Read 100 numbers

System.out.println("Enter 100 numbers:");

for (int i = 0; i < 100; i++) {

numbers[i] = scanner.nextDouble();

sum += numbers[i];

}

// Calculate average

double average = sum / 100;

// Count numbers above the average

int countAboveAverage = 0;

for (double number : numbers) {

if (number > average) {

countAboveAverage++;

}

}

// Display the results

System.out.println("Average: " + average);

System.out.println("Numbers above the average: " + countAboveAverage);

scanner.close();

}

}

82 of 140

Enhanced for Loop (for-each loop)

  • JDK 1.5 introduced a new for loop that enables you to traverse the complete array sequentially without using an index variable.
  • For example, the following code displays all elements in the array myList:

for (double value: myList)

System.out.println(value);

  • In general, the syntax is

for (elementType value: arrayRefVar) {

// Process the value

}

  • You still have to use an index variable if you wish to traverse the array in a different order or change the elements in the array.
  • Example::Test1.java

83 of 140

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;
  • Example:: copy_array.java

84 of 140

Copying Arrays

  • Using a loop:

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

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

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

targetArray[i] = sourceArray[i];

  • Example:: copy_array1.java

85 of 140

The arraycopy Utility

  • arraycopy(sourceArray, src_pos, targetArray, tar_pos, length);

  • Example:

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

  • Example:: copy_array2.java

86 of 140

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

Example::Pass_arg.java

87 of 140

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.

88 of 140

Pass By Value

  • Java uses pass by value to pass arguments to a method.
  • There are important differences between passing a value of variables of primitive data types and passing arrays.
  • For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method.
  • 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.

89 of 140

Simple Example(Pass_arg1.java)

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]

}

}

90 of 140

Call Stack

  • When invoking m(x, y), the values of x and y are passed to number and numbers. Since y contains the reference value to the array, numbers now contains the same reference value to the same array.

91 of 140

Heap

  • The JVM stores the array in an area of memory, called heap, which is used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order.

92 of 140

Passing Arrays as Arguments

  • Objective: Demonstrate differences of passing primitive data type variables and array variables.

  • Example:: TestPassArray.java

93 of 140

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 = {1, 2, 3, 4, 5, 6};

int[] list2 = reverse(list1);

  • Example:: Array_return.java

94 of 140

Trace the reverse Method

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

int[] list2 = reverse(list1);

94

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

1

2

3

4

5

6

0

0

0

0

0

0

Declare result and create array

95 of 140

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

int[] list2 = reverse(list1);

95

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

1

2

3

4

5

6

0

0

0

0

0

0

i = 0 and j = 5

96 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

96

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

1

2

3

4

5

6

0

0

0

0

0

0

i (= 0) is less than 6

97 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

97

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

1

2

3

4

5

6

0

0

0

0

0

1

i = 0 and j = 5

Assign list[0] to result[5]

98 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

98

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

1

2

3

4

5

6

0

0

0

0

0

1

After this, i becomes 1 and j becomes 4

99 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

99

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

1

2

3

4

5

6

0

0

0

0

0

1

i (=1) is less than 6

100 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

100

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

1

2

3

4

5

6

0

0

0

0

2

1

i = 1 and j = 4

Assign list[1] to result[4]

101 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

101

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

1

2

3

4

5

6

0

0

0

0

2

1

After this, i becomes 2 and j becomes 3

102 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

102

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

1

2

3

4

5

6

0

0

0

0

2

1

i (=2) is still less than 6

103 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

103

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

1

2

3

4

5

6

0

0

0

3

2

1

i = 2 and j = 3

Assign list[i] to result[j]

104 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

104

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

1

2

3

4

5

6

0

0

0

3

2

1

After this, i becomes 3 and j becomes 2

105 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

105

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

1

2

3

4

5

6

0

0

0

3

2

1

i (=3) is still less than 6

106 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

106

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

1

2

3

4

5

6

0

0

4

3

2

1

i = 3 and j = 2

Assign list[i] to result[j]

107 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

107

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

1

2

3

4

5

6

0

0

4

3

2

1

After this, i becomes 4 and j becomes 1

108 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

108

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

1

2

3

4

5

6

0

0

4

3

2

1

i (=4) is still less than 6

109 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

109

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

1

2

3

4

5

6

0

5

4

3

2

1

i = 4 and j = 1

Assign list[i] to result[j]

110 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

110

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

1

2

3

4

5

6

0

5

4

3

2

1

After this, i becomes 5 and j becomes 0

111 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

111

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

1

2

3

4

5

6

0

5

4

3

2

1

i (=5) is still less than 6

112 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

112

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

1

2

3

4

5

6

6

5

4

3

2

1

i = 5 and j = 0

Assign list[i] to result[j]

113 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

113

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

1

2

3

4

5

6

6

5

4

3

2

1

After this, i becomes 6 and j becomes -1

114 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

114

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

1

2

3

4

5

6

6

5

4

3

2

1

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

115 of 140

Trace the reverse Method, cont.

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

int[] list2 = reverse(list1);

115

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

1

2

3

4

5

6

6

5

4

3

2

1

Return result

list2

116 of 140

Variable-Length Arguments

  • You can pass a variable number of arguments of the same type to a method.

  • Example:; VarArgsDemo.java

117 of 140

Searching Arrays

  • Searching is the process of looking for a specific element in an array.
  • for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming.
  • There are many algorithms and data structures devoted to searching.
  • In this section, two commonly used approaches are discussed, linear search and binary search.

118 of 140

Linear Search

  • The linear search approach compares the key element, key, sequentially with each element in the array list.
  • The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found.
  • If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1.

119 of 140

Linear Search Animation

119

6

4

1

9

7

3

2

8

6

4

1

9

7

3

2

8

6

4

1

9

7

3

2

8

6

4

1

9

7

3

2

8

6

4

1

9

7

3

2

8

6

4

1

9

7

3

2

8

3

3

3

3

3

3

Key

List

120 of 140

Example::Linear.java

/** The method for finding a key in the list */

public static int linearSearch(int[] list, int key) {

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

if (key == list[i])

return i;

return -1;

}

Trace the method

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

int i = linearSearch(list, 4); // returns 1

int j = linearSearch(list, -4); // returns -1

int k = linearSearch(list, -3); // returns 5

121 of 140

Binary Search

  • For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order.

e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79

  • The binary search first compares the key with the element in the middle of the array.
  • Consider the following three cases:
    • If the key is less than the middle element, you only need to search the key in the first half of the array.
    • If the key is equal to the middle element, the search ends with a match.
    • If the key is greater than the middle element, you only need to search the key in the second half of the array.

122 of 140

Binary Search

122

1

2

3

4

6

7

8

9

1

2

3

4

6

7

8

9

1

2

3

4

6

7

8

9

8

8

8

Key

List

123 of 140

Binary Search, cont.

123

124 of 140

Binary Search, cont.

124

125 of 140

Binary Search, cont.

The binarySearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns

-insertion point - 1.

The insertion point is the point at which the key would be inserted into the list.

125

126 of 140

Example::Binary.java

/** Use binary search to find the key in the list */

public static int binarySearch(int[] list, int key) {

int low = 0;

int high = list.length - 1;

 

while (high >= low) {

int mid = (low + high) / 2;

if (key < list[mid])

high = mid - 1;

else if (key == list[mid])

return mid;

else

low = mid + 1;

}

 

return -1 - low;

}

127 of 140

The Arrays.binarySearch Method

  • Since binary search is frequently used in programming, Java provides several overloaded binarySearch methods for searching a key in an array of int, double, char, short, long, and float in the java.util.Arrays class.
  • For example, the following code searches the keys in an array of numbers and an array of characters.

int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};

System.out.println("Index is " +

java.util.Arrays.binarySearch(list, 11));

char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};

System.out.println("Index is " +

java.util.Arrays.binarySearch(chars, 't'));

  • For the binarySearch method to work, the array must be pre-sorted in increasing order.

Return is 4

Return is –4 (insertion point is 3, so return is -3-1)

128 of 140

Sorting Arrays

  • Sorting, like searching, is also a common task in computer programming.
  • Many different algorithms have been developed for sorting.
  • This section introduces a simple, intuitive sorting algorithms: selection sort.
  • Selection sort finds the smallest number in the list and places it first. It then finds the smallest number remaining and places it second, and so on until the list contains only a single number.

129 of 140

Selection Sort

130 of 140

UNIT-3 MULTIDIMENSIONAL ARRAYS

131 of 140

Motivations

  • You have used one-dimensional arrays to model linear collections of elements.
  • You can use a two-dimensional array to represent a matrix or a table.
  • For example, the following table that describes the distances between the cities can be represented using a two-dimensional array.

132 of 140

Motivations

133 of 140

Declare/Create Two-dimensional Arrays

// Declare array ref var

dataType[][] refVar;

// Create array and assign its reference to variable

refVar = new dataType[10][10];

// Combine declaration and creation in one statement

dataType[][] refVar = new dataType[10][10];

// Alternative syntax

dataType refVar[][] = new dataType[10][10];

134 of 140

Two-dimensional Array Illustration

135 of 140

Declaring, Creating, and Initializing Using Shorthand Notations

  • You can also use an array initializer to declare, create and initialize a two-dimensional array. For example,

int[][] array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9},

{10, 11, 12}

};

int[][] array = new int[4][3];

array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;

array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;

array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;

array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;

Same as

136 of 140

Lengths of Two-dimensional Arrays

  • int[][] x = new int[3][4];

137 of 140

Lengths of Two-dimensional Arrays, cont

int[][] array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9},

{10, 11, 12}

};

array.length

array[0].length

array[1].length

array[2].length

array[3].length

array[4].length ArrayIndexOutOfBoundsException

138 of 140

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.

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

139 of 140

Ragged Arrays, cont

140 of 140

Multidimensional Arrays

double[][][] scores = {

{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},

{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},

{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},

{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},

{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},

{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}

};