Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Arrays

Java Arrays

Arrays serve to consolidate multiple values within a solitary variable, eliminating the need for individual variable declarations.

When declaring an array, indicate the variable type followed by square brackets:

String[] cars;

We’ve defined a variable capable of holding an array of strings. To populate it, you can enclose the values within curly braces, separated by commas.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To generate an array of integers, you might express it as follows:

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

Access the Elements of an Array

You can retrieve an array element by referencing its index number.

This statement retrieves the value of the initial element in the “cars” array.

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo

 

Note that array indexes commence at 0: [0] represents the first element, [1] denotes the second element, and so forth.

Change an Array Element

To modify the value of a particular element, reference its index number.

Example

cars[0] = "Opel";

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo

Array Length

To determine the number of elements within an array, utilize the length property.

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4