Java Cantrips: Arrays

So you’ve picked up the building blocks of Java. You feel comfortable creating a Variable, you’ve created Loops and If statements, you may even have Instantiated an Object. Now you find that to complete your next project, you need more than one of the same Object. You could create an Instance for each Object you need, or you could create an Array:

int num;                  
//A variable holds one of an given class instance
int[] nums = new int[4];  
//An array can hold as many instances as specified when it is created
//  !!THIS CANNOT BE CHANGED LATER!!
String[] colors = {"Green", "Blue", "Red", "Purple"};   
//When you create an array, you can specify it's elements with {}

An Array is a set of Objects of any type of a size you chose at it’s creation (Be careful, you cannot change it later). You can reference a member of the Array by referring to it’s Index, or place in the Array. Arrays count starting from 0 so the first element in your Array will be found at Index 0.

int[] nums = {3,62,47,0,12};
// Prints out the length of nums (5)
System.out.println(nums.length); 
// Prints the element of nums at index 3 (0)
System.out.println(nums[3]);    

// This will break your code as the last index of an array 
// is always 1 less than the length of that array
System.out.println(nums[nums.length]);

Arrays work well with Loops, as they allow for the easy Initialization of your Arrays as well as a method to check every element.

int[] countdown = new int[5];
for (int i=0; i < countdown.length; i++){
    countdown[i] = countdown.length - i;
} 
//This creates an array with the numbers
//5,4,3,2,1 in that order

// This is an example of how to use a loop to display an array
for (int i=0; i <= countdown.length; i++){              
if(i == countdown.length){
        System.out.println("BLASTOFF!!!");
    }else{
        System.out.println(countdown[i]);
    }
}

That’s the basics of Arrays in Java. It’s a simple option available to you when coding that opens up a vast amount of possibilities.

Code available at https://github.com/StrategicNPC/CollaberaJUMPProjects/tree/master/Code/ArrayDemonstrations.
Additional information on at https://corejava.design.blog/2019/08/06/example-post/

Leave a comment

Design a site like this with WordPress.com
Get started