Understanding Java Packages: A Comprehensive Guide with Examples - Quiz
Total: 5 questions
1. What is a package in Java and what problems does it solve?
What is a package in Java and what problems does it solve?
A package is a mechanism for grouping classes, similar to directories in the file system (and it must align with it). Packages solve two problems: they organize a large number of classes and separate namespaces so that two classes with the same name do not conflict. Packages also control access: a package can define classes and members that are visible only to code within the same package.
2. How do you add a class to a package in Java?
How do you add a class to a package in Java?
There are two steps: place the package statement as the first line of the file, and put the class in a directory named after the package. The fully qualified class name then includes the package name — for example, lesson1.MyFirstApp.
package lesson1;
public class MyFirstApp {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
3. What are the naming rules for packages in commercial projects?
What are the naming rules for packages in commercial projects?
For commercial projects the package name usually starts with com, followed by the organization name and the project name, and then functional descriptors. For example, a project from examclouds.com could use com.examclouds.examples.code.lesson1. Package names should use lowercase letters only.
4. How do you compile and run a class located in the lesson1 package?
How do you compile and run a class located in the lesson1 package?
Use the -d option to tell the compiler where to place the compiled classes, along with the relative path to the source file. Then run the program by its fully qualified name (including the package name).
cd project1/src
javac -d ../classes lesson1/MyFirstApp.java
cd project1/classes
java lesson1.MyFirstApp
5. What is the import statement for, and where is it placed in a source file?
What is the import statement for, and where is it placed in a source file?
Without importing, a class from another package must be referred to by its fully qualified name, which is inconvenient. The import statement lets you use the short name of a class. Import statements come after the package declaration and before any class definitions. You can import a single class or a whole package using *.
import java.util.regex.Matcher;
import java.time.*;