The Dev Newbie
Published in

The Dev Newbie

Arrays in Java

Java Arrays

String[] cars;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

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

Change an Array Element

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

Array Length

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

Loop Through an Array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}

Use For-Each

for (type variable : arrayname) {
...
}

Multidimensional Arrays

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
public class MyClass 
{
public static void main(String[] args)
{
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}

--

--

A publication for new programmers, web developers and more. The Dev Newbie is an assortment of helpful notes - ranging from Angular, HTML and CSS to Java. Doesn’t matter whether you’re a complete beginner - or just revisiting a language after a long time - we’ve got you covered.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soumyadip

HTML, CSS, Angular and Java amateur at 16 years old. Is also learning UI/UX design as an encore.