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

Java Packages

Packages in Java are used to organize related classes and avoid naming conflicts. There are built-in packages that are part of the Java API library and can be imported, as well as user-defined packages that developers create. To use classes from a package, they must be imported either individually or by using a wildcard to import all classes from that package. Packages help organize code into a directory structure and control access levels between packages.

Uploaded by

Sri Harsha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views

Java Packages

Packages in Java are used to organize related classes and avoid naming conflicts. There are built-in packages that are part of the Java API library and can be imported, as well as user-defined packages that developers create. To use classes from a package, they must be imported either individually or by using a wildcard to import all classes from that package. Packages help organize code into a directory structure and control access levels between packages.

Uploaded by

Sri Harsha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Java Packages & API

A package in Java is used to group related classes.


Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a
better maintainable code. Packages are divided
into two categories:
 Built-in Packages (packages from the Java
API)
 User-defined Packages (create your own
packages)

Built-in Packages
The Java API is a library of prewritten classes, that
are free to use, included in the Java Development
Environment.
The library contains components for managing
input, database programming, and much much
more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/
.
The library is divided into packages and classes.
Meaning you can either import a single class
(along with its methods and attributes), or a whole
package that contain all the classes that belong to
the specified package.

To use a class or a package from the library, you


need to use the import keyword:
Syntax
import package.name.Class; // Import a single
class
import package.name.*; // Import the whole
package
Import a Class
If you find a class you want to use, for example,
the Scanner class, which is used to get user
input, write the following code:
Example
import java.util.Scanner;
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.

To use the Scanner class, create an object of the


class and use any of the available methods found
in the Scanner class documentation. In our
example, we will use the nextLine() method,
which is used to read a complete line:

Example
Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter username");

String userName = myObj.nextLine();


System.out.println("Username is: " +
userName);
}
}
Advantages of using a package in Java
These are the reasons why you should use packages in Java:

 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
 Providing controlled access: protected and default have package level
access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).

Adding a class to a Package : We can add more classes to a created package
by using package name at the top of the program and saving it in the package
directory. We need a new java file to define a public class, otherwise we can
add the new class to an existing .java file and recompile it.

Subpackages: Packages that are inside another package are the subpackages.


These are not imported by default, they have to imported explicitly. Also,
members of a subpackage have no access privileges, i.e., they are considered
as different package for protected and default access specifiers.

Package naming conventions : Packages are named in reverse order of


domain names, i.e., org.geeksforgeeks.practice. For example, in a college,
the recommended convention is college.tech.cse, college.tech.ee,
college.art.history, etc.

Import a Package
There are many packages to choose from. In the
previous example, we used the Scanner class from
the java.util package. This package also contains
date and time facilities, random-number generator
and other utility classes.
To import a whole package, end the sentence with
an asterisk sign (*). The following example will
import ALL the classes in the java.util package:

Example
import java.util.*;

User-defined Packages
To create your own package, you need to
understand that Java uses a file system directory to
store them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:


MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}

Execution steps
1.Save the file as MyPackageClass.java, and
compile it:
C:\>javac MyPackageClass.java
2.Compile the package
C:\>javac -d . MyPackageClass.java
This forces the compiler to create the
"mypack" package.
The -d keyword specifies the destination for
where to save the class file. You can use any
directory name, like c:/user (windows), or, if
you want to keep the package within the same
directory, you can use the dot sign ".", like in
the example above. The package name should
be written in lower case to avoid conflict with
class names.
3.When we compiled the package in the
example above, a new folder will be created,
called "mypack". To run the
MyPackageClass.java file, write the following:
C:\>java mypack.MyPackageClass

Output: This is my package!

Example for uses of java package


Program1:
package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}

Program 2:
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}

Example

Create two user defined packages and import them


in a new class

Step1 : Create a Package named package_1


File Name: ClassOne.java
// First package

package package_1;

public class ClassOne {


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

Step 2: Create a Package named package_2


File Name: ClassTwo.java
// Second package

package package_2;

public class ClassTwo {


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

Step3 : Create a class to import and use the classes


the two packages package_1 and package_2
File Name : Testing.java
// import first and second package

import package_1.ClassOne;
import package_2.ClassTwo;

public class Testing {


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

Step4 : Compile the packages


javac -d . ClassOne.java
javac -d . ClassTwo.java
Once you compile the packages, two folders will
be created with the package names package_1 and
package_2.
Inside the package_1 folder , ClassOne.class file
will be created
Inside the package_2 folder , ClassTwo.class file
will be created

Step5 : Compile and execute the Testing class that


import the packages

javac Testing.java
java Testing.java

Output: Hello there its ClassTwo


Hello there its ClassOne

Accessing Packages in Java

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.

The import keyword is used to make the classes and interface of another package
accessible to the current package.

import java.util.*;
import pacakage_1.*;

2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.

import package_1.ClassOne; 
import java.util.Scanner;

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

//save as A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save as B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully
qualified name
obj.msg();
}
}
How to Hide Class in a Package?

Hiding classes:
When we import a package using astric(*),all public classes are imported.however ,we may
prefer to “not import”certain classes.i.e,we may like to hide these classes from accessing
from outside of the package.such classes should be declared”not public”.

EX:

package p1;

public class X

Body of X

class Y
{

Body of Y

Here, the class y which is not declared public is hidden from out side of the package p1. this
class can be seen and used only by other classes in the same package note that a java
source file should contain only one public class and may include any number of non public
classes.

Now ,consider the following code ,which imports the package p1 that contains classes X and
Y:

import p1.*;

X objx = new X();

Y objy =new Y();

Java compiler would generate an error message for this code because the class Y,which
has not been declared public,is not imported and therefore not available for creating its
objects.

Static Import
The static import feature of Java 5 facilitate the java programmer to access any static
member of a class directly. There is no need to qualify it by the class name.

What is the difference between import and static import?


The import allows the java programmer to access classes of a package without
package qualification whereas the static import feature allows to access the static
members of a class without the class qualification. The import provides accessibility
to classes and interface whereas static import provides accessibility to static
members of the class.

Advantage of static import:


o Less coding is required if you have access any static member of a class oftenly.

Disadvantage of static import:


o If you overuse the static import feature, it makes the program unreadable and
unmaintainable.

Example:
import static java.lang.System.*;
class StaticImportExample{
public static void main(String args[]){

out.println("Hello");//Now no need of
System.out
out.println("Java");

Output:Hello
Java
}
}

With the help of static import, we can access the static members of a class
directly without class name or any object. For Example: we always use sqrt()
method of Math class by using Math class i.e. Math.sqrt(), but by using
static import we can access sqrt() method directly. 

Example 2
// Java Program to illustrate
// calling of predefined methods
// with static import
import static java.lang.Math.*;
class Test2 {
    public static void main(String[] args)
    {
        System.out.println(sqrt(4));
        System.out.println(pow(2, 2));
        System.out.println(abs(6.3));
    }
}

Output: 
2.0
4.0
6.3

You might also like