Skip to main content
Arrays
  • An array is a sequence of values
  • Used to store multiple values of the same type using a single variable
  • The size of the array is fixed, determined when created
  • The values in the array are called elements
  • Elements in arrays are accessed using an index
  • The index starts at 0, not 1

Creating Arrays

int[] data = new int[10];

double[] priceList;
priceList = new double[5];

String[] names = {"Ani", "Budi", "Cinta"};

Accessing Elements

int[] counts = new int[4];
counts[0] = 7;
counts[1] = counts[0] * 2;
counts[2]++;
counts[3] = counts[3] - 60;

Displaying Arrays

int[] values = {89, 50, 77};
System.out.println(values); // [I@15db9742

Array length

.length : digunakan untuk mengetahui panjang array yang dimiliki oleh suatu array
int[] values = {89, 50, 77};
for (int i = 0; i < 3; i++) {
    System.out.println(values[i]);
}
for (int i = 0; i < values.length; i++) {
    System.out.println(values[i]);
}

Copying Arrays

int[] a = {89, 50, 77};
int[] b = a;
b[0] = b[0] - 20;
System.out.println(a[0]);
System.out.println(b[0]);

Array Traversal

int[] values = {89, 50, 77};
for (int i = 0; i < values.length; i++) {
    System.out.println(values[i]);
}
for (int i = 0; i < values.length; i++) {
    values[i] = values[i] * 2;
}

String \Leftrightarrow char Array

String word = "lemon";
char[] characters = word.toCharArray();

characters[0] = 'm';
characters[2] = 'l';

String word2 = String.valueOf(characters);

System.out.println(word2);

Exercise

  • Create an array that can hold 15 integers
  • Fill up each element of the array with the number 123
  • Then display the contents of the array Question 1
  • Create an array that can hold 5 integers
  • Fill up the array with user inputs
  • Then display the contents of the array Question 2
  • Create an array that can hold nn integers
  • nn is user input
  • Fill up the array with user inputs
  • Then display the contents of the array Question 3
  • Create an array that can hold nn integers
  • nn is user input
  • Fill up the array with user inputs
  • Then display the contents of the array starting from the last element to the first Question 4
  • Create an array that can hold nn integers
  • nn is user input
  • Fill up the array with user inputs
  • Then display the contents of the array starting from the last element to the first Question 5 Question 5
  • Make a program to check whether a word entered by a user is palindrome or not
  • A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward
  • Examples:
    • eye
    • level
    • radar
    • madam
    • refer
    • Question 6
  • Write a program that asks the user to enter the student’s name and grade n times.
  • After all data is entered, the user can search for the grade of a student by entering his name.
  • The program stops when the user enters “-” when asked for the name Question 7