1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made...

34
1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method. – Modifying a value in a method does not have any effect on the caller – But if the value is a reference then the change affects ‘what is referred to’ and so all references will see the change. • References are addresses and hence a modification of the contents at the address will have “global” visibility • On the other hand non-referential argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents only of local memory)

description

3

Transcript of 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made...

Page 1: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

1

Arrays and Methods• Java always passes arguments by value – that is a copy of

the value is made in the called method and this is modified in the method.– Modifying a value in a method does not have any effect

on the caller– But if the value is a reference then the change affects

‘what is referred to’ and so all references will see the change.•References are addresses and hence a modification

of the contents at the address will have “global” visibility

•On the other hand non-referential argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents only of local memory)

Page 2: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

2

10

int a

int b

10In calling method

In called method

Any change made to b in called method will not be reflected outsidein the calling method.

Page 3: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

3

a[0]

a[1]

a[2]

a[3]

a[..]

a

b

‘a’ is a reference to the beginning of the array in the calling method. ‘b’ is the reference in the calledmethod. Any change made in thearray in the called method throughthe reference ‘b’ will be visible in the calling method.Note that ‘a’ and ‘b’ are referencesto the same array value.

Page 4: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

The Sorting Problem

Let S be a sequence of entities which can be ordered (that is for any 2 elements, say a, b in the sequence exactly one of the following is true a<b, a>b or a=b).Sort(S) : arranges the sequence in ascending or descending order.

Page 5: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Sort algorithms

• The sorting problem is one of the best studied problems and many algorithms exist.

• It is also practically important – sorting is routinely required in almost all database centred applications.

Page 6: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Selection sort: example

<| 9, 2, 4, 4, 3, 5> //green is min, | is separator<2, | 9, 4, 4, 3, 5> // after first round, blue sorted<2, 3, | 4, 4, 9, 5><2, 3, 4, | 4, 9, 5><2, 3, 4, 4, | 9, 5><2, 3, 4, 4, 5, | 9 > //stop since only one left<2, 3, 4, 4, 5, 9 | >

Page 7: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Selection sort algorithm

//S is the array to be sorted.sepIndex=0; loop (s.length-1) times {

minI=findMinIndex(S,sepIndex);

exchange(S,sepIndex,minI);sepIndex++;

}

Page 8: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Selection sort - findMinIndex

int findMinIndex(int[]S,int from) {int minI=from; for(int i=from+1;index<S.length;i++) {

if (S[i]<S[minI]) minI=i;}return minI;}

Page 9: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Bubble sort: example//sort ascending, | is unsorted-sorted separator<9, 2, 4, 4, 3, 5|> //interchange neighbours

from 0 till end< 2, 4, 4, 3, 5|, 9 > //after first pass< 2, 4, 3, 4 |, 5, 9 > //after second pass< 2, 3, 4|, 4, 5, 9 > //after third pass< 2, 3, 4|, 4, 5, 9 >//4th pass, no interchangeStop condition: no interchange or | is at start.

Page 10: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Bubble sort algorithm

lim=S.length-1;while (bubblePass(S,lim) && lim>0) {

lim--;}

Page 11: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Bubble sort - bubblePassboolean bubblePass(int [] s, int to){boolean interchange=false;for(int i=0; i<to; i++) {if (S[i]>S[i+1]){

//exchange contents of S[i],S[i+1]interchange=true;

}}return interchange;}

Page 12: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Mergesortmsort(s) { /* Split S into two (almost) equal parts s1,s2*/

split(s,s1,s2); msort(s1); msort(s2); /* at this point s1, s2 are sorted */ merge(s1,s2,ss); return ss;}

Page 13: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Mergemerge(s1, s2, s) { s=initialize to s1.length+s2.length i1=0;i2=0,i=0; while(i1<s1.length && i2<s2.length){ if(s1[i1]<s2[i2])s[i]=s1[i1++];

else s[i]=s2[i2++]; i++ } // Now copy rest of s1 or s2 to s return s;}

Page 14: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

14

Finding averageclass Average { public static void main (String arg[]) { double dailyRainFall[] = {12.3, 13.5, 4.2, 2.4,

1.1, 0, 10.8}; int i; double average = 0;

for (i=0; i<7; i++) { average += dailyRainFall[i]; } average /= 7; System.out.println (“Average rain fall: ” +

average + “ mm”); }}

Page 15: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

15

Finding maximumclass Maximum { public static void main (String arg[]) { int n = 100; double numbers[] = new double[n];

Initialize (numbers, n); System.out.println (“Maximum: ” +

FindMax (numbers, n)); }

Page 16: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

16

Finding maximum public static void Initialize (double

numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1))

+ Math.cos(2*Math.PI/(i+2)); } }

Page 17: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Finding maximum public static double FindMax (double numbers[],

int length) { double max = numbers[0]; int i;

for (i=1; i<length; i++) { if (numbers[i] > max) { max = numbers[i]; } } return max; }} // end class

