📌 Array in Java (Professional & Beginner-Friendly Explanation)
🔹 What is an Array?
An array in Java is an object that is used to store multiple values of the same (homogeneous) data type under a single variable name.
- Arrays store data using index positions.
- The size of an array is fixed once it is created.
- Array indexing starts from 0 and ends at size – 1.
- When an array is created in Java, an internal class is generated by the JVM.
- This internal class contains a final variable called length, which stores the size of the array.
🔹 Key Characteristics of Arrays
- Stores homogeneous data only
- Index-based data access
- Fixed size (cannot grow or shrink)
- Faster data access compared to collections
🔹 Syntax to Create an Array in Java
1️⃣ Using new keyword
dataType[] arrayName = new dataType[size];
Example:
int[] numbers = new int[5];
2️⃣ Using Array Literal
dataType[] arrayName = {value1, value2, value3};
Example:
int[] numbers = {10, 20, 30, 40};
🔹 Types of Arrays in Java
1️⃣ Primitive Data Type Array
- Stores primitive values such as int, float, char, boolean
- Only homogeneous primitive data is allowed
Example:
int[] marks = {70, 80, 90};
📌 Real-Life Example:
Storing student marks in a class where all values are integers.
2️⃣ Class Type (Object) Array
- Stores objects of the same class
- Only homogeneous objects are allowed
Example:
String[] names = {"Rahul", "Amit", "Neha"};
📌 Real-Life Example:
Storing employee names or product objects in an e-commerce application.
🔹 Important Notes
- Array length is accessed using:
- length is final, so it cannot be changed.
- Arrays can store objects, but only of the same class type.
📝 Summary
Comments
Post a Comment