Java Array
Java Tutorial » Java Array
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
If you need to store 50 car make then we create an array of the string type that can store this 50 car make.
To declare an array, define the variable type with square brackets as:
String[] cars_make;
Example:
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
How to create array of integers, example:
int[] my_Num = {11, 12, 13, 14, 15, 16, 17, 18};
Access an Elements of an Array, example
You access an array element by referring to the index number.
Example:
Output:
Mazda
public class Main {
public static void main(String[] args) {
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
System.out.println(cars_make[3]);
}
}
public static void main(String[] args) {
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
System.out.println(cars_make[3]);
}
}
Output:
Mazda
Change an Array Element
Example, how to change a value of a specific element,
Example:
Bugatti
public class Main {
public static void main(String[] args) {
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
cars_make[1] = "Bugatti";
System.out.println(cars_make[1]);
}
}
Output: public static void main(String[] args) {
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
cars_make[1] = "Bugatti";
System.out.println(cars_make[1]);
}
}
Bugatti
Loop Through an Array
You can loop through array elements with for loop, Then use the length property to specify how many times the loop should run.
Example:
Audi
AstonM
Opel
Mazda
Renault
public class Main {
public static void main(String[] args) {
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
for (int x = 0; x < cars_make.length; x++) {
System.out.println(cars_make[x]);
}
}
}
Output: public static void main(String[] args) {
String[] cars_make = {"Audi", "AstonM", "Opel", "Mazda", "Renault"};
for (int x = 0; x < cars_make.length; x++) {
System.out.println(cars_make[x]);
}
}
}
Audi
AstonM
Opel
Mazda
Renault
java array length, methods, append. of objects, initialization, declaration, add, class, to string, sort, java add element to array, define array, dynamic
Java Array - java
Online Editor
This tool makes it easy to create, adjust, and experiment with custom colors for the web.
HTML Templates

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.
CSS HTML Layout

Find here examples of creative and unique website layouts.
Free CSS HTML Menu

Find here examples of creative and unique website CSS HTML menu.