| Home | Resources | Papers | Essays | Short Fiction | About |

(Appendix) import and packages

Table of Contents

Introduction

When programming in Java you'll often want more functionality than what's immediately available in a basic program. The way we obtain that additional functionality is through the import statement.

Using import

If we want to use a standard library object, like ArrayList, we first need to import it. We can do like so:

1: import java.util.ArrayList;
2: public class UsingPackages{
3:     public static void main(String[] args){
4:         ArrayList<Integer> lst = new ArrayList<>();
5:     }
6: }

Let's see what happens if we don't include the import:

1: public class UsingPackages{
2:     public static void main(String[] args){
3:         ArrayList<Integer> lst = new ArrayList<>();
4:     }
5: }

If we compile the above we get:

josephraskind@stargazer:/tmp/packages$ javac UsingPackages.java 
UsingPackages.java:3: error: cannot find symbol
        ArrayList<Integer> lst = new ArrayList<>();
        ^
  symbol:   class ArrayList
  location: class UsingPackages
UsingPackages.java:3: error: cannot find symbol
        ArrayList<Integer> lst = new ArrayList<>();
                                     ^
  symbol:   class ArrayList
  location: class UsingPackages
2 errors

Why? ArrayList is defined as part of the java.util package. The only package that is loaded in by default during the Java runtime is java.lang. This is why we can use String by default---String is also defined in java.lang. Anything that isn't a part of java.lang must be imported.

Defining packages

We can define our own packages through the use of the package keyword. We can see it below:

1: package mypackage;
2: public class MyClass{
3:     public MyClass(){}
4: }

This only works because MyClass has been defined in a directory named mypackage:

josephraskind@stargazer:/tmp/packages$ ls
mypackage  UsingPackages.java
josephraskind@stargazer:/tmp/packages$ ls mypackage/
MyClass.java

And we can import it easily:

1: import mypackage.MyClass;
2: public class UsingPackages{
3:     public static void main(String[] args){
4:         MyClass mc = new MyClass();
5:     }
6: }

We can also use the wildcard syntax:

1: import mypackage.*;
2: public class UsingPackages{
3:     public static void main(String[] args){
4:         MyClass mc = new MyClass();
5:     }
6: }

Wildcards do not import subpackages but only packages at that given level.

There are a few rules associated with defining packages:

  • Packages must be unique
    • There cannot be two packages with the same path
  • Packages may have the same class name in two different paths
Contact: [email protected] | rss feed | Compiled with org-mode | Licensed under CC BY-NC-SA 4.0