Java Arrays (Beginner Guide with Examples)
Java Arrays: Store Multiple Values in One Variable (With Examples)
✨ Quick Summary
In this post, you’ll learn what Arrays are in Java and how to use them to store multiple values in a single variable. We will cover array declaration, initialization, accessing elements, and looping through arrays with easy examples.
In our previous post, we learned about Java Loops and how to repeat tasks in Java.
Now let’s learn another important concept: Java Arrays.
An array is used to store multiple values of the same data type in a single variable.
1) Why Do We Need Arrays?
Imagine you want to store marks of 5 students.
Without arrays, you would write:
int m1 = 90;
int m2 = 85;
int m3 = 70;
int m4 = 88;
int m5 = 95;
This is not a good approach. Arrays make it easier.
2) Declaring an Array in Java
There are two common ways to declare an array:
Both are correct, but the recommended style is: int[] numbers;
3) Creating and Initializing an Array
After declaring an array, you must allocate memory using new.
Example
int[] numbers = new int[5];
This creates an array of size 5.
4) Assigning Values to an Array
You can assign values like this:
public class ArrayValuesExample {
public static void main(String[] args) {
int[] marks = new int[5];
marks[0] = 90;
marks[1] = 85;
marks[2] = 70;
marks[3] = 88;
marks[4] = 95;
System.out.println("First student marks: " + marks[0]);
System.out.println("Last student marks: " + marks[4]);
}
}
5) Another Way: Array Initialization in One Line
You can also initialize an array directly:
int[] marks = {90, 85, 70, 88, 95};
6) Looping Through an Array
The best part about arrays is that you can use loops to access elements easily.
Example using for loop
public class ArrayLoopExample {
public static void main(String[] args) {
int[] marks = {90, 85, 70, 88, 95};
for (int i = 0; i < marks.length; i++) {
System.out.println("Marks: " + marks[i]);
}
}
}
7) Enhanced for Loop (for-each loop)
Java provides a special loop for arrays called the for-each loop.
public class ForEachExample {
public static void main(String[] args) {
int[] marks = {90, 85, 70, 88, 95};
for (int value : marks) {
System.out.println(value);
}
}
}
8) Array Length
In Java, arrays have a built-in property called length.
System.out.println(marks.length);
This will return the size of the array.
Conclusion
Arrays are one of the most important topics in Java because they allow you to:
- ✅ Store multiple values easily
- ✅ Access values using index
- ✅ Use loops to work with large data
In the next post, we will learn about Java Strings and how to work with text in Java!
Beginner friendly tutorial
ReplyDeleteNext blog please
ReplyDelete