Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Java Packages?
3.
Why Use Packages
4.
All Packages
5.
java.util Package
6.
java.lang Package
7.
java.io Package
8.
java.awt Package
9.
Java.time Package
10.
Java.sql Package
11.
Java.net Package
12.
Java.math Package
13.
Java.text Package
14.
Javax.xml Package
15.
Frequently Asked Questions
15.1.
What is the use of packages in Java?
15.2.
How many packages are there in Java?
15.3.
What is a Java package with an example?
15.4.
How do Java packages work?
16.
Conclusion
Last Updated: Jun 27, 2024
Medium

Java Packages List

Author Shiva
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Ain’t finding a book from a library containing thousands of books a tiring task? Thousands of books, and you search for the one you are looking for right from the first shelf line by line. Thankfully it’s not so. The university library department is kind enough to group the books Department Wise, followed by Subject Wise categorization, and then books with the same author are placed together. The Department wise categorization is also enlisted as a list outside the library.

Java Packages List

The same way Java classes and Interfaces are grouped under a Package. A Package is a collection of similar Java entities such as classes, interfaces, sub-packages, exceptions, errors, and enums. 

To know more about Packages in Java and Java Packages list, read out the entire blog.

Also, read about -  Iteration Statements in Java, Duck Number in Java

What are Java Packages?

As per Official Documentation, A package is a grouping of related types providing access protection and namespace management. Note that types refer to classes, interfaces, enumerations, and annotation types.

Packages in Java are mainly used for providing access protection and namespace management. 

You can either use built-in packages or create your Package to group related classes and sub-packages together as a programmer. The related classes and interfaces are grouped using Packages. This way, other programmers can have a better understanding of your code.

Also see, Swap Function in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why Use Packages

Using Packages in Java can be helpful in many ways:-

  • Using packages in Java can aid in Data Encapsulation or Data Hiding.
  • Using packages in Java creates a new namespace so the names of your Class and interfaces won’t conflict with the type names in other packages.
  • You can allow types within the Package to have unrestricted access to one another yet still restrict access for types outside the Package.

All Packages

 

PackageDescription
Java.lang PackageThe java.lang package provides basic classes and interfaces for the Java programming language.
Java.util PackageThe Java.util package contains utility classes, data structures, and algorithms for Java applications.
 
java.io PackageThe java.io package provides classes for input/output tasks in Java programs, such as reading and writing to files, streams, and other input/output sources.
 
java.awt PackageThe java.awt (Abstract Window Toolkit) package provides classes for creating and managing graphical user interfaces (GUIs) in Java programs.
Java.time PackageThe java.time package contains classes for handling dates, times, and time zones, as well as classes for parsing and sorting date and time strings in Java programs.
Java.sql PackageThe java.sql package provides classes and interfaces for working with structured query language (SQL) databases in Java programs.
Java.net PackageThe java.net package provides communication capabilities, including TCP and UDP protocols, sockets, URLs, and URI parsing for building client-server applications, web-based applications, and distributed systems in Java.
Java.math PackageThe java.math package provides classes for performing arbitrary-precision integer and decimal arithmetic operations in Java programs.
Java.text PackageThe java.text package provides classes for formatting and parsing text, numbers, and dates in Java programs.
Javax.xml PackageThe javax.xml package provides classes and interfaces for working with XML (Extensible Markup Language) documents and data in Java programs.

java.util Package

The java.util package contains the collection framework, legacy collection classes, event model, date and time facilities, and miscellaneous utility classes like string tokenizer, a random-number generator, and a bit array.

Java directly depends on several classes in this package

  1. The HashTable class for implementing hashtables
  2. Enumeration interface for iterating through a collection of elements
  3. StringTokenizer class for parsing strings into distinct tokens
  4. The Collection Framework contains inbuilt implementations of various data structures and algorithms.
     

Consider the below example of using the ArrayList class of the Collection Framework inside the java.util Package and Calendar class.

import java.util.ArrayList;
import java.util.Calendar;

public class Demo {
	public static void main(String[] args) { 
		Calendar c = Calendar.getInstance();
		// Demonstration  of Calendar's get()method

		System.out.println("Current Calendar's Year: " + c.get(Calendar.YEAR));        
		System.out.println("Current Calendar's Day: " + c.get(Calendar.DATE));           

		// Demonstration of ArrayList class         

		ArrayList<String> list = new ArrayList<String>();         
		list.add("Java Packages List");         
		list.add("Coding Ninjas");         
		System.out.println(list);   
	}
}

 

The output of the above program is:

Current Calendar's Year: 2021Current Calendar's Day: 11[Java Packages List, Coding Ninjas]

 

There are a lot of useful classes, methods, and interfaces in this package. Do check out the official documentation for more details.

