Arrays


Collapse Content

Strings let you hold characters together into words and do things with them, but what if you want to keep a collection other data? For example, let's say you have a list of numbers, such as scores from a Skeeball tournament. It wouldn't make sense to create a new variable for each number, it would be simpler to keep all the numbers in one structure. Java provides various structures for storing collections of elements, but the simplest one is an array.

An array is a structure of a fixed length for storing items of one type together. It's like a shelf for storing related items. Instead of accessing a specific piece of data by calling its variable (or "container"), you can instead specify its location in the array (or "shelf").

simple empty array

In Java (and other languages), the first item in an array is located at position 0. You can think of the array as a number line, with the first item located in the 0th slot.

Arrays in Java use a special [brackets] syntax. To declare an array variable, you need to state the data type the array will hold, brackets to show that it's an array, and the array name:

int[] nums;

To create the actual array, you need to use the new keyword, state the type (again), and specify the length of the array:

nums = new int[8];

This will create an empty array that can hold up to 8 integers in index positions from 0-7.

You could have also combined the above steps into one line:

int[] nums = new int[8];

To put items in an array, you specify the position in the array with brackets and assign it to a value:

nums[0] = 7;
nums[3] = 3; 

This will put a 7 in the 0th spot and a 3 in the 3-index spot:

simple empty array

To get an element from an array, you can reverse that process:

 int num = nums[0];

This will access the 0th position and set num to 7.

When you create an 'empty' integer array, Java sets all the values in it to 0. To quickly create an array with specific values, you can use the following 'curly-braces' shortcut:

int[] numbers = {0, 1, 2, 3, 14, 15, 16, 17};

full-array

Let's say you're given the array numbers but you don't know how long it is. You need to access the property of an array called length. We'll cover Objects and their properties later, but for now, just remember this syntax: arrayName.length

For example, this code would assign the length of numbers to a variable length:

int length = numbers.length;

length will be 8, since that's the number of cells in numbers. The last cell in the array is at position numbers.length -1, since arrays are 0-indexed:

int last = numbers[numbers.length-1]; 

This will access the last (or 7th) spot, and set last to 17.

Other Array Examples
The above arrays just stored integers, but you can store other data types in Arrays also. For example, this code will create an array for Strings:

String[] words = new String[10]; 
words[0] = "jim";
String name = words[0];  //name is now "jim"

You can even create an array of arrays, or a 2D array:

 int[][] board = new int[8][8];

This 2D array could be used to store things like game boards.

Summary
Review this example code to make sure you get how arrays work:

Task Code Result Explanation
Declare and create an array int[] ar = new int[5]; {0,0,0,0,0} Creates an array with default 0 values
Create an array with specific values int[] ar2 = {5,4,3,2,1}; {5,4,3,2,1} Use Curly braces to create filled-in array
Set the value in an array ar[0] = 3; {3,0,0,0,0} Sets the 0th cell to 3
Get the value from an array int num = ar2[4]; 1 Sets num to the value of cell 4 in ar2
Bonus: get and set the value in an array ar[0] = ar2[4]; {1,0,0,0,0} Sets cell 0 of ar to the value of cell 4 of ar2

More Practice
After solving the challenge below, get some more practice with these challenges:

Challenge

You will be given an array of numbers ar. Create and return another array of length 2 that just contains the first and last number in the original array.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

In one line of code, declare and initialize an empty array of booleans named array with a length of 6.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

We need to get the second-to-last number in an array. In one line of code, declare an int variable n and set its value to equal the second-to-last number in the array numbers.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • I got the answer in the end, but my first attempt was:

    int CC = ar[ar.length-1];
    int VV = ar[0];
    return CC + VV;

  • int[] fl = new int[2];
    fl[0] = ar[0];
    fl[1] = ar[ar.length - 1];
    return fl;

  • Thanks for the site I am really learning from it.
    One thing I'd like to be able to do is practice typing things out as I'm following along with your explanations. I think it would help reinforce

    cont...
  • @Robin, if you just want to take notes I think it would make sense to do in your own note-taking program, though we can consider adding such a feature. Note that if you click on "split-screen

    cont...
  • Just a funny quote here... On the challenge Second-to-Last i scratched my head for two days trying to think how to declare the variable in a single sentence the reason was because i was understanding: from the second (meaning starting at index 1) to the last, rather than actually thinking about penultimate! Frustrated not being able to declare the variable i decided that i was not understanding the exercise, clear enough google explained me second-to-last=penultimate... OMG LOL

    cont...
  • What does "Second to last" mean?

  • HOLY MOLY. 2D ARRAYS MADE MY SUDOKU SOLVER EASIER!

  • And here is the answer for the challenge:

    int [] ars = {ar [0], ar [ar.length -1]};
    return ars;

  • these are very good

  • If you get a number from an array, and do not know what slot its in. Is there a code to retrieve the slot?
    Example;
    I found the largest number in the array and want to know what slot that is in.

  • I don't understand why my challenges are wrong:
    1. int n = numbers[6];
    2. boolean [] frank= new boolean [6];

  • I had the write awnser but it still does not work, what is wrong in this:

    int[] ar2 = new int[2];
    ar2[0] = ar[0];
    ar2[1] = ar[ar.lenght - 1];
    return ar2;

  • sorry i solved it lenght mus be length pfffffffffffff :-)

  • Is the free memebership limit forever? Doesn't it restore after certain time?

  • It doesn't currently restore since it's considered a free trial.

  • Or declare regular variables:

    int a = ar[0];
    int b = ar[ar.length -1];
    int[] az = {a,b};

    return az;

  • Second-to-last means, the second element in the array starting counting from the last index.

  • import java.util.Scanner;
    public class Main(){
    public static void main(String[] args){
    int n;
    int[] numbers= new int[8];
    int[] numbers={2,3,4,5,6,7,8,9};
    for(int i=0;i<8;i=i+1){
    System.out.print(numbers[i]);
    if(i==6){
    n=numbers[i]
    System.out.print(n);
    }
    }
    }
    }

  • Do it easy guys ...
    int[] res = {ar[0], ar[ar.length -1]};
    return res;

All Node Comments
Contact Us
Sign in or email us at [email protected]