Java Arrays

JK JK 2038 
Created at
Updated at  
9,133 0 0

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, you can 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 can access an array element by referring to the index number.

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

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

Change an Array Element

To change the value of a specific element, refer to the index number:

Example 1)

cars[0] = "Opel";

Example 2)

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

Array Length

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

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

Loop Through an Array

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

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

Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

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

The following example outputs all elements in the cars array, using a "for-each" loop:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

The example above can be read like this: for each String element (called i - as in index) in cars, print out the value of i.

If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.


Multidimensional Arrays

A multidimensional array is an array of arrays.

Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows and columns.

To create a two-dimensional array, add each array within its own set of curly braces:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.


Access Elements

To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. This example accesses the third element (2) in the second array (1) of myNumbers:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(myNumbers[1][2]); // Outputs 7

Change Element Values

You can also change the value of an element:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7

Loop Through a Multi-Dimensional Array

We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we still have to point to the two indexes):

public class Main {
  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]);
      }
    }
  }
}

 

Below YouTube content is also helpful for better understanding:

Tags Array Array Element Array Length Java Array Multi-Dimensional Array Facebook X
Comments 0
  1. Java Servlet Example
    7,216
  2. How do I replace content that based on the HTML UI Template
    7,247
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,287
  4. Dataset of California Foodbanks
    7,267
  5. Java Tutorials associated with AP Computer Science A
    7,804
  6. Java Inner Classes
    7,179
  7. Java Polymorphism
    7,156
  8. Java Inheritance (Subclass and Superclass)
    7,274
  9. Java Packages
    7,285
  10. Java Abstract Classes and Methods
    7,941
  11. Java Classes and Objects
    7,221
  12. Java Recursion
    7,292
  13. Java Scope
    7,218
  14. Java Methods
    7,193
  15. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    8,083
  16. Java Switch Statements
    7,542
  17. Java Short Hand If...Else (Ternary Operator)
    7,716
  18. Java If ... Else
    7,530
  19. Java Math
    7,573
  20. Java Variables
    7,616
  21. Java Comments
    8,243
  22. The Print() Method
    7,261
  23. Java Syntax
    7,591
  24. Java Getting Started
    7,530
  25. What is Java?
    7,181
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    1,045
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    915
  3. Michael Jackson's Billie Jean
    434
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    414
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    362
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    401
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    397
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    426
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,409
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    576
  11. The Evolution and Production Reality of Agentic AI
    458
  12. How to Activate or Waive Your UIUC Student Health Insurance
    590
  13. Complete Guide to Building a Machine Learning Model
    605
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,648
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    608
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,388
  17. Clean Python Environments: The Power of venv vs. Docker
    1,131
  18. What is Docker? Why is Docker also useful in a development environment?
    842
  19. UIUC 2026-2027 Academic Calendar
    2,089
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,107
  21. Open-Source LLMs: The AI Revolution
    1,007
  22. Resume 2.0: Leveling Up for My First Software Gig
    3,074
  23. Not everyone will understand what this man just did
    2,535
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,901
  25. Unpacking IU's Shopper
    1,002
  26. Jackie Chan's Police Story: The Action Masterpiece
    894
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,248
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,420
  29. Open Databases for Sex Crime Occurrences in the U.S.
    1,009
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,492
  31. My First Day at University of Illinois-Urvana Champaign
    1,402
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,453
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,521
  34. Sipping the Stars: My Starbucks Adventure
    10,230
  35. Exciting explore at Sequoia National Park
    7,888
  36. My Life Shot at Death Valley
    2,103
  37. Ip Man fights with Muay Thai Master
    1,166
  38. Mad Clown - Don't Die
    1,281
  39. How to get Student Enrollment and Degree Verification at UIUC
    6,024
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,115
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,388
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,172
  43. 10CM - To Reach You (너에게 닿기를)
    1,357
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,771
  45. BOYNEXTDOOR - If I Say I Love You
    1,412
  46. The Future of Software Engineer - AI Engineering
    1,131
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,139
  48. Lie - Legend song by BIGBANG
    8,034
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,126
  50. Reimbursement after Vaccination at McKinley Health Center
    1,254