Page 18: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Finding maximum• Want to print the position of the maximum

also– Need to return two values from FindMax– Use a 2-element array as return type– Shows why returning local reference does not

work– Shows the distinction between two different

memory areas: stack and heap

Page 19: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Finding max and max indexclass Maximum { public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[];

Initialize (numbers, n); result = FindMax (numbers, n); // Danger! System.out.println ("Maximum: " + result[0] + ",

Position: " + (int)result[1]); }

Page 20: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Finding max and max index public static void Initialize (double

numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) +

Math.cos(2*Math.PI/(i+2)); } }

Page 21: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Finding max and max index public static double[] FindMax (double numbers[],

int length) { // Does not work double result[] = {numbers[0], 0}; int i;

for (i=1; i<length; i++) { if (numbers[i] > result[0]) { result[0] = numbers[i]; result[1] = i; } } return result; // Local reference on stack }} // end class

Page 22: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Finding max and max index public static double[] FindMax (double numbers[], int

length) { // This one works double result[] = new double[2]; // On heap result[0] = numbers[0]; result[1] = 0; int i;

for (i=1; i<length; i++) { if (numbers[i] > result[0]) { result[0] = numbers[i]; result[1] = i; } } return result; // Reference on heap }} // end class

Page 23: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Array layout in memory• Recall that every variable requires some

space to be stored in memory– Often the compiler is responsible for allocating

this space– In other words, every variable has an address

(just like you and I have addresses)– The address is often called a reference of a

variable in Java– If I try to print the value at this address, I will get

the value of the variable• How is an array stored in memory?

Page 24: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Array layout in memory• The array elements are stored contiguously

in memory– numbers[0], numbers[1], …– Starting address is numbers (same as the

address of numbers[0]), add 8 to get the address of numbers[1]

– doubles are 64 bits in size and memory is always byte addressed (one byte is 8 bits)

– Putting array names in method arguments is equivalent to passing the arrays by reference: modifications to arrays inside the method are reflected outside the method

– Of course, it is possible to pass individual array elements (not by reference, but by value i.e. as private copies)

Page 25: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

FindMax: reference as a valueclass Maximum { // Still pass by value public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[] = new double[2];

Initialize (numbers, n); result[0] = numbers[0]; result[1] = 0; FindMax (numbers, n, result); // reference System.out.println ("Maximum: " + result[0] + ",

Position: " + (int)result[1]); }

Page 26: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

FindMax: reference as a value public static void Initialize (double

numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) +

Math.cos(2*Math.PI/(i+2)); } }

Page 27: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

FindMax: reference as a value public static void FindMax (double numbers[], int

length, double r[]) { int i;

for (i=1; i<length; i++) { if (numbers[i] > r[0]) { r[0] = numbers[i]; r[1] = i; } } }} // end class

Page 28: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

FindMax: passing valuesclass Maximum { // This example does not work public static void main (String arg[]) { int n = 100; double numbers[] = new double[n]; double result[] = new double[2];

Initialize (numbers, n); result[0] = numbers[0]; result[1] = 0; FindMax (numbers, n, result[0], result[1]); System.out.println ("Maximum: " + result[0] + ",

Position: " + (int)result[1]); }

Page 29: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

FindMax: passing values public static void Initialize (double

numbers[], int length) { int i; for (i=0; i<length; i++) { numbers[i] = Math.sin(2*Math.PI/(i+1)) +

Math.cos(2*Math.PI/(i+2)); } }

Page 30: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

FindMax: passing values public static void FindMax (double numbers[], int

length, double max, double position) { int i;

for (i=1; i<length; i++) { if (numbers[i] > max) { max = numbers[i]; position = i; } } }} // end class

Page 31: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Always pass by value• Java always passes arguments by value

– References are just a special kind of values– Modifying a value in a method does not have

any effect on the caller– Modifying a value pointed to by a reference in a

method does change the value in the caller also

• References are addresses and hence a modification of the contents at the address will have “global” visibility

• On the other hand, argument values are just copied in the “local memory” of a method; so a modification to a value within a method always remains local (changes contents of local memory)

Page 32: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Reversing an arrayclass Reverse { public static void main (String arg[]) { int size = 10; int somethingStrange[] = new int[size];

Initialize (somethingStrange, size); PrintArray (somethingStrange, size); Reverse (somethingStrange, size); PrintArray (somethingStrange, size); }

Page 33: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Reversing an array public static void Initialize (int array[], int

size) { int i; array[0] = 1; for (i=1; i<size; i++) { array[i] = (array[i-1]*3) % 23; } }

Page 34: 1 Arrays and Methods Java always passes arguments by value – that is a copy of the value is made in the called method and this is modified in the method.

Reversing an array public static void Reverse (int array[], int

size) { int head = 0, tail = size-1;

while (head < tail) { Swap (array, head, tail); head++; tail--; } }