Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Fundamental Programming

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

© All rights reserved. 2


Array Initialization

If array size is small – use shortcuts If array size is big – use loops

double[ ] A = { 2.4, 3.2, 1.8, 7.6 } ;


Scanner sc = new Scanner(System.in)
OR double[ ] A = new double[100];
for ( 𝑖 = 0; 𝑖 ≤ 𝐴. 𝑙𝑒𝑛𝑔𝑡ℎ; 𝑖 + + )
double[ ] A = new double[4]; A[ 𝑖 ] = sc.nextDouble();
A[0] = 2.4 ;
A[1] = 3.2 ;
A[2] = 1.8 ;
A[3] = 7.6 ;
© All rights reserved. 3
Examples
Initializing to random
integers

Printing the content

Summing all elements

Finding the maximum

© All rights reserved. 4


Examples (cont.)

Random shuffling

Printing the content


using for-each loop

© All rights reserved. 5


Two-Dimensional Arrays

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;

But how 2D arrays stored in memory? See next slide

© All rights reserved. 6


Row-Major Representation
• Multi-dimensional arrays (1D, 2D, 3D, etc) are stored
in memory row-by-row A[0][0] 5
row 0 A[0][1] 3
A[0][2] 1
[0] [1] [2]
A[1][0] 6
[0] 5 3 1
row 1 A[1][1] 2
In memory
[1] 6 2 8 A[1][2] 8
[2] 4 1 9 A[2][0] 4
[3] 0 1 3 row 2 A[2][1] 1
A[2][2] 9
From previous slide
A[3][0] 0
row 3 A[3][1] 1
© All rights reserved. A[3][2] 3 7
Examples

2D array initialization

Printing the content

Summing all elements

© All rights reserved. 8


Arrays Utility
• Built-in class that contains various methods for manipulating arrays
• Some supported methods (see Java documentation for more):
Arrays.copyof(T[] original, int length) Return a copy of the array with the specified length
Arrays.sort(T[] original) Sort the array ascendingly
Arrays.equals(T[] A, T[] B) Return true if two arrays are equal
Arrays.deepEquals(T[] A, T[] B) Return true if the two arrays are deeply equal to each other
Arrays.fill(T[] original, int from, int to, T value) Fill the specified range in array with the given value
Arrays.toString(T[] A) Return a string representing the content of the array

© All rights reserved. 9


Back to Strings
• A String is essentially an array of characters
• Java has a verity of built-in methods for manipulating strings
• Examples of supported methods
String str = “welcome to the exciting world of Java!”;
char c = str.charAt(5); // return the character at index 5, which is m
int x = str.indexof(‘e’); // return the index of the first occurrence of ‘e’, which is 1
int y = str.length(); // return the length of the string, which is 38
String w = str.replace(‘w’,’#’); // replace all occurrences of ‘w’ with ‘#’
char[] t = str.toCharArray(); // convert the string into an array of characters

© All rights reserved. 10


More Examples on Strings
String s1 = “Welcome to Java”;
System.out.print(s1.startsWith(“We”)); // prints true
System.out.print(s1.endWith(“a”)); // prints true
System.out.print(s1.indexOf(‘a’)); // prints 12
System.out.print(s1.lastIndexOf(‘a’)); // prints 14
System.out.print(s1.indexOf(“come”)); // prints 3
System.out.print(s1.substring(8)); // prints “to Java”
System.out.print(s1.substring(8,12)); // prints “to J”
System.out.print(s1.concate(“!!!”)); // prints “Welcome to Java!!!”
System.out.print(s1.toLowerCase()); // prints “welcome to java”
System.out.print(s1.toUpperCase()); // prints “WELCOME TO JAVA”
System.out.print(s1.replace(‘a’, ’A’); // prints “welcome to jAvA”

© All rights reserved.


Methods

• Methods define reusable code in programs


• Having methods lead to simplified and organized programs
• Methods have zero or more input arguments
• Methods can return an output
• Methods can be called by other methods in the program

© All rights reserved. 12


Method Example

Method definition

Question: What does the


keyword “void” mean?

Invoking a method

© All rights reserved. 13


Invoking Methods
• What happens when a method invokes another method?

• When a method is invoked, JVM creates an activation record (aka


activation frame), which stores values for parameters and variables
• Activation records are kept in an area of memory called the call stack
© All rights reserved. 14
Call Stack
average average
Activation Activation
record record
result: result: 4.3
n2: 3.2 n2: 3.2
n1: 5.4 n1: 5.4

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

© All rights reserved. 16


Method Overloading
• Java allows having methods with the same name if they have different signatures

© All rights reserved. 17


Naming Convention
• When naming identifiers for variables or methods, use lowercase letters.
• If the name consists of multiple words, concatenate them while making
the first word lowercase, and use uppercase only for the first letter in
subsequent letters.
• When naming classes, capitalize the first letter only. Remaining letters are
lowercase.
• When naming constants, capitalize all letters.

© All rights reserved. 18


The Scope of Variables
• The scope of a variable is the part of the program where the variable
can be referenced.
• A variable defined inside a method is referred to as a local variable.
• The scope of a local variable starts from its declaration and continues to the
end of the block that contains the variable.
• A local variable must be declared and assigned a value before it can be used.
• A parameter is actually a local variable.
• The scope of a method parameter covers the entire method.

© All rights reserved. 19


The Scope of Variables (Cont.)
A variable declared in the
initial-action part of a for-
loop header has its scope
in the entire loop.

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.

© All rights reserved. 20


The Scope of Variables (Cont.)
• You can declare a local variable with the same name in
different blocks in a method.
• But you cannot declare a local variable twice in the same block
or in nested blocks.

© All rights reserved. 21


Classroom Exercise 1
• Write a java program that creates a 3D integer array with dimension
sizes: 5, 2, and 3, then initializes the content of the array to random
integers between 100 and 200, and then prints the content of the
array.

© All rights reserved. 22


Classroom Exercise 2
• Write a method, called countOfZeroes, that receives an array of
integers A as an input argument, and then the function will return an
integer representing the count of pairs with sum equal to zero.
• E.g., if the input A = [3 , -4, 0, -5, 1, -1, -3], then the returned value
should be 2. This is because A has two pairs with zero sum: (1,-1) and
(-3,3).

© All rights reserved. 23


Classroom Exercise 3
• Write a method, called isPalindrome, that receives a string s as an
input argument, and then it returns true if the given string is a
palindrome. Note that a string is a palindrome if it reads from left to
right the same way from right to left. For example, the words “kayak”
and “noon” are palindromes.

© All rights reserved. 24


Classroom Exercise 4
• Write a method, called shiftRight, that shifts a given input array A to
the right by one element.
• E.g., if the given array is A = [4 , 7, 1, 2], then the method should shift
the array to the right to become A = [2, 4, 7, 1].

© All rights reserved. 25

You might also like