{"id":"arrays-shorthand","slug":"the-short-way","title":"The short way to create an array","text":"### Creating an array with its values\n\nWhen you know the values as you write the program, list them in braces:\n\n```java\nint[] values = {3, 1, 4};\nString[] days = {\"Mon\", \"Tue\", \"Wed\"};\nSystem.out.println(values.length);\nSystem.out.println(days[2]);\n```\n\n```output\n3\nWed\n```\n\nJava counts the values and makes an array of that size, so `{3, 1, 4}` does the same as `new int[3]` followed by three assignments. The braces alone work only in the line that declares the variable. Anywhere else, such as in a method call, write `new int[]` in front of them: `total(new int[] {3, 1, 4})`.\n\n### Printing an array\n\nPrinting the array variable itself doesn't print the values:\n\n```java\nint[] values = {3, 1, 4};\nSystem.out.println(values);\n```\n\nThis prints `[I@` followed by a code of letters and digits, which can change from one run to the next. `[I` stands for \"array of int\", and the code says nothing about the values. To see them, you can print the elements with a loop, as in the earlier steps. Or let Java do it: `Arrays.toString` gives the values as text, in square brackets. It lives in the class `java.util.Arrays`, which needs an import line, as `Scanner` does:\n\n```java\nimport java.util.Arrays;\n\npublic class Main {\n    public static void main(String[] args) {\n        int[] values = {3, 1, 4};\n        String[] days = {\"Mon\", \"Tue\", \"Wed\"};\n        System.out.println(Arrays.toString(values));\n        System.out.println(Arrays.toString(days));\n    }\n}\n```\n\n```output\n[3, 1, 4]\n[Mon, Tue, Wed]\n```\n\nIt's a handy tool for checking what an array holds while you work on a program.\n\n### Array or list?\n\n| | Array | ArrayList |\n|---|---|---|\n| Size | fixed when it's created | grows and shrinks |\n| Size in code | `values.length` | `list.size()` |\n| Reading an element | `values[i]` | `list.get(i)` |\n| Whole numbers | `int[]` | `ArrayList<Integer>` |\n| Ready-made tools | in the `Arrays` class, such as `Arrays.toString` | the list's own methods: `add`, `remove`, `contains`, `indexOf` |\n\nA list is the everyday choice when the number of values changes or isn't known in advance: reading until the user stops, or a to-do list that items come and go from. An array fits when the size is fixed and known, like the seven days of a week. It's especially good for **counting**, when the value itself can be the index.\n\n### Counting with an array\n\nEach line of input here is a vote for option 1, 2 or 3, until a 0. The line `votes[option]++;` adds one to that option's counter. The array has four places so that options 1 to 3 can use their own number as the index; index 0 is simply never used.\n\n```java\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int[] votes = new int[4];\n        while (true) {\n            int option = Integer.valueOf(scanner.nextLine());\n            if (option == 0) {\n                break;\n            }\n            votes[option]++;\n        }\n        for (int option = 1; option < votes.length; option++) {\n            System.out.println(\"Option \" + option + \": \" + votes[option]);\n        }\n    }\n}\n```\n\n```input\n2\n3\n2\n1\n2\n0\n```\n\n```output\nOption 1: 1\nOption 2: 3\nOption 3: 1\n```\n\nWithout an array, this would take a separate counter and an `if` for each option. With one, counting 30 options instead of 3 changes only the size of the array.\n","task":"Fill in the blanks. Create the array the short way, holding 2, 3, 5, 7 and 11, and print it with `Arrays.toString`. The program prints:\n\n```\n5 primes\n[2, 3, 5, 7, 11]\n```\n","kind":"fill","seed":"import java.util.Arrays;\n\npublic class Main {\n    public static void main(String[] args) {\n        int[] primes = [[{2, 3, 5, 7, 11}‖new int[] {2, 3, 5, 7, 11}]];\n        System.out.println(primes.length + \" primes\");\n        System.out.println(Arrays.[[toString]](primes));\n    }\n}\n","solution":"import java.util.Arrays;\n\npublic class Main {\n    public static void main(String[] args) {\n        int[] primes = {2, 3, 5, 7, 11};\n        System.out.println(primes.length + \" primes\");\n        System.out.println(Arrays.toString(primes));\n    }\n}\n","hints":["The values go in braces, separated by commas: `{2, 3, 5, 7, 11}`.","The method of `Arrays` that turns an array into text is `toString`."],"tests":[{"name":"Output","stdin":"","expect":"5 primes\n[2, 3, 5, 7, 11]","hidden":false}],"require":[],"forbid":[],"more":[{"task":"A form stores its answers in an array of Strings, and a question left unanswered is the empty String `\"\"`. Write a method `withoutBlanks(String[] answers)` that returns a **new** array holding only the answers that aren't empty, in the same order. An array can't grow, so count those answers first, and then create an array of exactly that size. The check passes the array `{\"red\", \"\", \"green\", \"\", \"blue\"}` and prints what your method returns with `Arrays.toString`:\n\n```\n[red, green, blue]\n```\n","kind":"code","seed":"import java.util.Arrays;\n\npublic class Main {\n    public static void main(String[] args) {\n        String[] answers = {\"red\", \"\", \"green\", \"\", \"blue\"};\n        System.out.println(Arrays.toString(withoutBlanks(answers)));\n    }\n\n    // Write the withoutBlanks method here.\n}\n","solution":"import java.util.Arrays;\n\npublic class Main {\n    public static void main(String[] args) {\n        String[] answers = {\"red\", \"\", \"green\", \"\", \"blue\"};\n        System.out.println(Arrays.toString(withoutBlanks(answers)));\n    }\n\n    public static String[] withoutBlanks(String[] answers) {\n        int count = 0;\n        for (String answer : answers) {\n            if (!answer.equals(\"\")) {\n                count++;\n            }\n        }\n        String[] result = new String[count];\n        int next = 0;\n        for (String answer : answers) {\n            if (!answer.equals(\"\")) {\n                result[next] = answer;\n                next++;\n            }\n        }\n        return result;\n    }\n}\n","hints":["The method starts `public static String[] withoutBlanks(String[] answers) {`. A first loop counts the answers where `!answer.equals(\"\")`, and then `String[] result = new String[count];` makes the new array.","A second loop copies each answer that isn't empty to `result[next]`, and then adds one to `next`, the index where the next answer goes."],"tests":[{"name":"Test 1","stdin":"","call":"String[] answers = {\"red\", \"\", \"green\", \"\", \"blue\"};\nSystem.out.println(Arrays.toString(withoutBlanks(answers)));\n","expect":"[red, green, blue]","hidden":false},{"name":"Test 2","stdin":"","call":"String[] answers = {\"\", \"\"};\nSystem.out.println(Arrays.toString(withoutBlanks(answers)));\n","expect":"[]","hidden":true},{"name":"Test 3","stdin":"","call":"String[] answers = {\"yes\", \"no\"};\nSystem.out.println(Arrays.toString(withoutBlanks(answers)));\nSystem.out.println(Arrays.toString(answers));\n","expect":"[yes, no]\n[yes, no]","hidden":true},{"name":"Test 4","stdin":"","call":"String[] answers = {\"\", \"only\", \"\"};\nString[] kept = withoutBlanks(answers);\nSystem.out.println(kept.length + \" \" + kept[0]);\nSystem.out.println(Arrays.toString(answers));\n","expect":"1 only\n[, only, ]","hidden":true}],"require":[],"forbid":[{"pattern":"\\bArrayList\\b","message":"Build the new array without a list: count first, then create it with the right size."}]},{"task":"Read die rolls, one per line, until `0`. Each roll is a whole number from 1 to 6, and there's at least one. Count how many times each face came up, using an int array as the counters. Then print each face with its count, from 1 to 6, and last the face that came up most often. If several faces tie, print the smallest of them. For the input `4`, `2`, `6`, `4`, `1`, `4`, `2` and `0` the program prints:\n\n```\nFace 1: 1\nFace 2: 2\nFace 3: 0\nFace 4: 3\nFace 5: 0\nFace 6: 1\nMost common: 4\n```\n","kind":"code","seed":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n\n    }\n}\n","solution":"import java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        int[] counts = new int[7];\n        while (true) {\n            int roll = Integer.valueOf(scanner.nextLine());\n            if (roll == 0) {\n                break;\n            }\n            counts[roll]++;\n        }\n        int mostCommon = 1;\n        for (int face = 1; face < counts.length; face++) {\n            System.out.println(\"Face \" + face + \": \" + counts[face]);\n            if (counts[face] > counts[mostCommon]) {\n                mostCommon = face;\n            }\n        }\n        System.out.println(\"Most common: \" + mostCommon);\n    }\n}\n","hints":["`int[] counts = new int[7];` has the indexes 0 to 6, so each face can use its own number: `counts[roll]++;`","Finding the most common face is the largest-value search from this module, over the indexes 1 to 6. Start from face 1, and switch only on a count that's `>` the best so far, so the smallest face wins a tie."],"tests":[{"name":"Test 1","stdin":"4\n2\n6\n4\n1\n4\n2\n0\n","expect":"Face 1: 1\nFace 2: 2\nFace 3: 0\nFace 4: 3\nFace 5: 0\nFace 6: 1\nMost common: 4","hidden":false},{"name":"Test 2","stdin":"6\n3\n3\n6\n0\n","expect":"Face 1: 0\nFace 2: 0\nFace 3: 2\nFace 4: 0\nFace 5: 0\nFace 6: 2\nMost common: 3","hidden":true},{"name":"Test 3","stdin":"5\n0\n","expect":"Face 1: 0\nFace 2: 0\nFace 3: 0\nFace 4: 0\nFace 5: 1\nFace 6: 0\nMost common: 5","hidden":true},{"name":"Test 4","stdin":"1\n2\n3\n4\n5\n6\n6\n0\n","expect":"Face 1: 1\nFace 2: 1\nFace 3: 1\nFace 4: 1\nFace 5: 1\nFace 6: 2\nMost common: 6","hidden":true}],"require":[{"pattern":"new\\s+int\\s*\\[\\s*[67]\\s*\\]","message":"Count in an int array with a place for each face: `new int[7]` (or `new int[6]`)."}],"forbid":[{"pattern":"\\bArrayList\\b","message":"Count in an array, not a list."},{"pattern":"==\\s*[2-6]\\b","message":"Let the roll be the index: `counts[roll]++;` counts any face, without an `if` for each one."}]}]}