Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Arrays

    int[] values = {1, 2, 5};
    System.out.print("CS ");
    System.out.print(values[0]);
    System.out.print(values[1]);
    System.out.print(values[2]);
    System.out.print(" rocks!");

    This lesson presents some exciting new things, and also start to leverage what we already know to build our first small useful programs.

    Sequential Data
    Sequential Data

    Until now we’ve been limited to working with single data values. That’s all that our variables could store!

    But a lot of data around us can’t be reduced to a single data value. So throughout our journey we’ll periodically upgrade our ability to work with data in our programs, allowing us to program more of the real world around us.

    Our first step is to consider series: 0 or more values of the same type arranged in some order. For example, consider the three individual values 1, 2, and 4. I can consider them unordered as three separate values. Or, I can order them, in several different ways:

    Notice that from 3 different values I can create 6 different unique orderings. And the order matters! If you were choosing an introductory CS course, you’d prefer 1, 2, 4 to 4, 2, 1. (Not like there is anything wrong with CS 421. It’s just not an introductory course.)

    Data Structures
    Data Structures

    Putting multiple values in order is our first example of a data structure. Data structures bring structure to data. Putting values in a sequence is just one way that we can structure them. We’ll explore others later in the course.

    Note also that the structure introduces additional data about the data that it stores. We sometimes calls this metadata, since it’s data about data! In the case of a sequence, the metadata is the position of each value in the series. Placing the values 1, 2, and 4 in the order 4, 2, 1, associates a position with each value: 4 is first, 2 is second, 1 is third.

    Java Arrays
    Java Arrays

    In Java one of the ways that we can store sequential data is using an array. An array orders zero or more values. Let’s dive into to declaring and initializing our first array and then unpack what is happening slowly.

    int[] values = new int[8];

    This is not that different than what we’ve seen before. We see an assignment operator, meaning that there is a variable on the left and what is being assigned to it on the right. On the left, instead of int, we see int[], which indicates that values will store a series of int values.

    The right side is a bit more mysterious: new int[8]. new is not going to make complete sense for a while, but for now you can think of it as indicating that we are creating a new array. int is the type, and the value 8 which appears inside square brackets sets the size.

    In Java, we cannot change the size of an array after it has been created. Later in the course we’ll look at other sequential data structures that are more flexible. But, they are also built on top of arrays, so you’ll be able to understand exactly how they work.

    We’re also going to see something a bit strange if we try and print values:

    int[] values = new int[8];
    System.out.println(values);

    We’ll show you how to display the values stored inside Java arrays in just a minute. But just be prepared for this confusing display if you try and directly print the value of a variable that stores an array.

    Array Indexing
    Array Indexing

    We’ve created our first array! But how do we actually store and retrieve the data inside it? Let’s go over that together:

    double[] temperatures = new double[12];
    System.out.println(temperatures[0]);
    temperatures[0] = 78.8;
    System.out.println(temperatures[0]);

    Arrays put values in order. So, to access the data inside them we need to tell Java what position to either save or retrieve. Here’s an example of changing the first value of an array:

    boolean[] results = new boolean[4];
    System.out.println(results[0]);
    results[0] = true;
    System.out.println(results[0]);

    Here’s an example changing the second value:

    boolean[] results = new boolean[4];
    System.out.println(results[1]);
    results[1] = true;
    System.out.println(results[1]);

    And the last (or fourth) value:

    boolean[] results = new boolean[4];
    System.out.println(results[3]);
    results[3] = true;
    System.out.println(results[3]);

    Notice something strange? Array indices start at 0. To a computer scientist, 0 means first, 1 means second, and 3 means fourth. This may seem strange to you when you are getting started, but it quickly becomes second nature:

    long[] measurements = new long[8];

    Out of Bounds
    Out of Bounds

    What happens if we use a bad position value? Let’s find out!

    char[] letters = new char[4];
    letters[-1] = 'X'; // X marks the spot!

    Array Literals
    Array Literals

    Just like we could set a variable with a literal, Java also has array literals. They look like this:

    char[] letters = { 'C', 'S', '1', '2', '5' };
    System.out.println(letters[0]);
    System.out.println(letters[4]);

    You’ll notice above that when we initialize an array with a literal we don’t need to specify a size. Java sets the size of the array based on the number of values in the literal.

    Default Values
    Default Values

    Finally, you may wonder what values Java uses when we create an empty array. Use the playground below to find out! (Or consult this reference.)

    int[] defaults = new int[4];
    System.out.println(defaults[0]);

    Sources of Confusion
    Sources of Confusion

    Let’s walk through some of the possible bits of confusion regarding arrays.

    int[] values;

    Solve: Array Basics (Practice)

    Created By: Geoffrey Challen
    / Version: 2020.6.0

    Let's get some practice with basic array usage. Below, you have two tasks. First, declare an array of ints named numbers and initialize it to contain the values 0, 8, 9, 4, and 5, in that order. Second, given an existing array of doubles named values, print its first value and also change its third value to 1.25.

    Digital Joys
    Digital Joys

    We’re just getting started working with data. But even being able to work with series of data using arrays opens up some exciting possibilities. This is largely due to digitization: the conversion of data to numeric format so that computers can work with it. Let’s look at examples of digitization that produce sequential or linear data.

    Solve: Quiz Score Advice

    Created By: Geoffrey Challen
    / Version: 2021.8.0

    Quizzes are a chance to test what you know and how your understanding of the course content is developing. If you do poorly on a quiz, please approach the course staff for help! We can help get you back on track, but the sooner we know, the better.

    However, please don't misinterpret your quiz score! Writing code in a proctored environment is difficult, and it's normal to make small mistakes. If you miss one of the programming questions due to a small error that you couldn't fix in time, that's usually OK, and not a sign of trouble. If you miss a programming question because you had no idea how to approach it or the concepts involved, that might be a sign of trouble. Reach out to us!

    Let's write a snippet of code that, given a quiz score in the int variable quizScore, prints out a suggestion about how to interpret that score:

    • If the score is below 70, print "You should reach out to the course staff".
    • If the score is between 70 and 90, print "Nice job, and you can probably do better next time"
    • If the score is above 90, print "Great job"

    CS People: Grace Hopper
    CS People: Grace Hopper

    Grace Hopper made multiple pioneering contributions to computer science. Among other accomplishments, she helped invent COBOL, one of the first high-level programming languages. (And which is still in use today.) She also served in the Navy until almost 80 years of age, and retired as one of a small number of female admirals.

    First, watch this short video to learn more about her biography and accomplishments:

    But if you have a few more minutes, don’t miss her delightful appearance on Letterman, and watch her get the best of Dave on several occasions. And while Grace Hopper never received the Turing Award(1), the main computer science professional society—the ACM—did name an entire award after her. There’s also a Grace Hopper Celebration of Computing, which gathers women and non-binary people in technology.

    More Practice

    Need more practice? Head over to the practice page.