0% found this document useful (0 votes)
3 views9 pages

Java Package

A Java package is a container for similar classes and interfaces, categorized into built-in and user-defined packages. Packages enhance code organization, provide access protection, and prevent naming collisions. The document explains how to create, import, and use packages, along with access specifiers and Java naming conventions.

Uploaded by

adarshbiswal.ab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Java Package

A Java package is a container for similar classes and interfaces, categorized into built-in and user-defined packages. Packages enhance code organization, provide access protection, and prevent naming collisions. The document explains how to create, import, and use packages, along with access specifiers and Java naming conventions.

Uploaded by

adarshbiswal.ab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

JAVA PACKAGE:

 A java package is a group/container of similar types of classes, interfaces and sub-


packages. Package in java can be categorized in two form, built-in package and user-
defined package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc. The package keyword is used to create a package in java.
 A package represents a directory that contains related group of classes and
interfaces For example, when we write statemens like: import java.io.*;
 Here we are importing classes of java.io package. Here, java is a directory
name and io is another sub-directory within it. The ‘*’ represents all the classes
and interfaces of that io sub directory.
 We can create our own packages called user-defined packages or extend the
available packages
 User-defined packages can also be imported into other classes and used exactly
in the same way as the Built-in packages.
 Packages provide reusability
Advantage of Java Package:
1. Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2. Java package provides access protection.
3. Java package removes naming collision.
General form for creating a package: package packagename;
eg: package pack;
 The first statement in the program must be package statement while creating a
package.
 While creating a package except instance variables, declare all the members and the
class itself as public then only the public members are available outside the package
to other programs
Example:
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile Java Package: javac -d.Simple.java
To Run: java mypack.Simple
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
Output: Welcome to package
How to access package from another package?
 There are three ways to access the package from outside the package.
o import package.*;
o import package.classname;
o fully qualified name.
1) Using packagename.*
 If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
 The import keyword is used to make the classes and interface of another package
accessible to the current package.
 Example of package that import the packagename.*
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello
2) Using packagename.classname
 If you import package.classname then only declared class of this package will be
accessible.
 Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output: Hello
3) Using fully qualified name
 If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
 Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output: Hello
Note: If we import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, we need to import the sub-
package as well.
Sequence of the program must be package then import then class.

Program 1: Write a program to create a package pack with Addition class(Adding a


class to package)
package pack;
public class Addition{
private double d1,d2;
public Addition(double a,double b){
d1 = a;
d2 = b;
}
public void sum(){
System.out.println ("Sum of two given numbers is : " + (d1+d2) );
}
}
Output: package pack with Addition class is ready

Program 2: Write a program to use the Addition class of package pack


//Using the package pack
import pack.Addition; //import class Addition from package pack
class Use{
public static void main(String args[]){
Addition ob1 = new Addition(10,20); ob1sum(); }
}

Program 3: Write a program to add one more class Subtraction to the same package pack
//Adding one more class to package pack:

package pack;
public class Subtraction
{
private double d1,d2;
public Subtraction(double a, double b)
{
d1 = a;
d2 = b;
}
public void difference()
{System.out.println ("Sum of two given numbers is : " + (d1 - d2) );
}
}

Program 4: Write a program to access all the classes in the package pack
//To import all the classes and interfaces in a class using import pack.*;

import pack.*;
class Use
{
public static void main(String args[])
{
Addition ob1 = new Addition(105,206);
ob1.sum();
Subtraction ob2 = new Subtraction(302,4011);
ob2.difference();
}
}
In this case, please be sure that any of the Addition java and Subtraction java
programs will not exist in the current directory Delete them from the current
directory as they cause confusion for the Java compiler The compiler looks for byte
code in Addition java and Subtraction java files and there it gets no byte code and
hence it flags some errors.

 If the package pack is available in different directory, in that case the compiler should
be given information regarding the package location by mentioning the directory
name of the package in the classpath.
 The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import.
 If our package exists in e:\sub then we need to set class path as follows:

 We are setting the classpath to e:\sub directory and current directory () and
%CLASSPATH% means retain the already available classpath as it is
Subpackages:
 Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly.
 Also, members of a subpackage have no access privileges, i.e., they are considered as
different package for protected and default access specifiers.
 Example : import java.util.*;
util is a subpackage created inside java package.
Accessing classes inside a package
 Consider following two statements :
import java.util.vector; // import the Vector class from util package.
import java.util.*; // import all the classes from util package
 First Statement is used to import Vector class from util package which is contained
inside java.
 Second statement imports all the classes from util package.
 Example:
// Java program to demonstrate accessing of members when corresponding
classes are imported and not imported.
import java.util.Vector;
public class ImportDemo{
public ImportDemo()
{
// java.util.Vector is imported, hence we are able to access directly in our code.
Vector newVector = new Vector();
// java.util.ArrayList is not imported, hence we were referring to it using the
complete package.
java.util.ArrayList newList = new java.util.ArrayList();
}
public static void main(String arg[]){
new ImportDemo();
}
}
Built-in Packages: These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
 java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
 java.io: Contains classed for supporting input / output operations.
 java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
 java.applet: Contains classes for creating Applets.
 java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
 java.net: Contain classes for supporting networking operations.
