Java Creating Arrays

In the last lesson you learned about Java arrays. Now letโ€™s actually make one. Thereโ€™s more than one way, so letโ€™s learn the array syntax for every case.

๐Ÿงฉ The two parts of an array variable

An array type is a type plus square brackets, read as โ€œarray of intโ€.

int[] marks; // an array that will hold int values
String[] names; // an array that will hold String values
  • This line only declares the variable. A declaration is just the promise of a variable, with its type.
  • It does not make the array yet. You still create it with one of the ways below.
  • Java splits the steps so you can decide the size later, maybe after asking the user.

โœ๏ธ Two ways to write the brackets

You will see both styles in real code. This declaration style is only about looks.

  • int[] marks puts brackets after the type. The style almost everyone uses.
  • int marks[] puts them after the name. The old C-style way, still legal.
  • Both make the exact same array.
int[] marks; // โœ… recommended: brackets with the type
int marks[]; // โœ… also legal, older style

Prefer int[]: the brackets belong to the type, so the variable reads as โ€œarray of intโ€ and matches most Java code.

๐Ÿ“ Way 1: create with values you already know

If you have the values, list them inside curly braces. This {...} form is the array literal.

int[] marks = {85, 90, 78, 92, 88};
String[] names = {"Alex", "Riya", "Arjun"};
  • Java counts the values, so you never write the size yourself.
  • It sizes the array to fit: marks gets 5 slots, names gets 3.
  • The values go in order, so marks[0] is 85 and names[0] is โ€œAlexโ€.
  • The literal only works on the same line as the declaration. More on this in Common Mistakes.

Use this whenever the data is ready at the start, like a fixed list of weekday names.

๐Ÿ”ข Way 2: create empty slots with new

When you do not have the values yet (reading them from the user, filling them in a loop), create the array with a size using new.

int[] marks = new int[5]; // 5 slots, ready to fill
  • The word new builds the array in memory and makes room for 5 int values.
  • It does not put any real data in yet, like an empty tray with 5 compartments.
  • You fill the slots later, one at a time, by their index.
int[] marks = new int[5];
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
// marks[3] and marks[4] are still at their default
System.out.println(marks[0]);
System.out.println(marks[1]);
  • new int[5] makes 5 slots.
  • We set the first three by index.
  • marks[3] and marks[4] are untouched, so they hold a default.
  • Printing the first two shows the data we put in.

Output

85
90

Use this when you know how many but not which values up front. The size is fixed the moment you call new: you can change what is inside a slot, but you cannot grow to a sixth slot later.

๐Ÿ“‹ Way 3: declare now, create later

Declare the variable first, then create the array further down. Handy when the size depends on something you learn later.

int[] marks; // declare now, no array yet
int count = 5; // maybe this came from somewhere else
marks = new int[count]; // create it once you know the size
  • The size can be a variable, not just a fixed number. new int[count] makes exactly count slots.
  • The literal {...} cannot be split like this, so delayed creation is a job only new can do.

๐Ÿซฅ What is in an empty slot? Default values

When you create an array with new, the slots are not truly empty. Java fills each with a default value based on the type, so you never get random garbage.

  • Number types (int, long, double) start at 0 (written 0.0 for decimals).
  • boolean starts at false.
  • char starts at a blank character (value zero, which prints as nothing).
  • Object types like String start at null, meaning โ€œpoints to nothingโ€.

This prints the slots of two fresh arrays before we set anything.

int[] scores = new int[3];
String[] words = new String[3];
System.out.println(scores[0]); // a number default
System.out.println(words[0]); // an object default

The int array starts as zeros, the String array as null.

Output

0
null

The word null matters, so slow down on it:

  • An object array does not hold the objects. It holds links to objects.
  • new String[3] gives three links that point to nothing yet, so each slot has no String attached.
  • A number slot already holds a usable value, 0. An object slot holds null, which is not usable.
  • Using a null slot like a real String crashes the program. We will see that crash in Common Mistakes.

๐Ÿ” Creating an array from a loop

Way 2 shines with a loop: make the empty slots, then a loop fills them with computed values. This code makes 5 slots, then fills each with its index times ten.

int[] table = new int[5];
for (int i = 0; i < table.length; i++) {
table[i] = i * 10; // fill slot i
}
System.out.println(table[0]);
System.out.println(table[4]);

We looped up to table.length, not a hard-coded 5, so changing the size later needs no other edit.

Output

0
40

โŒจ๏ธ Creating an array from user input

Real programs often do not know the size until the person tells them, so you ask first, then create. Here we read how many numbers the user wants, then read each one into the array.

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("How many numbers? ");
int n = sc.nextInt();
int[] nums = new int[n]; // size from the user
for (int i = 0; i < nums.length; i++) {
nums[i] = sc.nextInt(); // read into slot i
}
System.out.println("You entered " + nums.length + " numbers.");
}
}
  • We ask n, then new int[n] builds an array of exactly that size.
  • The loop reads one value into each slot.
  • The literal form could never do this, since we knew neither the values nor the size when we wrote the code. This is the everyday reason new exists.

