Java | Packages

05 min read

Packages:

Most frequently used Java Predefined Packages:

All packages are prefixed with 'java' or 'javax'.

1. java.lang - Supports the basic language features and the handling of arrays and strings. Classes in this package are essential for our programs to work and so it is always automatically loaded with all programs by default. No need to import them explicitly.

2. java.io - Contains classes for data input and output operations.

3. java.util - Contains the collection framework, legacy collection classes, event models, date and time facilities, internationalization and miscellaneous utility classes (a String Tokenizer, a random-number generator, and a bit-array).

4. java.awt - Contains all of the classes for creating user interfaces and for painting Graphics and images.

5. java.applet - Provides classes necessary to create an applet and the classes an applet uses to communicate with its applet context.

6. java.net - Provides classes for implementing networking applications.

7. java.swing - Provides easy-to-use and flexible components for building GUI's. The components in this package are referred to as Swing components.

 

Package:

  • It is a named collection of classes. It is both a naming control and visibility control mechanism. It's a way to properly manage the namespace.
  • All the programs which we have done so far, have been stored in the default package which does not have any name.
  • If needed, a new package can be created and all the files (classes) which we wish to store within that package can be defined inside it. So, those classes that are defined within that package become inaccessible by the code outside the package, unless that package is imported (within the code which wants to access it).
  • Example: If there is a package named 'NumberChecking' in which we wish to store classes like Armstrong number, Palindrome, PerfectNumber, etc., then these 3 classes become unavailable to the classes outside the package 'NumberChecking'.

 

How to define a package?

  • 'package' statement must be included and this must be the first statement in a Java Otherwise the class names will be saved inside the default package.
  • Syntax: package packageName;
  • Note: If there are any import statements within the program, they should also appear only after the package statement.
  • Example: package number checking
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error