Java Programming 2 5
Java Programming 2 5
Definition of a Constructor
1. In Java, a constructor is a special block of code that is similar to a method but is used
specifically to initialize a newly created object.
2. It is called automatically when an instance of a class is created using the new
keyword.
Key Characteristics:
1. Default Constructor
1. If you do not define any constructor in your class, the Java compiler automatically
inserts a default constructor for you.
2. It initializes member variables with default values (e.g., 0 for integers, null for
objects).
2. No-Argument Constructor
Code Example:
class Student {
String name;
// No-argument constructor
Student() {
name = "Unknown";
[Link]("No-argument constructor called.");
}
}
Code Example:
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
1. In Java, this is a reference variable that refers to the current object (the instance of
the class in which the code is currently executing).
2. It is most commonly used inside constructors and methods.
When a constructor or method has parameters with the same name as the class's instance
variables (fields), the parameter "shadows" the field. The this keyword is used to specify
that you are referring to the instance variable rather than the local parameter.
Code Example:
class Employee {
String name; // Instance variable
void display() {
[Link]("Employee Name: " + [Link]);
}
}
You can use this() to call one constructor from another constructor within the same class.
This is useful for reducing code duplication when you have multiple constructors
(overloading).
Code Example:
class Box {
int length, width;
Sometimes a method needs to pass the entire object it is working on to another method. You
can use this as the argument.
Code Example:
class Calculator {
void printTotal(Calculator obj) {
[Link]("Processing object...");
}
void execute() {
printTotal(this); // Passing the current instance to another method
}
}
Summary of Key Uses
1. Command line arguments are parameters that are passed to a Java program when it
is executed.
2. These arguments allow you to provide input to the program from the console or
terminal without modifying the source code.
In Java, command line arguments are stored as String objects in a String array, which is
passed to the main method of your class.
String[] args: This is an array of strings. Every word or value you type after the
program name in the command line is stored in this array.
If you want to create a program that greets a user by the name they provide at the command
line:
Code Example:
Key Characteristics:
Array indexing: The first argument is stored at args, the second at args, and so on.
Data Type: All arguments are passed as Strings. If you need to use them as numbers
(like integers), you must convert them using methods like [Link](args).
Count: You can find out how many arguments were passed using [Link].
To declare a varargs parameter, you follow the data type with three dots (...).
Syntax Example:
Important Rules:
Only one varargs parameter: A method can have only one variable-length
argument.
Positioning: The varargs parameter must be the last parameter in the method
signature. For example, void method(String s, int... i) is correct, but void
method(int... i, String s) is invalid.
Application and Code Example
A common application of varargs is creating a utility method that can process any number of
inputs, such as calculating a sum or formatting a string.
Code Example:
Reduces Method Overloading: You don't need to write multiple versions of the
same method to handle different numbers of arguments.
Cleaner Syntax: It makes the method call look simpler than passing an explicit array
(e.g., sum(1, 2) vs. sum(new int[]{1, 2})).
1. Visibility control, or Access Modifiers, are keywords used to set the accessibility
(visibility) of classes, constructors, methods, and variables.
2. They define which parts of a program can "see" or interact with a specific member.
3. There are four levels of visibility in Java:
3. protected
Scope: The member is accessible within the same package and by subclasses (even
if they are in different packages).
Use Case: This is used in Inheritance when you want a child class to have access to
a parent's member but still keep it hidden from the general public.
Scope: The member is accessible from any other class in any package.
Use Case: Used for methods and classes that are intended to be the "entry points" or
API of your application.
Example: public void start() { ... }
Introduction to Array
1. An Array in Java is a container object that holds a fixed number of values of a single
type (homogeneous data).
2. It is an indexed-based data structure where the first element is stored at index 0.
1. Declaration: This tells the compiler the variable name and the type of data it will
hold.
o int[] myArray; (Recommended)
o int myArray[];
2. Creating an Array: This allocates memory for the array using the new keyword.
o myArray = new int; (Creates an array of size 5)
3. Initialization: This assigns values to the array elements.
o Manual: myArray = 10;
o Inline (Declaration + Initialization): int[] myArray = {10, 20, 30, 40,
50};
Array Types in Java
Code Example:
public class ArrayExample {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = {10, 20, 30, 40};
Advantages Disadvantages
Code Optimization: Allows us to retrieve or sort Fixed Size: Once created, you cannot change
data efficiently. the size of an array at runtime.
Random Access: We can get any data located at Homogeneous Data: It can only store one type
an index position instantly. of data (e.g., only integers).
Memory Efficiency: Better memory
Memory Wastage: If you declare a large size
management for storing multiple elements of the
but use only a few elements, memory is wasted.
same type.
Application
Arrays are used whenever we need to store multiple items of the same type, such as a list of
student names, marks in different subjects, or coordinates in a game.
Introduction to String
There are two primary ways to create and initialize a String object in Java:
String Types/Categories
While the String class is the most common, Java provides other "types" of character
sequences for different needs:
Code Example
public class StringDemo {
public static void main(String[] args) {
// Declaration and Initialization
String greeting = "Welcome to Java";
// Concatenation
String s1 = "Hello ";
String s2 = "World";
String s3 = [Link](s2); // Combines strings
[Link](s3);
}
}
Advantages and Disadvantages
Advantages Disadvantages
Memory Overhead: Every time you modify a
Security: Because Strings are immutable,
String (e.g., adding a character), a completely
they are safe to use as keys in maps and for
new object is created, which can be slow and
networking/database connections.
memory-intensive.
String Pool: Efficient memory Not suitable for heavy manipulation: For
management by sharing identical string frequent changes (like in a loop), you must use
literals. StringBuilder instead.
Thread-Safety: Immutability
No Subclassing: The String class is final, so
automatically makes Strings thread-safe
you cannot extend it to add custom behavior.
without needing synchronization.
Application
Strings are used in almost every Java application, from storing user input and passwords to
processing data from files or APIs and displaying text in user interfaces.
1. String Literal:
o Syntax: String str = "Java";
o Functionality: This is the most efficient way. Java uses a String Constant
Pool to store literals. If the string "Java" already exists in the pool, the variable
points to that existing object instead of creating a new one.
2. Using new Keyword:
o Syntax: String str = new String("Java");
o Functionality: This always creates a new object in the heap memory, even if
"Java" is already present in the String Pool.
// Immutability Check
String upper = [Link](); // Creates a NEW string
[Link]("Original: " + text); // Still "Learning Java"
[Link]("Modified: " + upper); // "LEARNING JAVA"
}
}
Advantages Disadvantages
Performance Overhead: Since Strings cannot
Security: Immutability makes Strings safe
be changed, every modification (like
for storing sensitive data like passwords or
concatenation) creates a new object, consuming
URLs.
memory.
Not suitable for heavy loops: Using + in a loop
Caching (String Pool): Saves memory by
to build a string is very slow; you must use
reusing identical string literals.
StringBuilder instead.
Thread-Safety: Because they are
immutable, they can be shared across No Subclassing: The class is final, so it cannot
multiple threads without synchronization be inherited.
issues.
Application
Strings are fundamental to almost all Java applications. They are used for user input/output,
storing data from databases, network communication, and creating dynamic content in web
applications.
Introduction to StringBuffer
1. In Java, StringBuffer is a class used to create mutable (modifiable) strings.
2. Unlike the String class, which creates fixed-length objects that cannot be changed, a
StringBuffer can grow or shrink in size and its content can be modified without
creating a new object every time.
3. It is thread-safe, meaning multiple threads cannot access it simultaneously, making it
safe for use in multi-threaded environments.
Unlike Strings, StringBuffer objects cannot be created using literals. They must be
created using the new keyword.
1. Default Creation:
o StringBuffer sb = new StringBuffer();
Functionality: Creates an empty string buffer with an initial capacity of 16
o
characters.
2. With Initial String:
o StringBuffer sb = new StringBuffer("Hello");
Functionality: Creates a buffer containing the specified string.
o
3. With Specific Capacity:
o StringBuffer sb = new StringBuffer(50);
o Functionality: Creates an empty buffer with a defined initial capacity of 50.
Code Example
public class BufferDemo {
public static void main(String[] args) {
// Initialization
StringBuffer sb = new StringBuffer("Hello");
// Modifications (Mutable)
[Link](" Java"); // Original object is modified
[Link](5, " World");
[Link]();
[Link]("Reversed: " + sb); // Output: avaJ dlroW olleH
}
}
Application
UNIT-III
Concept of Inheritance
Goal: To promote code reusability and establish a "IS-A" relationship (e.g., a Car is
a Vehicle).
1. Single Inheritance
class Animal {
void eat() { [Link]("Eating..."); }
}
class Dog extends Animal {
void bark() { [Link]("Barking..."); }
}
// Dog inherits eat() from Animal
2. Multilevel Inheritance
This involves a chain of inheritance where a subclass acts as a parent for another subclass.
Application: Used for multi-level classifications (e.g., Animal -> Mammal -> Dog).
Code Example:
3. Hierarchical Inheritance
Application: Used when multiple entities share a common base but have different
specific behaviors (e.g., a Shape class inherited by Circle, Square, and Triangle).
Code Example:
Java does not support multiple inheritance with classes to avoid the "Diamond Problem"
(ambiguity). However, a class can implement multiple Interfaces.
5. Hybrid Inheritance
A combination of two or more types of inheritance. Since Java doesn't support multiple
inheritance with classes, hybrid inheritance is also only possible through Interfaces.
The provided source material, "Architectural Blueprints: The Java Constructor Explained,"
focuses exclusively on explaining constructors and does not contain any information
regarding Interfaces in Java. The following explanation is based on general Java
programming knowledge and is not derived from your sources; therefore, you may want to
independently verify this information.
Introduction to Interface
1. An Interface in Java is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
2. It is a blueprint of a class that specifies what a class must do, but not how it does it.
3. It is the primary way to achieve 100% abstraction and multiple inheritance in Java.
Abstract Methods: By default, all methods in an interface are public and abstract
(you don't need to write these keywords).
Constants: All variables declared in an interface are implicitly public, static, and
final.
No Instantiation: You cannot create an object of an interface (e.g., new Drawable()
is invalid).
Multiple Implementation: A single class can implement multiple interfaces at the
same time.
Code Example
// Interface definition
interface Animal {
void sound(); // Abstract method
}
Advantages Disadvantages
Total Abstraction: It hides the implementation Complexity: Adding too many interfaces
details and only shows the functionality to the can make the code harder to follow and
user. maintain.
Versioning Issues: If you add a new
Multiple Inheritance: It allows a class to inherit
method to an interface, you must update
behaviors from multiple sources, which is not
every single class that implements it
possible with classes.
(unless you use default methods).
Loose Coupling: It reduces the dependency No State: You cannot store the state of an
between classes, making the system more object (no instance variables) in an
modular and flexible. interface.
Application
1. Interfaces are widely used in Java for defining contracts. For example, the List
interface defines how a list should behave, and classes like ArrayList or LinkedList
provide the specific logic.
2. They are also essential in API development, design patterns, and plugin-based
architectures.
Implementation of an Interface:
Code Example:
interface Printer {
void print(); // Abstract method
}
1. Just as a class can inherit from another class, an interface can inherit from another
interface.
2. This is done using the extends keyword.
3. This allows you to build a hierarchy of interfaces, adding more specific functionality
to a base interface.
interface Animal {
void eat();
}
// Extended Interface
interface Pet extends Animal {
void play();
}
// A class implementing 'Pet' must now implement BOTH 'eat' and 'play'
class Dog implements Pet {
public void eat() {
[Link]("Dog is eating.");
}
public void play() {
[Link]("Dog is playing.");
}
}
Summary of Differences
Application
Code Example
class Calculator {
// METHOD OVERLOADING (Same name, different parameters)
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
class Animal {
// METHOD OVERRIDING (Parent class method)
void sound() { [Link]("Animal makes a sound"); }
}
Application
Introduction to Packages
1. A Package in Java is a mechanism used to group related classes, interfaces, and
sub-packages.
2. It acts like a folder in a computer directory, helping to organize code and prevent
"naming conflicts" (where two classes have the same name).
Types of Packages
There are three main ways to access a class from another package:
Code Example
File 1: [Link] (Inside a package)
Advantages Disadvantages
Categorization: Large projects become File Structure Dependency: The package name
easier to navigate by grouping similar must match the folder structure on the disk,
classes together. which can be rigid.
Access Limitations: If a class is not marked
Naming Conflict Resolution: Two classes
public, it cannot be accessed outside its
can have the same name (e.g., Date) as long
package, which can lead to visibility issues if
as they are in different packages.
not planned.
Access Protection: Packages provide a Overhead: Importing entire packages (.*) can
level of visibility control (default/package- slightly increase compilation time (though not
private access). runtime performance).
Application
1. Packages are essential for modular programming and are used in every professional
Java application.
2. They allow developers to build reusable libraries and frameworks (like Spring or
Hibernate) that can be easily imported into other projects without clashing with the
user's existing code.
The Import Statement in Java
The import statement is a keyword used to bring classes, interfaces, or entire packages into
the current source file. This allows you to use those classes in your code without having to
type their "fully qualified names" (the full package path) every time.
Placement: The import statement must be placed at the top of your Java file, after
the package declaration but before the class definition.
Syntax:
o To import a single class: import [Link];
o To import an entire package: import [Link].*;
1. Specific Class Import: Imports only the specified class. This is generally preferred as
it makes the code's dependencies clear.
o Example: import [Link];
2. Wildcard Import: Uses the asterisk (*) to import all classes within a specific
package. It does not import classes in sub-packages.
o Example: import [Link].*;
3. Static Import: Introduced in Java 5, this allows you to access static members (fields
and methods) of a class directly without qualifying them with the class name.
o Example: import static [Link]; (allows you to call
sqrt(25) instead of [Link](25)).
Code Example
package [Link]; // Package declaration first
Functionality Note
It is important to remember that the [Link] package (which includes classes like String,
System, and Integer) is automatically imported by the Java compiler into every program.
You never need an explicit import statement for classes in that package.
UNIT-IV
1. In Java, an error or exception is an issue that prevents the program from executing as
intended.
2. These are generally categorized into three main types:
Compile-time errors,
Runtime errors,
Logical errors.
These errors occur while you are writing or compiling the code. The Java compiler (javac)
detects these issues and prevents the creation of a .class file until they are fixed.
These errors occur after the code has successfully compiled, while the program is actually
running. They typically cause the program to crash or "terminate abnormally."
Cause: Invalid operations during execution that the compiler couldn't predict.
Examples: Dividing a number by zero (ArithmeticException) or trying to access
an array index that doesn't exist (ArrayIndexOutOfBoundsException).
3. Logical Errors
These are the most difficult to find because the program compiles and runs without
crashing, but it produces the wrong output.
The try block contains the code that might throw an exception, while the catch block
handles that exception if it occurs.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Code Example:
Code Example:
try {
try {
int[] arr = new int;
arr = 50; // Inner exception
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Inner Catch: Array index error.");
}
int x = 10 / 0; // Outer exception
} catch (ArithmeticException e) {
[Link]("Outer Catch: Arithmetic error.");
}
3. Finally Statement
1. The finally block is used to execute important code such as closing a database
connection or a file stream.
2. It always executes, whether an exception is handled or not.
Code Example:
try {
int data = 25 / 5;
} catch (NullPointerException e) {
[Link](e);
} finally {
[Link]("Finally block: This always runs.");
}
4. Throws Keyword
The throws keyword is used in a method signature to declare that the method might throw a
"Checked Exception." It "passes the buck" to the caller of the method to handle the exception.
Code Example:
import [Link].*;
class Test {
// Declaring that this method might throw an IOException
void findFile() throws IOException {
throw new IOException("File not found");
}
1. Graceful Termination: To prevent the program from crashing when a user enters
invalid data or a network connection fails.
2. Resource Management: Using finally to ensure that system resources (like
memory or file handles) are released even if an error occurs.
3. Separation of Error Logic: It allows you to keep your main logic clean and separate
from error-handling code.
4. Debugging: It provides helpful error messages (stack traces) that help developers find
exactly where and why a program failed.
1. Built-in exceptions are those provided by the Java libraries (primarily in the
[Link] and [Link] packages) to handle common error conditions that occur
during program execution.
2. These are automatically available for use in any Java application.
These occur during the execution of the program and are subclasses of the
RuntimeException class. The compiler does not force you to handle these.
ArithmeticException: Occurs during an illegal mathematical operation, such as
dividing by zero. (Mentioned in our previous discussion).
NullPointerException: Occurs when you try to use a reference variable that points
to null.
ArrayIndexOutOfBoundsException: Occurs when you try to access an array with an
index that is negative or greater than the array's size. (Mentioned in our discussion on
arrays).
NumberFormatException: Occurs when a string cannot be converted into a numeric
format (e.g., trying to turn "ABC" into an integer).
2. Checked Exceptions
These are exceptions that the Java compiler forces you to handle using a try-catch block or
declare with the throws keyword. They are usually related to outside factors like files or
databases.
IOException: Occurs during input or output failures, such as reading a file that
doesn't exist. (Mentioned in our previous discussion on throws).
ClassNotFoundException: Occurs when the JVM tries to load a class but cannot
find its definition.
SQLException: Occurs during database access errors.
Advantages Disadvantages
Generic Nature: Sometimes a built-in
Standardization: Since these are built-in, every
exception is too broad and doesn't explain
Java developer understands what a
the specific context of your application's
NullPointerException means.
error.
Robustness: They provide a safety net for Overhead: Catching too many exceptions
common coding mistakes (like array index unnecessarily can make the code slower and
errors). harder to read.
Application
Introduction to Multi-threading
In this method, you create a new class that extends the built-in [Link] class.
This class must override the run() method, which contains the code that the thread will
execute.
Execution: To start the thread, you create an object of your class and call the
start() method.
Code Example:
This is the more flexible way to create a thread. You create a class that implements the
[Link] interface and provide an implementation for the run() method.
Execution: Since the class is not a Thread itself, you must wrap your Runnable
object inside a Thread object before calling start().
Code Example:
Application
2. Runnable State
Once the start() method is called, the thread moves from the New state to the Runnable
state. In this state, the thread is considered "ready to run." It is placed in the runnable pool
and is waiting for the Thread Scheduler to allocate CPU time to it.
Note: Being in the Runnable state does not mean the thread is currently executing; it
means it is eligible to execute.
3. Running State
A thread enters the Running state when the Thread Scheduler picks it from the runnable
pool. This is the state where the code inside the run() method is actually being executed by
the CPU.
Transition: A thread can move back to the Runnable state if it is "yielded" or if its
time slice (quantum) expires, allowing other threads to run.
A thread enters this state when it is alive but currently not eligible to run. It remains in this
state until a specific event occurs that moves it back to the Runnable state.
Causes:
o Waiting for an I/O operation to complete.
o Waiting to acquire a monitor lock (synchronized block).
o Calling sleep(), wait(), or join().
Recovery: Once the sleep time expires or the resource becomes available, the thread
moves back to the Runnable state (not directly to Running).
5. Dead State (Terminated State)
A thread enters the Dead or Terminated state when its run() method has finished execution.
This can happen normally (the task is done) or abnormally (due to an unhandled exception).
Rule: Once a thread is dead, it cannot be restarted. If you call start() on a dead
thread, it will throw an IllegalThreadStateException.
Advantages: Efficient thread state management ensures that the CPU is never idle if
there is work to be done, improving application responsiveness.
Disadvantages: Context switching (the process of moving threads between Running,
Runnable, and Blocked states) consumes CPU cycles and can slow down performance
if there are too many threads.
1. Thread methods are built-in functions in Java used to manage and control the
execution, synchronization, and state transitions of threads.
2. They allow developers to pause, resume, or terminate thread activity based on
program requirements.
1. sleep(long millis)
This method causes the currently executing thread to pause its execution for a specified
number of milliseconds.
wait(): Causes the current thread to wait until another thread calls notify() or
notifyAll() on the same object. Unlike sleep(), wait() releases the lock it holds.
notify(): Wakes up a single thread that is waiting on that object's monitor.
4. stop() (Deprecated)
Status: This method is deprecated and considered highly unsafe. It causes the thread
to unlock all monitors it has locked, which can leave objects in an inconsistent or
"damaged" state.
Code Example
class SharedResource {
synchronized void waitAndPrint() {
try {
[Link]("Thread waiting...");
wait(); // Thread releases lock and waits
[Link]("Thread Resumed!");
} catch (InterruptedException e) { [Link](); }
}
Application
wait and notify: Used in the Producer-Consumer pattern, where one thread
creates data and another thread processes it.
sleep: Used in polling mechanisms (e.g., checking for updates every 10 seconds) or
for creating simple animations.
Safe Termination: Instead of stop(), developers now use a boolean flag (like
volatile boolean running) to signal a thread to exit its run() method gracefully.
UNIT-V
Introduction to Streams
In Java, a Stream is a sequence of data elements. There are two primary contexts for
"Streams" in Java:
1. I/O Streams ([Link]): Used for reading and writing data to various sources like
files, memory, or network connections.
2. Stream API ([Link]): Introduced in Java 8, this is a way to process
collections of objects in a functional and declarative style.
The Stream API is not a data structure (it doesn't store data); instead, it carries values from a
source (like an Array or a Collection) through a pipeline of computational steps.
Advantages Disadvantages
Performance Overhead: For very small
Conciseness: Reduces boilerplate code (no need
datasets, traditional loops are often faster
for complex loops and conditional checks).
than streams.
Debugging: It is harder to set breakpoints
Readability: The code describes what to do
or step through code inside a stream
rather than how to do it (declarative).
pipeline.
Parallelism: You can easily process data in Learning Curve: Requires an
parallel using .parallelStream() to utilize understanding of lambda expressions and
multi-core CPUs. functional programming concepts.
Application
Streams are extensively used in data processing, filtering large datasets, aggregating
values (like finding a sum or average), and converting data from one format to another
(mapping).
1. In Java, Stream Classes are part of the [Link] package and are used to perform
input and output operations.
2. A "stream" is a continuous flow of data from a source (like a file or keyboard) to a
destination (like a console or file).
3. Java categorizes these classes based on the type of data they handle: bytes or
characters.
Byte streams are used to handle input and output of 8-bit bytes. They are primarily used for
reading or writing binary data like images, audio, or video files.
Character streams are used to handle 16-bit Unicode characters. They are specifically
designed for reading and writing text data and automatically handle character encoding.
1. In Java, Stream Classes are part of the [Link] package and are used to perform
input and output operations.
2. A "stream" is a continuous flow of data from a source (like a file or keyboard) to a
destination (like a console or file).
3. Java categorizes these classes based on the type of data they handle: bytes or
characters.
Byte streams are used to handle input and output of 8-bit bytes. They are primarily used for
reading or writing binary data like images, audio, or video files.
Character streams are used to handle 16-bit Unicode characters. They are specifically
designed for reading and writing text data and automatically handle character encoding.
1. In Java, Byte Stream classes are part of the [Link] package and are used to perform
input and output of 8-bit bytes.
2. They are the most basic form of I/O in Java and are used for reading or writing
binary data, such as images, audio files, video files, or any compiled code.
Byte streams are defined by two class hierarchies rooted in abstract classes:
This abstract superclass defines the methods for receiving bytes from a source.
This abstract superclass defines the methods for sending bytes to a destination.
int byteData;
// Read one byte at a time until the end of the file (-1)
while ((byteData = [Link]()) != -1) {
[Link](byteData);
}
[Link]("File copied successfully!");
} catch (IOException e) {
[Link]("An error occurred: " + [Link]());
}
}
}
Application
Multimedia Processing: Essential for reading and writing image, audio, and video
files.
Network Communication: Used for sending raw data packets over sockets.
File Copying: The most reliable way to copy files where the content format is
unknown.
Introduction to the File Class and I/O Exception
1. In Java, the File class (from [Link]) is an abstract representation of file and
directory pathnames.
2. It is used to create, delete, and inspect properties of files (like size or permissions).
3. Because interacting with a physical disk can fail (e.g., the disk is full or the file is
missing), most operations involving the File class require handling the IOException.
1. Creation of Files: To create a physical file on the disk, you first initialize a File
object with a path and then call the createNewFile() method.
2. Reading and Writing Bytes: As discussed in our section on Byte Streams,
FileInputStream and FileOutputStream are used to read and write raw 8-bit data.
3. Handling Primitive Data Types: To read or write Java primitives (like int, double,
or boolean) directly, you use DataOutputStream and DataInputStream. These
"wrap" around a byte stream to provide methods like writeInt() or readDouble().
Code Example
import [Link].*;
try {
// 1. Creation of file
if ([Link]()) {
[Link]("File created: " + [Link]());
}
Application
Persistent Storage: Saving user settings, high scores in games, or application state.
Data Serialization: Writing complex data structures to a file to be sent over a
network.
Logging: Creating and managing log files to track application errors or performance.
……………………………………………………………………………………………………………………