LEARN JAVA: ARRAYS
Introduction
We have seen how to store single pieces of data in variables. What happens when we need to store a group of data? What if we have a list of students in a classroom? Or a ranking of the top 100 Gamers finishing a car race?
If we were storing 5 lottery ticket numbers, for example, we could create a different variable for each value:
int firstNumber = 11;
int secondNumber = 16;
int thirdNumber = 5;
int fourthNumber = 1;
int fifthNumber = 10;
That is a lot of ungainly repeated code. What if we had a hundred lottery numbers? It is more clean and convenient to use a Java array to store the data as a list.
An array holds a fixed number of values of one type. Arrays hold
double
s, int
s, boolean
s, or any other primitives. Arrays can also contain String
s, or any other objects!
Each index of an array corresponds with a different value. Here is a diagram of an array filled with integer values:
Notice that the indexes start at 0! The element at index 0 is 11, while the element at index 1 is
16
. This array has a length of 5, since it holds five elements, but the highest index of the array is 1.
Let’s explore how to create and use arrays in Java, so that we can store all of our Java data types.
Creating an Array Explicitly
Imagine that we’re using a program to keep track of the prices of different clothing items we want to buy. We would want a list of the prices and a list of the items they correspond to. To create an array, we first declare the type of data it holds:
double[] prices;
Then, we can explicitly initialize the array to contain the data we want to store:
prices = {13.15, 15.87, 14.22, 16.66};
Just like with simple variables, we can declare and initialize in the same line:
double[] prices = {13.15, 15.87, 14.22, 16.66};
We can use arrays to hold
String
s and other objects as well as primitives:String[] clothingItems = {"White-shirts", "Black pants", " white-Socks", "T-shirts"};Importing Arrays
When we printed out the array we created in the last exercise, we saw a memory address that did not help us understand what was contained in the array.If we want to have a more descriptive printout of the array itself, we need atoString()
method that is provided by theArrays
package in Java.
import java.util.Arrays;We put this at the top of the file, before we even define the class!When we import a package in Java, we are making all of the methods of that package available in our code.TheArrays
package has many useful methods, includingArrays.toString()
. When we pass an array intoArrays.toString()
, we can see the contents of the array printed out:
import java.util.Arrays;//tushargahora.blogspot.com public class Lottery(){ public static void main(String[] args){ int[] lotteryNumbers = {11, 16, 5, 10, 1,}; String betterPrintout = Arrays.toString(lotteryNumbers); //lottrylagyi ;) System.out.println(betterPrintout); } }This code will print:
[4, 8, 15, 16, 23, 42]Get Element By Index
Now that we have an array declared and initialized, we want to be able to get values out of it.We use square brackets,[
and]
, to access data at a certain index:
double[] prices = {13.1, 15.87, 14.22, 16.66}; System.out.println(prices[1]);This command would print:
15.87Because15.87
is the item at the1
index of the array. Remember that arrays start at index0
!
Creating an Empty Array
We can also create empty arrays and then fill the items one by one. Empty arrays have to be initialized with a fixed size:
String[] menuItems = new String[5];Once you declare this size, it cannot be changed! This array will always be of size5
.After declaring and initializing, we can set each index of the array to be a different item:
menuItems[0] = "Veggie Burger"; menuItems[1] = "Potato salad"; menuItems[2] = "Pizza"; menuItems[3] = "Sandwich "; menuItems[4] = "ice cream";This group of commands has the same effect as assigning the entire array at once:
String[] menuItems = {"Veggie Burger", "Potato salad", "Pizza", "Sandwich", "ice cream"};We can also change an item after it has been assigned! Let’s say this restaurant is changing its broccoli dish to a cauliflower one:
menuItems[3] = "Cake";Now, the array looks like:
["Veggie Burger", "Potato salad", "Pizza", "Cake", "ice cream"]Length
What if we have an array storing all the usernames for our program, and we want to quickly see how many users we have? To get the length of an array, we can access thelength
field of the array object:
String[] menuItems = new String[5]; System.out.println(menuItems.length);This command would print5
, since themenuItems
array has5
slots, even though they are all empty.If we print out the length of theprices
array:
double[] prices = {13.1, 15.87, 14.22, 16.66}; System.out.println(prices.length);We would see4
, since there are four items in theprices
array!String[] args
When we writemain()
methods for our programs, we use the parameterString[] args
. Now that we know about array syntax, we can start to parse what this means.AString[]
is an array made up ofString
s. Examples ofString
arrays:
String[] humans = {"Trisha", "Tushar", "Momo", "Smile"}; String[] robots = {"Jarvis", "Cortana", "Siri", "Alexa"};Theargs
parameter is another example of aString
array. In this case, the arrayargs
contains the arguments that we pass in from the terminal when we run the class file. (So far,args
has been empty.)So how can you pass arguments tomain()
? Let’s say we have this classHelloYou
:
public class HelloYou { public static void main(String[] args) { System.out.println("Hello " + args[0]); } }When we run the fileHelloYou
in the terminal with an argument of"Momo"
:
java HelloYou MomoWe get the output:
Hello MomoTheString[] args
would be interpreted as an array with one element,"Momo"
.When we useargs[0]
in the main method, we can access that element like we did inHelloYou
.Review:
we have learned about:
- Creating arrays explicitly, using
{
and}
.- Accessing an index of an array using
[
and]
.- Creating empty arrays of a certain size, and filling the indices one by one.
- Getting the length of an array using
length
.- Using the argument array
args
that is passed into themain()
method of a class.
No comments: