Font Awesome Icons

Tutorial

Java Packages

Packages are used in Java, in order to avoid name conflicts and to control access of class, interfaces etc. Packages in Java are a way to encapsulate interfaces, Java classes and also subclasses. They are used for the following tasks –

  • Java Packages are used to prevent the naming conflicts which can occur between the classes.

  • Packages in Java make the searching and locating of classes or annotations much easier.

  • Java Packages provide access control to the classes.

  • Packages are used for data encapsulation.

Types of  packages in Java:

 

1)Built-in Packages in Java

 

Built-in Java packages are a part of Java API and it offers a variety of packages, list of java packages are –

  • lang – Automatically imported and it contains language support classes.

  • io – Contains classes for input and output operations.

  • util – contains utility classes for implementing data structures.

  • applet – This package contains classes that create appl

  • awt – Contain classes that implement compounds for GUI.

  • Swing-contains classes for making light-weighted user interfaces for desktop applications.

  • net – This package contains classes that support networking operations.

  • Sql-This package contains classes that support database operations.

 

User-defined Packages in Java

 

Java User creates these Java packages.

 

 

The first example of a java package:

 

package A;  

public class First

{  

public static void main(String args[])

{  

                        System.out.println(“First package”);  

            }

}

 

How to compile:            javac -d . First.java 

How to run:                     java  A.First

 

Accessing package from another  package

Using packagename.*

 

package pack1;  

public class A

{  

  public void msg()

{

System.out.println(“Hello package”);

}  

}

 

 

package pack2;  

import pack1.*;  

class B

{  

            public static void main(String args[])

{  

                        A obj = new A();  

                        obj.msg();  

            }  

}

 

 

Using packagename.classname

 

package P1;  

public class A

{  

public void msg()

{

System.out.println(“Hello Package”);

}  

}  

 

package P2;  

import P1.A;  

class B

{  

            public static void main(String args[])

{  

                        A obj = new A();  

                        obj.msg();  

            }  

}

Note: The second technique is used only when we know the exact name of a particular class otherwise the first technique is fine.