Comprehensive Notes on Java Packages, Interfaces, Stream I/O, and Exception Handling
Packages in Java
Definition of Packages
A package is a namespace that organizes a set of related classes and interfaces.
It can be understood as a collection or group of similar classes and interfaces.
Classifications of Java Packages
Java Inbuilt Packages:
java.lang- Provides essential classes likeObject,String, etc.java.util- Contains utility classes such asArrayList,Scanner.java.awt- Provides classes for creating user interfaces likeButton.
User-defined Packages: Custom packages created by developers to organize their own classes and interfaces.
Advantages of Java Packages
Categorization: Helps in organizing classes and interfaces for easy maintenance.
Access Protection: Controls visibility of classes, interfaces, and their members.
Naming Collision Avoidance: Helps in avoiding naming conflicts among classes.
Creating a Java Package
Use the keyword
packagefollowed by the package name.Example:
package animals;.
Compiling a Java Package
Use the Java command with directory indicator.
Format:
javac -d <directory> <file_name.java>.
Importing Packages
Importing classes and packages:
import package.*;- Imports all classes in the package.import package.ClassName;- Imports a specific class.Fully qualified name - Using the complete path of the class (e.g.,
package.ClassName).
CLASSPATH in Java
The CLASSPATH defines where the JVM looks for classes and packages.
Format:
Windows: Paths separated by
;(e.g.,C:\path1;C:\path2)Unix: Paths separated by
:(e.g.,/path1:/path2)
The default class path includes the current directory and the JAR files containing Java platform classes.
Access Control in Java Packages
Public Members: Accessible from anywhere.
Private Members: Accessible only within the same class.
Protected Members: Accessible by subclasses and within the same package.
Default Members: Accessible only within the same package, not visible outside.
Interfaces in Java
Definition of Interfaces
An interface is a completely abstract class that contains a group of abstract methods without bodies.
Example: An interface named
Languagecould be defined with methods likegetType()andgetVersion().
Implementing Interfaces
To use an interface, another class must implement it using the
implementskeyword.Multiple interfaces can be implemented by separating them with commas.
Variables in Interfaces
Static and Final: Variables in interfaces are, by default,
public,static, andfinal.Must be initialized in the interface itself and cannot be modified by the implementing class.
Extending Interfaces
An interface can extend another interface, inheriting its methods.
A class implementing a child interface must provide code for all methods in both child and parent interfaces.
An interface cannot extend multiple interfaces in Java.
Key Points Regarding Interfaces
Initiate an interface using the
interfacekeyword.Implement the interface in a class using
implementskeyword.Define methods within the implementing class.
Facilitate multiple inheritance through interface implementation.
Understand variable characteristics and constraints within interfaces.
Stream-based I/O in Java
Concept of Streams
Streams are sequences of data that can be read from a source or written to a destination.
Input Stream: Used for reading data from a source.
Output Stream: Used for writing data to a destination.
Types of Streams
Byte Streams: Handle binary data. Classes include
FileInputStreamandFileOutputStream.Character Streams: Handle character data, such as
FileReaderandFileWriter.
Closing Streams
It is important to close streams when they are no longer needed to avoid resource leaks, ideally using a
finallyblock for cleanup.
BufferedReader Class
The
BufferedReaderclass, injava.io, is used for efficient reading of characters, arrays, and lines.Offers methods like
readLine()and can be faster compared toScanner.
Scanner Class
The
Scannerclass injava.utilcan parse primitive types and strings using regular expressions.Includes methods like
nextLine(),nextInt(), etc.
Console Class
Consoleclass provides methods for reading passwords and hiding sensitive data.
Command-Line Arguments
Java programs can accept command-line arguments for dynamic input during execution.
Exception Handling in Java
What is an Exception?
An exception is an event during program execution that disrupts the normal flow of instructions.
Types of Exceptions
Checked Exceptions: Must be declared in the method signature or caught (e.g.,
IOException,SQLException).Unchecked Exceptions (Runtime): Do not need to be declared (e.g.,
NullPointerException,ArithmeticException).Errors: Severe problems that applications usually cannot catch (e.g.,
OutOfMemoryError).
Exception Handling Mechanism
An exception is thrown when an error occurs, creating an exception object containing error details.
The call stack is searched for an appropriate exception handler that can handle the thrown exception.
Using Try and Catch
Use
tryto define a block of code to test andcatchto handle exceptions that might occur.Multiple
catchblocks can be used to handle different exceptions.The order of catch blocks should be from the most specific to the most general.
Throwing Exceptions
Use the
throwkeyword to throw an exception explicitly from within a method.The
throwskeyword in a method signature signifies that the method may throw certain exceptions.The
finallyblock can be used to execute code aftertryandcatch, regardless of whether an exception occurred.
Creating Custom Exceptions
Custom exceptions can be created by extending the
Exceptionclass and defining specific behavior.