Understanding arrays

From the course: Learning Java 8

  • Course details

    Java is one of the top-five programming languages, and is used for websites, embedded controllers, and Android app development. This is an introduction to get you started programming with Java. Peggy Fisher introduces the basics: data types, strings, arrays, expressions, loops, and functions. She'll help you control the flow and logic of your code, and create classes using the principles of object-oriented design. Then go a bit beyond the basics and learn advanced techniques for working with arrays, manipulating files, and building graphical user interfaces (GUIs) that respond to user input. This three-hour capsule course is perfect for developers who need to get up to speed with Java fast, as well as for beginning programmers who want their first taste of this popular language.

    Instructor

    • Click here to view Peggy Fisher’s instructor page

      Peggy Fisher

      Content Strategist, Software Development Languages at Linkedin Learning Solutions with Lynda.com content

      Peggy Fisher is a programmer and content manager at LinkedIn Learning.

      Peggy's main focus is application programming in Java, Arduino, and C++. She has also worked on courses in COBOL and discrete ,athematics. Previously she was a faculty member at Penn State University's College of Information Sciences and Technology. She started out as a programmer working for a large insurance company, but after 18 years she left her job as a director of information technology to pursue her true passion teaching. She earned a master's degree in math education, and went on to teach high school math and computer science in Pennsylvania. In 2012, Peggy accepted a position as an instructional designer at Penn State, and shortly thereafter began teaching Intro to Application Programming with Java. She is a strong supporter of women in STEM. As one of the few female programming teachers, she serves as a mentor to incoming female freshmen who are considering a career in programming. She was also the K–12 outreach coordinator for the college, where she scheduled, ran, and taught summer camps for middle school and high school students. In a PBS NewsHour interview, she expressed that all students should take at least one programming class either in high school or college. Peggy enjoys constantly learning and finding new and exciting ways to bring technology to life in and outside of the classroom, such as using Arduino microcontrollers or Lego Mindstorms, to help make learning hands-on and fun.

    Skills covered in this course

  • Welcome

    - If you wanted to write an application that is used to keep track of all items on a grocery list, this is easy when there's only a few items. But what if you need to buy 100 items or even more than 100. Then you would need at least 100 string variables just for the name of the items and another 100 double variables for the price of each item because it would include both the dollars and cents. So it includes the fractional portion. As you can see, this is getting pretty complicated fast. As you guessed it, there is a better way. We can use a special type of data structure called an array. This is a tool used in most programming languages that allows us to store and work with multiple values of the same data type using a single variable name. The values in the array are stored in consecutive memory locations. The syntax for creating an array is data type, such as int, or double, character, string. Then you use a open square bracket and a close square bracket. The square brackets are what indicate to the computer that it's an array. Then you give it a name. A variable name. And you set it equal to New which is a keyword, data type, again, you have to repeat the data type, that was on the left-hand side, brackets, size, bracket and a semicolon. Arrays must be declared with the size or a list of values which is called an initializer list. Each element in the array is accessed using an index value, which indicates it's position in memory. Note, the index values always start with zero. This is going to be very important, as we start to use arrays. There is one more item of caution. Beware of the out-of-bounds error. Since arrays are a fixed size, if you try to access data at an index value greater than the size of the array, your program will end abruptly during execution, because this is not checked ahead of time by the compiler. Okay, let's write a program, that allows the user to enter the price of five items. We will save the prices in an array, and then add them together and print the total. I've already created a project called Grocery List. I'm gonna start by adding the array! So, I'm going to remove the comment, To Do Code Application Here, and I'm going to type in the data type. We said prices, need to include decimal, so I want to use double, square bracket, square bracket, space, and then an array name. Let's call it Prices, and we set that equal to a new array, a new double array. Again, make sure that the data type on the right, matches the data type on the left, and we have to give it a size. Let's go ahead and keep track of five prices. Okay, now I want to ask the user to enter in the price of each item, but in order to do that, I need to use the Scanner Class. So let's go up here to Line five, and let's import the Scanner Class. So, Import, Java.Util.Scanner. Now, I can go back down to Line 17, and create an instance of the Scanner Class. So, Scanner, space. I'm going to name my variable, In, equals a new instance, so New Scanner, and I need to tell it that it's supposed to read from the System, from the Console, so System.In. If you're follow along, make sure you note the capitalization. Remember, Java is case sensitive. Okay. Now I can ask the user to enter in the five prices. So, in order to prompt the user, I have to write a message out to the Console. So, I'm going to do System.Out.PrintLn, which will print a message and then go to the next line, and I'm going to say, Enter Five Prices. Now I can read the prices into my array. Remember, I have to specify the index value of each item. So, I'm going to do Prices, bracket. Where do I start? At zero. Good. This again is really important, equals In.nextDouble. We need to repeat this for the next four prices. Okay. Notice that my index values started at zero, and since there's five items, the last index value is a four. If I tried to access the fifth element, remember, it would cause an error in my program, and my program would end abruptly. Okay. Now, I can calculate the total by adding up each element in the array. I need to create a variable to hold the total, so I'm going to do Double Total is equal to Prices at index value zero, and I need to continue with each of the elements in the array. Okay, don't forget your semicolon at the end of the line. It's kind of like a period at the end of a sentence. Syntax for a programming language is a lot like grammar is to English. You have to have something at the end of each statement. Now, that I calculated the total, let's print it back out again. System.Out.PrintLn to print line, and I'm going to print out the total. The total for all five items is, and I need to include the total. So remember, earlier we talked about strings, we talked about concatenating. I'm going to add, using a plus sign, and I'm going to add the variable Total. So when it prints to the screen, it will print out the literal that's in double quotes, plus the value that's in the variable called Total. Okay, let's run our program. It says enter five prices. I'm going to enter five prices. $10.00, $5.50, $4.75, $3.90, and one more, $11.75. The total for all five items, is 35.9. One note here is it's nice to format the output, to include a dollar sign and make sure that both of the decimal points show up. Let's go back to our program, and instead of doing a PrintLn, I'm going to change this to a PrintF to talk about formatting. So PrintF, and now I need to add the format code. I want to do a dollar sign and then I'm going to put five positions to the left of the decimal, point two, to get two positions to the right, and I specify that it's a floating point number, because it includes a decimal, with the letter F. The tricky part here, is instead of doing plus Total, I want to do comma, cause it's going to take the Total variable and it's going to put it wherever the symbol is, percent sign five point two F, it's going to replace that with the value Total. Okay, let's try it again. I'm just going to enter random prices and one more. A pack of gum. You can see that looks much better. The total for all five items is $25.40. There is a much more detailed section on arrays later in the course.

  • Practice while you learn with exercise files

    Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.

    Download the exercise files for this course. Get started with a free trial today.

  • Download courses and learn on the go

    Watch courses on your mobile device without an internet connection. Download courses using your iOS or Android LinkedIn Learning app.

    Watch this course anytime, anywhere. Get started with a free trial today.

Contents