[go: up one dir, main page]

0% found this document useful (0 votes)
88 views10 pages

.Trashed 1742732429 Java Packages GeeksforGeeks

The document provides an overview of Java packages, explaining their purpose in organizing classes, preventing naming conflicts, and controlling access. It details the structure of packages, how to import classes, and the distinction between built-in and user-defined packages. Additionally, it covers static imports, handling name conflicts, and setting the CLASSPATH for Java applications.

Uploaded by

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

.Trashed 1742732429 Java Packages GeeksforGeeks

The document provides an overview of Java packages, explaining their purpose in organizing classes, preventing naming conflicts, and controlling access. It details the structure of packages, how to import classes, and the distinction between built-in and user-defined packages. Additionally, it covers static imports, handling name conflicts, and setting the CLASSPATH for Java applications.

Uploaded by

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

Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithrea

Java Packages
Last Updated : 04 Feb, 2025

Packages in Java are a mechanism that encapsulates a group of classes,


sub-packages, and interfaces. Packages are used for:

Prevent naming conflicts by allowing classes with the same name to


exist in different packages, like college.staff.cse.Employee and
college.staff.ee.Employee.
They make it easier to organize, locate, and use classes, interfaces,
and other components.
Packages also provide controlled access for Protected members that
are accessible within the same package and by subclasses.
Also for default members (no access specifier) that are accessible
only within the same package.

By grouping related classes into packages, Java promotes data


encapsulation, making code reusable and easier to manage. Simply
import the desired class from a package to use it in your program.

Working of Java Packages

Directory Structure: Package names and directory structures are


closely related. For example, if a package name is college.staff.cse, then
three directories are, college, staff, and cse, where cse is inside staff,
and staff is inside the college.

Naming Conventions: Package names are written in reverse order of


We use cookies to ensure you have the best browsing experience on our website. By using our site, you
domain names, that
acknowledge e.g.,
youorg.geeksforgeeks.practice. In a& college,
have read and understood our Cookie Policy the
Privacy Policy
convention might be: Got It !
college.tech.cse
college.tech.ee
college.art.history

Example:

import java.util.*;

Here, util is a sub-package created inside the java package.

Accessing Classes Inside a Package


In Java, we can import classes from a package using either of the
following methods:

1. Import a specific class:

import java.util.Vector;

This imports only the Vector class from the java.util package.

2. Import all classes from a package:

import java.util.*;

This imports all classes and interfaces from the java.util package but
does not include sub-packages.

Example: Importing Class

// Import the Vector class from


// the java.util package
import java.util.Vector;

public class Geeks {

public Geeks() {
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
// java.util.Vector is imported, hence we are
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
// able to access it directly in our code.
Vector v = new Vector();
// java.util.ArrayList is not imported, hence
// we are referring to it using the complete
// package name.
java.util.ArrayList l = new java.util.ArrayList();
}

public static void main(String[] args) {

// Creating an instance of Geeks


// class to invoke the constructor
new Geeks();
}
}

Note:

Using import package.*; imports all classes in a package, but not


classes from its sub-packages.
When two packages have classes with the same name (e.g.,
java.util.Date and my.package.Date), use the fully qualified name to
avoid conflicts:

import java.util.Date;

import my.package.Date;

Types of Java Packages


Built-in Packages
User-defined Packages

1. Built-in Packages

These packages consist of a large number of classes which are a part of


Java API.Some of the commonly used built-in packages are:

java.lang: Contains language support classes(e.g classes which


defines primitive data types, math operations). This package is
automatically imported.
java.io: Contains classes for supporting input / output operations.
java.util:
We use Contains
cookies to ensure utility
you have the bestclasses
browsing which implement
experience on our website.data structures
By using our site, you
likeacknowledge
Linked List,that you have read and
Dictionary andunderstood
support our ;Cookie Policy &/ Time
for Date Privacy Policy
operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for
graphical user interfaces (like button , ;menus etc). 6)
java.net: Contain classes for supporting networking operations.

2. User-defined Packages

These are the packages that are defined by the user.

1. Create the Package:

First we create a directory myPackage (name should be same as the


name of the package). Then create the MyClass inside the directory
with the first statement being the package names.

// Name of the package must be same as the directory


// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}

2. Use the Class in Program:

Now we will use the MyClass class in our program.

// import 'MyClass' class from 'names' myPackage


import myPackage.MyClass;

