
















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

















CS212: Object-Oriented Programming Arrays In Java
2
MULTIDIMENSIONAL ARRAYS- DIRECT Syntax 2D Array Direct Initialization: data_type[][] array_name = { {valueR1C1, valueR1C2, ....}, {valueR2C1, valueR2C2, ....} }; Example:
5 (^) Declaring two-dimensional array b[2][2] int b[][] = { { 1 , 2 }, { 3 , 4 } }; 1 and 2 initialize b[0][0] and b[0][1] 3 and 4 initialize b[1][0] and b[1][1] MULTIDIMENSIONAL ARRAYS b[0] [0]= b[0] [1]= b[1] [0]= b[1] [1]= row 0 row 1 col 0 col 1
1 2 3 4 5
Accessing 2D Array Elements class Test { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { System.out.print("arr[" + i + "][" + j + "] =" + arr[i][j]+” \t ”); } System.out.println(); } } }
Exercise :
Subject 1 [0] Subject 2 [1] Student 1 [0] 10 20 Student 2 [1] 30 43. Student 3 [2] 69 83
10 20 30 43. 69 83
Defining & Using Methods
Method Call Method Definition
14 PASSING ARRAYS TO METHODS
(^) Specify array name without brackets Array hourlyTemperatures is declared as: int hourlyTemperatures[] = new int[ 24 ]; (^) The method call modifyArray( hourlyTemperatures ); (^) Passes array hourlyTemperatures to method modifyArray
16
Two ways to pass arguments to methods (^) Pass-by-value (^) Copy of argument’s value is passed to called method In Java, every primitive is pass-by-value (^) Pass-by-reference (^) Caller gives called method direct access to caller’s data Called method can manipulate this data Improved performance over pass-by-value PASSING ARRAYS TO METHODS (CONT.)
PASSING ARRAYS TO METHODS (CONT.)
Pass array element array[3] to method modifyElement Method modifyArray manipulates the array directly Method modifyElement manipulates a primitive’s copy 19
20
Unspecified number of arguments (^) Use ellipsis (…) in method’s parameter list (^) Can occur only once in parameter list (^) Must be placed at the end of parameter list (^) Array whose elements are all of the same type VARIABLE LENGTH ARGUMENTS