Java Packages and API

Introduction to Java Packages

In Java, a package is a way to make a group of similar classes, interfaces, and sub-packages together under one name. You can think of it like a folder on our computer that stores similar files.

Packages make our Java projects more organized, easy to manage, and scalable as they grow larger.

When we start writing multiple classes in a big project, managing them without structure can become confusing. Packages solve this by keeping related code in one logical unit. For example, all database-related classes can go in one package, and all user-interface classes in another.

Packages also help avoid naming conflicts. For example, two developers might create a class named Student, but if they are in different packages, like school.Student and collage.Student, Java can easily differentiate between them.

Syntax of Import Packages:

import packageName.className;     // imports a single class
import packageName.*; // imports all classes in a package

Types of Java Packages

There are two main types of packages in Java Programming:

  • Built-in packages
  • User-defined packages

1) How to Use Built-in Java Packages

Java provides a rich collection of built-in packages inside its Java API (Application Programming Interface).

These packages include ready-made classes and interfaces that simplify common programming tasks such as handling data, performing input/output operations, managing collections, and working with files or dates.

It means, we don’t need to write everything form starting, just import the required package and start using its classes directly.

Example: Using java.util package

import java.util.ArrayList;

public class Main {
public static void main(String[] args) {
// Using ArrayList class from java.util package
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");

System.out.println("Popular Languages: " + languages);
}
}

Output:

Popular Languages: [Java, Python, C++]
  • Here, we imported java.util.ArrayList, that used to store dynamic lists.
  • The import statement allows us to access this predefined class easily.
  • Without importing, we would have to write long paths, such as java.util.ArrayList every time.

2) Creating a User-Defined Package

Sometimes, we want to organize our own classes in a clean and structured way. That’s why we use user-defined packages because they allow you to create your own logical groups of related classes, just like folders on your computer.

Steps to Create and Use a Package:

  1. Create the Package:
    • Use the package keyword at the very top of your Java file.
  2. Compile the Package:
    • Use the javac -d . filename.java command. The -d option creates the folder automatically.
  3. Use the Package:
    • Import the package into another class and access its methods or data.

Code Example: Creating and Using a Custom Package

Step 1 – Create the Package:

File path: vehicles/Car.java

package vehicles;

public class Car {
public void startEngine() {
System.out.println("The car engine has started smoothly!");
}
}

Compile the Package:

javac -d . Car.java
  • This will automatically create a folder named vehicles and place the compiled .class file inside it.

Use the Package in Another File:

File: Main.java

import vehicles.Car; // Importing the custom package

public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.startEngine();
}
}

Output:

The car engine has started smoothly!

Explanation of this code:

  • package vehicles tells Java this class belongs to the vehicles package.
  • javac -d . Car.java creates the proper folder structure for the package.
  • import vehicles.Car allows us to use the Car class form another file.

Java API (Application Programming Interface)

The Java API is like a ready-made toolbox that comes with Java. It contains thousands of predefined classes, methods, and interfaces that help developers write code faster.

Java provides us with built-in solutions for the most common programming tasks, such as managing data, working with files, connecting to databases, and even communicating over the internet.

You can think of the Java API as a huge library that extends the power of the Java language. Just we need to import required package and use its classes directly in our program.

Some important areas of the Java API:

1) Data Structures: The Java API have multiple collections of data-handling classes under the java.util package. These help us to store and manage data without writing complex code.

For example, ArrayList, HashMap, and HashSet.

2) File Handling: It handles file-related tasks, such as reading, writing, or updating files are made simple with Java’s java.io and java.nio packages.

See this examples:

  • File – to represent a file or directory
  • BufferedReader – to read text efficiently
  • FileWriter – to write data to a file

This is useful for saving user data, reading configurations, or creating log files in desktop and web applications.

3) Networking: Java provides networking classes in the java.net package to help developers build applications that can communicate over the internet or local networks.

For example:

  • Socket – for sending and receiving data between computers
  • URL – for accessing web addresses
  • HttpURLConnection – for connecting to web servers

4) Database Connectivity: The JDBC (Java Database Connectivity) API allows us to connect Java programs with databases such as MySQL, Oracle, or PostgreSQL.

    For example:

    • Connection – establishes a link between Java and the database
    • Statement – executes SQL queries
    • ResultSet – stores the results of database queries

    It is perfect for applications that store and manage large amounts of data, like user accounts or product inventories.

    Commonly Used Built-in Java Packages

    Below are some of the most commonly used built-in packages in Java:

    1) java.lang

    This is the core package of Java and is automatically imported in every program. You don’t need to manually import it.

    This package contains essential classes like String, Math, System, Object, etc. So when you print something using System.out.println(), you are already using java.lang package.

    2) java.util:

    The java.util package provides a set of utility classes that make it easier to manage data structures and collections.

    It also includes classes for working with dates, random numbers, and event handling. It contains ArrayList, HashMap, Collections, Date, and Calendar.

    3) java.io:

    The java.io package is used for input and output operations, such as reading and writing files or handling user input. It simplifies file management and data transfer in Java programs.

    These package contains File, BufferedReader, FileWriter, PrintWriter.

    4) java.net:

    This package is useful for network programming that allows Java programs to communicate over the internet or within a local network. It has some classes like URL, Socket, InetAddress, etc.

    5) java.sql:

    The java.sql package is used for database connectivity in Java using JDBC (Java Database Connectivity). It has some important classes such as Connection, Statement, ResultSet, and more.

      Access Modifiers and Packages

      How to Importing Java Packages

      Example 1: Importing a Specific Class

      Here, we are importing only one class, Scanner from java.util package.

      import java.util.Scanner;

      public class GreetingApp {
      public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      System.out.print("Enter your name: ");
      String name = input.nextLine();

      System.out.println("Welcome, " + name + "! Have a great day!");
      }
      }

      Output Example:

      Enter your name: Poll
      Welcome, Poll! Have a great day!

      Explanation of this code:

      • import java.util.Scanner; tells Java that we want to use the Scanner class from the java.util package.

      Example 2: Importing All Classes from a Package

      If you need multiple classes from the same package, you can import all of them using a * (wildcard symbol).

      Code example:

      import java.util.*;

      public class CollectionDemo {
      public static void main(String[] args) {
      ArrayList<String> fruits = new ArrayList<>();
      fruits.add("Apple");
      fruits.add("Mango");
      fruits.add("Banana");

      System.out.println("Fruit List: " + fruits);
      System.out.println("Total Fruits: " + fruits.size());
      }
      }

      Output Example:

      Fruit List: [Apple, Mango, Banana]
      Total Fruits: 3
      • Here, import java.util.*; imports all classes like ArrayList, HashSet, LinkedList, etc.

      Also Learn Important Topics of Java

      Leave a Comment