Docsity

Java: Multidimensional Arrays and Passing Arrays to Methods, Assignments of Java Programming

Partial preview of the text

Download Java: Multidimensional Arrays and Passing Arrays to Methods and more Assignments Java Programming in PDF only on Docsity!

CS212: Object-Oriented Programming Arrays In Java

2

MULTIDIMENSIONAL ARRAYS

Array of arrays

Tables with rows and columns

Two-dimensional array

m-by-n array

MULTIDIMENSIONAL ARRAYS- DIRECT Syntax 2D Array Direct Initialization: data_type[][] array_name = { {valueR1C1, valueR1C2, ....}, {valueR2C1, valueR2C2, ....} }; Example:

int b[][] = {

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 :

 Suppose there are 3 students, who are

studying 2 subjects (subject 1 and subject 2).

Develop a program to store, manage & display

the marks of all the students enrolled in those

two subjects.

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

 Syntax for method definition & call

Method Call Method Definition

14 PASSING ARRAYS TO METHODS

To pass array argument to a

method

 (^) 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.)

Argume

nts

Argume

nts

Primitive^ Primitive

Referenc

e

Referenc

e

Pass array element array[3] to method modifyElement Method modifyArray manipulates the array directly Method modifyElement manipulates a primitive’s copy 19

20

Variable-length argument lists

 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