Core Java

Java Packages – How to use them

 1. Introduction

We look at java packages in this article. If you want to learn java, java packages topic will be a great start. We look at code samples to present how to use the java packages.

2. Java Packages

Java packages help in avoiding naming collisions, access control, and separation of modules.They help in making usage of interfaces, annotations, and classes simpler. It helps in grouping a set of classes and related types. It is easier to locate and search by package namespace. In java, we use java.lang and java.io for writing basic code. They help in bundling modules and breaking down a complex system to a group of packages. There are built-in packages such as java.lang , javax.swing, java.sql, java.net, java.awt, and java.util in java sdk.

Java Packages
Java Packages

2.1 Prerequisites

Java 8 is required on the Linux, Windows or Mac operating system. Eclipse Oxygen can be used for this example.

2.2 Download

You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site.

2.3 Setup

2.3.1 Java Setup

Below are the setup commands required for the Java Environment.

Setup

JAVA_HOME=”/jboss/jdk1.8.0_73″
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

2.4 IDE

2.4.1 Eclipse Oxygen Setup

The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.

2.4.2 Launching IDE

Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screenshot below:

Java Packages - Launching IDE
Launching IDE

You can select the workspace from the screen which pops up. The attached image shows how it can be selected.

Java Packages - IntelliJ vs Eclipse
Eclipse Workspace

You can see the eclipse workbench on the screen. The attached screenshot shows the Eclipse project screen.

Java Packages - Eclipse Workbench
Eclipse Workbench

Java Hello World class prints the greetings. The screenshot below is added to show the class and execution on the eclipse.

Java Packages - Java Hello
Java Hello

2.5 What is a java package?

A java package is a group of classes, interfaces, enumerations, and annotations. Package keyword is used to declare the namespace of class, interface enumeration and annotation. Below is the code which defines a package by name “org.java.examples” and a class SimpleExample.

Package Keyword

/**
 * 
 */
package org.java.examples;

/**
 * @author bhagvan.kommadi
 *
 */
public class SimpleExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		System.out.println("Printing Java Package Examples");
	}

}

The output of the code when you run it in eclipse is shown in the screenshot below:

Java Packages - Simple Package
Simple Package Example

Default package is taken when the package name is not specified. Package statement needs to be mentioned before import statements in a class, interface, enumeration, and annotation. The sample code is shown below for a DefaultExample class with no package definition.

Default Package

/**
 * @author bhagvan.kommadi
 *
 */
public class DefaultExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Printing Default Java Package Example");
	}

}

The output of the above code, when executed in eclipse, is shown in the screenshot below.

Java Packages - Default Package
Default Package

2.6 How to import a java package

Importing a java package is done using the keyword import. In the example below, SimpleExample class is imported using the keyword import. It is imported as org.java.examples.SimpleExample.

Importing a java package

package org.java.services;

import org.java.examples.SimpleExample;

/**
 * @author bhagvan.kommadi
 *
 */
public class UsePackageExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
      SimpleExample example = new SimpleExample();
      
      example.print();

	}

}

The output of the above code, when executed in eclipse is shown in the screenshot below.

Import a Java Package

2.6.1 Static Import

Let us look at how static import is used. A static import helps in accesses the class static members without mentioning the class name statically. Sample code below shows how to use static import of “java.lang.System.out” class.

Static Import

package org.java.examples;

import  static java.lang.System.out;

/**
 * @author bhagvan.kommadi
 *
 */
public class StaticExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		out.println("Inside Static Import Example");

	}

}

In the screenshot below, the output of code when executed in eclipse is shown.

Static Import

2.6.2 Command-Line Options

You can use commands in the terminal to get the package structure. Packages are closely related to the directories. “tree” command can be used to show the package structure. The output of the command tree is presented in the screenshot below.

Tree Command

You can use javac -d option to compile a Java class and place the compiled class in the package folder.

Command Line Option

mkdir Test
javac -d test Test.java

The output of the commands after execution is shown in the screenshot below.

command line option

2.7 How to create your own package in Eclipse

In eclipse, you can create a package from the menu after creating a java project. The menu that you need to select will be -> New Package. The screenshot below shows the menu navigation.

Create Package

Next screen, you need to input the name of the package. The screenshot below shows the screen.

Name the Package

You can name the package as org.java.examples. The screenshot below shows the input screen.

Input the package Name

The project gets updated with a package created. The screenshot below shows the final result.

Created Package in the Project

2.8 Package name conventions

Java packages are named in lower case to avoid conflict with names of interfaces, classes, enumerations, and annotations. Commercial software packages are named using “com” prefix. Opensource software packages are named using the “org” prefix. Java sdk and api use “java” prefix. Java package should not start with a digit or non-alphabetic character as per java name convention.

2.9 Package Access

Default access for the classes in a package is package level access. The default access modifier for a class is used to mention that this class cannot be used outside the package. Sample code is shown below :

Package Access

/**
 * @author bhagvan.kommadi
 *
 */
public class DefaultExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Printing Default Java Package Example");
	}

}

2.10 Package Class

The package class has methods to find about the specification and implementation of a java package. It has methods such as getName(), getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.

Package Metadata

package org.java.examples;

/**
 * @author bhagvan.kommadi
 *
 */
public class PackageMetaDataExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Package pack=Package.getPackage("java.lang");  
		  
		System.out.println("Package  - "+pack.getName());  
		  
		System.out.println(" Package Specification Title - "+pack.getSpecificationTitle());  
		System.out.println("Package Specification Vendor - "+pack.getSpecificationVendor());  
		System.out.println("Package Specification Version - "+pack.getSpecificationVersion());  
		  
		System.out.println("Package Implementaion Title - "+pack.getImplementationTitle());  
		System.out.println("Package Implementation Vendor - "+pack.getImplementationVendor());  
		System.out.println(" Package Implementation Version - "+pack.getImplementationVersion());  
		System.out.println("Package Check If sealed - "+pack.isSealed());  

	}

}

You can use Package class to get the metadata of the packages which are loaded from the classpath. The output of the code, when executed in eclipse, is shown in the screenshot below.

Package Metadata

3. Download the Source Code

Download
You can download the full source code of this example here: Java Packages – How to use them

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button