Java
Java intro
Java basics
Java variables
Java conditionals
Java loops
Java arrays
Java OOP 1
Java OOP 2
Java interfaces
Java Strings
Java user input
Java exceptions
Java packages
Java rand numbers
Java GUI's
Java GUI layout
Java events
Java applets
Java graphics
Java sounds
Java summary

Programming

Programming intro

Markup

First webpage guide HTML
XHTML

Style & Layout

CSS

Browser scripting

Javascript
VBScript
AJAX

Server scripting

PHP
ASP

Making money online

Make money online

Java packages

A package is a group of related classes and interfaces that work together to provide functionality for various purposes.

This lesson focuses on:

Importing packages

The purpose of importing packages is to be able to use classes and interfaces located in those specific packages. If you try to use a class or interface without importing the package it is located in, you will get an error.

There is one package that is imported by default into all Java programs - the java.lang package. The java.lang package provides classes that are fundamental to developing Java programs. Classes within the java.lang package include the String class for working with text strings and the Math class for performing various calculations and working with numeric data, among others. For all other classes, you must import the appropriate package(s).

Importing packages is achieved by using the import keyword followed by a single space followed by the name of the package to be imported followed by the name of the class or interface to import followed by a semicolon.

NOTE: The import keyword should appear first in code, even before the class declaration!

Syntax:

import packageName.className;
import packageName.interfaceName;

Example:

import java.util.Random;
import java.util.Vector;

class Book{

}

In the above example, a class named Book imports the Random and Vector classes from the java.util package. Because of this, the Book class can now use these classes from this package.

Instead of importing single classes or interfaces from packages, you can specify that a class imports all the classes and interfaces from a package using the * character.

Syntax:

import packageName.*;

Example:

import java.util.*;

class Book{

}

In the above example, a class named Book imports all the classes and interfaces from the java.util package using the * character. Because of this, the Book class can now use all the interfaces and classes located in the java.util package.

Different Java packages

Java provides many different packages for a wide variety of functionality.

Some of Java's packages:

Practice

Online code editor
Practical examples
Practical exercises
Step-by-step tutorials

Reference

Terms glossary
Reference material

Rate this site

Rate this site
Visitor comments