Java Arrays
Greetings friends! Today we will begin our introduction to some infamous or famous, depending on who you ask lol, data structures used in development work. Our topic today will be Java Arrays! Arrays are a type of data structure that allows you to 'store' elements(items, strings, integers) in indexes(spots, slots, positions) and recall them when you need to use them. Not to be confused with it's cousin, the ArrayList, Arrays are limited by the initialized size(amount of slots you desire) and mostly are accessed using the for or for each loop. Today, we will use the for loop to access our items within the array. Let's dive in!
We first begin with number one. Typically we declare arrays with a data type of String, followed by brackets[](this declares an Array) and the name of our array 'toysInBox'. After the equals sign, we use curly braces {} with string names in parentheses and separated by commas. Within our toysInBox array, we now have five elements that hold a position in what we call indexes. The very first string, "Buzz Lightyear" is in the 0 index and our "Tonka Truck" is in the number 4 index. In arrays, unlike how we normally begin counting with 1, you want to remember the index at 0 is the first element or index in the array.
Next, number two is the for loop we are using to go through (traverse, search, travel through) our array to find the elements within. As in my previous article on for loops(please check them out for a more comprehensive explanation), we have the initialized variable i equal to zero, the test condition that states 'as long as i is less than the length of the number of indexes(elements) in the array then the condition is true until false, and finally, our updation to count each loop occurrence until our test condition is false.
领英推荐
For number three, we want to print out our results of the loop by looking at the index(i) of each element in our array.
Finally, for number four, we see our expected result.
I hope that was fun for you as much as it was for me! Arrays can be a fun way of storing, retrieving, and searching for data and are commonly used in various programming languages. I want to encourage you to try them out and see what you can do. As always, stay Java and take care until next time.