Java Packages & Imports

What is a Package?

A package is a way to group related classes together. It helps organize your code, especially in large applications.

Think of packages like folders on your computer that store related files.

Loading...
Output:

Creating a Package

Use the package keyword at the top of your file to define which package the class belongs to.

The package name usually matches the folder structure of your project.

Loading...
Output:

What is an Import?

The import keyword allows you to use classes from other packages without writing their full path.

This makes your code cleaner and easier to read.

Loading...
Output:

Using Built-in Packages

Java includes many built-in packages that provide useful classes.

For example, java.util includes tools like Scanner and ArrayList.

Loading...
Output:

Wildcard Imports

You can import all classes from a package using the * symbol.

This is useful for quick programs, but in larger applications, it is better to import only what you need.

Loading...
Output:

Using Custom Packages

You can create your own packages and import them into other classes.

This is commonly used in real-world projects to separate logic into different modules.

Loading...
Output:

Default Package

If you do not declare a package, your class is placed in the default package.

This is fine for small programs, but not recommended for larger applications.

Why Use Packages?

Packages help organize your code and make it easier to maintain.

  • Prevents class name conflicts
  • Keeps related code together
  • Makes large projects easier to manage

Practice

Create a utilities package with a MathHelper class and use it in another class.

Loading...
Output:

Need Help?