Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Object-Oriented Programming Module 5

1. The document discusses arrays and methods in Java programming over weeks 6-7 of a course. It covers declaring, initializing, and accessing array elements using indexes from 0 to length-1. Methods allow storing and retrieving multiple values in an organized way. 2. Examples show how to declare arrays, assign values during declaration, access elements using indexes, and modify values. Arrays provide a way to efficiently work with large sets of related data in Java. 3. The key aspects of arrays discussed are declaration syntax, default element values, initializing during/after declaration, accessing via indexes in for loops or individually, and modifying element values.

Uploaded by

Glenlyn Forel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Object-Oriented Programming Module 5

1. The document discusses arrays and methods in Java programming over weeks 6-7 of a course. It covers declaring, initializing, and accessing array elements using indexes from 0 to length-1. Methods allow storing and retrieving multiple values in an organized way. 2. Examples show how to declare arrays, assign values during declaration, access elements using indexes, and modify values. Arrays provide a way to efficiently work with large sets of related data in Java. 3. The key aspects of arrays discussed are declaration syntax, default element values, initializing during/after declaration, accessing via indexes in for loops or individually, and modifying element values.

Uploaded by

Glenlyn Forel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PAMANTASAN NG LUNGSOD NG MUNTINLUPA

LEARNING COLLEGE OF INFORMATION TECHNOLOGY


MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 1 of 22

WEEK 6 - 7

ARRAYS AND METHODS

At the end of the discussion, the student should be able to:


1. Create a program that uses an array and apply I/O to demonstrate the
used of the control structure in Java programming.
2. Design an array program and use a simple OOP to emphasize the used
of OOP in Java.
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 2 of 22

6.1 Arrays
In this chapter we'll learn how to deal with Java arrays. Using examples, we'll learn how to declare,
initialize, and access array elements.

An array is a set of related data types. It is a container which holds one type of data (values). You can
create an array, for example, that can hold 100 values of type int.

In Java, arrays are a fundamental construct allowing you to easily store and access a large number of
values.

6.1.1 How to declare an array?


So here's how we can declare an array in Java.
dataType[] arrayName;

 dataType = Primitive data types, such as int, char, double, bit, etc., or Java objects

 arrayName = it is an identifier

Let's take an example,


double[] data;

Here, data is an array which can hold double type values.

But, how many elements can array this hold?

Fair question anyway! We will assign the array to memory. The memory determines the number of
elements the array can contain.

data = new Double[10];

In this case the array size is 10. That means it can keep up to 10 elements (10 values for double types).
The size of an array is also called the array length.

Note: This can not be changed in the program once the length of the array is defined.
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 3 of 22

Let's take another example:


int[] age;

age = new int[5];

Here, age is an array. It can hold 5 values of int type.

In Java, we are able to declare and assign array memory in a single sentence. For instance,
int[] age = new int[5];

6.1.2 Java Array Index


For Java a number is associated with each element in an array. The number is known as an index to an
array. With such indices we can access elements of an array. For instance,
int[] age = new int[5];

Here, we have an array of length 5. We can see in the image that each element is composed of a
number (array index). The indices on the array always start with 0.

Now, we are able to use the index number to access array elements. For example, we can use age[0] to
access the first element in the sequence, and access the second element using age[1], and so on.

Note: If the length of an array is n, arrayName[0] will be the first element in the array and arrayName[n-1]
will be the last component.

If we have not stored any value in an array, the array will store a certain default value (0 for type int
and false for type boolean) by itself. For instance,

