Java Unit 3: String Notes
String in Java
Definition:
A String in Java is a sequence of characters. It is immutable, meaning once a string is
created, it cannot be changed. If we modify it, a new object is created.
Example:
String name = "Anu";
name = name + " Sharma"; // Now name refers to a new string "Anu Sharma"
Easy Explanation:
Imagine you're writing your name on a printed certificate. Once printed, you cannot
edit it; you must print a new copy. Similarly, in Java, Strings cannot be changed
directly; Java makes a new String.
Real-life Connection:
Think of WhatsApp messages — once sent, you can't edit them (you resend a new
one instead). Java Strings work the same way!
StringBuffer in Java
Definition:
StringBuffer is a class used to create mutable strings. It allows direct modification
and is thread-safe, meaning multiple threads can use it safely.
Example:
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Output: Hello World
Easy Explanation:
StringBuffer is like a whiteboard — you can erase and rewrite without needing a
new board. Unlike Strings, you modify the same memory space.
Real-life Connection:
It’s like a family notice board at home where everyone can add or remove notes.
Even with many people editing, it stays safe and organized.
StringBuilder in Java
Definition:
StringBuilder is similar to StringBuffer but is not thread-safe. It is faster and should
be used when only one thread is accessing it.
Example:
StringBuilder sb = new StringBuilder("Hi");
[Link](" There"); // Output: Hi There
Easy Explanation:
StringBuilder is like your personal notebook. Since only you are writing in it, there’s
no need for security locks. This makes it faster than StringBuffer.
Real-life Connection:
Just like updating your personal diary — only you write in it, making it quick and
smooth.
StringTokenizer in Java
Definition:
StringTokenizer helps break a string into smaller parts (tokens) based on a
delimiter like space or comma.
Example:
StringTokenizer st = new StringTokenizer("Pizza, Burger, Fries", ",");
while ([Link]()) {
[Link]([Link]());
}
Easy Explanation:
StringTokenizer works like scissors cutting a long thread into smaller pieces. It
helps separate a long text into small, manageable parts.
Real-life Connection:
Imagine your shopping list "Milk, Bread, Butter" — you separate them into
individual items to pick them one by one, just like StringTokenizer does.