0% found this document useful (0 votes)
32 views11 pages

Avoiding Naming Collisions in Java Packages

Packages in Java allow for better organization and reuse of code. A package is a namespace that groups related classes and interfaces to avoid naming collisions. There are built-in Java packages as well as user-defined packages. User-defined packages follow a convention of using reversed domain names to ensure uniqueness. Packages can be used to organize large projects and allow code to be reused through importing relevant packages. Setting the CLASSPATH environment variable allows packages and JAR files to be referenced from any directory.

Uploaded by

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

Avoiding Naming Collisions in Java Packages

Packages in Java allow for better organization and reuse of code. A package is a namespace that groups related classes and interfaces to avoid naming collisions. There are built-in Java packages as well as user-defined packages. User-defined packages follow a convention of using reversed domain names to ensure uniqueness. Packages can be used to organize large projects and allow code to be reused through importing relevant packages. Setting the CLASSPATH environment variable allows packages and JAR files to be referenced from any directory.

Uploaded by

babu cme
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Packages

 A Package can be defined as a grouping of related types (classes,


interfaces, enumerations and annotations) providing access
protection and namespace management.

 We can use classes from other programs without physically copying


them into the programs under development.

 Package is another way of achieving the re-usability in java.

 We have two types of packages in Java: built-in packages and the


packages we can create (also known as user defined package).

 Because software written in the Java programming language can be


composed of hundreds or thousands of individual classes, it makes
sense to keep things organized by placing related classes and
interfaces into packages.

Advantage of packages:
 Reusability: While developing a project in java, we often feel
that there are few things that we are writing again and again in
our code. Using packages, you can create such things in form of
classes inside a package and whenever you need to perform that
same task, just import that package and use the class.

 Better Organization: Again, in large java projects where we have


several hundreds of classes, it is always required to group the
similar types of classes in a meaningful package name so that you
can organize your project better and when you need something you
can quickly locate it and use it, which improves the efficiency.
 Name Conflicts: We can define two classes with the same name in
different packages so to avoid name collision, we can use
packages.

Types of packages in Java


 User defined package: The package we create is called user-defined
package.
 Built-in package: The already defined package
Example:
[Link].*;
[Link].*;
[Link] ;
[Link].*;
etc are known as built-in packages

for example, when we need user input, we import a package like this:
import [Link];
Here:
→ java is a top-level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

Naming conventions:
 According to standard java naming rules, packages begin with
lowercase letters. This makes it easy for users to distinguish
package names from class names.

 Every package name must be unique to make the best use of


packages. Duplicate names will cause run-time errors. Duplicate
package names are un-avoidable since multiple users work on
Internet.

 Therefore, java designers suggested a package naming convention


that ensures uniqueness. Since internet domain names are unique,
it is preferred using domain names in reverse order and prefix to
the preferred pack names.

 for example, if my domain name is [Link], and I want to


create a package with the name math, I can create my package as
follows:
[Link]
Creating a package:
 we use package keyword to create a package. For example
package pack1;
public class Test
{
public static void main(String[] args)
{
[Link]("Welcome to packages in java");
}
}
To compile:
javac –d . [Link]

 The -d switch specifies the destination where to put the generated


.class file.
 You can use any directory name like d:/abc. If you want to keep
the package within the same directory, you can use . (dot)
To run the program:
Java [Link]

import keyword is used to import packages in java. Following are the


various examples to import a package in java.
import [Link].*;
Above imports all classes and interfaces available in util package.
But does not import the calsses and interfaces available in a sub-
package inside the util package.
import [Link];
Above statement, imports only the Scanner class from util package.
Program-1
package maths;
public class Calc
{
public int add(int x, int y)
{
return (x+y);
}
public int diff(int x, int y)
{
return (x-y);
}
public double prod(int x, int y)
{
return (x*y);
}
}
Program-2

package mypack;
import maths.*;

class Test
{
public static void main(String args[])
{
Calc obj = new Calc();
int sum = [Link](10,20);
[Link]("sum= "+sum);
}
}

Example for package usage:


To compile the program:
javac –d . *.java

To run the program:


java [Link]

Output: sum=30
difference = 10

Sub-package in java
Package inside the package is called the sub-package. It should be
created to categorize the package further.

package mypack.mp1.mp2.mp3;
import maths.*;
class Test
{
public static void main(String args[]){
Calc obj = new Calc();

int sum = [Link](10,20);


[Link]("sum= "+sum);
int diff = [Link](20,10);
[Link]("difference = "+diff);
double prod = [Link](10,20);
[Link]("Product = "+prod);
}
}
To compile:
javac –d . [Link]

To run:
java [Link]

Output:

How to send the class file to another directory or drive?


There is a scenario, I want to put the class file of [Link] source
file in classes folder of c: drive. For example:

To Compile:
e:\sources> javac -d c:\classes [Link]
To Run:
To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.

e:\sources> set CLASSPATH=c:\classes;.;


e:\sources> java [Link]

Setting CLASSPATH to avoid fully qualified names


