Today we will discuss Java packages. This is one of the most important features in Java. Java comes with many pre-listed packages. Knowingly or unknowingly, you may have used them in your code. I will explain this later on. Even if you are a beginner you had used Java package. First of all we will learn what Java package is, then what its features, its importance are and how to use them in your program code.

What is Java Package?

The simplest example that will give you a most satisfactory explanation is, packages are like your book shelf. In your book shelf, you arrange school books in a row; in another row you arrange your comic books, your novels, your CD and many more. Similarly, Java also used several shelves to arrange similar kind of codes files that are used by programmers. These shelves are known as Java package. Also you must have heard about Java runtime environment ( jre ). When we compile a code it directly interact jre and use the default package which was set by Java. And the package is "java.lang". This default package is already imported in your program code. That’s why whenever we need to use the classes of java.lang package we don’t need to import this package. For other packages we need to import them explicitly.

Java Package - Importance/features

The one of the most important feature of Java package is that you can create your own package and import it in your program code without creating a .jar file. You simply need to set the classpath of your command line interpreter. For example, if you frequently use the code to calculate the area, then instead of writing the code to calculate the area in each program code you can simply write the code in a separate file and compile it. Then set the classpath of that particular class in your command line interpreter. Now you don’t need to write the same code again and again.

How to use packages in your Program Code?

Part A : Using Sun’s Java package.
In this part we will learn how to use pre-existing package. Some of the most commonly used Java packages are

In below program code we will use javax.swing package and will use some pre-existing code file.

Code: java

import javax.swing // it should be the line to import any package in your program code.Class GuiApp{JFrame f1; // pre-existing code file named as JFrame javax.swing packageJPanel p1; // pre-existing code file named as JPanel javax.swing packageJLabel l1; // pre-existing code file named as JLabel in javax.swing package