Tutorials References Exercises Videos Menu
Free Website Get Certified Pro

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java Inner Classes Java Abstraction Java Interface Java Enums Java User Input Java Date Java ArrayList Java LinkedList Java HashMap Java HashSet Java Iterator Java Wrapper Classes Java Exceptions Java RegEx Java Threads Java Lambda

Java File Handling

Java Files Java Create/Write Files Java Read Files Java Delete Files

Java How To

Add Two Numbers

Java Reference

Java Keywords Java String Methods Java Math Methods

Java Examples

Java Examples Java Compiler Java Exercises Java Quiz Java Certificate


Java Arrays


Java Arrays

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:

String[] cars;

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:

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

To create an array of integers, you could write:

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

Access the Elements of an Array

You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Example

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

Try it Yourself »

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.


Change an Array Element

To change the value of a specific element, refer to the 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

Try it Yourself »


Array Length

To find out how many elements an array has, use the length property:

Example

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

Try it Yourself »


Test Yourself With Exercises

Exercise:

Create an array of type String called cars.

  = {"Volvo", "BMW", "Ford"};

Start the Exercise