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.
Problem
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);
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));
}
Defining Methods
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
Program
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);
}
}
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
Trace Method Invocation
7
i is now 5
Trace Method Invocation
8
j is now 2
Trace Method Invocation
9
invoke max(i, j)
Trace Method Invocation
10
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
Trace Method Invocation
11
declare variable result
Trace Method Invocation
12
(num1 > num2) is true since num1 is 5 and num2 is 2
Trace Method Invocation
13
result is now 5
Trace Method Invocation
14
return result, which is 5
Trace Method Invocation
15
return max(i, j) and assign the return value to k
Trace Method Invocation
16
Execute the print statement
CAUTION (Method_demo.java )
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;
}
Reuse Methods from Other Classes
Call Stacks
Trace Call Stack
20
i is declared and initialized
Trace Call Stack
21
j is declared and initialized
Trace Call Stack
22
Declare k
Trace Call Stack
23
Invoke max(i, j)
Trace Call Stack
24
pass the values of i and j to num1 and num2
Trace Call Stack
25
Declare result
Trace Call Stack
26
(num1 > num2) is true
Trace Call Stack
27
Assign num1 to result
Trace Call Stack
28
Return result and assign it to k
Trace Call Stack
29
Execute print statement
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
Pass by Value
Pass by Value, cont.
Overloading Methods
Overloading Methods
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);
}
}
Output:
Display method with one argument: 10
Display method with two arguments: 20 and 30
Explanation:
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);
}
}
Output:
Display method with int parameter: 10
Display method with double parameter: 15.5
Explanation:
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);
}
}
Output:
Display method with int and String: 10, Hello
Display method with String and int: World, 20
Explanation:
Method Overloading and
Type Promotion
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);
}
}
Type Promotion table:
byte → short → int → long
short → int → long
int → long → float → double
float → double
long → float → double
Can we overload java main() method?
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!
Ambiguous Invocation
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
Explanation:
—--------------------------------------------------------------------------------------------------------------------------
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.
Scope of Local Variables
Scope of Local Variables
Scope of Local Variables
UNIT-3 SINGLE-DIMENSIONAL ARRAYS
Problem
Introducing Arrays
Declaring Array Variables
Example:
double[] myList;
Example:
double myList[];
Creating Arrays
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
Declaring and Creating in One Step
double[] myList = new double[10];
double myList[] = new double[10];
The Length of an Array
arrayRefVar.length
For example,
myList.length returns 10
Default Values
Indexed Variables
arrayRefVar[index];
Using Indexed Variables
myList[2] = myList[0] + myList[1];
Array Initializers
double[] myList = {1.9, 2.9, 3.4, 3.5};
Declaring, creating, initializing Using the Shorthand Notation
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
CAUTION
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
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
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
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
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
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
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
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)
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.
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.
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)
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
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
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)
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
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
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)
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();
}
}
Enhanced for Loop (for-each loop)
for (double value: myList)
System.out.println(value);
for (elementType value: arrayRefVar) {
// Process the value
}
Copying Arrays
Copying Arrays
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];
The arraycopy Utility
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
Anonymous Array
printArray(new int[]{3, 1, 2, 6, 4, 2});
new dataType[]{literal0, literal1, ..., literalk};
Pass By Value
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]
}
}
Call Stack
Heap
Passing Arrays as Arguments
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);
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
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
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
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]
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
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
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]
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
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
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]
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
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
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]
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
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
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]
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
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
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]
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
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.
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
Variable-Length Arguments
Searching Arrays
Linear Search
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
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
Binary Search
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
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
Binary Search, cont.
123
Binary Search, cont.
124
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
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;
}
The Arrays.binarySearch Method
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'));
Return is 4
Return is –4 (insertion point is 3, so return is -3-1)
Sorting Arrays
Selection Sort
UNIT-3 MULTIDIMENSIONAL ARRAYS
Motivations
Motivations
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];
Two-dimensional Array Illustration
Declaring, Creating, and Initializing Using Shorthand Notations
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
Lengths of Two-dimensional Arrays
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
Ragged Arrays
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
Ragged Arrays, cont
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}}
};