java packages

Package:
                      package is a namespace it contains a group of similar types of classes, interfaces, sub-classes. To overcome naming space packages are very helpful.
There are two different types of packages in java
 User-defined package
 Built-in package

Advantages with packages:
To overcome naming convention packages are very helpful.
Easy to identify classes and interfaces.
Accessing is very easy and provides protection.
Examples:
java.lang   (presents fundamental classes)
java.io   (input, output functions available)

Creating a package:
                To create package choose a name of the package and use  package keyword along with the package name.
Syntax:
                package nameofpackage;
Compile:
                javac –d . <packagename> <filename>
                d------> destination folder
                . -----> current folder
Example:  javac  –d . food   sample.java
Run:
java packagename. Filename
Example:   java food.sample

importing a package:
                By using import keyword we can import the existing packages into our class.There are two ways to import package into a class. Importing entire package and another thing importing only required classes from a package.
Example:
Create package with name of food

package food; ( assume it has few classes and interfaces)
import food.eat;   (importing only eat class from food package)
import food.*; (importing entire package into a class)

 Interview questions:

Define package in java?
Why we are using packages in java?
What is the use of packages?
How to compile and execute a package in java?
How many ways we can import the packages into java class?


EmoticonEmoticon