Packages In Java

Packages In Java

Introduction

  1. Package is an encapsulation mechanism to group all the related classes and interface in a single module
    1. While using inbuilt classes also, internally sun microsystem has used the packages to keep the classes.

Advantages Of Using Packages

  1. It resolves the name conflicts
  2. It improves modularity(maintenance) of the application
  3. It provides security
  4. It helps the programmer to debug the application in an easy way be referring to the packages

How to name a package

StringBuilder
StringBuffer
String
NullPointerException
ArithmeticException
System
Scanner
javac Sample.java => it would just compile the .class file
javac -d. Sample.java
-d => indicates the destination folder where the package should be created
. => indicates the location where the package should be created
it represent the current location

example:

  1. We use reverse domain name format
package in.ineuron;// this denotes our class file is in 'in' ->'ineuron'
public class Sample
{
public static void main(String[] args)
{
System.out.println("Hey i am working with packages");
}
}

Note: By default eclipse ide will create a package whose name will be the same as the class name which has the public static void main function in it . We will not have any naming conflict error here

Standard Structure Of Java Program

  1. Package statement(only one should be there)
  2. Import statement(can be any number)
  3. Declaration of class/interface/enum (any number, but only one should be marked as public)