Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS2011 Introduction to Programming I Arrays (II)

Similar presentations


Presentation on theme: "CS2011 Introduction to Programming I Arrays (II)"— Presentation transcript:

1 CS2011 Introduction to Programming I Arrays (II)
Chengyu Sun California State University, Los Angeles

2 Primitive Types Are Passed By Value
If a parameter is of a primary type (e.g. int and double), the value of the argument is passed to the parameter public static void inc( int n ) { ++n; } public static void main( String args[] ) { int n = 10; inc(n); System.out.println(n);

3 Arrays Are Passed By Reference
Why the difference? public static void inc( int[] n ) { ++n[0]; } public static void main( String args[] ) { int[] n = {10}; inc(n); System.out.println(n[0]);

4 Copy An Array Is b a copy of a, or are they the same array??
int[] a = {1, 2, 3}; int[] b = a; b[0] = 10; System.out.println( a[0] ); Is b a copy of a, or are they the same array?? How do we make a copy of an array??

5 Return An Array Notice the return type
public static int[] createArray( int n ) { int[] a = new int[n]; for( int i=0 ; i < a.length ; ++i ) a[i] = i + 1; return a; } Notice the return type Why it works when a is a local variable?

6 Heap JVM divides the memory it uses to run a program into a stack and a heap Stack is the part of the memory that stores activation records (i.e. local variables and parameter) Heap is the part of the memory that stores data that is created with the new keyword (i.e. objects and arrays)

7 Array Reference Stack Heap Stack Heap create Array() a main() main() b
a references the array created on the heap The array references is returned to main() and assigned to b

8 Garbage Collection Data on the heap will be removed when the JVM determines that it's no longer used by any code (i.e. no more references to the data), and this process is known as Garbage Collection

9 Variable-Length Argument List
A.K.A. varargs Allows any number of arguments of the specified type The arguments are treated as an array in the method public static int sum( int… numbers ) { int sum = 0; for( int i=0 ; i < numbers.length ; ++i ) sum += numbers[i]; return sum; }

10 Arrays Methods Arrays contains some useful methods for common array operations Examples copyOf equals sort binarySearch

11 Readings Chapter 7 of the textbook (there will be a quiz next week)


Download ppt "CS2011 Introduction to Programming I Arrays (II)"

Similar presentations


Ads by Google