There are a lot of useful classes, methods, and interfaces in this package. Do check out the official documentation for more details.

You can also check about Java Tokens here.

java.lang Package

Among the in-built Java Packages, the java.lang package provides classes that are fundamental to the design of the Java programming language. The most important Class in this Package is the Object class, which is the root of the class hierarchy and Class whose instances represent the classes at run time.

Furthermore, wrapper classes Boolean, Character, Integer, Float, and Double are also present in this Package.

This Package is automatically imported to each of the Java programs. Some of the essential Java classes and interfaces present in the Java.lang package are listed below:-

ClassDescription
ObjectClass Object is the root of the class hierarchy, every Class has Object as a superclass.
ThreadA thread is a thread of execution in a program. Thread class controls each thread in a multithreaded program.
ThrowableThe Throwable class is the superclass of all errors and exceptions in Java language,
MathThe class Math contains methods for basic mathematical operations in Java


There are a lot of classes and interfaces in the Java.lang package. Do check out the official documentation for more details.

Consider the below example that uses the methods defined inside Math and Integer classes of java.lang package

public class Demo  {
	public static void main(String[] args) {
		System.out.println(“Exploring Java packages list”); 
		int a = 60, b = 80;                  // Using methods defined inside Math class of Java
		int sum = Math.addExact(a, b);
		int multiply = Math.multiplyExact(a, b);
		System.out.println("Sum is: " + sum + " and multiplication is: " + multiply);               
		// Using methods defined inside Integer Wrapper class of Java

		int c = 100;                        // Use to convert an integer to string

		System.out.println("Using toString(c): " + Integer.toString(c));
		// Use to convert an integer to Binary String

		System.out.println("Using toBinaryString(c): " + Integer.toBinaryString(c));  
	}
}

 

The output of the above program is:-

Exploring Java Packages ListSum is: 140 and multiplication is: 4800Using toString(c): 100Using toBinaryString(c): 1100100

java.io Package

This Package is one of the fundamental packages in the Java packages list. It provides classes and interfaces for handling input and output operations using data streams, serialization, and the file system. In Java, all the fundamental input and output operations are based on streams. A stream is a conceptually endless stream of data from InputStream or a Reader to OutputStream of a Writer.

Some of the essential Java classes and interfaces present in the java.io Package are listed below.

ClassesDescription
FileReaderThis Class is used to read character files, the constructors of this Class assume default encoding and default byte-buffer-size are appropriate
FileWriterThis Class is used for writing streams of characters. This class also provides a method to write strings directly.
BufferedWriterThis Class inherits the Writer class and is used to provide buffering for Writer Instances.
BufferedReaderThis class is used for reading text from a character-based input stream and inherits the Reader class,

 

Source: Documentation

Exception classes of the java.io Package, Source Documentation

Consider the following program that uses FileOutputStream class of the java.io package to write a primitive value and a string to a file at the location specified. If the file is not present in the specified location, a new file will be created.

import java.io.FileOutputStream;
public class Demo {
	public static void main(String[] args) {
		System.out.println("Exploring Java Packages List");
		try {
			FileOutputStream fout = new FileOutputStream("/workspaces/Demo-Web/Java/newfile.txt");
			// writing specified byte to the output stream

			fout.write(65);                                          // Writing String
			String str = “Coding Ninjas”;                   // Converting string to byte array
			byte[] arr = str.getBytes();
			fout.write(arr);                                         // Closing the FileOutputStream object
			fout.close();
			System.out.println("Successfully added ....");
		}
		catch(Exception e) {
			System.out.println("Exception Occured");
			System.out.println(e);
		}
	}
}

 

The output of the above program is:

Exploring Java Packages ListSuccessfully added ….

 

Try and compile it on java compiler. The file newFile.txt will contain the following content ACoding Ninjas

For more information regarding methods do check out the official documentation.

java.awt Package

Java is a rich language in terms of in-built Java Packages. The java awt or Abstract Window Toolkit package contains classes and interfaces used to develop graphical user interfaces. The root of all AWT components is the Component class

Hierarchy of classes in Java.awt package

Some of the essential classes and interfaces in Java.awt Package is enlisted below:

  1. AlphaComposite
  2. Button
  3. Canvas
  4. CardLayout
  5. Container
  6. Dialog

 

You can study more about all the classes, interfaces, and methods in Java.awt Package in the official documentation.

There are 11 more in-built java packages in the Java package list. They all provide really useful classes and built-in methods to make a programmer’s life easier. 

Java.time Package

The java.time package contains LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Duration, and Time classes. It also allows date and time string parsing and formatting and advanced functions like leap seconds, time-based arithmetic, and the ISO calendar system.