Can be done in two ways:
1. Temporary:
 By setting the CLASSPATH in the command prompt
 By –classpath/-cp switch

2. Permanent:
 By setting the CLASSPATH in the environment variables
 By creating the jar file, that contains all the class files, and
copying the jar file in the jre/lib/ext folder.

What is CLASSPATH?
The CLASSPATH is an environment variable that tells the java compiler
where to look for class files to import. CLASSPATH is generally set
to a directory or a JAR (Java Archive) file.

To see the currently set calsspath in the command prompt user the
following command: c:\> echo %CLASSPATH%
The JAR Files
 A JAR (java archive) file is that contains compressed version of
.class files, audio files, image files or directories.

 We can imagine a .jar file as zipped file (.zip) that is created


by using WinZip software. JAR file is useful to bundle up several
files related to a project and use them easily.

 To create .jar file in java we use jar command in the following


ways:
1. jar cf [Link] maths – in this command, cf represents
create file. And maths package will be converted into
[Link].

2. jar tf [Link] – in this command, tf represents table view


of file [Link].
The first two entries represent that there is a manifest file
created and added to [Link] file. The third entry represents
the sub directory with the name maths and the last two represent
the file names in the directory maths.

When we create a .jar file, it automatically receives the


default manifest file. There can be only one manifest file in an
archive, and it always has the pathname.

Set the CLASSPATH permanently to the [Link]. let us assume that


[Link] is in the subdirectory pack. Follow the steps:

Step-1: Right click on This Pcselect Properties from pop-up.


Step-2:

Step-3:
Step-4:

Step-5:

Step-6: click ok 3 time in all previously opened windows, your


CLASSPATH is set.
* * *

Common questions

Powered by AI

Setting the CLASSPATH in Java is crucial because it tells the Java compiler where to look for class files to import, allowing the program to locate the necessary resources. To set it permanently, you can add it to the environment variables or create a JAR file with all class files and place it in the `jre/lib/ext` folder. This ensures that the required classes are always accessible without needing to specify their location each time .

To create a user-defined package in Java, use the `package` keyword at the beginning of your Java file. For example, `package mypack;`. To compile the Java program and specify a directory for the class file, use the command `javac -d . Test.java`, where `-d` specifies the destination and `.` denotes the current directory. You can replace `.` with any directory path like `d:/abc` to change the destination .

A developer might set the CLASSPATH temporarily when working on a particular project or when testing applications that don’t require a consistent environment setup. Temporary setting can be done via command prompt or using `-classpath`/`-cp` switch. In contrast, setting CLASSPATH permanently is beneficial when the changes need to persist, such as for long-term projects or environments where multiple applications use the same dependencies, thereby avoiding redundancy and the need to set it each time .

Creating a JAR file in Java involves using the `jar` command with specific options. `jar cf maths.jar maths` creates a JAR file named `maths.jar` from the `maths` package. JAR files bundle several files related to a project, allowing for easy distribution and deployment. They can contain compressed versions of .class files, audio files, image files, or directories, which saves space and simplifies file management .

Java package naming conventions ensure uniqueness by using reverse domain names as part of the package name. This method is important because it helps avoid naming collisions in a global context, especially on the Internet where multiple users may choose the same package name. By prefixing package names with reversed domain names, developers can ensure their package names remain unique .

Sub-packages in Java help to further categorize and organize packages within a project. They allow for a hierarchical arrangement of classes, which aids in maintaining a clean and manageable codebase. For example, `package mypack.mp1.mp2.mp3;` denotes a deep package hierarchy. Implementing sub-packages involves importing necessary resources and creating a structure that reflects the project's logical divisions, as shown in the example where sub-packages are used to organize related mathematical operations .

To compile a Java file and send the class file output to a specific directory outside the current one, use the command `javac -d <target-directory> FileName.java`, where `<target-directory>` is the path to the desired directory. For example, using `javac -d c:\classes Simple.java` compiles the Java file `Simple.java` and places the resulting class file in the `c:\classes` directory .

Packages in Java are used to organize related classes and interfaces, providing access protection and namespace management. The primary benefits of using packages include reusability of code, better organization of large Java projects, and avoidance of naming conflicts by allowing classes to have the same name in different packages .

The import keyword is used in Java to bring external classes or entire packages into a program for use without needing to fully qualify their names every time. A specific import, like `import java.util.Scanner;`, imports only the `Scanner` class. In contrast, a wildcard import, like `import java.util.*;`, imports all classes and interfaces from the `util` package, but not sub-packages. Wildcard imports can lead to unnecessary loading of classes, which might impact performance .

Importing packages in Java enhances project efficiency by allowing developers to reuse existing classes and interfaces, reducing the need to write code from scratch. This leads to faster development and reduced potential for errors. However, limitations exist such as only importing classes and interfaces from the specified package, not any sub-packages, unless specifically imported . Moreover, indiscriminately importing all classes from a package using `import java.util.*;` can lead to unused imports, which might affect performance and readability .

You might also like