Arrays in Java: Definition, Types, Syntax, and Real-Life Examples

📌 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:
          arrayName.length
  • length is final, so it cannot be changed.
  • Arrays can store objects, but only of the same class type.

📝 Summary

Feature.                    Array
Data Type.         Homogeneous
Size.                          Fixed
Index.                    0 to size-1
Performance.           Fast
Memory.              Contiguous

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know