User-defined packages: These are the packages that are defined by the user. First we create
a directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.

// Name of the package must be same as the directory under which this file is saved
package myPackage;

public class MyClass{


public void getNames(String s){
System.out.println(s);
}
}
Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */


import myPackage.MyClass;
public class PrintName {
public static void main(String args[]) {
String name = "GeeksforGeeks"; // Initializing the String variable with a value
MyClass obj = new MyClass();// Creating an instance of class MyClass in the package.
obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage directory since it is a part of the
package.

Using Static Import


 Static import is a feature introduced in Java programming language ( versions 5 and
above ) that allows members ( fields and methods ) defined in a class as
public static to be used in Java code without specifying the class in which the field is
defined.
 Following program demonstrates static import :
import static java.lang.System.*; // Note static keyword after import.
class StaticImportDemo{
public static void main(String args[])
{
// We don't need to use 'System.out' as imported using static.
out.println("GeeksforGeeks");
}
}
Output: GeeksforGeeks

Access Specifier:
 Specifies the scope of the data members, class and methods
 private members of the class are available with in the class only. The scope of
private members of the class is “CLASS SCOPE”
 public members of the class are available anywhere. The scope of public members
of the class is "GLOBAL SCOPE"
 default members of the class are available with in the class, outside the class and in
its sub class of same package
 It is not available outside the package. So the scope of default members of the class
is "PACKAGE SCOPE"
 protected members of the class are available with in the class, outside the class and
in its sub class of same package and also available to subclasses in different package
also

Class Member Access private No Modifier protecte public


d
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- No No No Yes
subclass
Program 6: Write a program to create class A with different access specifiers
//create a package same
package same;
public class A{
private int a = 1;
public int b = 2;
protected int c = 3;
int d = 4;
}

Program 7: Write a program for creating class B in the same package


//class B of same package package same;
import same.A;
public class B{
public static void main(String args[])
{
A obj = new A();
System.out.println(obj a);
System.out.println(obj b);
System.out.println(obj c);
System.out.println(obj d);
}
}

Program 8: Write a program for creating class C of another package package another;
import same.A;
public class C extends A{
public static void main(String args[]){
C obj = new C();
System.out.println(obj a);
System.out.println(obj b);
System.out.println(obj c);
System.out.println(obj d);
}
}
Java Naming Convention
 Java naming convention is a rule to follow as you decide what to name your
identifiers such as class, package, variable, constant, method, etc.
 But, it is not forced to follow. So, it is known as convention not rule. These
conventions are suggested by several Java communities such as Sun Microsystems
and Netscape.
 All the classes, interfaces, packages, methods and fields of Java programming
language are given according to the Java naming convention. If you fail to follow
these conventions, it may generate confusion or erroneous code.
Advantage of Naming Conventions in Java
 By using standard Java naming conventions, you make your code easier to read for
yourself and other programmers.
 Readability of Java program is very important.
 It indicates that less time is spent to figure out what the code does.
Naming Conventions of the Different Identifiers
Identifiers Naming Rules Examples
Type
Class It should start with the uppercase letter. public class Employee{
It should be a noun such as Color, Button, System, //code snippet
Thread, etc. }
Use appropriate words, instead of acronyms.
Interface It should start with the uppercase letter. interface Printable{
It should be an adjective such as Runnable, //code snippet
Remote, ActionListener. }
Use appropriate words, instead of acronyms.
Method It should start with lowercase letter. class Employee{
It should be a verb such as main(), print(), println(). // method
If the name contains multiple words, start it with a void draw(){
lowercase letter followed by an uppercase letter //code snippet
such as actionPerformed(). }
}
Variable It should start with a lowercase letter such as id, class Employee
name. {
It should not start with the special characters like & // variable
(ampersand), $ (dollar), _ (underscore). int id;
If the name contains multiple words, start it with //code snippet
the lowercase letter followed by an uppercase letter }
such as firstName, lastName.
Avoid using one-character variables such as x, y, z.
Package It should be a lowercase letter such as java, lang. //package
If the name contains multiple words, it should be package com.javatpoint;
separated by dots (.) such as java.util, java.lang. class Employee{
//code snippet
}
Constant It should be in uppercase letters such as RED, class Employee{
YELLOW. //constant
If the name contains multiple words, it should be static final
separated by an underscore(_) such as int MIN_AGE = 18;
MAX_PRIORITY. //code snippet
It may contain digits but not as the first letter. }
CamelCase in Java naming conventions
 Java follows camel-case syntax for naming the class, interface, method, and variable.
 If the name is combined with two words, the second word will start with uppercase
letter always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
Handling name conflicts
 The only time we need to pay attention to packages is when we have a name conflict .
For example both, java.util and java.sql packages have a class named Date. So if we
import both packages in program as follows:
import java.util.*;
import java.sql.*;
//And then use Date class, then we will get a compile-time error :
Date today ; //ERROR-- java.util.Date or java.sql.Date?
 The compiler will not be able to figure out which Date class do we want. This
problem can be solved by using a specific import statement:
import java.util.Date;
import java.sql.*;
 If we need both Date classes then, we need to use a full package name every time we
declare a new object of that class. For Example:
java.util.Date deadLine = new java.util.Date();
java.sql.Date today = new java.sql.Date();

You might also like