Packages & imports (concept)
Computer Science · Java
Question 1 of 10
0Which package contains the commonly used ArrayList class?
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Packages & imports (concept) explained
A package is a group of related Java classes, and it gives each class a fully qualified name made of the package name and the class name. Packages keep names from clashing and organise code into folders that mirror the package name.
A package is declared with a package statement at the top of a file, such as package com.example.shop;. Source files are normally stored in folders that match the package name, so com.example.shop is kept in com/example/shop/. Classes in the same package can use each other without an import. To use a class from another package, either write its full name, such as java.util.ArrayList, or add an import statement. Importing with java.util.* brings in the public classes of that package but not its sub-packages. The java.lang package is imported automatically, which is why String and Math need no import. Only a public class must match its file name, so a public class Cart belongs in Cart.java.
package com.example.shop;
import java.util.ArrayList;
public class Cart {
ArrayList<String> items = new ArrayList<>();
}
Worked example
This hypothetical file is Cart.java in the folder com/example/shop.
- Its package statement makes its fully qualified name com.example.shop.Cart.
- The import line lets Cart use ArrayList without writing java.util.ArrayList each time.
- String inside the class needs no import, because java.lang is automatic.
- Another class in the same package can use Cart with no import at all.
What you will practise
101 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.
Example questions
- A package in Java:
- The import statement:
- import java.util.*:
- A package name:
- Package-private is:
- Which keyword declares the package a Java source file belongs to?
- Which package is imported automatically into every Java source file?
- A fully qualified class name is:
…and 93 more.