03 - Programming Fundamentals Part2
03 - Programming Fundamentals Part2
in Java II
Instructor: Dr. Fahed Jubair
Arrays
• Arrays are used to store multiple data elements that have the same data type
• An array reference variable is used to access data elements inside an array
• Once created, an array size is fixed
How array arr is stored in memory.
• Example
int[ ] arr = new int[5]; arr[0] 8
Array element value
arr[0] = 8; Array reference name
arr[1] 4
arr[1] = 4;
arr[2] = -2; arr[2] -2
Array element index
arr[3] = 0; arr[3] 0
arr[4] = 12;
arr[4] 12
If array size is small – use shortcuts If array size is big – use loops
Random shuffling
columns
int[][] A = new int[4][3];
[0] [1] [2]
A[0][0] = 5; A[0][1] = 3; A[0][2] = 1; Visual [0] 5 3 1
representation
A[1][0] = 6; A[1][1] = 2; A[1][2] = 8; [1] 6 2 8
rows
A[2][0] = 4; A[2][1] = 1; A[2][2] = 9; [2] 4 1 9
[3] 0 1 3
A[3][0] = 0; A[3][1] = 1; A[3][2] = 3;
2D array initialization
Method definition
Invoking a method
Value is
returned
main main main main
Values
Activation are Activation Activation Activation
record passed record record record
k: k: i: 5.4 i: 5.4
j: 3.2 j: 3.2 j: 3.2 j: 3.2
i: 5.4 i: 5.4 K: K: 4.3
main is average is average is average is main is
invoked invoked executed terminated terminated
© All rights reserved. 15
Passing Parameters
• Primitive data types in Java are passed from caller to callee by value
• Callee cannot modify original variables in the caller
• Objects and arrays in Java are passed from caller to callee by reference
• Callee can modify original variables in the caller
A variable declared
inside a for-loop
body has its scope
limited in the loop
body from its
declaration to the
end of the block.