Java Arrays

JK JK 2038 
Created at
Updated at  
8,939 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,175
  2. How do I replace content that based on the HTML UI Template
    7,211
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,240
  4. Dataset of California Foodbanks
    7,227
  5. Java Tutorials associated with AP Computer Science A
    7,748
  6. Java Inner Classes
    7,137
  7. Java Polymorphism
    7,114
  8. Java Inheritance (Subclass and Superclass)
    7,234
  9. Java Packages
    7,235
  10. Java Abstract Classes and Methods
    7,846
  11. Java Classes and Objects
    7,177
  12. Java Recursion
    7,245
  13. Java Scope
    7,181
  14. Java Methods
    7,151
  15. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    8,012
  16. Java Switch Statements
    7,489
  17. Java Short Hand If...Else (Ternary Operator)
    7,660
  18. Java If ... Else
    7,489
  19. Java Math
    7,513
  20. Java Variables
    7,556
  21. Java Comments
    8,177
  22. The Print() Method
    7,216
  23. Java Syntax
    7,536
  24. Java Getting Started
    7,485
  25. What is Java?
    7,144
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    553
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    502
  3. Michael Jackson's Billie Jean
    346
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    241
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    262
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    285
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    302
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    337
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,008
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    486
  11. The Evolution and Production Reality of Agentic AI
    381
  12. How to Activate or Waive Your UIUC Student Health Insurance
    478
  13. Complete Guide to Building a Machine Learning Model
    500
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,573
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    519
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,267
  17. Clean Python Environments: The Power of venv vs. Docker
    1,049
  18. What is Docker? Why is Docker also useful in a development environment?
    772
  19. UIUC 2026-2027 Academic Calendar
    1,896
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,011
  21. Open-Source LLMs: The AI Revolution
    937
  22. Resume 2.0: Leveling Up for My First Software Gig
    2,750
  23. Not everyone will understand what this man just did
    2,272
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,789
  25. Unpacking IU's Shopper
    940
  26. Jackie Chan's Police Story: The Action Masterpiece
    816
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,132
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,347
  29. Open Databases for Sex Crime Occurrences in the U.S.
    907
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,157
  31. My First Day at University of Illinois-Urvana Champaign
    1,341
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,351
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,432
  34. Sipping the Stars: My Starbucks Adventure
    9,996
  35. Exciting explore at Sequoia National Park
    7,833
  36. My Life Shot at Death Valley
    1,963
  37. Ip Man fights with Muay Thai Master
    1,098
  38. Mad Clown - Don't Die
    1,211
  39. How to get Student Enrollment and Degree Verification at UIUC
    5,525
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,055
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,302
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,120
  43. 10CM - To Reach You (너에게 닿기를)
    1,306
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,712
  45. BOYNEXTDOOR - If I Say I Love You
    1,336
  46. The Future of Software Engineer - AI Engineering
    1,059
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,062
  48. Lie - Legend song by BIGBANG
    7,958
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,037
  50. Reimbursement after Vaccination at McKinley Health Center
    1,167