Professional Documents
Culture Documents
Packages
Packages
Packages
Advantage of packages:
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.
for example, when we need user input, we import a package like this:
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.
Naming conventions:
According to standard java naming rules, packages begin with
lowercase letters. This makes it easy for users to distinguish
package names from class names.
package mypack;
import maths.*;
class Test
{
public static void main(String args[])
{
Calc obj = new Calc();
int sum = obj.add(10,20);
System.out.println("sum= "+sum);
}
}
Output: sum=30
difference = 10
Sub-package in java
Package inside the package is called the sub-package. It should be
created to categorize the package further.
package mypack.mp1.mp2.mp3;
import maths.*;
class Test
{
public static void main(String args[]){
Calc obj = new Calc();
To run:
java mypack.mp1.mp2.mp3.Test
Output:
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set
classpath of the directory where the class file resides.
2. Permanent:
By setting the CLASSPATH in the environment variables
By creating the jar file, that contains all the class files, and
copying the jar file in the jre/lib/ext folder.
What is CLASSPATH?
The CLASSPATH is an environment variable that tells the java compiler
where to look for class files to import. CLASSPATH is generally set
to a directory or a JAR (Java Archive) file.
To see the currently set calsspath in the command prompt user the
following command: c:\> echo %CLASSPATH%
The JAR Files
A JAR (java archive) file is that contains compressed version of
.class files, audio files, image files or directories.
Step-3:
Step-4:
Step-5: