Contents
Packages
Packages in Java
A package in Java is a mechanism that groups together classes, subpackages, and interfaces. Packages serve the following purposes:
- Avoiding name conflicts. For instance, you can have two classes with the same name in different packages, like
university.department.cs.Student
anduniversity.department.ee.Student
. - Simplifying the search and usage of classes, interfaces, enumerations, and annotations.
- Controlling access. Package-level access control applies to members with protected and default access. Protected members are accessible within the same package and its subclasses, while default members (without an access specifier) are accessible within the same package only.
- Supporting data encapsulation (or data hiding). Related classes can be grouped into packages to make their use more efficient.
Once classes are organized into packages, you can import and reuse them easily in other parts of the code. You can import specific classes from packages or entire packages, depending on your needs.
How Packages Work
Packages help organize your code and prevent naming conflicts in large projects. Package names and directory structures are closely tied. For example, a package named university.department.cs
means there are three directories: university
, department
, and cs
, where cs
is nested within department
, and department
is inside university
. The directory structure is used to locate the classes when the program runs, and the base directory is accessed via the CLASSPATH variable.
Naming Conventions
Package names typically follow reverse domain name conventions. For example, in an organization, you could have packages like com.company.project.module
, and in a university, you might see package names like university.department.math
or university.department.physics
.
Adding Classes to a Package
You can add more classes to an existing package by declaring the package at the top of a new Java file and saving the file in the corresponding package directory. If you’re adding a public class, it must be in its own file. Otherwise, you can add the class to an existing file and recompile it.
Subpackages
A subpackage is a package that exists within another package. Subpackages need to be imported explicitly as they are not included with the parent package import by default. Members of a subpackage are considered as being part of a different package for access purposes.
Example:
import java.util.ArrayList;
import java.util.Scanner;
In this example, ArrayList
and Scanner
are classes in the util
subpackage of the java
package.
Accessing Classes in a Package
Consider the following two statements:
1. Importing a specific class from the package:
import java.util.ArrayList;
import java.util.*;
In the first statement, only the ArrayList
class is imported, while the second statement imports all the classes in the util
package. However, subpackages of util
are not included.
Example Code:
import java.util.List;
public class DemoImport {
public static void main(String[] args) {
// Direct access since List class is imported
List names = new ArrayList<>();
// Full name for classes that aren’t imported
java.util.LinkedList items = new java.util.LinkedList<>();
}
}
Types of Packages
1. Built-in Packages: These packages are part of the Java API. Some commonly used ones are:
java.lang
: Provides classes that support fundamental programming needs (e.g., primitive types and string manipulation).java.io
: Supports input and output operations.java.util
: Contains classes that implement data structures like lists and maps, and also supports date and time operations.java.awt
: Contains classes for creating graphical user interfaces.java.net
: Supports networking operations.
2. User-defined Packages: These are custom packages created by developers. First, you create a directory that matches the package name, then add Java files inside that directory.
Example:
// File: mypack/MyClass.java
package mypack;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in mypack.");
}
}
To use this class in another program:
// File: TestPackage.java
import mypack.MyClass;
public class TestPackage {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Output:
Hello from MyClass in mypack.
Static Import
Static import allows you to directly access static members of a class without specifying the class name. Here’s an example:
import static java.lang.Math.*;
public class StaticImportExample {
public static void main(String[] args) {
// No need to use Math.PI or Math.sqrt()
System.out.println(PI);
System.out.println(sqrt(16));
}
}
Output:
3.141592653589793
4.0
Handling Name Conflicts
If two imported packages contain classes with the same name, the Java compiler can’t distinguish between them. For example:
import java.util.Date;
import java.sql.*;
public class ConflictExample {
public static void main(String[] args) {
// Use fully qualified names to avoid conflicts
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
System.out.println("Util Date: " + utilDate);
System.out.println("SQL Date: " + sqlDate);
}
}
Output:
Util Date: Thu Oct 03 11:34:09 IST 2024
SQL Date: 2024-10-03
Directory Structure
The package name corresponds to the directory structure where classes are stored. For example, a class named Circle
in the package com.example.shapes
would be stored as:
$BASE_DIR/com/example/shapes/Circle.class
How to Create a Package in Java?
Package in Java
In Java, a package is a mechanism used to group related classes, interfaces, sub-packages, and other elements. Packages are primarily used to avoid name conflicts and help organize code. By organizing classes into packages, we can ensure that related classes are easily reusable and accessible, while others are hidden for internal use.
Types of Packages in Java
Java has two main types of packages:
1. Built-in Packages: These are packages that come with the Java Development Kit (JDK) such as java.util
, java.io
, java.lang
, etc.
2. User-defined Packages: These are packages that developers create to organize their own classes, interfaces, and sub-packages.
Importing Packages
To use classes from a package, we need to import the package. The syntax for importing a package is as follows:
import package.name.*;
Example 1: Importing Built-in Package
// Importing the java.util package
import java.util.*;
public class Example {
public static void main(String[] args) {
// Creating a Scanner object to take user input
Scanner input = new Scanner(System.in);
String name;
System.out.println("Please enter your name:");
name = input.nextLine(); // Read user input
// Display the name entered by the user
System.out.println("Your name is: " + name);
}
}
Input:
Please enter your name:
John Doe
Output:
Your name is: John Doe
Creating a User-defined Package
To create your own package, follow these steps:
1. Choose a name for your package.
2. Use the package keyword at the top of your Java file.
3.Organize your classes within the package directory.
Syntax for Declaring a Package:
package myPackage;
Example 2: Creating a Class in a Package
// Define the package name
package myPackage;
public class HelloWorld {
public static void main(String[] args) {
// Print a message
System.out.println("Hello from myPackage!");
}
}
Steps to Compile and Run:
1. Compile:javac -d . HelloWorld.java
This will create a folder named myPackage
and place the compiled class file inside it.
2. Run:java myPackage.HelloWorld
Output:
Hello from myPackage!
Example 3: Creating Another Package and Class
// Define the package name
package utilities;
public class Utility {
public void greet() {
System.out.println("Greetings from Utility class!");
}
}
To compile:
javac -d . Utility.java
This command will create a utilities
folder that holds the Utility.class
file.
Accessing a User-defined Package from Another Class
Example:
// Import the user-defined package
import utilities.*;
public class AccessUtility {
public static void main(String[] args) {
// Create an object of the Utility class
Utility util = new Utility();
// Call the method from the Utility class
util.greet();
}
}
Steps to Compile and Run:
1. Compile:javac AccessUtility.java
2. Run:java AccessUtility
Output:
Greetings from Utility class!
Static Import in Java
Static import allows us to directly access static members of a class without specifying the class name.
// Import static members from the System class
import static java.lang.System.out;
public class StaticImportDemo {
public static void main(String[] args) {
// No need to use System.out, we can directly call out.println
out.println("Static import in Java");
}
}
Output:
Static import in Java
Java.util Package in Java
In Java, identifiers are used to name various entities like classes, methods, variables, or labels. These names help in uniquely identifying different elements within a Java program.
Example of Java Identifiers
public class Test {
public static void main(String[] args) {
int a = 20;
}
}
Java.lang package in Java
The java.util
package provides a wide array of utility classes and is one of the most essential packages in the Java API. It contains classes and interfaces for collection frameworks, legacy collections, event models, date and time management, internationalization, and various other utility functions like random number generation, string tokenization, and bit manipulation.
Key Classes in java.util
Package:
1. AbstractCollection: Provides a basic implementation of the Collection interface to simplify the task of implementing this interface.
2. AbstractList: Offers a basic implementation of the List interface, useful when backing the list by a random-access data structure like an array.
3. AbstractMap<K, V>: Provides a skeletal implementation of the Map interface to ease the process of implementing this interface.
4. AbstractMap.SimpleEntry<K, V>: Represents an entry in a map, maintaining a key-value pair.
5. AbstractMap.SimpleImmutableEntry<K, V>: Represents an immutable key-value pair entry in a map.
6. AbstractQueue: Offers basic implementations of some operations in the Queue interface.
7. AbstractSequentialList: Provides a skeletal implementation of the List interface, suitable for data structures with sequential access, such as linked lists.
8. AbstractSet: Simplifies the task of implementing the Set interface by providing a skeletal implementation.
9. ArrayDeque: Implements a resizable array used to create a Deque.
10. ArrayList: Implements the List interface using a resizable array.
11. Arrays: Provides static utility methods for performing operations such as sorting and searching on arrays.
12. BitSet: Implements a vector of bits that can expand as needed.
13. Calendar: Provides an abstract class for converting between time and calendar fields like year, month, and day.
14. Collections: Consists of static methods for working with collections, such as sorting and shuffling.
15. Currency: Represents a specific currency.
16. Date: Represents a specific instant in time with millisecond precision.
17. Dictionary<K, V>: Serves as the abstract parent class for any key-value mapping, such as Hashtable.
18. EnumMap<K, V>: A specialized Map implementation for keys that are enum types.
19. EnumSet: A specialized Set implementation for use with enum types.
20. EventListenerProxy: A wrapper class for EventListener that associates extra parameters with a listener.
21. EventObject: The base class from which all event state objects are derived.
22. FormattableFlags: Modifies the output format for objects implementing Formattable.
23. Formatter: Interprets printf-style format strings.
24. GregorianCalendar: A concrete subclass of Calendar that implements the standard Gregorian calendar used worldwide.
25. HashMap<K, V>: Implements the Map interface using a hash table.
26. HashSet: Implements the Set interface, backed by a hash table.
27. Hashtable<K, V>: Implements a hash table that maps keys to values.
28. IdentityHashMap<K, V>: Implements the Map interface using reference-equality for comparing keys and values.
29. LinkedHashMap<K, V>: Implements a hash table and linked list for predictable iteration order in a map.
30. LinkedHashSet: Implements a hash table and linked list for predictable iteration order in a set.
31. LinkedList: Implements a doubly-linked list for the List and Deque interfaces.
32. ListResourceBundle: Manages resources for a locale using a list.
33. Locale: Represents a specific geographical, political, or cultural region.
34. Locale.Builder: A builder for creating Locale objects from various values.
35. Objects: Provides static utility methods for operations on objects, such as null-checks.
36. Observable: Represents an observable object, used in the model-view pattern.
37. PriorityQueue: An unbounded priority queue based on a priority heap.
38. Properties: Represents a persistent set of properties.
39. PropertyPermission: Used for controlling access to properties.
40. PropertyResourceBundle: A subclass of ResourceBundle that manages resources using a set of static strings.
42. Random: Generates pseudorandom numbers.
43. ResourceBundle: Contains locale-specific objects.
44. ResourceBundle.Control: Provides callbacks for controlling the loading of resource bundles.
45. Scanner: Parses primitive types and strings using regular expressions.
46. ServiceLoader: A facility for loading service providers.
47. SimpleTimeZone: A subclass of TimeZone for handling Gregorian calendars.
48. Stack: Implements a last-in-first-out (LIFO) stack of objects.
49. StringTokenizer: Breaks a string into tokens.
50. Timer: Schedules tasks for future execution in a background thread.
51. TimerTask: Represents a task scheduled by a Timer.
52. TimeZone: Represents a time zone offset and manages daylight saving time.
53. TreeMap<K, V>: Implements a NavigableMap using a red-black tree.
54. TreeSet: Implements a NavigableSet based on a TreeMap.
55. UUID: Represents a universally unique identifier (UUID).
56. Vector: Implements a growable array of objects.
57. WeakHashMap<K, V>: Implements the Map interface using weak references for keys.
Example 1: Using ArrayList
from the java.util
Package
import java.util.ArrayList;
public class Example1 {
public static void main(String[] args) {
// Create an ArrayList of String
ArrayList fruits = new ArrayList<>();
// Add elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Display the ArrayList
System.out.println("Fruits: " + fruits);
}
}
Output:
Fruits: [Apple, Banana, Cherry]
Java.lang package in Java
The java.lang
package provides fundamental classes that are essential to the core functionality of the Java programming language. It includes classes that define basic types and operations, such as strings, numbers, and threads. The most important classes include Object
, which serves as the root of the class hierarchy, and Class
, which represents classes and interfaces at runtime.
Key Classes in the java.lang
Package:
1. Boolean: Wraps a value of the primitive boolean type in an object.
2. Byte: Wraps a value of the primitive byte type in an object.
3. Character: Wraps a value of the primitive char type in an object.
4. Character.Subset: Represents specific subsets of the Unicode character set.
5. Character.UnicodeBlock: Represents character blocks from the Unicode specification.
6. Class: Represents classes and interfaces at runtime in a Java application.
7. ClassLoader: Responsible for dynamically loading classes at runtime.
8. ClassValue: Allows for lazy association of computed values with types.
9. Compiler: Supports native Java-to-code compilers and related services.
10. Double: Wraps a value of the primitive double type in an object.
11. Enum: Serves as the base class for all enumerated types in Java.
12. Float: Wraps a value of the primitive float type in an object.
13. InheritableThreadLocal: Extends ThreadLocal to allow inheritance of values from parent to child threads.
14. Integer: Wraps a value of the primitive int type in an object.
15. Long: Wraps a value of the primitive long type in an object.
16. Math: Contains methods for basic mathematical operations such as exponentiation, logarithms, and trigonometric functions.
17. Number: The abstract superclass of classes that represent numeric values, including BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and Short.
18. Object: The root class of the Java class hierarchy; all classes extend from Object.
19. Package: Provides version information about Java packages.
20. Process: Represents a native process, created via ProcessBuilder.start() or Runtime.exec().
21. ProcessBuilder: Used to create operating system processes.
22. ProcessBuilder.Redirect: Represents sources or destinations for subprocess input/output.
23. Runtime: Manages interactions between a Java application and the environment it runs in.
24. RuntimePermission: Defines permissions related to runtime operations.
25. SecurityManager: Implements a security policy for applications.
26. Short: Wraps a value of the primitive short type in an object.
27. StackTraceElement: Represents an element of the stack trace, typically returned by Throwable.getStackTrace().
28. StrictMath: Provides basic mathematical operations with strict floating-point precision.
29. String: Represents immutable sequences of characters.
30. StringBuffer: A thread-safe, mutable sequence of characters.
31. StringBuilder: A mutable sequence of characters, designed for faster, unsynchronized use compared to StringBuffer.
32. System: Provides methods and fields to access system-related resources like input, output, and error streams.
33. Thread: Represents a thread of execution within a program.
34. ThreadGroup: Represents a collection of threads.
35. ThreadLocal: Provides thread-local variables.
36. Throwable: The superclass for all error and exception types in Java.
37. Void: Serves as a placeholder to represent the Java keyword void.
Example 1: Using Integer
from java.lang
public class Example1 {
public static void main(String[] args) {
// Create an Integer object
Integer myNumber = Integer.valueOf(25);
// Display the integer value
System.out.println("The integer value is: " + myNumber);
// Convert the Integer to a primitive int
int primitiveNumber = myNumber.intValue();
System.out.println("Primitive value: " + primitiveNumber);
}
}
Output:
The integer value is: 25
Primitive value: 25
Example 2: Using String
from java.lang
public class Example2 {
public static void main(String[] args) {
// Create a String object
String greeting = "Hello, World!";
// Display the string
System.out.println("Greeting: " + greeting);
// Check the length of the string
int length = greeting.length();
System.out.println("Length of the string: " + length);
}
}
Output:
Greeting: Hello, World!
Length of the string: 13
Example 3: Using Thread
from java.lang
public class Example3 extends Thread {
public void run() {
// Print message inside thread
System.out.println("Thread is running...");
}
public static void main(String[] args) {
// Create and start a new thread
Example3 myThread = new Example3();
myThread.start();
}
}
Output:
Thread is running...
Exception in Java
The java.io
package is designed to provide system input and output through data streams, file system access, and serialization. Most classes in this package deal with reading from and writing to files, input streams, and output streams. If a null
argument is passed to a constructor or method in any class or interface in this package, it will result in a NullPointerException
unless specified otherwise.
Key Classes in the java.io
Package:
1. BufferedInputStream: Buffers input to improve performance when reading from input streams.
2. BufferedOutputStream: Buffers output to improve performance when writing to output streams.
3. BufferedReader: Buffers characters for efficient reading of text from character input streams.
4. BufferedWriter: Buffers characters for efficient writing of text to character output streams.
5. ByteArrayInputStream: Allows reading data from a byte array as an input stream.
6. ByteArrayOutputStream: Writes data to a byte array as an output stream.
7. CharArrayReader: Reads characters from a character array as a stream.
8. CharArrayWriter: Writes characters to a character array as a stream.
9. Console: Provides access to the console for reading input and writing output.
10. DataInputStream: Reads primitive data types from an input stream in a machine-independent way.
11. DataOutputStream: Writes primitive data types to an output stream in a machine-independent way.
12. File: Represents file and directory pathnames in an abstract, platform-independent way.
13. FileDescriptor: Provides a handle to an underlying file system resource, such as a file or socket.
14. FileInputStream: Obtains input bytes from a file.
15. FileOutputStream: Writes output bytes to a file.
16. FilePermission: Represents access rights to files and directories.
17. FileReader and FileWriter: Facilitate reading and writing character files.
18. FilterInputStream: Provides a base class for filtering input streams
19. FilterOutputStream: Provides a base class for filtering output streams.
20. FilterReader: Provides a base class for filtering character input streams.
21. FilterWriter: Provides a base class for filtering character output streams.
22. InputStream: Represents an abstract class for reading byte streams.
23. InputStreamReader: Bridges byte streams to character streams by converting byte data to characters.
24. LineNumberInputStream: Reads input streams and tracks line numbers.
25. LineNumberReader: Reads characters while tracking line numbers for text input streams.
26. ObjectInputStream: Deserializes objects from an input stream.
27. ObjectInputStream.GetField: Retrieves persistent fields from the stream.
28. ObjectOutputStream: Serializes objects to an output stream.
29, ObjectOutputStream.PutField: Provides a way to write persistent fields to an output stream.
30. ObjectStreamClass: Describes classes that are serialized in Object Streams.
31. ObjectStreamField: Represents the fields of a class.
32. OutputStream: Abstract class for writing byte streams.
33. OutputStreamWriter: Bridges character streams to byte streams by converting characters to byte data.
34. PipedInputStream: Provides a communication channel for threads through byte streams.
35. PipedOutputStream: Provides a communication channel for threads by sending output bytes to a piped input stream.
36. PipedReader: Provides a communication channel for threads through character streams.
37.PipedWriter: Provides a communication channel for threads by sending characters to a piped reader.
38. PrintStream: Adds functionality to output streams, including the ability to print various data representations.
39. PrintWriter: Adds functionality to writers, including printing formatted representations of data.
40.PushbackInputStream: Allows a byte of data to be “unread” and pushed back into the stream.
41.PushbackReader: Allows a character to be “unread” and pushed back into the stream.
42.RandomAccessFile: Enables random access to read from and write to a file.
43. Reader: Abstract class for reading character streams.
44. SequenceInputStream: Concatenates multiple input streams into one.
45. SerializablePermission: Controls access to serialization features.
46. StreamTokenizer: Parses input streams into tokens, which can be words, numbers, or other symbols.
47. StringBufferInputStream: Reads characters from a StringBuffer as a byte stream.
48. StringReader: Reads characters from a string as a character stream.
49. StringWriter: Writes characters to a string buffer as a stream.
50. Writer: Abstract class for writing character streams
Example 1: Using FileInputStream
and FileOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyExample {
public static void main(String[] args) {
try (FileInputStream inputStream = new FileInputStream("source.txt");
FileOutputStream outputStream = new FileOutputStream("destination.txt")) {
int byteData;
while ((byteData = inputStream.read()) != -1) {
outputStream.write(byteData);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
File copied successfully.
Example 2: Using BufferedReader
and BufferedWriter
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedReaderWriterExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
System.out.println("File processed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
File processed successfully.