CC 103
PROGRAMMING 2
Second Semester A.Y. 2023 - 2024
Java Arrays
An array in Java is a data structure that allows you to store
multiple values of the same data type under a single
variable name. Arrays are used to store collections of data
elements, such as integers, strings, or objects.
Java Arrays
• Declaring and Initializing Arrays:
To declare an array variable in Java, you specify the data type of the elements followed
by square brackets [] and then the variable name.
Java Arrays
To initialize an array, you can use the new keyword along with the data type and the
number of elements in the array. Here's how you initialize an array of integers with 5
elements:
Java Arrays
Accessing Array Elements
Array elements are accessed using their index, which starts from 0 for the first element.
You can access an element by specifying its index within square brackets [].
Java Arrays
Array Length
You can obtain the length of an array (i.e., the number of elements it contains) using
the length property. Here's how you can retrieve the length of an array:
Java Arrays
Iterating Through Arrays
You can use loops, such as for or for each, to iterate through the elements of an array.
Here's an example using a for loop:
Java Arrays
Exercise 1
Write a program that initializes an array of strings containing 5 names of your favorite
fruits. Then, iterate through the array and print each fruit name.
Exercise 2
Write a program that initializes an array of integers with 10 random numbers. Then,
find and print the maximum and minimum values in the array.
Exercise 3
Write a program that prompt the user to enter 5 integers. Then, calculate and print the
sum of all the elements in the array.
THANK YOU!