Styrow.dev
Question 233 of 247
Java Topic: General medium

What are packages?

Question

What are packages?

Answer

1.Packages are used to create libraries in java.

2.Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier.

3.There are three type of packages:

a.) Inbuilt packages

• Those packages which are available in rt.jar are inbuilt packages.

• These are standard packages which come as a part of Java Runtime Environment

• These are loaded in JVM itself.

• Some of the commonly used built-in packages are:

i.) java.lang - Contains language support classes ( for e.g classes which defines primitive data types, math operations, etc.). This package is automatically imported.

ii.) java.io - Contains classes for supporting input / output operations.

iii.) java.util - Contains utility classes which implement data structures like Linked List, Hash Table, Dictionary, etc and support for Date / Time operations.

iv.) java.applet - Contains classes for creating Applets.

v.) java.awt - Contains classes for implementing the components of graphical user interface ( like buttons, menus, etc. ).

vi.) java.net - Contains classes for supporting networking operations.

b.) Vendor specific packages

• Those packages provided by vendors like oracle, apache, IBM etc. are called vendor specific packages.

• In case of vendor specifc packages, we need to set the class path of packages.

c.) User defined packages

• We can create our own packages also, steps to create package:

i.) Use ‘package’ keyword in first line of the program (with the package name).

ii.) The package statement should be the first line in the source file.

iii.) Create the class public.

• Let us look at an example that creates a package called animals.

• It is a common practice to use lowercase names for packages, to avoid any conflicts with the names of classes or interfaces.

/* File name : Animal.java */ % package animals; % interface Animal { % public void eat(); % public void travel(); % }