Java Creating Arrays
Table of Contents + โ
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 valuesString[] 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[] marksputs 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 typeint marks[]; // โ
also legal, older stylePrefer 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:
marksgets 5 slots,namesgets 3. - The values go in order, so
marks[0]is 85 andnames[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
intvalues. - 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 defaultSystem.out.println(marks[0]);System.out.println(marks[1]);new int[5]makes 5 slots.- We set the first three by index.
marks[3]andmarks[4]are untouched, so they hold a default.- Printing the first two shows the data we put in.
Output
8590Use 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 yetint count = 5; // maybe this came from somewhere elsemarks = 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 exactlycountslots. - The literal
{...}cannot be split like this, so delayed creation is a job onlynewcan 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 (written0.0for decimals). booleanstarts at false.charstarts at a blank character (value zero, which prints as nothing).- Object types like
Stringstart 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 defaultSystem.out.println(words[0]); // an object defaultThe int array starts as zeros, the String array as null.
Output
0nullThe 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
nullslot 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
040โจ๏ธ 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, thennew 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
newexists.
Output
How many numbers? 310 20 30You 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 laterrows[0] = new int[]{1, 2, 3}; // first row has 3 itemsrows[1] = new int[]{4, 5}; // second row has 2 itemsJust 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.lengthis 5. - Loop up to
array.lengthinstead 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 linemarks = new int[]{85, 90, 78}; // โ
use new with the values insteadDeclaring but never creating: a bare declaration makes no array.
int[] marks;System.out.println(marks[0]); // โ no array exists yetint[] scores = new int[3]; // โ
create before you use itWrong 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 boundsSystem.out.println(marks[4]); // โ
last valid index is size minus oneNull 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 lengthnames[0] = "Alex"; // โ
put a real String in firstSystem.out.println(names[0].length()); // โ
now this worksNegative 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 sizeint[] data = new int[3]; // โ
size must be zero or moreTwo 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 arenull, 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โ). Bothint[] aandint a[]work, butint[] ais 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
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
What does new int[5] create?
Why: new int[5] makes 5 slots with valid indexes 0 through 4.
- 3
What is the default value in a new int array?
Why: Number arrays start filled with 0, not random data.
- 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.