Packages in Java UNIT II PART I
Packages in Java UNIT II PART I
have packages, used to organize the classes and interfaces files in java applications.
Packages are very similar as directories which help us to write better and
manageable code.
and interfaces. Classes with similar type of functionalities are put together inside a
package. It's the programmer who creates the package and adds the classes and
A package can contain other types as well like enums, annotation types,
subpackages. For simplicity we are referring classes and interfaces only, specially
The image below shows a hierarchy of different java elements where each element is
package packagename;
Example:
package mypack;
package com.refreshjava.mypack;
Here package is a keyword while packagename is the name of package given by
programmer. As per java the naming of packages should be in small letters only.
Types of packages
2. Built-in packages
This tutorial covers only user defined packages. For built-in packages refer built in
packages tutorial.
for an application/project you may need to create one or more packages in your
application. Each packages may have one or more classes and interfaces inside it.
As mentioned above, a package is also a directory. Each package that you define is a
computer. You can also declare the package in your program first and then create
the directory with same name(as package name) in your computer. Let's create a
project directory, you can choose your own directory. Currently mypack is just an
empty directory.
Once you have created the directory, you can use that directory as package name in
your program. Remember the package name declaration must be the first statement
in your program.
package packagename;
class className {
...
}
Example:
package mypack;
class Test {
...
}
package mypack;
class MyFirstPackageProgram {
public static void main(String args []) {
System.out.println("My first package program");
printMessage();
}
public static void printMessage() {
System.out.println("Inside printMessage method");
}
}
Notice here the package name and directory name is same. A package program
must be saved inside it's own(package name) directory. Now let's see how to
compile and execute the program.
Compilation and execution of package program
If you are not using tools like Eclipse, Netbeans etc, the compilation and execution of
programs having package declaration is a bit tricky. To compile above program,
open command prompt and move to the directory D:\project or the one that you
have used. Execute the below command which will create the .class file
inside mypack directory.
javac mypack\MyFirstPackageProgram.java
Now let's see how to run the above program. To run a package program you need to
give the class name with it's package name while executing the program like below :
java mypack.MyFirstPackageProgram
While compiling or executing the program, ensure that you are in D:\
project directory in command prompt or the one you have used for your package
directory.
Output:
It's mandatory to give the class name with it's package name while running the
program since java looks for the .class file in same directory(package name).
No a class can have only one package declaration. Declaring multiple package will
Yes multiple classes can have same package declaration. All these class files must
like classes or build directory. It's good programming style to separate the source
code and compiled code. To create .class files in separate directory java provides -
The -d option with javac command is used to specify the directory where
the .class files needs to be stored. Create a folder classes inside D:\
project directory in your computer and then execute the below command, it will
Here after -d option you need to specify the directory name where to save
the .class file. Here it's classes directory. The .class file will be generated
compilation java compiler will create a directory mypack inside classes directory.
If you want to save the .class files in current or same directory, you can use .(dot)
after -d option which tells the java compiler to save the .class file in current
directory.
Now to run the program you need to specify -classpath or -cp command line option
with java command. This option tells the java virtual machine where to look
Here after -cp or -classpath option you need to specify the directory name where to
look for the .class file. In this case it's classes directory where jvm will look
for .class file. To get more detail about classpath refer Path and Classpath tutorial.
Output:
What if JVM doesn't find the .class file at location given by cp/classpath
option ?
JVM will throw error like "Could not find or load main class ... ".
Java package program with multilevel directory
The program below demonstrates the package having multilevel directory structure.
package com.refreshjava.mypack;
class PackageDemo {
public static void main(String args []) {
System.out.println("Package with multilevel directory");
}
}
Output:
Package with multilevel directory
Advantages of Packages
2. Packages helps to avoid naming conflict. Classes with same name can exist
in different packages.
3. It also helps in controlling the access of one class inside other class.
A package defined inside another package is known as sub package. Sub packages
are nothing different than packages except that they are defined inside another
packages. Sub packages are similar as sub directories which is a directory created
Sub packages in itself are packages, so you have to use/access them similar as
packages. They can also have any types like classes, interfaces, enums etc inside
them.
mypack\testpack directory.
package mypack.testpack;
class MySubPackageProgram
{
public static void main(String args [])
{
System.out.println("My sub package program");
}
}
javac mypack\testpack\MySubPackageProgram.java
java mypack.testpack.MySubPackageProgram
Output:
creating sub folder inside a folder to categorize it further so that you can organize
your content more better which will make easy to access the content. A package
songs inside it. Then inside that we may create sub directories like hindi
songs and english songs or old songs and new songs to categories the songs
directory further. Doing this help us to organize or access the songs easily. The same
To access the classes or interfaces of a sub package, you need to import the sub
package in your program first. Importing the parent package of a sub package
doesn't import the sub packages classes or interfaces in your program. They must be
For example importing package mypack in your program will not import the classes of
sub package testpack given above. Importing sub packages is same as importing
Example
import mypack.testpack.*;
import mypack.testpack.MySubPackageProgram;
To get more detail about import statement, refer package import tutorial.
Example of Predefined SubPackages in Java
There are many predefined subpackages in java. Some of the examples of
subpackages in java 8 are :
1. The package java has subpackages like awt, applet, io, lang, net,
util etc. The package java doesn't have any class, interface, enums etc
inside it.
2. The package java.awt has subpackages like color, font, image etc inside it.
The package java.awt itself has many classes and interfaces declared inside
it.
3. The package java.util has subpackages like concurrent, regex, stream etc
inside it. The package java.util itself has many classes and interfaces
declared inside it.
import java.util.regex.Pattern;
// To imports all classes of java.util.regex subpackage.
// import java.util.regex.*;
class PatternMatch {
public static void main(String args[]) {
// Checks if the given string contains only alphabets
System.out.println(Pattern.matches("[a-zA-Z]*",
"RefreshJava"));
System.out.println(Pattern.matches("[a-zA-Z]*",
"RefreshJava2"));
// Checks if the given string contains only numbers
System.out.println(Pattern.matches("[0-9]*", "123456"));
System.out.println(Pattern.matches("[0-9]*", "123H456"));
}
}
Output:
true
false
true
false
Java has already defined some packages and included that in java software, these
contains a large number of classes and interfaces useful for java programmers for
and can use the classes and interfaces of these packages in that program.
comes in the form of jar files. By unzipping the jar file you can see the packages
available in that jar. For example if you unzip rt.jar file available in lib folder
of JRE, you can see the directory java which contains packages like lang, io, util,
sql etc.
There are many built-in packages available in java. In this tutorial we will see some
of the built-in packages and how to use their classes in our program. Some of the
1. java.awt : Contains classes for creating user interfaces and for painting
graphics and images. Classes like Button, Color, Event, Font, Graphics,
Image etc are part of this package.
5. java.sql : Provides the classes for accessing and processing data stored in a
database. Classes like Connection, DriverManager, PreparedStatement,
ResultSet, Statement etc are part of this package.
As mentioned above, you can unzip the jar files to see the list of all java packages or
you can refer this link to see the list of all packages available in java 11.
that is why we don't need any import statement in our programs for using classes
like String, StringBuffer, System etc. Except java.lang, other packages must be
imported first in your program to use the classes and interfaces available in that
Java AWT(Abstract Window Toolkit) package contains classes and interfaces used to
develop graphical user interface or window based applications in java. Java AWT
create components like textbox, button, checkbox etc. The program below creates
import java.awt.Frame;
import java.awt.Label;
class JavaAWTExample {
// Declaring constructor
public JavaAWTExample() {
Frame fm = new Frame(); //Creating a frame
Label lb = new Label(" Welcome to refresh java"); //Creating
a label
fm.add(lb); //adding label to the frame
fm.setSize(300, 200); //setting frame size
fm.setVisible(true); //setting frame visibility as true
}
public static void main(String args []) {
JavaAWTExample awt = new JavaAWTExample();
}
}
Here Frame and Label are classes defined in java.awt package. Frame class is used to
create frame while Label class is used to create label. AWT package is rarely used
today because of it's platform dependency and heavy-weight nature. Swing is the
preferred API over AWT for developing graphical user interface in java.
Output:
Java lang package(java.lang)
This packages contains the fundamental or core classes of java language without
which it won't be possible to write program in java. This package is automatically
imported to each program, which means we can use the classes of this package
directly in our program.
The program below shows how to use the Math class of java.lang package which
provides many different methods for different mathematical operations.
Java program of demonstrating use of java.lang package
class JavaLangExample {
public static void main(String args []) {
int a = 20, b =30;
int sum = Math.addExact(a,b);
int max = Math.max(a,b);
double pi = Math.PI;
System.out.printf("Sum = "+sum+", Max = "+max+", PI =
"+pi);
}
}
Output:
Sum = 50, Max = 30, PI = 3.141592653589793
As you can see we are able to use Math and System classes defined
in java.lang package without any import statement, it's because java.lang package
is imported implicitly.
Java io package(java.io)
Java IO(Input/Output) package provides classes and interfaces for handling
system(computer, laptop etc) input and output operations. Using these classes
programmer can take the input from user and do operations on that and then display
the output to user. Generally input is given using keyboard/keypad. We can also do
file handling(read/write) using the classes of this package.
The program below uses the Console class of java.io package to take the input from
user and then print that input to user's screen(command prompt or any other
terminal used).
Java program of demonstrating use of java.io package
import java.io.Console;
class JavaIOExample {
public static void main(String args []) {
Console cs = System.console();
System.out.println("Enter your name : ");
String name = cs.readLine();
System.out.println("Welcome : "+name);
}
}
Once you run this program, it will ask for your name and then it will display that
name in console window.
Output:
Enter your name :
Rahul
Welcome : Rahul
Java util package(java.util)
Java util package provides the basic utility classes to java programmers. It is one of
the most useful package for java programmers, it helps them to achieve different
types of requirements easily by using it's predefined classes.
The program below uses Arrays class of this package to sort an array of integers.
The Arrays class provides many api's(methods) for different array requirements.
Java program of demonstrating use of java.util package
import java.util.Arrays;
class JavaUtilExample {
public static void main(String args []) {
int[] intArray = {10,30,20,50,40};
Arrays.sort(intArray);
System.out.printf("Sorted array : %s",
Arrays.toString(intArray));
}
}
Output:
Sorted array : [10, 20, 30, 40, 50]