Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
int[] myArr;
We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:
int[] myArr = {1, 2, 3};
Access an array element by pointing to its index number
Example:
String[] myFriends = {"Ahmad", "Abu", "Ali"};
System.out.println(myFriends[0]);
// Output: Ahmad
To find out how many elements in an array just use length
property:
String[] myFriends = {"Ahmad", "Abu", "Ali"};
System.out.println(myFriends.length);
// Output: 3
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.
String[] myFriends = {"Ahmad", "Abu", "Ali"};
for (int i = 0; i < myFriends.length; i++) {
System.out.println(myFriends[i]);
}
// Output👇
// Ahmad
// Abu
// Ali
You can declare an array with empty element and initialize it later.
String[] favFood = new String[3]; // empty array
// initialize element in array
favFood[0] = "Karipap";
favFood[1] = "Nasi Lemak";
favFood[2] = "Ramen";
// print all elements in array
for (int i = 0; i < favFood.length; i++) {
System.out.println(favFood[i]);
}
// Output👇
// Karipap
// Nasi Lemak
// Ramen
The charAt()
method returns the character at the specified index in a string.
The index of the first character is 0, the second character is 1, and so on.
Example:
String text = "Mom";
char result = text.charAt(0);
System.out.println(result);
// Output: M
- applicable for string objects
- method returns the number of characters present in the string
- suitable for string objects but not for arrays.
Example:
String text = "Mom";
int length = text.length();
System.out.println(length);
// Output: 3
Determine position in string:
String text = "Mom";
for (int i = 0; i < text.length(); i++) {
System.out.print("At index " + i + ", the character is " + text.charAt(i));
}
// Output👇
// At index 0, the character is M
// At index 1, the character is 0
// At index 2, the character is m