public class Geeks {


public static void main(String args[]) {

// Initializing the String variable


// with a value
String s = "GeeksforGeeks";

// Creating an instance of class MyClass in


// the package.
MyClass o = new MyClass();

o.getNames(s);
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
Note: MyClass.java must be saved inside the myPackage directory since
it is a part of the package.

Static Import In Java


Static Import in Java is about simplifying access to static members and
separates it from the broader discussion of user-defined packages.

Static import is a feature introduced in Java programming language


(versions 5 and above) that allows members (fields and methods)
defined in a class as public static to be used in Java code without
specifying the class in which the field is defined.

Example:

// Note static keyword after import.


import static java.lang.System.*;

class Geeks {
public static void main(String args[]) {

// We don't need to use 'System.out'


// as imported using static.
out.println("GeeksforGeeks");
}
}

Output

GeeksforGeeks

Handling Name Conflicts


When two packages contain a class with the same name (e.g.,
java.util.Date and java.sql.Date), specify the full package name to avoid
conflicts.

import java.util.*;
import java.sql.*;

//And then use Date class, then we will get a compile-time error :
We use cookies
Date to ensure
today you have the java.util.Date
; //ERROR– best browsing experience on our website. By using our site, you
or java.sql.Date?
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
The compiler will not be able to figure out which Date class do we
want. This problem can be solved by using a specific import statement:

import java.util.Date;
import java.sql.*;

If we need both Date classes then, we need to use a full package name
every time we declare a new object of that class. For Example:

java.util.Date deadLine = new java.util.Date();


java.sql.Date today = new java.sql.Date();

Directory Structure and CLASSPATH


Package names correspond to a directory structure. For example, a class
Circle in package com.zzz.project1.subproject2 is stored as:

$BASE_DIR/com/zzz/project1/subproject2/Circle.class

Here $BASE_DIR represents the base directory of the package.


The “dot” in the package name corresponds to a sub-directory of the
file system.
The base directory ($BASE_DIR) could be located anywhere in the
file system.
Hence, the Java compiler and runtime must be informed about the
location of the $BASE_DIR so as to locate the classes.
It is is accomplished by an environment variable called CLASSPATH.
CLASSPATH is similar to another environment variable PATH, which
is used by the command shell to search for the executable programs.

Setting CLASSPATH
CLASSPATH can be set by any of the following ways:

CLASSPATH can be set permanently in the environment the steps In


We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Windows
acknowledgeis that you have read and understood our Cookie Policy & Privacy Policy
Go to Control Panel -> System -> Advanced -> Environment
Variables.

Select “System Variables” to apply the CLASSPATH for all users on


the system.
Select “User Variables” to apply it only for the currently logged-in
user.
Edit or Create CLASSPATH : If CLASSPATH already exists, select it
and click “Edit” or If it doesn’t exist, click “New”
Enter CLASSPATH Details: In the “Variable name” field, enter:
“CLASSPATH”, In the “Variable value” field, enter the directories
and JAR files separated by semicolons.
In the “Variable value” field, enter the directories and JAR files
separated by semicolons. Example:

.c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

The dot (.) represents the current working directory.


To check the current setting of the CLASSPATH, issue the following
command:

> SET CLASSPATH

CLASSPATH can be set temporarily for that particular CMD shell


session by issuing the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-


api.jar

Instead of using the CLASSPATH environment variable, you can also


use the command-line option -classpath or -cp of the javac and java
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
commands, for that
acknowledge example,
you have read and understood our Cookie Policy & Privacy Policy
> java –classpath c:\javaproject\classes
com.abc.project1.subproject2.MyClass3

Illustration of user-defined packages: Creating our first package: File


name – ClassOne.java

package package_name;

public class ClassOne {


public void methodClassOne()
{
System.out.println("Hello there its ClassOne");
}
}

Creating our second package: File name – ClassTwo.java

package package_one;

public class ClassTwo {


public void methodClassTwo()
{
System.out.println("Hello there i am ClassTwo");
}
}

Making use of both the created packages: File name – Testing.java

import package_name.ClassOne;
import package_one.ClassTwo;

public class Testing {


public static void main(String[] args)
{
ClassTwo a = new ClassTwo();
ClassOne b = new ClassOne();
a.methodClassTwo();
b.methodClassOne();
}
}

Now
We having
use cookies a look
to ensure youat the
have thedirectory
best browsingstructure ofour
experience on both theBypackages
website. using our site,and
you
acknowledge
the testing classthat you have read and understood our Cookie Policy & Privacy Policy
file:
Access Modifiers in the Context of Packages

1. Public: Members with the public modifier are accessible from


anywhere, regardless of whether the accessing class is in the same
package or not.
2. Protected: Memebers with the protected modifier are accessible
within the same package, In subclasses
3. Default: Members with no modifier are accessible only within the
same package
4. Private: Members with the private modifier are accessible only
within the same class. They cannot be accessed by classes in the
same package, subclasses, or different packages.

Important points:

Every class is part of some package.


If no package is specified, the classes in the file goes into a special
unnamed package (the same unnamed package for all files).
All classes/interfaces in a file are part of the same package. Multiple
files can specify the same package name.
If package name is specified, the file must be in a subdirectory called
name (i.e., the directory name must match the package name).
We can access public classes in another (named) package using:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
package-name.class-name
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Kickstart your Java journey with our online course on Java
Programming, covering everything from basics to advanced concepts.
Complete real-world coding challenges and gain hands-on
experience. Join the Three 90 Challenge—finish 90% in 90 days for a
90% refund. Start mastering Java today!

Comment More info


Next Article
Placement Training Program Java Interface

Similar Reads
Java | Java Packages | Question 3
Predict the output of following Java program // Note static keyword after
import. import static java.lang.System.*; class StaticImportDemo { public…
1 min read

Java | Packages | Question 1


Which of the following is/are true about packages in Java? 1) Every class
is part of some package. 2) All classes in a file are part of the same…
1 min read

Java | Packages | Question 2


Which of the following is/are advantages of packages? (A) Packages avoid
name clashes (B) Classes, even though they are visible outside their…
1 min read

Java - Divide the Classes into Packages with Examples


Let us first know what is a class and package in Java. Class in java is a
model for creating objects. It means that the properties and actions of th…
6 min read

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
How acknowledge
to Create thatDifferent
you have Packages For Different
read and understood Classes
our Cookie Policy in Java?
& Privacy Policy

You might also like