{"id":"packages-import","slug":"import","title":"import: short names for classes of other packages","text":"Writing `quiz.domain.Question` every time gets long. An **import** line at the top of a file lets the file's code use a class of another package by its simple name.\n\n### import\n\nThe quiz gets a second package, `quiz.logic`, with a class `Scorer` that adds up the points of the right answers. Main uses both classes, and imports both:\n\n```java\nimport quiz.domain.Question;\nimport quiz.logic.Scorer;\n\npublic class Main {\n    public static void main(String[] args) {\n        Question planet = new Question(\"Which planet is the largest?\", \"Jupiter\", 2);\n        Question gold = new Question(\"What is the chemical symbol for gold?\", \"Au\", 3);\n        Scorer scorer = new Scorer();\n        System.out.println(scorer.answer(planet, \"Jupiter\"));\n        System.out.println(scorer.answer(gold, \"Ag\"));\n        System.out.println(\"Score: \" + scorer.getScore());\n    }\n}\n// ==== quiz/domain/Question.java ====\npackage quiz.domain;\n\npublic class Question {\n    private String prompt;\n    private String answer;\n    private int points;\n\n    public Question(String prompt, String answer, int points) {\n        this.prompt = prompt;\n        this.answer = answer;\n        this.points = points;\n    }\n\n    public boolean isRight(String reply) {\n        return reply.trim().equalsIgnoreCase(this.answer);\n    }\n\n    public int getPoints() {\n        return this.points;\n    }\n\n    @Override\n    public String toString() {\n        return this.prompt + \" (\" + this.points + \" points)\";\n    }\n}\n// ==== quiz/logic/Scorer.java ====\npackage quiz.logic;\n\nimport quiz.domain.Question;\n\npublic class Scorer {\n    private int score;\n\n    public boolean answer(Question question, String reply) {\n        if (question.isRight(reply)) {\n            this.score += question.getPoints();\n            return true;\n        }\n        return false;\n    }\n\n    public int getScore() {\n        return this.score;\n    }\n}\n```\n\n```output\ntrue\nfalse\nScore: 2\n```\n\n- `import quiz.domain.Question;` names a class by its full name. From then on, the file's code says just `Question`.\n- An import counts only in its own file. Main imports Question for itself, and `Scorer.java` imports it again, since Scorer uses it too. Each file lists what it uses from other packages.\n- In a file with a package line, the order is fixed: the package line, then the imports, then the class.\n- An import copies nothing into the program and makes it no bigger. It only tells javac which class a simple name means.\n- A class of the file's own package needs no import.\n\n### A forgotten import\n\nWithout `import quiz.logic.Scorer;`, javac looks for a Scorer in Main's own package and in the imports, and finds none:\n\n```java\nimport quiz.domain.Question;\n\npublic class Main {\n    public static void main(String[] args) {\n        Question planet = new Question(\"Which planet is the largest?\", \"Jupiter\", 2);\n        Scorer scorer = new Scorer();\n        System.out.println(scorer.answer(planet, \"Jupiter\"));\n    }\n}\n// ==== quiz/domain/Question.java ====\npackage quiz.domain;\n\npublic class Question {\n    private String prompt;\n    private String answer;\n    private int points;\n\n    public Question(String prompt, String answer, int points) {\n        this.prompt = prompt;\n        this.answer = answer;\n        this.points = points;\n    }\n\n    public boolean isRight(String reply) {\n        return reply.trim().equalsIgnoreCase(this.answer);\n    }\n\n    public int getPoints() {\n        return this.points;\n    }\n}\n// ==== quiz/logic/Scorer.java ====\npackage quiz.logic;\n\nimport quiz.domain.Question;\n\npublic class Scorer {\n    private int score;\n\n    public boolean answer(Question question, String reply) {\n        if (question.isRight(reply)) {\n            this.score += question.getPoints();\n            return true;\n        }\n        return false;\n    }\n}\n```\n\n```javac\nMain.java:6: error: cannot find symbol\n        Scorer scorer = new Scorer();\n        ^\n  symbol:   class Scorer\n  location: class Main\nMain.java:6: error: cannot find symbol\n        Scorer scorer = new Scorer();\n                            ^\n  symbol:   class Scorer\n  location: class Main\n2 errors\n```\n\n`cannot find symbol` with `symbol: class Scorer` is the message for a class that javac doesn't know by that name. For a class of your own program, the fix is usually an import (or the full name).\n\n### A whole package with *\n\n`import quiz.domain.*;` imports every class of the package `quiz.domain` at once: the file can then use any of them by its simple name. Two things to know:\n\n- The `*` covers the classes of that one package, not the packages in its folders. `import quiz.*;` doesn't import `quiz.domain.Question`. The quiz has no classes in the package `quiz` itself, so javac even says `package quiz does not exist`.\n- Many programmers prefer one import per class, so that the top of a file lists exactly what the file uses. Programming editors write these lines for you. Both ways work the same.\n\n### java.util was a package all along\n\n`import java.util.Scanner;` and `import java.util.ArrayList;` are imports of classes of Java's package `java.util`, just like the imports above. `import java.util.*;` works too. And the classes you've used without any import, such as `String`, `Math`, `Integer` and `System`, are in the package `java.lang`, which every Java file imports automatically.\n\n### Full names instead of an import\n\nA full name works without any import, for Java's classes too:\n\n```java\npublic class Main {\n    public static void main(String[] args) {\n        java.util.ArrayList<String> planets = new java.util.ArrayList<>();\n        planets.add(\"Saturn\");\n        planets.add(\"Jupiter\");\n        planets.add(\"Mars\");\n        java.util.Collections.sort(planets);\n        System.out.println(planets);\n    }\n}\n```\n\n```output\n[Jupiter, Mars, Saturn]\n```\n\nWith imports this is easier to read, so full names are mostly used when two classes share a simple name. One file can't import both: after `import quiz.domain.Question;`, the name `Question` is taken, and `import survey.Question;` doesn't compile. javac says `a type with the same simple name is already defined by the single-type-import of Question`. The fix is to import one of them and write the other one's full name:\n\n```java\nimport quiz.domain.Question;\n\n...\nQuestion planet = new Question(\"Which planet is the largest?\", \"Jupiter\", 2);\nsurvey.Question opinion = new survey.Question(\"Did you like the quiz?\");\n```\n","task":"The shoe store's program has grown a second package, `shoestore.logic`, with a class `Stock`, which uses `Shoe` from `shoestore.domain`. `Shoe.java` and `Stock.java` are ready, but `Main.java` doesn't compile: it uses both classes by their simple names without importing them. Add the import lines at the top of `Main.java`, one for each class (or one for each package with `*`), and don't change the rest. The program prints:\n\n```\n3 pairs\n2 pairs in size 42\n```\n","kind":"code","seed":"// ==== Main.java ====\npublic class Main {\n    public static void main(String[] args) {\n        Stock stock = new Stock();\n        stock.add(new Shoe(\"Trail runner\", 42));\n        stock.add(new Shoe(\"Winter boot\", 39));\n        stock.add(new Shoe(\"Loafer\", 42));\n        System.out.println(stock.count() + \" pairs\");\n        System.out.println(stock.countSize(42) + \" pairs in size 42\");\n    }\n}\n\n// ==== shoestore/logic/Stock.java ====\npackage shoestore.logic;\n\nimport java.util.ArrayList;\nimport shoestore.domain.Shoe;\n\npublic class Stock {\n    private ArrayList<Shoe> shoes;\n\n    public Stock() {\n        this.shoes = new ArrayList<>();\n    }\n\n    public void add(Shoe shoe) {\n        this.shoes.add(shoe);\n    }\n\n    public int count() {\n        return this.shoes.size();\n    }\n\n    public int countSize(int size) {\n        int count = 0;\n        for (Shoe shoe : this.shoes) {\n            if (shoe.getSize() == size) {\n                count++;\n            }\n        }\n        return count;\n    }\n}\n\n// ==== shoestore/domain/Shoe.java ====\npackage shoestore.domain;\n\npublic class Shoe {\n    private String model;\n    private int size;\n\n    public Shoe(String model, int size) {\n        this.model = model;\n        this.size = size;\n    }\n\n    public int getSize() {\n        return this.size;\n    }\n\n    @Override\n    public String toString() {\n        return this.model + \", size \" + this.size;\n    }\n}\n","solution":"// ==== Main.java ====\nimport shoestore.domain.Shoe;\nimport shoestore.logic.Stock;\n\npublic class Main {\n    public static void main(String[] args) {\n        Stock stock = new Stock();\n        stock.add(new Shoe(\"Trail runner\", 42));\n        stock.add(new Shoe(\"Winter boot\", 39));\n        stock.add(new Shoe(\"Loafer\", 42));\n        System.out.println(stock.count() + \" pairs\");\n        System.out.println(stock.countSize(42) + \" pairs in size 42\");\n    }\n}\n\n// ==== shoestore/logic/Stock.java ====\npackage shoestore.logic;\n\nimport java.util.ArrayList;\nimport shoestore.domain.Shoe;\n\npublic class Stock {\n    private ArrayList<Shoe> shoes;\n\n    public Stock() {\n        this.shoes = new ArrayList<>();\n    }\n\n    public void add(Shoe shoe) {\n        this.shoes.add(shoe);\n    }\n\n    public int count() {\n        return this.shoes.size();\n    }\n\n    public int countSize(int size) {\n        int count = 0;\n        for (Shoe shoe : this.shoes) {\n            if (shoe.getSize() == size) {\n                count++;\n            }\n        }\n        return count;\n    }\n}\n\n// ==== shoestore/domain/Shoe.java ====\npackage shoestore.domain;\n\npublic class Shoe {\n    private String model;\n    private int size;\n\n    public Shoe(String model, int size) {\n        this.model = model;\n        this.size = size;\n    }\n\n    public int getSize() {\n        return this.size;\n    }\n\n    @Override\n    public String toString() {\n        return this.model + \", size \" + this.size;\n    }\n}\n","hints":["javac says `cannot find symbol` for `Stock` and `Shoe`: Main is in the default package, and the two classes are in other packages.","The first lines of `Main.java` become `import shoestore.domain.Shoe;` and `import shoestore.logic.Stock;`, above `public class Main`."],"tests":[{"name":"The program's output","stdin":"","expect":"3 pairs\n2 pairs in size 42","hidden":false},{"name":"Test 2","stdin":"","call":"Stock stock = new Stock();\nstock.add(new Shoe(\"Sandal\", 37));\nstock.add(new Shoe(\"Sneaker\", 37));\nSystem.out.println(stock.count() + \" \" + stock.countSize(37) + \" \" + stock.countSize(42));\n","expect":"2 2 0","hidden":true}],"require":[{"pattern":"==== Main\\.java ====(?:(?!// ====)[\\s\\S])*(?:^|;)[ \\t]*import\\s+shoestore\\.domain\\.(?:Shoe|\\*)\\s*;","flags":"m","raw":true,"message":"Import Shoe at the top of `Main.java`: `import shoestore.domain.Shoe;`."},{"pattern":"==== Main\\.java ====(?:(?!// ====)[\\s\\S])*(?:^|;)[ \\t]*import\\s+shoestore\\.logic\\.(?:Stock|\\*)\\s*;","flags":"m","raw":true,"message":"Import Stock at the top of `Main.java`: `import shoestore.logic.Stock;`."}],"forbid":[],"more":[{"task":"A school's timetable program has two classes in the package `school.domain`: `Period`, a lesson of the day with its subject and its number, and `Teacher`. Main imports the whole package. What does this program print?\n","kind":"predict","seed":"import school.domain.*;\n\npublic class Main {\n    public static void main(String[] args) {\n        Teacher teacher = new Teacher(\"Ms. Ito\");\n        teacher.teach(new Period(\"Math\", 1));\n        teacher.teach(new Period(\"Art\", 3));\n        java.util.ArrayList<String> subjects = teacher.subjects();\n        subjects.add(\"Music\");\n        System.out.println(teacher + \" \" + subjects);\n        System.out.println(subjects.getClass().getName());\n        System.out.println(teacher.getClass().getName());\n    }\n}\n// ==== school/domain/Period.java ====\npackage school.domain;\n\npublic class Period {\n    private String subject;\n    private int number;\n\n    public Period(String subject, int number) {\n        this.subject = subject;\n        this.number = number;\n    }\n\n    public String getSubject() {\n        return this.subject;\n    }\n\n    public int getNumber() {\n        return this.number;\n    }\n}\n// ==== school/domain/Teacher.java ====\npackage school.domain;\n\nimport java.util.ArrayList;\n\npublic class Teacher {\n    private String name;\n    private ArrayList<Period> periods;\n\n    public Teacher(String name) {\n        this.name = name;\n        this.periods = new ArrayList<>();\n    }\n\n    public void teach(Period period) {\n        this.periods.add(period);\n    }\n\n    public ArrayList<String> subjects() {\n        ArrayList<String> subjects = new ArrayList<>();\n        for (Period period : this.periods) {\n            subjects.add(period.getSubject());\n        }\n        return subjects;\n    }\n\n    @Override\n    public String toString() {\n        return this.name + \" teaches \" + this.periods.size() + \" periods\";\n    }\n}\n","solution":"import school.domain.*;\n\npublic class Main {\n    public static void main(String[] args) {\n        Teacher teacher = new Teacher(\"Ms. Ito\");\n        teacher.teach(new Period(\"Math\", 1));\n        teacher.teach(new Period(\"Art\", 3));\n        java.util.ArrayList<String> subjects = teacher.subjects();\n        subjects.add(\"Music\");\n        System.out.println(teacher + \" \" + subjects);\n        System.out.println(subjects.getClass().getName());\n        System.out.println(teacher.getClass().getName());\n    }\n}\n// ==== school/domain/Period.java ====\npackage school.domain;\n\npublic class Period {\n    private String subject;\n    private int number;\n\n    public Period(String subject, int number) {\n        this.subject = subject;\n        this.number = number;\n    }\n\n    public String getSubject() {\n        return this.subject;\n    }\n\n    public int getNumber() {\n        return this.number;\n    }\n}\n// ==== school/domain/Teacher.java ====\npackage school.domain;\n\nimport java.util.ArrayList;\n\npublic class Teacher {\n    private String name;\n    private ArrayList<Period> periods;\n\n    public Teacher(String name) {\n        this.name = name;\n        this.periods = new ArrayList<>();\n    }\n\n    public void teach(Period period) {\n        this.periods.add(period);\n    }\n\n    public ArrayList<String> subjects() {\n        ArrayList<String> subjects = new ArrayList<>();\n        for (Period period : this.periods) {\n            subjects.add(period.getSubject());\n        }\n        return subjects;\n    }\n\n    @Override\n    public String toString() {\n        return this.name + \" teaches \" + this.periods.size() + \" periods\";\n    }\n}\n","hints":["`import school.domain.*;` lets Main use both Teacher and Period by their simple names. Teacher uses Period without an import, since they're in the same package.","`subjects()` builds a new list each time it's called, so adding Music to that list doesn't give the teacher a third period. `java.util.ArrayList` is the list's full name, and Teacher's full name starts with its package."],"tests":[{"name":"Output","stdin":"","expect":"Ms. Ito teaches 2 periods [Math, Art, Music]\njava.util.ArrayList\nschool.domain.Teacher","hidden":false}],"require":[],"forbid":[],"lines":["Ms. Ito teaches 2 periods [Math, Art, Music]","java.util.ArrayList","school.domain.Teacher"]},{"task":"`Period.java` from the previous task is ready in `school/domain/`. In `school/logic/SchoolDay.java`, write the class `SchoolDay` in the package `school.logic`, with the import lines it needs, and:\n\n- a constructor `SchoolDay()`, which makes a day with no periods yet\n- `add(Period period)`, which adds a period to the day\n- `subjectAt(int number)`, which returns the subject of the period with that number, or `free` if the day has no period with that number\n- `count(String subject)`, which returns how many periods of that subject the day has\n\nThe check runs:\n\n```java\nSchoolDay monday = new SchoolDay();\nmonday.add(new Period(\"Math\", 1));\nmonday.add(new Period(\"Biology\", 2));\nmonday.add(new Period(\"Math\", 4));\nSystem.out.println(monday.subjectAt(2));\nSystem.out.println(monday.subjectAt(3));\nSystem.out.println(monday.count(\"Math\"));\n```\n\nand expects:\n\n```\nBiology\nfree\n2\n```\n","kind":"code","seed":"// ==== school/logic/SchoolDay.java ====\n// Write the package line, the imports and the class SchoolDay here.\n\n// ==== school/domain/Period.java ====\npackage school.domain;\n\npublic class Period {\n    private String subject;\n    private int number;\n\n    public Period(String subject, int number) {\n        this.subject = subject;\n        this.number = number;\n    }\n\n    public String getSubject() {\n        return this.subject;\n    }\n\n    public int getNumber() {\n        return this.number;\n    }\n}\n\n// ==== Main.java ====\nimport school.domain.Period;\nimport school.logic.SchoolDay;\n\npublic class Main {\n    public static void main(String[] args) {\n        SchoolDay monday = new SchoolDay();\n        monday.add(new Period(\"Math\", 1));\n        monday.add(new Period(\"Biology\", 2));\n        monday.add(new Period(\"Math\", 4));\n        System.out.println(monday.subjectAt(2));\n        System.out.println(monday.subjectAt(3));\n        System.out.println(monday.count(\"Math\"));\n    }\n}\n","solution":"// ==== school/logic/SchoolDay.java ====\npackage school.logic;\n\nimport java.util.ArrayList;\nimport school.domain.Period;\n\npublic class SchoolDay {\n    private ArrayList<Period> periods;\n\n    public SchoolDay() {\n        this.periods = new ArrayList<>();\n    }\n\n    public void add(Period period) {\n        this.periods.add(period);\n    }\n\n    public String subjectAt(int number) {\n        for (Period period : this.periods) {\n            if (period.getNumber() == number) {\n                return period.getSubject();\n            }\n        }\n        return \"free\";\n    }\n\n    public int count(String subject) {\n        int count = 0;\n        for (Period period : this.periods) {\n            if (period.getSubject().equals(subject)) {\n                count++;\n            }\n        }\n        return count;\n    }\n}\n\n// ==== school/domain/Period.java ====\npackage school.domain;\n\npublic class Period {\n    private String subject;\n    private int number;\n\n    public Period(String subject, int number) {\n        this.subject = subject;\n        this.number = number;\n    }\n\n    public String getSubject() {\n        return this.subject;\n    }\n\n    public int getNumber() {\n        return this.number;\n    }\n}\n\n// ==== Main.java ====\nimport school.domain.Period;\nimport school.logic.SchoolDay;\n\npublic class Main {\n    public static void main(String[] args) {\n        SchoolDay monday = new SchoolDay();\n        monday.add(new Period(\"Math\", 1));\n        monday.add(new Period(\"Biology\", 2));\n        monday.add(new Period(\"Math\", 4));\n        System.out.println(monday.subjectAt(2));\n        System.out.println(monday.subjectAt(3));\n        System.out.println(monday.count(\"Math\"));\n    }\n}\n","hints":["The file starts with `package school.logic;`, then two imports: `java.util.ArrayList` for the list, and `school.domain.Period`, which is in another package. Then comes `public class SchoolDay {`.","Keep the periods in an `ArrayList<Period>`. `subjectAt` goes through them and returns the subject of the one whose `getNumber()` is the number; after the loop, it returns `\"free\"`. `count` compares subjects with `equals`."],"tests":[{"name":"Test 1","stdin":"","call":"SchoolDay monday = new SchoolDay();\nmonday.add(new Period(\"Math\", 1));\nmonday.add(new Period(\"Biology\", 2));\nmonday.add(new Period(\"Math\", 4));\nSystem.out.println(monday.subjectAt(2));\nSystem.out.println(monday.subjectAt(3));\nSystem.out.println(monday.count(\"Math\"));\n","expect":"Biology\nfree\n2","hidden":false},{"name":"Test 2","stdin":"","call":"SchoolDay friday = new SchoolDay();\nSystem.out.println(friday.subjectAt(1) + \" \" + friday.count(\"Art\"));\nfriday.add(new Period(\"Art\", 5));\nfriday.add(new Period(\"History\", 6));\nfriday.add(new Period(\"Art\", 7));\nfriday.add(new Period(\"Art\", 8));\nSystem.out.println(friday.subjectAt(6) + \" \" + friday.subjectAt(8) + \" \" + friday.subjectAt(1));\nSystem.out.println(friday.count(\"Art\") + \" \" + friday.count(\"art\") + \" \" + friday.count(\"History\"));\n","expect":"free 0\nHistory Art free\n3 0 1","hidden":true}],"require":[{"pattern":"==== school/logic/SchoolDay\\.java ====(?:(?!// ====)[\\s\\S])*import\\s+school\\.domain\\.(?:Period|\\*)\\s*;","raw":true,"message":"SchoolDay uses Period from another package: import it in `SchoolDay.java` with `import school.domain.Period;`."}],"forbid":[]}]}