Code:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Duration;
public class DateTimeExample {
  public static void main(String[] args) {
     // Creating LocalDate object with the current date
     LocalDate currentDate = LocalDate.now();
     System.out.println("Current date: " + currentDate);
     // Creating LocalDateTime object with the current date and time
     LocalDateTime currentDateTime = LocalDateTime.now();
     System.out.println("Current date and time: " + currentDateTime);
     // Creating a Duration object of 5 hours
     Duration fiveHours = Duration.ofHours(5);
     System.out.println("Duration of 5 hours: " + fiveHours);
  }
}

Output: 

Current date: 2023-03-25
Current date and time: 2023-03-25T05:16:05.509648
Duration of 5 hours: PT5H

Must Read: Java System Out Println and Hashcode Method in Java.

Java.sql Package

Java's java.sql package contains classes and interfaces for connecting to and modifying relational databases. It is used in Java database programming and offers a standard API for working with different types of databases. The following are some of the important classes and interfaces in the java.sql package:

  • Connection: Represents a database relationship.
  • Statement: Executes a SQL query.
  • PreparedStatement: A SQL statement that has been precompiled and can be run numerous times with different parameters.
  • CallableStatement: Runs a database stored function.
  • ResultSet: This class represents the outcome of a query.
  • SQLException: A database exception that happened while working with it.

Java.net Package

The java.net package contains networking methods in Java. It includes classes for dealing with various network protocols such as TCP, UDP, HTTP, and FTP.

The Java.net Package is divided into 2 parts, which are discussed below:

A Low-Level API that handles the following abstractions:

  • Addresses are networking identifiers similar to IP numbers.
  • Sockets are fundamental bidirectional data transmission mechanisms.
  • Interfaces are used to define network interfaces.

A High-Level API that handles the following abstractions:

  • URIs are short for Universal Resource Identifiers.
  • URLs are short for Universal Resource Locators.
  • Connections, which indicate links to the resources referenced by URLs.

Java.math Package

The java.math package is a built-in Java package that contains classes for conducting advanced mathematical operations such as arbitrary-precision arithmetic, numerical computation, and random number generation.

Some important Classes in Java.math: 

  • BigDecimal: Signed decimal numbers with arbitrary accuracy that are immutable.
  • BigInteger: Immutable integers with arbitrary accuracy.
  • MathContext: Immutable objects that contain context settings for numerical operators, such as those implemented by the BigDecimal class.
  • RoundingMode: RoundingMode defines the rounding behavior for numerical processes that can discard precision.

Java.text Package

The java.text package is a built-in Java package that offers classes for formatting and parsing text, as well as numbers, dates, and times. This package is useful in internationalization and localization apps that require text to be formatted or parsed based on locales, languages, or cultural tastes.
Some important classes in Java.text Package are:

  • AttributedString: An AttributedString contains text as well as attribute information.
  • ChoiceFormat: A ChoiceFormat enables you to associate a format with a range of numbers.
  • Collator: The Collator class conducts locale-sensitive String comparison.
  • DateFormat: DateFormat is an abstract class for date/time formatting subclasses that format and parses dates or times in a language-independent way.

Javax.xml Package

The javax.xml package, which is part of the Java API for XML Processing (JAXP), contains classes for dealing with XML data in Java. It contains XML parsing, generation, transformation, and validation classes.

Class of Javax.xml Package is:

  • XMLConstants: Utility class containing constants representing fundamental XML values.


Must Read Conditional Statements in Java

Frequently Asked Questions

What is the use of packages in Java?

Using Packages in Java is advantageous because it aids in Data Encapsulation or Data hiding. Also, by using Package, name clashes can be avoided as a package creates a new namespace. Above all, using Packages helps in structuring your code well.

How many packages are there in Java?

Broadly, there are two types of packages in Java, namely, built-in packages and user-defined packages. There are 14 built-in Java packages. 

What is a Java package with an example?

As per Official Documentation, A package is a grouping of related types providing access protection and namespace management. Note that types refer to classes, interfaces, enumerations, and annotation types.

For example, The java.util package defines a number of useful classes primarily collection classes that are useful for working with a group of objects. It contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).

How do Java packages work?

In Java, package name and directory structure are closely related. So if you create a package called employee, you are creating a new directory called employee. Now all the files under the employee directory are a part of the package employee and all the subdirectories are sub-packages of the employee.

Conclusion

This blog attempted to give an overview of Packages in Java. Predefined packages in Java, along with their classes and interfaces, were also introduced.

With this done, you can now switch to learn more about the Java programming language

Solidify your understanding of Computer Science Fundamental by reading top-notch quality articles on Code studio. Don’t forget to upgrade yourself by solving various problems available on Coding Ninjas Studio and read about the interview experiences of scholars in top product-based companies.

Previous article
Java Applet
Next article
User Defined Packages in Java
Live masterclass