SCHOOL OF ENGINEERING
ELECTRICAL AND TELECOMMUNICATIONS DEPARTMENT
NAME:BRENDA IRENE MUHANJI
REG NO:TLE/4401/23
COURSE TITLE:OBJECT ORIENTED PROGRAMMING
COURSE CODE:COE 361
CAT 2
Question
-Write short notes on
•File management in Java • Garbage collection in Java • String manipulation in Java •
Wrapper dasses •Applets • Packages in Java
1. File Management
Java file management is concerned with the structured and managed handling of files and
directories. It handles interaction between a program and the host file system to perform
operations like creating, deleting, reading, writing, and modifying files.
Key Components
-Abstract Representation: The File class provides an abstract representation of file system
objects that enables easy querying of properties like whether it is a file or directory, size, and
permissions.
-Streams: Java utilizes streams (InputStream, OutputStream) to handle file I/O. They are
analogs to channels for reading input into a program or output out to a file.
-Buffered Operations: The buffered classes increase performance by lowering physical
read/writes. The data is first written into a buffer and then processed.
Character vs Byte Streams:
-Character-based classes (FileReader, FileWriter) handle text files.
-Byte-based classes (FileInputStream, FileOutputStream) work with binary files, such as
images or sound files.
Theoretical Concepts
-Paths for files are absolute (full path) or relative (relatively to the working directory).
-Exceptions like file not found or permission denied are managed by exception handling
(IOException, etc.).
-Facilities with great power in the java.nio.file package allow efficient directory traversal,
symbolic link resolution, and large file operations.
Core Classes and Their Usage
a.File Class: Represents files or directories in an abstract way. You can create, delete, and
query file attributes like size, existence, and more.Example
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
b.FileReader and FileWriter: Used to read and write character-based data.Example
import java.io.FileWriter;
import java.io.FileReader;
public class FileReadWriteExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, Java file management!");
writer.close();
FileReader reader = new FileReader("example.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
c.NIO (java.nio.file): Allows advanced file operations like reading all lines at once or
copying files.Example
import java.nio.file.*;
public class NIOExample {
public static void main(String[] args) {
try {
Path path = Paths.get("example.txt");
Files.write(path, "NIO File Handling".getBytes());
System.out.println(new String(Files.readAllBytes(path)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. Garbage Collection
-GC or garbage collection is a memory management technique that attempts to
automatically eliminate objects that are no longer being used in the heap, thus preventing
memory leaks and better resource utilization.
Why Garbage Collection Matters?
-Manual memory management risks: In C++-type languages, manual memory management
(say, with malloc and free) becomes a source of hazards, such as memory leaks or dangling
pointers. Java eliminates these risks.
-Efficiency: GC improves memory efficiency by recycling free memory, so programs can
utilize resources without developer effort.
Theories and Principles
Heap Memory Division:
-Young Generation: Newly created objects are kept here. Frequent garbage collections
(minor GCs) are done to remove temporary objects.
-Old Generation: Objects surviving multiple garbage collection cycles are moved here. Major
GCs are fewer.
-MetaSpace: Stores class metadata (introduced in Java 8, replacing PermGen).
GC Algorithms:
-Serial Collector: Performs garbage collection in a single thread; optimal for use in
single-threaded applications.
-Parallel Collector: Instead of using a single thread, uses several threads; hence, ideal for
multi-core hardware.
-G1 (Garbage First) Collector: Divides the heap into regions and tries to collect the garbage
from regions containing the most garbage, thus aiding in performance enhancement.
Finalization:
Prior to garbage-collecting an object by GC, JVM may call its finalize() method (although it is
deprecated and unreliable).
Code example
public class GarbageCollectionExample {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
System.out.println("Total Memory: " + runtime.totalMemory());
System.out.println("Free Memory before GC: " + runtime.freeMemory());
for (int i = 0; i < 10000; i++) {
String temp = new String("Garbage");
}
System.out.println("Free Memory after GC: " + runtime.freeMemory());
System.gc(); // Suggest garbage collection
System.out.println("Free Memory after calling GC: " + runtime.freeMemory());
}
}
3.String manipulation in java
-Strings are sequences of characters, and Java treats them as objects of the String class.
Effective string manipulation is the solution to working with textual information.
Important Theories
a.Immutability:
-After a String is created, its data cannot be changed. It is useful for thread safety and
ensures strings will not be accidentally modified.
Example: "abc".toUpperCase() creates a new string "ABC" without changing the original
string "abc".
b.Heap and String Pool:
-Strings created with double quotes ("example") are held in the String Pool, which is
memory-efficient by reusing identical string instances.
-Strings created with new String("example") are held in heap memory and not pooled,
unless explicitly interned with the intern() method.
c.StringBuilder vs StringBuffer:
-StringBuilder: Provides mutable strings and is faster but not thread-safe.
-StringBuffer: Like StringBuilder but thread-safe, offering synchronized methods for
multi-threaded environments.
d.Pattern Matching with Regex:
-Regular expressions offer advanced text searching, validation, and substitution.
Some sample use: email validation, pulling numeric data out, or pattern searching in logs.
Code example
public class StringManipulation {
public static void main(String[] args) {
String original = "Hello, Java!";
String reversed = new StringBuilder(original).reverse().toString();
System.out.println("Reversed String: " + reversed);
}
}
4.Wrapper classes
Java wrapper classes overcome the compatibility issue between reference types (objects)
and primitive types (say, int, char). Primitive values cannot be applied directly in object-only
contexts (say, Java collections like lists or sets). To overcome this, Java provides eight
wrapper classes in the package java.lang which encapsulate primitive values as objects.
They allow storing and utilizing primitives in object-oriented frameworks and APIs. Their
names follow Java class conventions, like starting with upper case letters e.g Boolean. It is
impossible to integrate primitives with the object-oriented features of the language without
wrapper classes.
Primitive type Wrapper class
Byte Byte
Short Short
Int Integer
Long Long
Float Float
double Double
Char Character
boolean Boolean
a. Numeric Wrapper Classes
-It wraps primitive numeric types (byte,short, int long, float, double) into objects.
-It parses strings to numeric values (e.g., `Integer.parseInt("100")`).
-It Converts between numeric types (e.g., `doubleValue()`, `intValue()`).
- Constants like `MIN_VALUE` and `MAX_VALUE`.
Example
String numStr = "123";
int num = Integer.parseInt(numStr);
Integer wrapperNum = num;
System.out.println(wrapperNum.doubleValue());
System.out.println(Integer.MAX_VALUE);
b.Character Wrapper Class
-It wraps the `char` primitive type into an object.
- Check character properties (e.g., `isLetter()`, `isDigit()`).
- Case conversion (e.g., `toUpperCase()`).
Example
Character wrapperCh = 'a';
boolean isLetter = Character.isLetter(wrapperCh);
char upper = Character.toUpperCase(wrapperCh);
Code example
public class WrapperExample {
public static void main(String[] args) {
int number = 42;
Integer wrapped = Integer.valueOf(number); // Boxing
int unwrapped = wrapped.intValue(); // Unboxing
System.out.println("Wrapped: " + wrapped + ", Unwrapped: " + unwrapped);
}
}
5. Applets
-Applets are Java programs that are designed to be transmitted via the Internet and
executed automatically by a Java-enabled browser. Applets are downloaded as needed
(e.g., when a link is clicked) and executed on the client, carrying out such functions as
displaying server data, handling user input, or doing simple computations (e.g., a loan
calculator), delegating some server responsibility to the client.
-Applets revolutionized web development with dynamic, auto-running code inserted into the
cyberrealm, as opposed to passive information like emails or static downloads. But they
posed security concerns (protection against auto-downloaded code causing damage) and
portability concerns (running on varied OS environments).
An applet is a small Java program written to be executed within a web page and launched by
a Java-capable browser. It is executed within a "sandbox" environment to preserve security.
Applets vs. Standalone Programs
-Browser Dependency: Applets are executed within a browser (with a Java plugin), whereas
standalone Java applications are executed on the JVM.
-Security Restrictions: Due to security, applets are given limited access to system resources
like files and the network.
-Interactive Features: Applets can dynamically interact with users, including features like
forms, graphics, and animation.
Applet Life Cycle
-An applet's life cycle is managed by special methods:
a.init(): Called once to initialize an applet. Can be employed to initialize resources like GUI
widgets.
b.start(): Called when the applet starts or resumes.
c.paint(Graphics g): Used to paint the shapes, text, or images.
d.stop(): Called if the applet is suspended or the user navigates away from the page.
e.destroy(): Called to free resources before the applet is destroyed.
Code example
import java.applet.*;
import java.awt.*;
public class SimpleApplet extends Applet {
public void init() {
System.out.println("Applet Initialized");
}
public void paint(Graphics g) {
g.drawString("Welcome to Applets!", 20, 20);
}
}
6.Packages in java
-Package Declaration
• It is Optional
• It is placed after documentation
• To declare the package name in which the class is placed.
• There can be only one package statement in a java program and it must be defined before
any class or interface declaration. Package declaration is necessary because a Java class
can be placed in different packages and directories based on the module they are used.
•Example
package argentina; //where argentina is the package name package com.argentina; //where
com is the root directory and argentina is the subdirectory
-Use `package pkg;` as the first line in a Java file to declare that all classes in the file belong
to the package `pkg`.
• Example: `package MyPackage;` creates a package named `MyPackage`.
- If no `package` statement is used, classes go into the **unnamed default package**,
suitable only for small programs.
- Packages map directly to directories in the file system. Example: A class in `package
MyPackage;` must reside in a directory named `MyPackage`.
- Case-sensitive Directory names must exactly match the package name.
- Multiple files can share the same package declaration.
Note:
-Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
Code example
-Creating a package named mypackage with a class:
// Save as MyClass.java in a folder named 'mypackage'
package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("This is from mypackage!");
}
}
-Using the package in another program
// Save as Main.java
import mypackage.MyClass;
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.displayMessage();
}
}