Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Create a File in a Specified Directory
Next article icon

How to Create a Package in Java?

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some classes are accessible or exposed and others are kept for internal purposes. We can reuse existing classes from the packages as many times as we need them in our program. Package names and directory structure are closely related

Types of Packages in Java

There are two types of packages in java:

  1. User-defined Package (Create Your Own Package's)
  2. Built-in packages are packages from the java application programming interface that are the packages from Java API for example such as swing, util, net, io, AWT, lang, javax, etc.

In this article, we will see How To Create A Package In Java. A package is a group of similar types of Classes, Interfaces, and sub-packages. We use Packages to avoid name conflicts. 

Syntax: To import a package

import package.name.*;

Example: Importing java.util package

Java
// Java Program to Import a package  // Importing java utility package import java.util.*;  // Main Class class GFG {      // Main driver method     public static void main(String[] args)     {          // Scanner to take input from the user object         Scanner myObj = new Scanner(System.in);         String userName;          // Display message         // Enter Your Name And Press Enter         System.out.println("Enter Your Name:");          // Reading the integer age entered using         // nextInt() method         userName = myObj.nextLine();          // Print and display         System.out.println("Your Name is : " + userName);     } } 

Input

Enter Your Name:
geeksforgeeks

Output:

Your Name is : geeksforgeeks

Here In The Above Program, 'java.util' package is imported Scanner class is used to take input from the user. These are called as Inbuilt Packages. 

Creating a Package in Java

Now in order to create a package in java follow the certain steps as described below: 

  1. First We Should Choose A Name For The Package We Are Going To Create And Include. The package command In The first line in the java program source code.
  2. Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made in the package. For example, the below single statement creates a package name called “FirstPackage”.

Syntax: To declare the name of the package to be created. The package statement simply defines in which package the classes defined belong.

package FirstPackage ;

Implementation: To Create a Class Inside A Package 

  1. First Declare The Package Name As The First Statement Of Our Program.
  2. Then We Can Include A Class As A Part Of The Package.

Example 1: Creating a Class Inside a Package

Java
// Name of package to be created package FirstPackage;  // Class in which the above created package belong to class Welcome {     // main driver method     public static void main(String[] args)     {         // Print statement for the successful         // compilation and execution of the program         System.out.println(             "This Is The First Program Geeks For Geeks..");     } } 

So Inorder to generate the above-desired output first do use the commands as specified use the following specified commands

Procedure to Generate Output:

1. Compile the Welcome.java file: 

Command: javac Welcome.java 

2. This command creates a Welcome.class file. To place the class file in the appropriate package directory, use:

Command: javac -d . Welcome.java 

3. This command will create a new folder called FirstPackage. To run the class, use:

Command: java FirstPackage.Welcome 

Output: The Above Will Give The Final Output Of The Example Program.

Output

Example 2: Another Package Example 

Java
// Name of package to be created package data;  // Class to which the above package belongs public class Demo {      // Member functions of the class- 'Demo'     // Method 1 - To show()     public void show()     {          // Print message         System.out.println("Hi Everyone");     }      // Method 2 - To show()     public void view()     {         // Print message         System.out.println("Hello");     } } 

Again, in order to generate the above-desired output first do use the commands as specified use the following specified commands

Procedure: 

1. Compile the Demo.java file:

Command: javac Demo.java 

2. This command will generate a Demo.class file: 

Command: javac -d . Demo.java 

3. This command will create a new folder called data containing the Demo.class file.

Note: In data Demo.java & Demo.class File should be present 

Example 3: Accessing Data from Another Program

Java
// Name of the package import data.*;  // Class to which the package belongs class ncj {      // main driver method     public static void main(String arg[])     {          // Creating an object of Demo class         Demo d = new Demo();          // Calling the functions show() and view()         // using the object of Demo class         d.show();         d.view();     } } 


Procedure to Generate the Output:

1. Compile the ncj.java file:

Command: javac ncj.java 

2. The above command compiles ncj.java and requires the Demo.class file to be present in the data package.

Command: java ncj 
// To Run This File

Output: Generated on the terminal after the above command Is executed 

Hi Everyone
Hello

Next Article
Java Program to Create a File in a Specified Directory

N

nishanthec19
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Packages
Practice Tags :
  • Java

Similar Reads

  • How to Create a Directory in Java?
    In Java, creating a directory is a common operation when working with file system manipulation. Directories are used to organize files and other directories into a hierarchical structure. This article will guide you through the process of creating a directory in Java, providing step-by-step examples
    2 min read
  • Java Program to Create a New File
    There are two standard methods to create a new file, either directly with the help of the File class or indirectly with the help of the FileOutputStream class by creating an object of the file in both approaches. Methods to Create Files in JavaThere are two methods mentioned below Using the File Cla
    4 min read
  • Java Program to Create a Word Document
    A Word file is supposed to be created without Word with the help of Java application protocol interfaces. Concepts Involved: Apache POI and Maven Apache POI Is an API provided by Apache foundation which is a collection of different java libraries. This facility gives the library to read, write, and
    5 min read
  • Java Program to Create a File in a Specified Directory
    Creating a file in a specific directory using Java can be done in various ways. This is done using predefined packages and Classes. In this article, we will learn about how to create a file in a specified directory. Methods to Create a File in a Specified DirectoryThree such methods to create a file
    3 min read
  • Java Program to Create blank Excel Sheet
    ApachePOI stands for poor obfuscation Implementation which is a Java API for reading and writing Microsoft documents. It contains classes and interfaces namely Wordbook, Sheet, Row, and Cell. Apache POI can be used to access 'xlsx' extension files and as well as 'xlsx' extension files Concept: Apach
    3 min read
  • Java Program to Create a Blank PPT Document
    Program to create a blank PPT document using Java. The external jar(Java archive) file is required for the creation of a new PPT document. Below is the implementation for the same. An object of XMLSlideShow class inside External Apache POI module is required for the creation of a new PPT. Algorithm:
    1 min read
  • Create Password Protected Zip File in Java
    Primarily, java does not have any function or package that will create a password-protected zip file without using some native codes. Java has some useful library which is good but they use some native codes to perform their task that makes their usage platform dependent to some extent. Whereas in t
    5 min read
  • Java Swing | Create a simple text editor
    To create a simple text editor in Java Swing we will use a JTextArea, a JMenuBar and add JMenu to it and we will add JMenuItems. All the menu items will have actionListener to detect any action.There will be a menu bar and it will contain two menus and a button:  File menuopen: this menuitem is used
    6 min read
  • Java Program to Create Directories Recursively
    A directory/folder is a File System used in computing that acts as a named memory location for storing related files or even subfolders. This allows better management of files and folders and is premised on the concept of real-world folders used for storing files. This system is the implementation o
    5 min read
  • How to Create Different Types of Cells in a Spreadsheet using Java?
    Apache POI is an API which was provided by Apache Foundation and is used to set the various type of values to the cell. The overloading function setCellValue() of Apache POI is used to set the value type of the cell. Maven is a powerful project management tool that is based on POM (project object mo
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences