Revision
Revision
StringBuffer Methods
is a mutable sequence of characters. Unlike String , which is
StringBuffer
1. append(String str) :
Deletes the characters from the specified start index to end index
(exclusive).
4. deleteCharAt(int index) :
Revision 1
StringBuffer sb = new StringBuffer("Hello");
sb.deleteCharAt(0);
// Output: "ello"
Replaces the substring from start to end (exclusive) with the specified
string.
6. reverse() :
7. capacity() :
8. ensureCapacity(int minCapacity) :
Ensures that the StringBuffer has at least the specified capacity. If not, it
increases the capacity.
Revision 2
sb.ensureCapacity(30);
9. toString() :
Summary
Here is a quick recap of the key methods:
StringBuffer Methods
append() , insert() , delete() , deleteCharAt() , replace()
StringBuilder in Java
StringBuilder is a mutable sequence of characters in Java that allows you to create
and manipulate strings efficiently. Unlike the String class, StringBuilder objects
can be modified without creating new objects, which makes it faster for
operations like appending, inserting, or deleting characters.
Key Features
1. Mutability: Changes to a StringBuilder object occur in the same object, unlike
String .
Revision 3
3. Not Thread-Safe: Unlike StringBuffer , StringBuilder is not synchronized,
making it faster but unsuitable for multi-threaded environments.
Revision 4
Garbage Collection in Java
Garbage Collection (GC) is a process by which Java automatically manages
memory by reclaiming unused memory and cleaning up objects that are no longer
in use, preventing memory leaks.
5. GC Phases:
1. System.gc() :
2. Runtime.gc() :
Revision 5
Similar to System.gc() , but it is invoked from the Runtime class. It suggests
that the JVM run the garbage collector.
3. finalize() :
@Override
protected void finalize() throws Throwable {
// Cleanup code (not recommended to rely on it)
super.finalize();
}
These classes are used to create references that allow the garbage
collector to reclaim objects even if they are still referenced.
unreachable.
PhantomReference : Used for more advanced use cases like cleanup after the
object is finalized.
4. G1 Garbage Collector: A server-style collector aiming for low latency and high
throughput.
Revision 6
When Does Garbage Collection Happen?
Low Memory: The JVM may trigger garbage collection when it runs low on
memory.
Important Notes:
No Direct Control: Java does not give direct control over garbage collection.
You can only suggest it with gc() , but the JVM decides when to run it.
Memory Leaks: If objects are still referenced (even if not in use), they won’t
be garbage collected, causing memory leaks.
Summary:
Garbage collection is automatic memory management in Java that frees
memory by reclaiming unreachable objects.
Revision 7