Packaging

Packages
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality.
* A package provides a unique namespace for the types it contains.
* Classes in the same package can access each other's package-access members.
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. 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.
The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.
The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java SE platform. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation.
Some of the existing packages in Java are::
* java.lang - bundles the fundamental classes
* java.io - classes for input , output functions are bundled in this package
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, annotations are related.
Advantage of Package:
* Package is used to categorize the classes and interfaces so that they can be easily maintained.
* Package provids access protection.
* Package removes naming collision.

Access Protection:
Classes and packages are both means of encapsulating and containing the name space and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code. The class is Java’s smallest unit of abstraction. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members:
* Subclasses in the same package
* Non-subclasses in the same package
* Subclasses in different packages
* Classes that are neither in the same package nor subclasses
The three access specifiers,private,public, andprotected, provide a variety of ways to produce the many levels of access required by these categories.

Private  No modifier  Protected  Public
Same class  Yes  Yes  Yes  Yes 
Same package subclass No Yes  Yes  Yes 
Same package non-subclass No Yes  Yes  Yes 
Different  package subclass No No  Yes  Yes 
Different  package non-subclass No No  No Yes 

Creating a package:
When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be put into an unnamed package.
1. Creating a package in java is quite easy. Simply include a package command followed by name of the package as the first statement in java source file.
2. Java uses file system directory to store package. For example the .class for any classes you to define to be part of mypack package must be stored in a directory called mypack.
Example: -
package mypack;
class Book
{
String bookname;
String author;
Book(String b, String c)
{
this.bookname = b;
this.author = c;
}
public void show()
{
System.out.println(bookname+" "+ author);
}
}
class test
{
public static void main(String[] args)
{
Book bk = new Book("Anuj","Bhargava");
bk.show();
}
}
C:\java\package>javac mypack\test.java
C:\java\package>java mypack.test
Anuj Bhargava
import keyword
import keyword is used to import built-in and user-defined packages into your java source file. So that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
1. Using fully qualified name (But this is not a good practice.)
class MyDate extends java.util.Date
{
//statement;
}
2. import the only class you want to use.
Example :-
import java.util.Date;
class MyDate extends Date
{
//statement
. }
3. import all the classes from the particular package
Example : -
import java.util.*;
class MyDate extends Date
{
//statement;
}
import statement is kept after the package statement.
Common imports
There are 166 packages containing 3279 classes and interfaces in Java 5. However, only a few packages are used in most programming. GUI programs typically use at least the first three imports.
import java.awt.*;          Common GUI elements.
import java.awt.event.*;         The most common GUI event listeners.
import javax.swing.*;         More common GUI elements. Note "javax".
import java.util.*;         Data structures (Collections), time, Scanner, etc classes.
import java.io.*;         Input-output classes.
import java.text.*;         Some formatting classes.
import java.util.regex.*;          Regular expression classes.
Example :-
package mypack;
import static java.lang.Math.*;
public class Test
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(144));
}
}
Command line argument in Java
The command line argument is the argument passed to a program at the time when you run it. To access the command-line argument inside a java program is quite easy, they are stored as string in String array passed to the args parameter of main() method.
Example: -
class cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}
C:\java\package\mypack>javac test.java
C:\java\package\mypack>java cmd 10 20 30 40
10
20
30
40
Final in Java
Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java . Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application.
Final is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.
Final variable in Java
Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. Here is an example of final variable in Java
Final method in Java
Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time. Here is an example of final method in Java:
Final method in Java
Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes. Here is an example of final class in java
Final and Immutable Class in Java
Final keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and String is primary example of immutable and final class which I have discussed in detail on Why String is final or immutable in Java. Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java.
Benefits of final keyword in Java
1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.
2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.
3. Final keyword allows JVM to optimized method, variable or class.
Rules using final in Java
1. Final keyword can be applied to member variable, local variable, method or class in Java.
2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.
3. You can not reassign value to final variable in Java.
4. Local final variable must be initializing during declaration.
5. Only final variable is accessible inside anonymous class in Java.
6. Final method can not be overridden in Java.
7. Final class can not be inheritable in Java.
8. Final is different than finally keyword which is used on Exception handling in Java.
9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.
10. All variable declared inside java interface are implicitly final.
11. Final and abstract are two opposite keyword and a final class can not be abstract in java.
12. Final methods are bonded during compile time also called static binding.
13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".
14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.
15. As per Java code convention final variables are treated as constant and written in all Caps e.g.
private final int COUNT=10;
16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection.
For example:
private final List Loans = new ArrayList();
list.add(“home loan”); //valid
list.add("personal loan"); //valid
Example: -
class Point
{
int x, y;
}
class ColoredPoint extends Point
{
int color;
}
// Colored3dPoint class cannot be extended further
final class Colored3dPoint extends ColoredPoint
{
int z;
}
class FinalClassDemo
{
public static void main(String args[])
{
Colored3dPoint cObj = new Colored3dPoint();
cObj.z = 10;
cObj.color = 1;
cObj.x = 5;
cObj.y = 8;
System.out.println("x = " + cObj.x);
System.out.println("y = " + cObj.y);
System.out.println("z = " + cObj.z);
System.out.println("Color = " + cObj.color);
}
}
Output:; -
C:\java\package\mypack>javac test.java
C:\java\package\mypack>java FinalClassDemo
x = 5
y = 8
z = 10
Color = 1


Free Web Hosting