Definition
📌 Arrays
Java arrays store multiple values of the same type in a fixed-size, indexed structure — but unlike C, Java arrays are objects, and Java performs automatic bounds checking at runtime..
Syntax
syntax
type[] arrayName = new type[size];
type[] arrayName = {value1, value2, ...};Example
java
public class Main {
public static void main(String[] args) {
int[] scores = {90, 85, 70, 60, 95};
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + " ");
}
}
}Output
output90 85 70 60 95
Important Points
- Array indices start at
0, same as C/C++. array.lengthis a field (no parentheses) that gives the array's size.- Accessing an invalid index throws
ArrayIndexOutOfBoundsExceptionat runtime — a safety net C lacks. - For dynamic sizing, use
ArrayListfromjava.utilinstead of a plain array.
Common Mistakes
- Writing
array.length()with parentheses — it's a field, not a method, so no parentheses. - Accessing index
array.lengthinstead ofarray.length - 1for the last element. - Trying to resize a plain array — its size is fixed once created.
Interview Tip
🎯 Before your interview
Know the difference between
array.length (a field, arrays) and list.size() (a method, ArrayList/collections) — a very common trip-up.
