Lab 5
Lab 5
OBJECT-ORIENTED PROGRAMMING
LAB 5: REVIEW
I. Objective
After completing this tutorial, we want you to:
• Review about Array in Java,
• Review String in Java,
• Review OOP, Class, and Encapsulation in Java.
II. Array
1. Array is used to store multiple values in a single variable, instead of declaring separate
variables for each value:
4. To find out how many elements an array has, use the length property:
5. You can loop through the array elements with the for loop, and use the length property to
specify how many times the loop should run.
6. There is also a "for-each" loop, which is used exclusively to loop through elements in the
array:
int[] nums = {10, 20, 30, 40};
for (int num : nums) {
System.out.println(num);
}
III. String
1. Strings are used for storing text. A String variable contains a collection of characters
surrounded by double quotes:
3. You can reference the individual characters in a string by using the method charAt() with
the same index that you would use for an array:
5. You can use the concat() method to concatenate two strings. You can also concatenate two
strings to form another string by using the “+” operator:
public Student() {
this.name = "";
this.gender = "male";
this.age = 0;
}
V. Exercises
Array
1) Write a Java program:
a) Write method public static int maxEven(int[] a) to find the greatest even number in
an array.
b) Write method public static int minOdd(int[] a) to find the smallest odd number in
an array.
c) Write method public static int sumMEMO(int[] a) to calculate the sum of the greatest
even number and the smallest odd number in an array.
d) Write method public static int sumEven(int[] a) to calculate the sum of even
numbers in an array.
e) Write method public static int prodOdd(int[] a) to calculate the product of odd
numbers in an array.
f) Write method public static int idxFirstEven(int[] a) returns the position of the
first even number in the array.
g) Write method public static int idxLastOdd(int[] a) returns the position of the last
odd number in the array.
h) Write method public static int[] input(int n) returns an array with n elements
which input from keyboard.
i) Write a main method public static void main(String[] args):
-- END --