Skip To Content7

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 10

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

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

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Packages In Java
How to Create a Package in Java?
Java.util Package in Java
Java.lang package in Java
Java.io Package in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
How to Create a Package in Java?
Last Updated : 24 Jul, 2024
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:

User-defined Package (Create Your Own Package’s)


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 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:

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

First Declare The Package Name As The First Statement Of Our Program.
Then We Can Include A Class As A Part Of The Package.
Example 1: Creating a Class Inside a Package

// 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

// 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

// 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

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Feeling lost in the vast world of Backend Development? It's time for a change! Join
our Java Backend Development - Live Course and embark on an exciting journey to
master backend development efficiently and on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks

nishanthec19

36
Previous Article
Packages In Java
Next Article
Java.util Package in Java
Read More
Down Arrow
Similar Reads
Java Program to Create a Package to Access the Member of External Class and Same
Package
As the name suggests a package in java that contains all the same kinds of classes,
Abstract classes, interfaces, etc that have the same functionality. A Single
package can contain many classes, Abstract classes e.g. java.util package etc.
There are two types of packages: Built-in-package: These are the packages that are
predefined in the java jar
2 min read
Java.lang.Package class in Java
Java 2 added a class called Package that encapsulates version data associated with
a package. Package version information is becoming more important because of the
proliferation of packages and because a java program may need to know what version
of a package is available. This versioning information is retrieved and made
available by the ClassLoad
8 min read
Java.util Package in Java
Java.util PackageIt contains the collections framework, legacy collection classes,
event model, date and time facilities, internationalization, and miscellaneous
utility classes (a string tokenizer, a random-number generator, and a bit
array).Following are the Important Classes in Java.util package :
AbstractCollection: This class provides a skelet
4 min read
Java.lang package in Java
Java.lang package in JavaProvides classes that are fundamental to the design of the
Java programming language. The most important classes are Object, which is the root
of the class hierarchy, and Class, instances of which represent classes at run
time. Following are the Important Classes in Java.lang package : Boolean: The
Boolean class wraps a val
3 min read
Java.io Package in Java
Java.io Package in JavaThis package provides for system input and output through
data streams, serialization and the file system. Unless otherwise noted, passing a
null argument to a constructor or method in any class or interface in this package
will cause a NullPointerException to be thrown. Following are the important classes
in Java.io package:
1 min read
HTTP API of java.net.http Package With Examples
HTTP Client and WebSocket APIs provide high-level client interfaces to HTTP
(versions 1.1 and 2) and low-level client interfaces to WebSocket. The main types
defined are namely as follows: HttpClientHttpRequestHttpResponse The protocol-
specific requirements are defined in the Hypertext Transfer Protocol Version 2
(HTTP/2), the Hypertext Transfer Pr
14 min read
javax.xml.crypto Package in Java
Common classes having the XML cryptography for the Package javax.xml.crypto. now
this crypto package includes similar classes that are used to accessing XML
cryptographic on its operations, such as creating an XML signature or encrypted XML
data. There are two types of javax.xml.crypto classes in this package that are
KeySelector class, which allow
4 min read
Package getSpecificationVendor() method in Java with Examples
The getSpecificationVendor() method of java.lang.Package class is used to get the
vendor of the specification of this package. The method returns the specification
vendor of the package as a String.Syntax: public String getSpecificationVendor()
Parameter: This method does not accept any parameter.Return Value: This method
returns the specification
2 min read
Package getImplementationTitle() method in Java with Examples
The getImplementationTitle() method of java.lang.Package class is used to get the
title of the implementation of this package. The method returns the implementation
title of the package as a String.Syntax: public String getImplementationTitle()
Parameter: This method does not accept any parameter.Return Value: This method
returns the implementation
2 min read
Package getImplementationVersion() method in Java with Examples
The getImplementationVersion() method of java.lang.Package class is used to get the
version of the implementation of this package. The method returns the
implementation version of the package as a String.Syntax: public String
getImplementationVersion() Parameter: This method does not accept any
parameter.Return Value: This method returns the implem
2 min read
Article Tags :
Java
Java Programs
Java-Packages
Practice Tags :
Java
three90RightbarBannerImg
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
course-img
216k+ interested Geeks
Java Programming Online Course [Complete Beginner to Advanced]
Avail 90% Refund
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th 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
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
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
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@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
Got It !
Lightbox

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy