Java Notes Part 6
String handling in Java:
● In Java, a String is an object that represents a sequence of characters.
Example:
String message = "Welcome to Chitkara";
● Here, the message is a reference variable of type String, not a primitive type like int,
char, etc. Instead, it points to a String object.
Important points:
● String is a class, not a primitive data type.
● It belongs to the [Link] package, which is automatically imported.
● Strings are created using double quotes (" ").
Example:
String name = "Java";
Here:
● name: reference variable
● "Java": String object stored in memory
Ways to Create String Objects
● There are two ways to create String objects in Java.
1 Using String Literals
Example:
String s1 = "Hello";
String s2 = "Hello";
What happens internally?
● Java stores string literals inside a special memory area called the String Pool.
● If a string already exists in the pool, Java reuses the same object instead of creating a
new one.
● This process is called String Interning.
Example:
String s1 = "Welcome";
String s2 = "Welcome";
if (s1 == s2)
[Link]("same");
else
[Link]("not same");
Output:
same
Reason:
● Both variables point to the same memory location in the String Pool.
2. Using a new Keyword
Example:
String s1 = new String("Welcome");
String s2 = new String("Welcome");
if (s1 == s2)
[Link]("same");
else
[Link]("not same");
// Output: not the same
● Here, since we use the new operator to create 2 different String class objects, both will
be created at different locations inside the heap area, so the output will be “Not Same”.
String Pool
● The String Pool is a special area inside heap memory used to store unique string
literals.
Benefits:
● Saves memory
● Improves performance
● Reuses existing strings
Example:
String a = "Java";
String b = "Java";
String c = "Python";
● Both a and b point to the same "Java" object.
intern() Method
● The intern() method moves a string object to the String Pool.
Example:
String s1 = "hello";
String s2 = new String("hello");
[Link](s1 == s2); // false
String s3 = [Link]();
[Link](s1 == s3); // true
Explanation:
● s2 was created in the heap
● intern() returns reference from string pool
Comparing 2 String objects:
● To compare the content of two String objects, irrespective of how they are created
(using string literal or new keyword), you should always use the equals() method
defined in the String class. The equals() method compares the actual content
(character sequence) of the strings, whereas the == operator compares the memory
references of the objects.
Example:
String str1 = "Welcome"; // Created using a string literal
String str2 = new String("Welcome"); // Created using the new keyword
[Link](str1 == str2); // Output: false
// Explanation: '==' compares memory references. Since str1 is in the String Pool and
//str2 is on the heap, the references are different.
[Link]([Link](str2)); // Output: true
// Explanation: equals() compares the content of the strings.
//Both have the same character sequence, so it returns true.
equalsIgnoreCase()
● Ignores case differences.
Example:
[Link]("Java".equalsIgnoreCase("java")); // true
Some of the constructors of the String class
● String(): Creates an empty String
● String(byte [] brr): Creates a String from the given byte array
● String(char[] chr): Creates a String from a given character array
● String(String s): Creates a String from a given String object
● String(StringBuilder sb): Creates a String from the given StringBuilder object
● String(StringBuffer sb): Creates a String from the given StringBuffer object
Some of the Important String Methods:
1. char charAt(int position): returns the character at the position from the calling string
2. int length(): returns the total number of characters in the calling string
3. byte[] getBytes(): returns a byte array from the characters of a String
4. char[] toCharArray(): returns characters array from the characters of a String
Examples:
String s1 = "Java";
[Link]([Link](2)); //v
[Link]([Link]()); //4
byte brr[] = [Link]();
for(byte b: brr)
[Link](b + " "); //74 97 118 97
[Link]();
char chr[] = [Link]();
for(char ch: chr)
[Link](ch + " "); //J a v a
5. static String valueOf(int b): returns a String representation of the int value
6. static String valueOf(float f): returns a String representation of the float value.
7. static String valueOf(boolean b): returns a String representation of the boolean value.
8. static String valueOf(double d): returns a String representation of the double value.
9. static String valueOf(char c): returns a String representation of the char value.
10.static String valueOf(long l): returns a String representation of the long value.
11.static String valueOf(char[] chr): returns a String representation of the char[]..
12.static String valueOf(Object d): returns String representation of parameter object
value; It calls toString() method
Example1:
String statement = "Yogesh of age " + 16 + " years has scored " + 92.25 + "% in class XII";
Internally converted as:
String statement = "Yogesh of age " + [Link](16) + " years has scored " +
[Link](92.25) + "% in class XII";
13.boolean equals(Object str): return true if the parameter and calling object have the
same content (matching is case sensitive)
14.boolean equalsIgnoreCase(String str): return true if the parameter and the calling
object have the same content (matching is case insensitive)
15.int compareTo(String str): return 0 if the parameter and calling object have the same
content (matching is case sensitive); otherwise return the difference of the first character
mismatch; otherwise if no character mismatch but any String exhausted then
[Link]() - [Link]()
16.int compareToIgnoreCase(String str): Same as compareTo, but matching is
case-insensitive
17.boolean startsWith(String str): returns true if calling String starts with str
18.boolean endsWith(String str): returns true if calling String ends with str
Examples:
[Link]("Java".equals("Java")); //true
[Link]("Java".equals("java")); //false
[Link]("Java".equalsIgnoreCase("java")); //true
[Link]("Java".compareTo("Java")); //0
[Link]("Java".compareTo("java")); //-32
[Link]("Java".compareToIgnoreCase("java")); //0
[Link]("java".compareTo("Java")); //32
[Link]("javaw".compareTo("java")); //1
[Link]("java".compareTo("javaw")); //-1
[Link]("Java".startsWith("Ja")); //true
[Link]("Java".startsWith("va")); //false
[Link]("Java".endsWith("va")); //true
[Link]("Java".endsWith("Ja")); //false
19.int indexOf(char ch): returns the first matching index of the string specified by the
parameter, or returns -1 if the character is not found.
20.int indexOf(String str): returns the first matching index of the string specified by str,
returns -1 if str is not found.
21.int lastIndexOf(int ch): returns the last matching index of the character specified by ch,
returns -1 if ch is not found.
22.int lastIndexOf(String str): returns the last matching index of the string specified by str,
returns -1 if str is not found.
Examples:
[Link]("bluetooth".indexOf('o')); //5
[Link]("bluetooth".lastIndexOf('o')); //6
String temp = "value has a value only if the value is valued";
[Link]([Link]("value")); //0
[Link]([Link]("value")); //39
23.String substring(int startIndex): returns the substring starting from startIndex to the
end of the string
24.String substring(int startIndex, int endIndex): returns the substring starting from
startIndex to the endIndex - 1 of the String
25.String replace(char original, char replacement): returns a new String in which the
original character is replaced with a replacement character for the calling string.
26.String replaceAll(String regex, String replacement): replace parts of a string that
match a regular expression (regex) with another string.
27.String trim(): returns a new String with leading and trailing spaces truncated from the
calling string.
28.String toLowerCase(): returns a new String with all characters in lowercase of the
calling string.g
29.String toUpperCase(): returns a new String with all characters of the calling string in
uppercase.
30.boolean contains(String s): checks if the substring exists.
Example:
[Link]("bluetooth".substring(4)); //tooth
[Link]("bluetooth".substring(0, 4)); //blue
[Link]("Hook".replace('H', 'L')); //Look
[Link](" java ".length()); //9
[Link](" java ".trim().length()); //4
[Link]("Java".toUpperCase()); //JAVA
[Link]("Java".toLowerCase()); //java
[Link]("Hello World".contains("World")); //true
[Link]("Java is fun".replaceAll("fun", "powerfull")); // Java is powerfull
[Link]("Java".replaceAll("[aeiou]", "*")); //J*v*
[Link]("123Java456".replaceAll("[0-9]", ""));//Java
31.String format(String s, Object …): Creates a formatted string.
Example:
String name = "John";
int age = 25;
String msg = [Link]("My name is %s and I am %d years old", name, age);
[Link](msg);
Common format specifiers:
%s: String
%d: Integer
%f: Float
%c: Character
%b: Boolean
32.static String join(CharSequence delimiter, CharSequence... elements):
33.static String join(CharSequence delimiter, Iterable<? extends CharSequence>
elements):
● The [Link]() method is used to join multiple strings together using a
specified delimiter (separator).
● It was introduced in Java 8
Example1:
String result = [Link]("-", "Java", "Python", "C++", "JavaScript");
[Link](result);
Output:
Java-Python-C++-JavaScript
Example2:
String[] languages = { "Java", "Python", "C++" };
String result = [Link](" | ", languages);
[Link](result);
Output:
Java | Python | C++
Tokenizing a String in Java:
● Tokenizing a string means breaking a large string into smaller parts called tokens
based on a delimiter (separator).
● A delimiter is a character that separates the tokens, such as:
○ space " "
○ comma ","
○ hyphen "-"
○ colon ":"
Example string:
"Java,Python,C++,JavaScript"
Tokens using , delimiter:
Java
Python
C++
JavaScript
● In Java, tokenizing can be done mainly in two ways:
1. Using the StringTokenizer class
2. Using the split() method of the String class
1. Tokenizing Using StringTokenizer
● StringTokenizer is a class present in the [Link] package.
● It breaks a string into tokens using a specified delimiter.
import [Link];
Important Methods:
1. boolean hasMoreTokens(): Checks if more tokens exist
2. String nextToken(): Returns the next token
3. int countTokens(): Returns the number of tokens.
Example1: Tokenizing Using Space
● Default delimiter = space
package [Link];
import [Link];
public class Demo {
public static void main(String[] args) {
String str = "Java Python C++ JavaScript";
StringTokenizer st = new StringTokenizer(str);
while([Link]()) {
[Link]([Link]());
}
}
}
Output:
Java
Python
C++
JavaScript
Example 2: Tokenizing Using Comma
package [Link];
import [Link];
public class Demo {
public static void main(String[] args) {
String str = "Java,Python,C++,JavaScript";
StringTokenizer st = new StringTokenizer(str, ",");
[Link]("Total Tokens: " + [Link]());
while ([Link]()) {
[Link]([Link]());
}
}
}
2. Tokenizing Using the split() Method
● The split() method belongs to the String class.
● It splits a string based on a delimiter and returns an array of strings.
Syntax:
String[] arr = [Link](delimiter);
Example 1: Tokenizing Using Comma
package [Link];
public class Demo {
public static void main(String[] args) {
String str = "Java,Python,C++,JavaScript";
String[] tokens = [Link](",");
for (String s : tokens) {
[Link](s);
}
}
}
Example 2: Tokenizing Using Space
package [Link];
public class Demo {
public static void main(String[] args) {
String str = "Java Python C++ JavaScript";
String[] words = [Link](" ");
for (String word: words) {
[Link](word);
}
}
}
When to Use Which?
Use StringTokenizer when:
● Simple tokenization is needed
● Working with legacy Java code
Use split() when:
● Regex support is required
● Working with modern Java programs
Immutability Concept of String object:
● Immutability refers to the property of an object whose state cannot be changed after it is
created. The String class in Java is immutable, which means that once a String object is
created, it cannot be modified. If you perform any operation on a String, a new String
object is created rather than modifying the original one.
Example:
String message = "Welcome";
[Link](" user");
[Link](message);
Output:
Welcome // Original String is unchanged.
Reason: Here, we are using the concat() method to add another string to the previous string.
Since string objects are immutable, if we call any method to make any modification in the string
object, that method will return a new string object with modified content.
Example:
String message = "Welcome";
String newMessage = [Link](" user");
[Link](message);
[Link](newMessage);
//Another Example
String s1 = "Welcome";
s1 = [Link](" user");
[Link](s1);
//The immutability applies to the String object stored in memory, not the
//reference variable of the String type.
Why is String Immutable in Java?
● In Java, the String class is immutable, which means that once a String object is
created, its value cannot be changed. If any modification is performed on a string, a
new String object is created instead of modifying the existing one.
● The main reasons for making String immutable in Java are as follows:
1. Security
● Strings are widely used in security-sensitive operations, such as storing file paths,
database URLs, network connections, usernames, and passwords. If strings were
mutable, their values could be changed by malicious code after validation, which could
lead to security vulnerabilities. Immutability ensures that once a string is created, its
value cannot be altered, making the system more secure.
2. String Pooling (Memory Efficiency)
● Java uses a special memory area called the String Constant Pool to store string
literals. When multiple variables refer to the same string value, Java stores only one
copy of that string in memory. Since strings are immutable, different parts of the
program can safely share the same object without worrying about unexpected
modifications. This improves memory efficiency and performance.
3. Thread Safety
● Because String objects cannot be modified after creation, they are inherently
thread-safe. Multiple threads can access the same string object simultaneously without
causing data inconsistency or requiring synchronization. This simplifies concurrent
programming and improves performance in multi-threaded environments.
In summary, making strings immutable improves security, memory efficiency through
string pooling, and thread safety, which are essential for reliable and efficient Java
applications.
StringBuffer and StringBuilder Classes in Java:
● In Java, the String class is immutable, meaning that once a string object is created, its
value cannot be changed. If we try to modify a string, a new object is created in
memory.
● Because of this behavior, frequent string modifications can create many unnecessary
objects, which may reduce performance.
● To solve this problem, Java provides two mutable companion classes:
○ StringBuffer
○ StringBuilder
● Both classes belong to the [Link] package and allow modifying the same object
instead of creating new ones, which improves performance when performing many
string operations.
1. StringBuilder Class
● The StringBuilder class is used to create and manipulate mutable strings.
It provides methods for appending, inserting, replacing, deleting, and reversing
characters in a string.
● StringBuilder is not thread-safe, which makes it faster than StringBuffer.
Example:
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](sb);
Output:
Hello World
2. StringBuffer Class
● StringBuffer works almost the same as StringBuilder. The main difference is
that StringBuffer is thread-safe, meaning it is safe to use in multi-threaded
environments.
● However, because of synchronization, StringBuffer is slower than StringBuilder.
Example
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link](sb);
Output:
Hello World
Difference Between StringBuilder and StringBuffer:
Feature StringBuilder StringBuffer
Thread Safety Not thread-safe Thread-safe
Performance Faster Slower
Use Case Single-threaded programs Multi-threaded programs
When to Use
Use StringBuilder when:
● The program runs in a single-threaded environment
● Performance is important
● Thread safety is not required.
Use StringBuffer when:
● The program runs in a multi-threaded environment
● Thread safety is required.
Creating StringBuilder Objects
1. Creating an Empty StringBuilder
StringBuilder builder = new StringBuilder();
Default Capacity: 16 characters
2. Creating a StringBuilder with Custom Capacity
StringBuilder builder = new StringBuilder(50);
● This creates a StringBuilder object with a capacity of 50 characters.
Common Methods of StringBuffer / StringBuilder
● Both classes provide many useful methods for modifying strings.
1. append()
● Adds text at the end of the string.
StringBuffer sb = new StringBuffer("Java");
[Link](" Programming");
[Link](sb);
Output:
Java Programming
2. insert()
● Inserts text at a specific position.
StringBuffer sb = new StringBuffer("Java");
[Link](4, " Language");
[Link](sb);
Output
Java Language
3. replace()
● Replaces characters between two indexes.
StringBuffer sb = new StringBuffer("Hello World");
[Link](6, 11, "Java");
[Link](sb);
Output
Hello Java
4. delete()
● Deletes characters between indexes.
StringBuffer sb = new StringBuffer("Java Programming");
[Link](4, 16);
[Link](sb);
Output
Java
5. reverse()
● Reverses the characters of the string.
StringBuffer sb = new StringBuffer("Java");
[Link]();
[Link](sb);
Output
avaJ
6. capacity()
● Returns the total capacity of the buffer.
StringBuffer sb = new StringBuffer();
[Link]([Link]());
Output
16
7. length()
● Returns the number of characters currently stored in the object.
StringBuffer sb = new StringBuffer("Java");
[Link]([Link]());
Output
8. ensureCapacity()
● Increases the capacity if required.
StringBuffer sb = new StringBuffer();
[Link](50);
● This ensures the buffer can hold at least 50 characters.
9. charAt()
● Returns the character at a specific index.
StringBuffer sb = new StringBuffer("Java");
[Link]([Link](2));
Output
v
10. setCharAt()
● Changes the character at a specific index.
StringBuffer sb = new StringBuffer("Java");
[Link](0, 'K');
[Link](sb);
Output
Kava
Capacity vs Length in StringBuffer / StringBuilder
● When working with StringBuffer or StringBuilder, two important concepts are:
● Length: Length represents the number of characters currently stored in the
object.
● Capacity: Capacity represents the maximum number of characters that can be
stored in the object before the buffer needs to resize itself.
● StringBuffer and StringBuilder allocate extra memory so that frequent resizing can be
avoided.
Example:
StringBuffer sb = new StringBuffer("Java");
[Link]("Length: " + [Link]());
[Link]("Capacity: " + [Link]());
Output
Length: 4
Capacity: 20
Explanation
● The string "Java" contains 4 characters, therefore:
Length = 4
● When a StringBuffer or StringBuilder object is created using a String, Java
calculates the capacity using the following formula:
Default Capacity Formula
Capacity = 16 + length of the string
Capacity Expansion in StringBuffer / StringBuilder
● Both StringBuffer and StringBuilder maintain an internal buffer capacity.
● If the number of characters stored in the object exceeds the current capacity, Java
automatically increases the capacity of the buffer.
● This process is called Capacity Expansion.
Capacity Expansion Formula
● When the current capacity is exceeded, Java increases the capacity using the following
formula:
New Capacity = (Old Capacity × 2) + 2
Example
● Suppose the current capacity is:
Old Capacity = 20
● If more characters are added and the buffer becomes full, Java increases the capacity
as follows:
New Capacity = (20 × 2) + 2
= 40 + 2
= 42
● So the new capacity becomes:
42 characters
[Link]:
public class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
[Link]("Initial Length: " + [Link]());
[Link]("Initial Capacity: " + [Link]());
[Link](" Programming Language");
[Link]("After Append Length: " + [Link]());
[Link]("After Append Capacity: " + [Link]());
}
}
Output:
Initial Length: 4
Initial Capacity: 20
After Append Length: 24
After Append Capacity: 42
Explanation:
Initial capacity = 16 + 4 = 20
After adding more characters: capacity exceeded
New capacity = (20 × 2) + 2 = 42
Converting String to Primitive Types:
String num = "123";
int n = [Link](num);
double d = [Link]("3.14");
long l = [Link]("12345");
boolean b = [Link]("true");
Converting Primitive to String:
● Using valueOf(): Recommended to use
int age = 25;
String s = [Link](age);
● Using + operator:
int age = 10;
String s = age+"";
[Link](s);
Java internally does something similar to:
new StringBuilder().append(age).append("").toString();
Text-Block in Java: (New feature introduced in Java 15)
● Java 15 introduced a new type of string literal called a text-block which allows
programmers to preserve indents and multiple lines without the need to add white
spaces within quotes.
● In Java, we can create a text block by enclosing the text in the triple quote(”””).
Example:
String html = """
<html>
<body>
<h1>Hello</h1>
</body>
</html>
""";
}
[Link](htmlCode);
● You can also use text blocks to create formatted Strings, using placeholders like %s or
%d.
Example:
String name = "Rahul";
int age = 30;
String message = """
Hello, my name is %s
And I am %d years old.
""";
String formatedString = [Link](message, name, age);
[Link](formatedString);
Student Task:
1. Predict the Output:
String s1 = "Java";
String s2 = "Java";
[Link](s1 == s2);
A. true
B. false
C. Compilation error
D. Runtime error
2. Predict the Output:
String s1 = new String("Java");
String s2 = new String("Java");
[Link](s1 == s2);
A. true
B. false
C. Compilation error
D. Runtime error
3. Predict the Output:
StringBuffer sb1 = new StringBuffer("Java");
StringBuffer sb2 = new StringBuffer("Java");
[Link]([Link](sb2));
A. true
B. false
C. Compilation error
D. Runtime error
4. Predict the Output:
String s1 = "Java";
String s2 = new String("Java");
[Link]([Link](s2));
A. true
B. false
C. Compilation error
D. Runtime error
5. Predict the Output:
StringBuffer sb = new StringBuffer("Java");
[Link]([Link]());
[Link]([Link]());
A. 4 20
B. 4 16
C. 4 4
D. 20 4
6. Predict the Output:
String s = "Java";
StringBuilder sb = new StringBuilder(s);
[Link]();
[Link](s);
A. avaJ
B. Java
C. Compilation error
D. Runtime error
7. Predict the Output:
StringBuilder sb = new StringBuilder("Java");
[Link](1,3);
[Link](sb);
A. Ja
B. Jva
C. J
D. Java
Explanation:
delete(start, end) removes characters from start index to end-1.
8. Which statement is correct?
A. String is mutable
B. StringBuilder is thread-safe
C. StringBuffer is thread-safe
D. StringBuilder is immutable
9. Check if a String is a Palindrome
● Write a Java program to check whether a string is a palindrome using
StringBuilder.
Solution:
package [Link];
public class Demo {
public static void main(String[] args) {
String str = "madam";
StringBuilder sb = new StringBuilder(str);
String reversed = [Link]().toString();
if ([Link](reversed))
[Link]("Palindrome");
else
[Link]("Not Palindrome");
}
}
10.Remove Vowels from a String using StringBuffer:
Solution:
package [Link];
public class Demo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java Programming");
for(int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if("aeiouAEIOU".indexOf(ch) != -1) {
[Link](i);
i--;
}
}
[Link](sb);
}
}
11.Replace Spaces with Hyphens using StringBuilder:
● Write a Java program to replace all spaces in a string with '-' using
StringBuilder.
Solution:
package [Link];
public class Demo {
public static void main(String[] args) {
String str = "Java Programming Language";
StringBuilder sb = new StringBuilder(str);
for(int i = 0; i < [Link](); i++) {
if([Link](i) == ' ') {
[Link](i, '-');
}
}
[Link](sb);
}
}