Output

How many numbers? 3
10 20 30
You entered 3 numbers.

๐Ÿ“ A quick word on jagged arrays

An โ€œarray of arraysโ€ is when each slot holds another array, and those inner arrays can each have a different length. Because the rows are uneven, people call this a jagged array. You create the outer array with new, then create each inner array on its own.

int[][] rows = new int[2][]; // 2 rows, lengths decided later
rows[0] = new int[]{1, 2, 3}; // first row has 3 items
rows[1] = new int[]{4, 5}; // second row has 2 items

Just know each row is really its own little array. We go deep on this in the multidimensional arrays lesson. For now, keep your arrays flat and simple.

๐Ÿ“ The length field

Every array remembers its own size in a field called length, read with a dot like marks.length. It is a field, not a method, so there are no brackets after it.

int[] marks = {85, 90, 78, 92, 88};
System.out.println("This array has " + marks.length + " items.");
  • Here marks.length is 5.
  • Loop up to array.length instead of writing the number, so your loop still works when the size changes.

Output

This array has 5 items.

length has no brackets

For arrays it is array.length with no (). That is different from String, where you use text.length() with brackets. Arrays use a field. Strings use a method. Mixing them up is a common compile error.

โš ๏ธ Common Mistakes

These array-creation slip-ups show up again and again.

Literal after declaring: the {...} form only works on the same line as the declaration.

int[] marks;
marks = {85, 90, 78}; // โŒ literal not allowed on a later line
marks = new int[]{85, 90, 78}; // โœ… use new with the values instead

Declaring but never creating: a bare declaration makes no array.

int[] marks;
System.out.println(marks[0]); // โŒ no array exists yet
int[] scores = new int[3]; // โœ… create before you use it

Wrong index: new int[5] gives slots 0 to 4, so there is no slot 5.

int[] marks = new int[5];
System.out.println(marks[5]); // โŒ crashes: index out of bounds
System.out.println(marks[4]); // โœ… last valid index is size minus one

Null object array: an object array starts full of null, so using a slot before you fill it crashes.

String[] names = new String[3];
System.out.println(names[0].length()); // โŒ crashes: null has no length
names[0] = "Alex"; // โœ… put a real String in first
System.out.println(names[0].length()); // โœ… now this works

Negative size: the size must be zero or more. A negative size compiles but crashes at run time.

int[] data = new int[-3]; // โŒ crashes: negative array size
int[] data = new int[3]; // โœ… size must be zero or more

Two famous crashes

ArrayIndexOutOfBoundsException means you used an index that does not exist, like asking for slot 5 in a 5-slot array. NullPointerException means you used an object slot that still holds null. Both are about reaching for something that is not there. Knowing which is which makes them easy to fix.

โœ… Best Practices

These habits keep array creation clean and bug-free.

  • Use the {...} form when you already know the values. It is short and reads clearly.
  • Use new type[size] when you only know the size. Then fill the slots later, often in a loop.
  • Loop with .length, never a hard-coded number. So your code stays correct even if the size changes.
  • Fill object arrays before you read them. New String[] slots are null, and using a null slot crashes.
  • Keep the brackets with the type, like int[] marks. It matches what most Java code looks like.
  • Remember the defaults. New number arrays start at 0, booleans at false, objects at null.

๐Ÿงฉ What Youโ€™ve Learned

Letโ€™s recap how to make arrays.

  • โœ… An array type is written with square brackets, like int[] (โ€œarray of intโ€). Both int[] a and int a[] work, but int[] a is preferred.
  • โœ… Use {values} when you already know the data, and Java sizes the array for you. It only works on the same line as the declaration.
  • โœ… Use new type[size] when you know the size but not the values yet, even getting the size from a variable or the user.
  • โœ… New arrays start with default values: 0 for numbers, false for boolean, null for objects.
  • โœ… Object arrays hold null until you fill them, so reading an unfilled slot crashes.
  • โœ… Read the size with array.length (no brackets), and loop with it instead of a fixed number.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    Which line creates an array with values you already know?

    Why: The curly-brace form lists the values directly, and Java sizes the array to fit.

  2. 2

    What does new int[5] create?

    Why: new int[5] makes 5 slots with valid indexes 0 through 4.

  3. 3

    What is the default value in a new int array?

    Why: Number arrays start filled with 0, not random data.

  4. 4

    How do you get the size of an array?

    Why: Arrays use the length field with no brackets: array.length.

๐Ÿš€ Whatโ€™s Next?

You can create and fill arrays now. The real power comes when you reach into a specific slot to read or change its value. Next we learn how to access array elements by their index.

Java Accessing Array Elements

Share & Connect