π° Introduction to Arrays in Java
In Java programming, one of the first major problems beginners face is how to store and manage multiple values efficiently.
Creating a separate variable for every value is not practical and leads to messy code.
Thatβs where arrays come into the picture.
π An array is a data structure that allows us to store multiple values of the same data type in a single variable.
Arrays form the foundation for:
- Loops
- Searching & sorting
- Strings
- Collections
- Data Structures
- Competitive programming & interviews
Understanding arrays properly will make everything else in Java easier.
π§ What Exactly Is an Array?
An array is:
- A fixed-size container
- Stores homogeneous data (same data type)
- Accessed using index values
- Stored in contiguous memory locations
π Important:
- First index =
0 - Last index =
size - 1
π§± Single Dimensional Array in Java (1D Array)
A single dimensional array stores data in a linear sequence, like a list.
π Declaring a Single Dimensional Array
πΉ Syntax
dataType[] arrayName;
πΉ Example
int[] marks;
π§ Explanation:
int[]β type of arraymarksβ reference variable- No memory allocated yet
β οΈ This line does not create the array, it only creates a reference.
πΎ Allocating Memory to Array
πΉ Using new keyword
marks = new int[5];
π§ Explanation:
newβ creates array objectint[5]β size of array = 5- Index range β
0 to 4
π Once size is fixed, it cannot be changed.
π§© Declaration + Allocation Together (Most Used)
int[] marks = new int[5];
β Clean
β Recommended
β Industry standard
π― Assigning Values to Array Elements
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
marks[3] = 88;
marks[4] = 92;
π§ Explanation:
- Each value is stored at a specific index
- Index must be within range
β οΈ Common Beginner Mistake β Invalid Index
marks[5] = 100;
β Runtime Error
β ArrayIndexOutOfBoundsException
π Valid indexes: 0 β 4 only
π Accessing Array Elements
System.out.println(marks[2]);
π§ Output:
78
π Traversing Array Using for Loop
for(int i = 0; i < marks.length; i++) {
System.out.println(marks[i]);
}
π§ Line-by-line explanation:
i = 0β start from first indexmarks.lengthβ total size of array- Loop stops before invalid index
marks[i]β access element at indexi
π length is a variable, not a method
β marks.length() β WRONG
π Traversing Using Enhanced for Loop (for-each)
for(int value : marks) {
System.out.println(value);
}
β No index handling
β Cleaner syntax
β Index not available
β Cannot modify element position
β οΈ Default Values in Array
When you create an array, Java automatically assigns default values.
| Data Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| char | ‘\u0000’ |
| boolean | false |
| String | null |
int[] arr = new int[3];
System.out.println(arr[0]);
π§ Output:
0
β Confusion: Array Size vs Index
int[] arr = new int[3];
β Size = 3
β Indexes = 0, 1, 2
β Index 3 is invalid
𧨠Tricky Example β Zero Length Array
int[] arr = new int[0];
System.out.println(arr.length);
π§ Output:
0
β Valid array
β Cannot store values
π« Null Array Confusion
int[] arr = null;
System.out.println(arr.length);
β Runtime Error
β NullPointerException
π Array object does not exist in memory
π§± Multidimensional Array in Java (2D Array)
A multidimensional array stores data in rows and columns, similar to a table.
π Declaring 2D Array
int[][] matrix;
πΎ Allocating Memory
matrix = new int[2][3];
π§ Meaning:
- 2 rows
- 3 columns each
π― Assigning Values
matrix[0][0] = 10;
matrix[0][1] = 20;
matrix[0][2] = 30;
π First index β row
π Second index β column
π Traversing 2D Array (Nested Loop)
for(int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
π§ Explanation:
matrix.lengthβ number of rowsmatrix[i].lengthβ columns in that row- Nested loop required
β οΈ Common 2D Array Mistake
matrix[2][3] = 50;
β Index out of range
β Runtime error
π§© Jagged Array in Java (Important Concept)
Jagged array means unequal column sizes.
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[1];
β Valid in Java
β Frequently asked in interviews
β Confusing for beginners
𧨠Tricky Interview Code
int[] arr = {1, 2, 3};
arr = new int[]{9, 8};
System.out.println(arr.length);
π§ Output:
2
π Old array is discarded
π Reference points to new array
String Arrays in Java
So far, we have seen examples using int arrays.
In real applications, we often need to store text data such as names, cities, subjects, usernames, etc.
For this purpose, Java provides String arrays.
A String array is an array that stores multiple String values.
Declaring a String Array
String[] names;
At this stage:
- Only a reference is created
- No memory is allocated for storing strings
Creating a String Array
names = new String[3];
This creates an array that can store 3 String values.
Valid indexes are:
names[0]names[1]names[2]
Each element is initialized with the default value null.
Declaring and Creating a String Array Together
String[] names = new String[3];
This is the most commonly used way to create a String array.
Assigning Values to a String Array
String[] names = new String[3];
names[0] = "Ajay";
names[1] = "Rahul";
names[2] = "Neha";
Each index stores exactly one String value.
Accessing Elements from a String Array
System.out.println(names[0]);
System.out.println(names[1]);
System.out.println(names[2]);
Output:
Ajay
Rahul
Neha
String Array Using Direct Initialization
String[] languages = {"Java", "Python", "C++"};
Here:
- Array size is automatically decided
- Values are assigned at the time of creation
Traversing a String Array Using for Loop
String[] fruits = {"Apple", "Banana", "Mango"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
Traversing a String Array Using for-each Loop
for (String fruit : fruits) {
System.out.println(fruit);
}
This loop is:
- Easy to read
- Mostly used when index is not required
Default Values in String Arrays
String[] data = new String[2];
System.out.println(data[0]);
System.out.println(data[1]);
Output:
null
null
Unlike int arrays (default value 0),
String arrays have null as the default value.
Common Mistake with String Arrays
Using == instead of equals() to compare strings.
Wrong way:
if (names[0] == "Ajay") {
System.out.println("Match");
}
Correct way:
if (names[0].equals("Ajay")) {
System.out.println("Match");
}
Searching an Element in a String Array
String[] cities = {"Pune", "Mumbai", "Delhi"};
String search = "Mumbai";
boolean found = false;
for (String city : cities) {
if (city.equals(search)) {
found = true;
break;
}
}
System.out.println(found);
Multidimensional String Array (2D)
Just like int, Java also supports 2D String arrays.
String[][] students = {
{"Ajay", "Rahul"},
{"Neha", "Priya"}
};
Accessing Elements from 2D String Array
System.out.println(students[0][0]); // Ajay
System.out.println(students[1][1]); // Priya
Traversing a 2D String Array
for (int i = 0; i < students.length; i++) {
for (int j = 0; j < students[i].length; j++) {
System.out.print(students[i][j] + " ");
}
System.out.println();
}
Important Points About String Arrays
- String arrays store references to String objects
- Default value is
null - Size is fixed
- Index starts from
0 - Invalid index access throws
ArrayIndexOutOfBoundsException
β Common Mistakes & Confusions (Very Important)
β Accessing invalid index
β Confusing length and length()
β Using array before initialization
β Forgetting nested loop for 2D array
β Assuming array size is dynamic
β Null array vs empty array confusion
π― When Should You Use Arrays?
β Fixed number of elements
β Fast access using index
β Base for data structures
β Simple memory management
π Conclusion
Arrays are the backbone of Java programming.
Most bugs in beginner programs happen due to array misunderstanding, not syntax.
If you clearly understand:
- Indexing
- Size
- Traversal
- Memory behavior
- 1D vs 2D arrays
π Youβll automatically improve in loops, strings, collections, and DSA.
π My advice:
Practice array programs daily, intentionally make mistakes, and analyze errors β thatβs how arrays truly become easy.
β Common Array Practice Questions
- Write a program to find the largest element in an array.
- Write a program to find the smallest element in an array.
- Write a program to calculate the sum of all elements in an array.
- Write a program to reverse an array.
- Write a program to count how many elements are even and how many are odd.
- Write a program to search for a given element in an array (Linear Search).
- Write a program to copy all elements from one array into another array.
- Write a program to sort an array in ascending order (use any sorting technique).
- Write a program to remove duplicate elements from an array.
- Write a program to find the second largest element in an array.