class ArrayExample {
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 4 of 22

public static void main(String[] args) {

// create an array of length 5

int[] age = new int[5];

// access each element of the array using the index number

System.out.println(age[0]);

System.out.println(age[1]);

System.out.println(age[2]);

System.out.println(age[3]);

System.out.println(age[4]);

Output:

In the example above, we generated an array called era. We did not assign any values to the array,
however. Therefore the default values are printed to the screen when we reach the individual elements of the
series.

Here, the elements of the collection are accessed individually. There is a simpler way of using a loop to
access array elements (generally for-loop). For instance,

class ArrayExample {

public static void main(String[] args) {


PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 5 of 22

// create an array of length 5

int[] age = new int[5];

// accessing elements using for loop

for (int i = 0; i < 5; ++i) {

System.out.println(age[i]);

Output:

6.1.3 How to initialize arrays in Java?


In Java, we can initialize arrays during declaration, or you can initialize them later as per your
requirement in the program.

6.1.4 Initialize an Array During Declaration


Here's how you can initialize an array during declaration.
int[] age = {12, 4, 5, 2, 5};

This statement generates an array called age and initializes it in the curly brackets with the value given.

The array length is determined by the number of values within the curly braces, separated by commas.
In our case, the age limit is 5.
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 6 of 22

Let's write a simple program to print out this list of elements.


class ArrayExample {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5, 2, 5};

// access elements of tha arau

for (int i = 0; i < 5; ++i) {

System.out.println("Element at index " + i +": " +


age[i]);

Output:

Element at index 0: 12

Element at index 1: 4

Element at index 2: 5

Element at index 3: 2

Element at index 4: 5

6.1.4 How to access array elements?


We can easily access and modify elements of an array using its numeric index, as discussed before. For
instance,
class ArrayExample {

public static void main(String[] args) {


PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 7 of 22

int[] age = new int[5];

// insert 14 to third element

age[2] = 14;

// insert 34 to first element

age[0] = 34;

for (int i = 0; i < 5; ++i) {

System.out.println("Element at index " + i +": " + age[i]);

Output:

Element at index 0: 34

Element at index 1: 0

Element at index 2: 14

Element at index 3: 0

Element at index 4: 0

6.1.4 Example: Java arrays


The following software calculates the number and average of values stored in an int-type array.
class SumAverage {

public static void main(String[] args) {

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};

int sum = 0;

Double average;
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 8 of 22

// for each loop is used to access elements

for (int number: numbers) {

sum += number;

int arrayLength = numbers.length;

// Change sum and arrayLength to double as average is in


double

average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);

System.out.println("Average = " + average);

Output:

Sum = 36

Average = 3.6

In the above example, we have created an array of named numbers. We have used the for...each loop to
access each element of the array.

\We calculate the sum of every element within the loop. Remark the line,

int arrayLength = number.length;

Here we use the array's longitude attribute to measure the array 's height.

average = ((double)sum / (double)arrayLength);

As you can see, the int value is transformed into a double. In Java this is called category casting.
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 9 of 22

6.1.5 Java Multidimensional Arrays


Using examples, we will learn about the multidimensional Java array in this tutorial using 2-
dimensional arrays and 3-dimensional arrays.

A multidimensional array is a multiplicity of arrays. Each element of a multidimensional array is itself


an array. For instance,

int[][] a = new int[3][4]

We generated a multi-dimensional array called a here. It is a 2-dimensional array, which can hold up to
12 elements,

Note, Java uses zero-based indexing, that is, Java array indexing begins with 0 rather than 1.

Let's take one more example of Multidimensional Collection. We are constructing a 3-dimensional
sequence this time. For example,
String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of type String.

6.1.5 How to initialize a 2d array in Java?

Here is how we can initialize a 2-dimensional array in Java.


int[][] a = {

{1, 2, 3},
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 10 of 22

{4, 5, 6, 9},

{7},

};

As we can see, every element in the multidimensional array is itself an array. And also, unlike C / C++,
every row in Java's multidimensional array can be of different lengths.

6.1.5 Example: 2-dimensional Array

class MultidimensionalArray {
public static void main(String[] args) {

// create a 2d array

int[][] a = {

{1, 2, 3},

{4, 5, 6, 9},

{7},

};

// calculate the length of each row

System.out.println("Length of row 1: " + a[0].length);

System.out.println("Length of row 2: " + a[1].length);


PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 11 of 22

System.out.println("Length of row 3: " + a[2].length);

Output:

Length of row 1: 3

Length of row 2: 4

Length of row 3: 1

In the above example, a multidimensional array named “a” is being generated. Since any part of a
multidimensional array is also an array (a[0], arrays are also a[1] and a[2]).

We use the longitudinal attribute here to measure the length of each row.

6.1.6 Example: Print all elements of 2d array Using Loop

class MultidimensionalArray {

public static void main(String[] args) {

int[][] a = {

{1, -2, 3},

{-4, -5, 6, 9},

{7},

};

for (int i = 0; i < a.length; ++i) {

for(int j = 0; j < a[i].length; ++j) {

System.out.println(a[i][j]);

}
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 12 of 22

Output:

-2

-4

-5

We can also use the for ... each loop to access multidimensional array elements. For instance,
class MultidimensionalArray {

public static void main(String[] args) {

// create a 2d array

int[][] a = {

{1, -2, 3},

{-4, -5, 6, 9},

{7},

};

// first for...each loop access the individual array

// inside the 2d array

for (int[] innerArray: a) {

// second for...each loop access each element inside the


row

for(int data: innerArray) {

System.out.println(data);

}
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 13 of 22

Output:

-2

-4

-5

We have generated a 2d array called an in the above example. We then used to access each part of the
array for loop and for ... each loop.

6.1.7 How to initialize a 3d array in Java?


Let's see how we can use a Java 3d series. A 3d array similar to the 2d array can be initialised. For instance,

// test is a 3d array

int[][][] test = {

{1, -2, 3},

{2, 3, 4}

},

{-4, -5, 6, 9},

{1},

{2, 3}

}
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 14 of 22

};

A 3d array is basically a collection of 2d arrays. The length of a 3d array's rows can also differ just as in a 2d array.

6.1.8 Example: 3-dimensional Array


class ThreeArray {

public static void main(String[] args) {

// create a 3d array

int[][][] test = {

{1, -2, 3},

{2, 3, 4}

},

{-4, -5, 6, 9},

{1},

{2, 3}

};

// for..each loop to iterate through elements of 3d array

for (int[][] array2D: test) {

for (int[] array1D: array2D) {

for(int item: array1D) {

System.out.println(item);

}
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 15 of 22

Output:

-2

-4

-5

6.2 Introduction to Array Methods in Java


Array class provides static methods for dynamically constructing as well as accessing Java
arrays. Arrays have only static methods, and Object type methods.
The following are the top ten Java Array methods. They are the stackoverflow questions with
the most votes.

1. Print an array in Java


int[] intArray = { 1, 2, 3, 4, 5 };

String intArrayString = Arrays.toString(intArray);

// print directly will print reference value

System.out.println(intArray);

// [I@7150bd4d

System.out.println(intArrayString);
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 16 of 22

// [1, 2, 3, 4, 5]

2. Create an ArrayList from an array


String[] stringArray = { "a", "b", "c", "d", "e" };

ArrayList<String> arrayList = new


ArrayList<String>(Arrays.asList(stringArray));

System.out.println(arrayList);

// [a, b, c, d, e]

3. Check if an array contains a certain value


String[] stringArray = { "a", "b", "c", "d", "e" };

boolean b = Arrays.asList(stringArray).contains("a");

System.out.println(b);

// true

4. Concatenate two arrays


int[] intArray = { 1, 2, 3, 4, 5 };

int[] intArray2 = { 6, 7, 8, 9, 10 };

// Apache Commons Lang library

int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

5. Declare an array inline


method(new String[]{"a", "b", "c", "d", "e"});

6. Joins the elements of the provided array into a single String

// containing the provided list of elements

// Apache common lang

String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");

System.out.println(j);

// a, b, c

7. Covnert an ArrayList to an array


String[] stringArray = { "a", "b", "c", "d", "e" };

ArrayList<String> arrayList = new


ArrayList<String>(Arrays.asList(stringArray));

String[] stringArr = new String[arrayList.size()];

arrayList.toArray(stringArr);
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 17 of 22

for (String s : stringArr)

System.out.println(s);

8. Convert an array to a set


Set<String> set = new HashSet<String>(Arrays.asList(stringArray));

System.out.println(set);

//[d, e, b, c, a]

9. Reverse an array
int[] intArray = { 1, 2, 3, 4, 5 };

ArrayUtils.reverse(intArray);

System.out.println(Arrays.toString(intArray));

//[5, 4, 3, 2, 1]

10. Remove element of an array


int[] intArray = { 1, 2, 3, 4, 5 };

int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array

System.out.println(Arrays.toString(removed));
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 18 of 22

SELF-EVALUATION
1. Examine Java code below. What is the name of the string variable which is converted to a byte array?

a. getBytes c. loginName

b. Undefined d. loginBytes

2. What is the name of the method being used to display a readable version of the byte array coolArray in
this Java code?

a. getBytes c. toString

b. getString d. System.out.print

3. When converting a string to a byte array in Java, the values in each bucket of the array are .

a. EBSIDEC c. ASCII

b. Void d. Byte counts

4. An array in Java that would have rows and columns is called a _____ array?

a. Cubic c. Two-dimensional

b. Sequence d. Three-dimensional

5. What type of an array is this?


PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 19 of 22

a. String c. Double

b. Integer d. Character

6. Which of the following is FALSE about arrays on Java

a. A java array is always an object

b. Lenght of array can be changed after creation of array.

c. Arrays in Java are always allocated on heap

7. Predict the output?

// file name: Main.java

public class Main {

public static void main(String args[]) {

int arr[] = {10, 20, 30, 40, 50};

for(int i=0; i < arr.length; i++)

System.out.print(" " + arr[i]);

a. 10 20 30 40 50

b. Compile Error

c. 10 20 30 40

8. Predict the output?

a. 0 0 c. Compile Error

b. garbage value d. Exception

garbage value
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 20 of 22

9. Predict the output?

a. 0 0 c. Compile Error

b. garbage value d. Exception

garbage value

10. Predict the output?

a. Compile error

b.
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 21 of 22

c.

d.
PAMANTASAN NG LUNGSOD NG MUNTINLUPA
LEARNING COLLEGE OF INFORMATION TECHNOLOGY
MODULE
AND COMPUTER STUDIES
University Road, Poblacion, Muntinlupa City

QD/CITCS/0__ Course Title: OOP23-OBJECT-ORIENTED-PROGRAMMING


Issue No. 0 Revision No. 0 Effectivity Date 07 September 2020 Page No. 22 of 22

LABORATORY EXERCISES
Machine Problem 1:
Write a Java program to remove a given array's duplicate elements, and return the new array
length.
Sample array: [20, 20, 30, 40, 50, 50, 50]
After removing the duplicate elements the program should return 4 as the new length of the
array.

Machine Problem 2:
Write a Java program to find smallest and second smallest elements of a given array.

Machine Problem 3:
Write a Java program to find the second largest element in an array

Machine Problem 4:
Write a Java program to find the second smallest element in an array

Machine Problem 5:
Write a Java program to find the number of even and odd integers in a given array of integers.

You might also like