0% found this document useful (0 votes)
17 views

Packages in Java UNIT II PART I

Project 3

Uploaded by

582.tableau
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Packages in Java UNIT II PART I

Project 3

Uploaded by

582.tableau
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

Packages in Java

As in our computer we have directories to organize the files, similarly in java we

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.

A package, as the name itself suggest is a group(pack) of similar types of classes

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

interfaces inside that package.

A package can contain other types as well like enums, annotation types,

subpackages. For simplicity we are referring classes and interfaces only, specially

the classes in this tutorial.

The image below shows a hierarchy of different java elements where each element is

a subset of next element. For example a method is a group of statements, similarly

an application is a group of packages.

A package declaration looks like below :

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

Packages can be categorized in two types :

1. User defined packages

2. Built-in packages

This tutorial covers only user defined packages. For built-in packages refer built in

packages tutorial.

User defined packages in Java

Packages defined by programmer is known as user defined packages. While working

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.

Let's see how to create a user defined package.

Creating packages in Java

As mentioned above, a package is also a directory. Each package that you define is a

directory in your computer. For example a package name mypack will be a

directory mypack inside your computer. Similarly a package

name com.refreshjava.mypack will have a directory structure

as com/refreshjava/mypack, where directory mypack will be

inside refreshjava directory which will be inside com directory.

So to create a package, first you need to create a directory anywhere in your

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

directory mypack inside the computer. In my computer it is created inside D:\

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 {
...
}

Now let's create the class MyFirstPackageProgram.java as given below inside

the D:\project\mypack\ directory.

Java package program

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:

My first package program

Inside printMessage method

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).

Can a class have multiple package declaration ?

No a class can have only one package declaration. Declaring multiple package will

result in compilation error.


Can multiple classes have same package declaration ?

Yes multiple classes can have same package declaration. All these class files must

go inside same directory.


Creating .class files in separate directory
In above program we created the .class file in mypack directory but in real world

applications, generally we use to create the .class files in separate directory

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 -

d option which is used with javac command.

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

create the .class file inside classes directory.

javac -d classes mypack\MyFirstPackageProgram.java

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

inside D:\project\classes directory, so ensure that it already exist. After successful

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

for .class files.

java -cp classes mypack.MyFirstPackageProgram // or

java -classpath classes mypack.MyFirstPackageProgram

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:

My first package program

Inside printMessage method

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.

Create the directory structure com/refreshjava/mypack inside D:\project directory

and then save below program inside that directory.

package com.refreshjava.mypack;

class PackageDemo {
public static void main(String args []) {
System.out.println("Package with multilevel directory");
}
}

Execute below commands to compile and run the program.

javac -d classes com\refreshjava\mypack\PackageDemo.java

java -cp classes com.refreshjava.mypack.PackageDemo

Output:
Package with multilevel directory

Advantages of Packages

The advantages of using packages are :

1. Packages makes easy to search or locate class or interface files.

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.

4. Packages helps in encapsulation of classes and interfaces.

5. Packages helps to reuse the classes and interfaces.

Sub Packages in Java

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

inside another directory.

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.

How to create and use sub packages in Java

It's similar as creating packages in java. In previous tutorial, we created a

package mypack which is a directory in computer. Now if I create a

package(directory) testpack inside mypack directory, then package testpack will be

called as sub package.


Let's create a class inside this sub package. I have created a

class MySubPackageProgram.java as given below and saved it inside D:\project\

mypack\testpack directory.

Subpackage program in Java

package mypack.testpack;

class MySubPackageProgram
{
public static void main(String args [])
{
System.out.println("My sub package program");
}
}

Notice here the package name is mypack.testpack which is a subpackage. Let's


compile and run this program by executing the commands given below. If you don't
know how to compile and execute package program, refer packages tutorial first.

javac mypack\testpack\MySubPackageProgram.java
java mypack.testpack.MySubPackageProgram

Output:

My sub package program


Why do we create Sub Packages

Subpackages are created to categorize/divide a package further. It's similar as

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

may have many sub packages inside it.


For an example in our computer generally we create directory like songs to store

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

thing applies with sub packages as well.

How to import Sub packages

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

imported explicitly in your program to access their classes and interfaces.

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

packages. The syntax of importing a sub package is :

// To import all classes of a sub package


import packagename.subpackagename.*;
// To import specific class of a sub package
import packagename.subpackagename.classname;

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.

The program below shows how to use the Pattern class


of java.util.regex subpackage. This sub package contains classes and interfaces
for regular expressions. The Pattern class is generally used to search or match a
particular pattern inside a given string.

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

Built in packages in Java

Java has already defined some packages and included that in java software, these

packages are known as built-in packages or predefined packages. These packages

contains a large number of classes and interfaces useful for java programmers for

different requirements. Programmers can import these packages in their program

and can use the classes and interfaces of these packages in that program.

Built-in packages comes automatically in your jdk/jre download. These packages

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

inbuilt packages in java are :

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.

2. java.io : Provides classes for system input/output operations. Classes


like BufferedReader, BufferedWriter, File, InputStream, OutputStream,
PrintStream, Serializable etc are part of this package.

3. java.lang : Contains classes and interfaces that are fundamental to the


design of Java programming language. Classes like String, StringBuffer,
System, Math, Integer etc are part of this package.

4. java.net : Provides classes for implementing networking applications. Classes


like Authenticator, HttpCookie, Socket, URL, URLConnection,
URLEncoder, URLDecoder 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.

6. java.util : Contains the collections framework, some internationalization

support classes, properties, random number generation classes. Classes


like ArrayList, LinkedList, HashMap, Calendar, Date, TimeZone 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.

The package java.lang is automatically imported to every program that we write,

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

packages. To get complete detail about how to import packages in java,

refer package import tutorial.

Java awt package(java.awt)

Java AWT(Abstract Window Toolkit) package contains classes and interfaces used to

develop graphical user interface or window based applications in java. Java AWT

components are platform-dependent since they uses operating system resources to

create components like textbox, button, checkbox etc. The program below creates

a frame containing a label using java.awt classes.

Java awt package program

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]

You might also like