Navigation: Main Tutorial Index | Practice Programs | Previous: Arrays | Next: Exception Handling
Practice: Practice Programs | Practice Program Index
A String is a sequence of characters used to represent text.
For example:
String name = "Ayush";
String language = "Java Programming";
String message = "Welcome to Java";In Java, String is a predefined class available in the java.lang package.
Unlike primitive data types such as int, char, and double, String is a reference type.
Strings are used to:
- Store names and addresses.
- Store passwords and usernames.
- Display messages.
- Process user input.
- Validate email addresses and other text.
- Search and manipulate text.
- Read and process files.
- Exchange information between applications.
- A String represents a sequence of characters.
- String is a class, not a primitive data type.
- Strings are immutable in Java.
- String objects can be created using literals or the
newkeyword. - String provides many built-in methods.
- String belongs to the
java.langpackage, so no explicit import is required.
Java provides two commonly used ways to create String objects.
A String literal is created by writing text inside double quotation marks.
public class StringLiteral {
public static void main(String[] args) {
String name = "Ayush";
String language = "Java";
System.out.println(name);
System.out.println(language);
}
}Output:
Ayush
Java
String literals are stored in the String Constant Pool when an equivalent pooled String is not already available.
We can also create a String object using the new keyword.
public class StringUsingNew {
public static void main(String[] args) {
String name = new String("Ayush");
System.out.println(name);
}
}Output:
Ayush
Using new String("Ayush") explicitly creates a new String object, even if an equivalent String already exists in the pool.
| String Literal | new String() |
|---|---|
| Uses double quotation marks | Uses the new keyword |
| Uses the String Constant Pool | Explicitly creates a new String object |
| Reuses an existing pooled String when available | Creates a distinct object |
| Generally preferred for ordinary String creation | Useful when a distinct object is specifically required |
The String Constant Pool is a special area associated with the JVM's String handling.
It allows Java to reuse String literals instead of creating unnecessary duplicate pooled objects.
Consider the following code:
String s1 = "Java";
String s2 = "Java";Both variables refer to the same pooled String object.
Instead of storing two identical literal objects, Java can reuse one.
public class StringPoolExample {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);
}
}Output:
true
Both references point to the same object.
public class StringPoolExample2 {
public static void main(String[] args) {
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}Output:
false
true
Explanation:
s1refers to the pooled String.s2refers to a newly created String object.==compares references.equals()compares String contents.
The intern() method returns the canonical pooled representation of a String.
public class InternExample {
public static void main(String[] args) {
String s1 = "Java";
String s2 = new String("Java");
String s3 = s2.intern();
System.out.println(s1 == s2);
System.out.println(s1 == s3);
}
}Output:
false
true
| Expression | Behavior |
|---|---|
String s1 = "Java"; |
Uses pooled literal |
String s2 = "Java"; |
Reuses equivalent pooled literal |
String s3 = new String("Java"); |
Creates a new String object |
String s4 = s3.intern(); |
Returns the pooled representation |
Important: The String Constant Pool is managed by the JVM. In modern Java, pooled Strings are stored in the heap.
One of the most important characteristics of String is immutability.
Immutability means that once a String object is created, its contents cannot be changed.
If we perform an operation that appears to modify a String, Java creates or returns another String rather than modifying the original object.
public class StringImmutability {
public static void main(String[] args) {
String name = "Java";
name.concat(" Programming");
System.out.println(name);
}
}Output:
Java
Why?
Because concat() returns a new String. It does not modify the original String.
public class StringImmutability2 {
public static void main(String[] args) {
String name = "Java";
name = name.concat(" Programming");
System.out.println(name);
}
}Output:
Java Programming
The original String was not modified. The variable name was reassigned to refer to the returned String.
String immutability provides several benefits:
- Security: Strings are widely used for usernames, file paths, URLs, and configuration values.
- Thread Safety: Immutable String objects can safely be shared between threads.
- String Pooling: Shared String literals can be reused without one reference changing their contents for another.
- Hash Code Caching: A String's hash code can be cached because its contents do not change.
- Reliability: String values cannot be unexpectedly modified through another reference.
The length() method returns the number of UTF-16 code units in a String.
stringName.length();public class StringLength {
public static void main(String[] args) {
String name = "Ayush";
System.out.println("Length: " + name.length());
}
}Output:
Length: 5
Important: Java's String.length() counts UTF-16 code units, not necessarily user-perceived characters. Some Unicode characters use two code units.
Java provides many built-in methods for working with Strings.
Returns the number of UTF-16 code units.
String str = "Java";
System.out.println(str.length());Output:
4
Returns the character at the specified index.
public class CharAtExample {
public static void main(String[] args) {
String str = "Java";
System.out.println(str.charAt(0));
System.out.println(str.charAt(2));
}
}Output:
J
v
Converts a String to uppercase.
String str = "java";
System.out.println(str.toUpperCase());Output:
JAVA
Converts a String to lowercase.
String str = "JAVA";
System.out.println(str.toLowerCase());Output:
java
Removes leading and trailing characters whose code point is at most U+0020.
String str = " Java Programming ";
System.out.println(str.trim());Output:
Java Programming
Note: trim() does not remove every Unicode whitespace character. Java 8 does not provide the later strip() methods.
Extracts a portion of a String.
There are two commonly used forms:
substring(int beginIndex)
substring(int beginIndex, int endIndex)The beginning index is included, but the ending index is excluded.
public class SubstringExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println(str.substring(5));
System.out.println(str.substring(0, 4));
}
}Output:
Programming
Java
Checks whether a String contains a particular sequence of characters.
String str = "Java Programming";
System.out.println(str.contains("Java"));
System.out.println(str.contains("Python"));Output:
true
false
Checks whether a String begins with a specified prefix.
String str = "Java Programming";
System.out.println(str.startsWith("Java"));Output:
true
Checks whether a String ends with a specified suffix.
String str = "Java Programming";
System.out.println(str.endsWith("Programming"));Output:
true
Returns the index of the first occurrence of a character or substring.
If the value is not found, it returns -1.
String str = "Java Programming";
System.out.println(str.indexOf('a'));
System.out.println(str.indexOf("Programming"));Output:
1
5
Returns the index of the last occurrence.
String str = "Java Programming";
System.out.println(str.lastIndexOf('a'));Output:
3
Replaces matching characters or character sequences.
String str = "Java Programming";
System.out.println(str.replace('a', 'o'));Output:
Jovo Progr omming
Replaces all substrings matching a regular expression.
String str = "Java123Programming456";
System.out.println(str.replaceAll("[0-9]", ""));Output:
JavaProgramming
Replaces the first substring matching a regular expression.
String str = "Java Java Java";
System.out.println(str.replaceFirst("Java", "Python"));Output:
Python Java Java
Checks whether the String length is zero.
String str1 = "";
String str2 = "Java";
System.out.println(str1.isEmpty());
System.out.println(str2.isEmpty());Output:
true
false
Compares two Strings based on their contents.
String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2));Output:
true
Compares Strings without considering case differences.
String s1 = "JAVA";
String s2 = "java";
System.out.println(s1.equalsIgnoreCase(s2));Output:
true
Compares two Strings lexicographically.
It returns:
- A negative number if the first String comes before the second.
- Zero if the Strings are equal.
- A positive number if the first String comes after the second.
String s1 = "Apple";
String s2 = "Banana";
System.out.println(s1.compareTo(s2));Output:
-1
The exact nonzero return value is not guaranteed to be -1 or 1; it only indicates the comparison result's sign.
Joins two Strings.
String s1 = "Hello";
String s2 = " Java";
System.out.println(s1.concat(s2));Output:
Hello Java
Splits a String into an array using a regular expression.
public class SplitExample {
public static void main(String[] args) {
String str = "Java,Python,C++";
String[] languages = str.split(",");
for (String language : languages) {
System.out.println(language);
}
}
}Output:
Java
Python
C++
| Method | Purpose |
|---|---|
length() |
Returns String length in UTF-16 code units |
charAt() |
Returns a character at an index |
toUpperCase() |
Converts to uppercase |
toLowerCase() |
Converts to lowercase |
trim() |
Removes leading and trailing basic whitespace/control characters |
substring() |
Extracts a portion |
contains() |
Checks for a sequence |
startsWith() |
Checks prefix |
endsWith() |
Checks suffix |
indexOf() |
Finds first occurrence |
lastIndexOf() |
Finds last occurrence |
replace() |
Replaces characters or literal sequences |
replaceAll() |
Replaces regex matches |
replaceFirst() |
Replaces first regex match |
isEmpty() |
Checks whether length is zero |
equals() |
Compares contents |
equalsIgnoreCase() |
Compares contents ignoring case |
compareTo() |
Lexicographic comparison |
concat() |
Joins Strings |
split() |
Splits into an array |
intern() |
Returns pooled canonical String |
This is one of the most frequently asked Java interview questions.
The == operator compares primitive values when used with primitive operands.
When used with object references, it checks whether both references point to the same object.
The equals() method checks logical equality based on the class implementation.
For String, it compares character contents.
public class StringComparison {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
}
}Output:
true
false
true
== |
equals() |
|---|---|
| Compares primitive values or object references | Compares logical equality according to the implementation |
| For references, checks object identity | For String, checks character contents |
| Operator | Method |
| Does not compare String contents by itself | Compares String contents |
When comparing two Strings for content equality, normally use:
str1.equals(str2);If the String reference might be null, use a null-safe comparison such as:
"Java".equals(str);String concatenation means joining two or more Strings.
Java provides multiple ways to concatenate Strings.
public class StringConcatenation {
public static void main(String[] args) {
String firstName = "Ayush";
String lastName = "Soni";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
}
}Output:
Ayush Soni
String s1 = "Hello";
String s2 = " World";
System.out.println(s1.concat(s2));Output:
Hello World
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb);Output:
Hello World
Repeated String concatenation can create many temporary String objects because Strings are immutable.
For repeated modifications, StringBuilder is generally more efficient.
StringBuilder is a mutable sequence of characters.
Unlike String, its contents can be modified without creating a new String object for every operation.
It was introduced in Java 5.
Consider the following code:
String str = "Java";
str = str + " Programming";
str = str + " Language";Each concatenation produces another String result.
For repeated modifications, this can create unnecessary temporary objects.
StringBuilder provides a more efficient alternative.
StringBuilder sb = new StringBuilder("Java");public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb);
}
}Output:
Java Programming
Adds content at the end.
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
System.out.println(sb);Output:
Java Programming
Inserts content at a specified position.
StringBuilder sb = new StringBuilder("Java");
sb.insert(4, " Programming");
System.out.println(sb);Output:
Java Programming
Replaces a range of characters.
The start index is included and the end index is excluded.
StringBuilder sb = new StringBuilder("Java Programming");
sb.replace(5, 16, "Development");
System.out.println(sb);Output:
Java Development
Deletes characters within a specified range.
StringBuilder sb = new StringBuilder("Java Programming");
sb.delete(4, 16);
System.out.println(sb);Output:
Java
Reverses the character sequence.
StringBuilder sb = new StringBuilder("Java");
sb.reverse();
System.out.println(sb);Output:
avaJ
Returns the current capacity of the StringBuilder.
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity());Output:
16
A default StringBuilder starts with a capacity of 16 characters.
Ensures that the capacity is at least the specified minimum.
StringBuilder sb = new StringBuilder();
sb.ensureCapacity(50);
System.out.println(sb.capacity() >= 50);Output:
true
Changes the character at a specified index.
StringBuilder sb = new StringBuilder("Java");
sb.setCharAt(0, 'K');
System.out.println(sb);Output:
Kava
| Method | Purpose |
|---|---|
append() |
Adds content at the end |
insert() |
Inserts content at an index |
replace() |
Replaces a range |
delete() |
Removes a range |
reverse() |
Reverses the sequence |
capacity() |
Returns current capacity |
ensureCapacity() |
Ensures minimum capacity |
setCharAt() |
Changes a character |
length() |
Returns the current length |
toString() |
Converts to String |
StringBuffer is another mutable sequence of characters.
It is similar to StringBuilder, but its methods are synchronized.
This makes individual StringBuffer operations synchronized, which can be useful when multiple threads access the same StringBuffer.
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb);
}
}Output:
Java Programming
StringBuffer provides many methods similar to StringBuilder:
append()insert()replace()delete()reverse()capacity()length()setCharAt()
public class StringBufferReverse {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Programming");
sb.reverse();
System.out.println(sb);
}
}Output:
gnimmargorP
This is a very important Java interview topic.
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread safety | Safe to share because immutable | Not synchronized | Synchronized methods |
| Performance for repeated modifications | Often less efficient | Generally faster | Generally slower than StringBuilder |
| Introduced | Java 1.0 | Java 5 | Java 1.0 |
| Use case | Fixed text | Frequent modifications in one thread | Shared mutable text with synchronized operations |
Use String when:
- Storing fixed text.
- Comparing names.
- Working with messages.
- Building values that do not require frequent modification.
Use StringBuilder when:
- Building large Strings.
- Repeatedly appending or modifying text.
- Working in a single-threaded context or when access is externally controlled.
Use StringBuffer when:
- Multiple threads share the same mutable character sequence.
- You need synchronized individual operations.
Important: StringBuffer's synchronized methods do not automatically make a multi-operation workflow atomic. Additional synchronization may still be necessary.
Java provides String.format() to create formatted Strings.
It uses format specifiers.
| Specifier | Meaning |
|---|---|
%s |
String |
%d |
Integer |
%f |
Floating-point value |
%c |
Character |
%b |
Boolean |
%n |
Platform-specific line separator |
public class StringFormatExample {
public static void main(String[] args) {
String name = "Ayush";
int age = 22;
double percentage = 88.75;
String result = String.format(
"Name: %s, Age: %d, Percentage: %.2f",
name,
age,
percentage
);
System.out.println(result);
}
}Output:
Name: Ayush, Age: 22, Percentage: 88.75
Java provides methods to convert values between Strings and other data types.
Using String.valueOf():
int number = 100;
String str = String.valueOf(number);
System.out.println(str);Output:
100
Using Integer.parseInt():
String str = "100";
int number = Integer.parseInt(str);
System.out.println(number + 50);Output:
150
String str = "25.75";
double value = Double.parseDouble(str);
System.out.println(value);Output:
25.75
String str = "true";
boolean value = Boolean.parseBoolean(str);
System.out.println(value);Output:
true
If a String does not contain a valid numeric representation, parsing may throw NumberFormatException.
Example:
String str = "Java";
int number = Integer.parseInt(str);This causes a NumberFormatException.
Regular expressions (Regex) are patterns used to search, match, and manipulate text.
Java supports regular expressions through the java.util.regex package and methods such as matches(), replaceAll(), and split().
| Pattern | Meaning |
|---|---|
[0-9] |
Any digit |
[a-z] |
Lowercase letter |
[A-Z] |
Uppercase letter |
[a-zA-Z] |
Any English alphabetic letter |
\\d |
Digit |
\\w |
Word character |
\\s |
Whitespace |
+ |
One or more occurrences |
* |
Zero or more occurrences |
? |
Zero or one occurrence |
. |
Any character except line terminators by default |
^ |
Beginning of input |
$ |
End of input |
public class RegexExample {
public static void main(String[] args) {
String number = "123456";
System.out.println(number.matches("[0-9]+"));
}
}Output:
true
public class RemoveDigits {
public static void main(String[] args) {
String text = "Java123Programming456";
String result = text.replaceAll("[0-9]", "");
System.out.println(result);
}
}Output:
JavaProgramming
Note: Regular expressions are powerful, but validation of complex data such as email addresses should generally use appropriate validation rules rather than a simplistic pattern.
public class ReverseString {
public static void main(String[] args) {
String str = "Java";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed: " + reversed);
}
}Output:
Reversed: avaJ
For better efficiency when building a result character by character, use StringBuilder.
public class ReverseUsingBuilder {
public static void main(String[] args) {
String str = "Programming";
StringBuilder sb = new StringBuilder(str);
System.out.println(sb.reverse());
}
}Output:
gnimmargorP
A palindrome is a word or sequence that reads the same forward and backward.
Examples:
- madam
- level
- radar
public class StringPalindrome {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = true;
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
if (isPalindrome) {
System.out.println("Palindrome");
} else {
System.out.println("Not a palindrome");
}
}
}Output:
Palindrome
public class VowelsConsonants {
public static void main(String[] args) {
String str = "Java Programming";
int vowels = 0;
int consonants = 0;
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i));
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}Output:
Vowels: 5
Consonants: 10
Spaces and non-English characters are not counted in this example.
public class CountWords {
public static void main(String[] args) {
String str = "Java is a programming language";
String trimmed = str.trim();
int count = trimmed.isEmpty()
? 0
: trimmed.split("\\s+").length;
System.out.println("Word count: " + count);
}
}Output:
Word count: 5
public class CharacterFrequency {
public static void main(String[] args) {
String str = "programming";
char target = 'g';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == target) {
count++;
}
}
System.out.println("Frequency: " + count);
}
}Output:
Frequency: 2
public class RemoveSpaces {
public static void main(String[] args) {
String str = "Java Programming Language";
String result = str.replaceAll("\\s+", "");
System.out.println(result);
}
}Output:
JavaProgrammingLanguage
public class CapitalizeWords {
public static void main(String[] args) {
String str = "java programming language";
String[] words = str.split("\\s+");
StringBuilder result = new StringBuilder();
for (String word : words) {
if (!word.isEmpty()) {
String formatted = word.substring(0, 1).toUpperCase()
+ word.substring(1).toLowerCase();
if (result.length() > 0) {
result.append(" ");
}
result.append(formatted);
}
}
System.out.println(result);
}
}Output:
Java Programming Language
Two Strings are anagrams if they contain the same characters with the same frequencies, regardless of order.
Example:
- listen
- silent
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String s1 = "listen";
String s2 = "silent";
char[] a = s1.toLowerCase().toCharArray();
char[] b = s2.toLowerCase().toCharArray();
Arrays.sort(a);
Arrays.sort(b);
if (Arrays.equals(a, b)) {
System.out.println("Anagrams");
} else {
System.out.println("Not Anagrams");
}
}
}Output:
Anagrams
This example assumes English letters and ignores case, but does not ignore spaces or punctuation.
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
boolean alreadyChecked = false;
for (int j = 0; j < i; j++) {
if (str.charAt(j) == ch) {
alreadyChecked = true;
break;
}
}
if (alreadyChecked) {
continue;
}
int count = 0;
for (int j = 0; j < str.length(); j++) {
if (str.charAt(j) == ch) {
count++;
}
}
if (count > 1) {
System.out.println(ch + " = " + count);
}
}
}
}Output:
r = 2
g = 2
m = 2
public class FirstNonRepeatingCharacter {
public static void main(String[] args) {
String str = "swiss";
boolean found = false;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
int count = 0;
for (int j = 0; j < str.length(); j++) {
if (str.charAt(i) == str.charAt(j)) {
count++;
}
}
if (count == 1) {
System.out.println("First non-repeating: " + ch);
found = true;
break;
}
}
if (!found) {
System.out.println("No non-repeating character.");
}
}
}Output:
First non-repeating: w
public class OnlyDigits {
public static void main(String[] args) {
String str = "123456";
boolean valid = !str.isEmpty();
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
valid = false;
break;
}
}
System.out.println(valid ? "Only digits" : "Contains non-digits");
}
}Output:
Only digits
public class UpperLowerCount {
public static void main(String[] args) {
String str = "Java Programming";
int upper = 0;
int lower = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
upper++;
} else if (Character.isLowerCase(ch)) {
lower++;
}
}
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}Output:
Uppercase: 2
Lowercase: 13
public class RemoveDuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (result.indexOf(String.valueOf(ch)) == -1) {
result.append(ch);
}
}
System.out.println(result);
}
}Output:
progamin
public class LongestWord {
public static void main(String[] args) {
String str = "Java is a powerful programming language";
String[] words = str.split("\\s+");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
System.out.println("Longest word: " + longest);
}
}Output:
Longest word: programming
| Mistake | Explanation |
|---|---|
Using == to compare String contents |
Use equals() for content comparison |
| Assuming String is mutable | String is immutable |
Ignoring the return value of concat() |
Store the returned String if needed |
Using an invalid charAt() index |
Valid indexes range from 0 to length() - 1 |
Confusing length with length() |
Strings use length() |
| Using String concatenation repeatedly in large loops | Prefer StringBuilder in many such cases |
| Calling methods on a null String | Can cause NullPointerException |
Assuming trim() removes all Unicode whitespace |
It only removes a limited range of characters |
Assuming replaceAll() uses literal text |
It interprets the search pattern as a regular expression |
| Forgetting case sensitivity | Most String comparison methods are case-sensitive |
Q1. What is a String in Java?
Answer: A String is an object representing a sequence of characters.
Q2. Is String a primitive or non-primitive data type?
Answer: String is a reference type.
Q3. Why is String immutable in Java?
Answer: Immutability provides benefits such as safe sharing, security, String pooling, and reliable hash codes.
Q4. What is the String Constant Pool?
Answer: It is a JVM-managed pool used to reuse canonical String literals.
Q5. What is the difference between String literal and new String()?
Answer: A literal uses the pooled representation, while new String() explicitly creates a new String object.
Q6. What is the use of intern()?
Answer: It returns the canonical pooled representation of a String.
Q7. What is the difference between == and equals()?
Answer: For object references, == compares identity. For String, equals() compares contents.
Q8. What is the use of charAt()?
Answer: It returns the character at a specified index.
Q9. What is the use of substring()?
Answer: It extracts a portion of a String.
Q10. What is String concatenation?
Answer: It is the process of joining multiple Strings.
Q11. What is StringBuilder?
Answer: StringBuilder is a mutable sequence of characters used for efficient String construction and modification.
Q12. What is StringBuffer?
Answer: StringBuffer is a mutable sequence of characters with synchronized methods.
Q13. What is the difference between StringBuilder and StringBuffer?
Answer: StringBuilder is not synchronized and is generally faster in single-threaded use. StringBuffer synchronizes its methods.
Q14. Is StringBuilder thread-safe?
Answer: No. It is not synchronized.
Q15. Is StringBuffer thread-safe?
Answer: Its individual methods are synchronized, although compound operations may still require external synchronization.
Q16. What is the use of append()?
Answer: It adds content to the end of a StringBuilder or StringBuffer.
Q17. What is the use of reverse()?
Answer: It reverses the character sequence in StringBuilder or StringBuffer.
Q18. What is the difference between equals() and equalsIgnoreCase()?
Answer: equals() compares content with case sensitivity, while equalsIgnoreCase() ignores case differences.
Q19. What is the difference between replace() and replaceAll()?
Answer: replace() performs literal character or sequence replacement, while replaceAll() uses a regular expression.
Q20. What is the use of split()?
Answer: It divides a String into an array using a regular expression.
Q21. Why is String commonly used as a HashMap key?
Answer: String is immutable and provides stable equality and hash-code behavior.
Q22. Can we create a mutable String?
Answer: String itself is immutable. For mutable character sequences, use StringBuilder or StringBuffer.
Q23. What is the default capacity of StringBuilder?
Answer: The default initial capacity is 16 characters.
Q24. What happens when StringBuilder exceeds its capacity?
Answer: Its internal storage grows automatically.
Q25. What is the difference between isEmpty() and isBlank()?
Answer: isEmpty() checks whether the length is zero. isBlank() checks whether the String is empty or contains only whitespace, but isBlank() was introduced in Java 11 and is not available in Java 8.
Q26. What is the difference between trim() and strip()?
Answer: trim() is available in Java 8 and removes leading and trailing characters up to U+0020. strip() uses Unicode whitespace rules and was introduced in Java 11.
Q27. Does String length always equal the number of visible characters?
Answer: No. length() counts UTF-16 code units. Some Unicode characters use multiple code units, and visible grapheme clusters may contain multiple code points.
Q28. Can we override the String class?
Answer: No. String is final, so it cannot be subclassed.
Q29. Why is String declared final?
Answer: It prevents subclasses from changing String's behavior and helps preserve its design guarantees.
Q30. What is the difference between String and char array?
Answer: String is immutable, while a character array can be modified. Character arrays can be useful when handling sensitive data, although they still require careful memory management.
Instructions: Solve the following questions independently. Write separate Java programs and test your code using different inputs. Do not rely entirely on built-in methods; implement the logic manually where possible.
- Write a Java program to accept a String from the user and display it.
- Find the length of a String without using the
length()method. - Convert a String into uppercase without using
toUpperCase(). - Convert a String into lowercase without using
toLowerCase(). - Reverse a String using a loop.
- Reverse a String using StringBuilder.
- Check whether a String is a palindrome.
- Count vowels and consonants in a String.
- Count the number of words in a sentence.
- Count the number of spaces in a String.
- Count uppercase and lowercase characters.
- Count digits, letters, and special characters.
- Find the frequency of a particular character.
- Check whether a String contains only digits.
- Remove all spaces from a String.
- Find duplicate characters in a String.
- Remove duplicate characters while preserving their first occurrence.
- Find the first non-repeating character.
- Find the first repeating character.
- Check whether two Strings are anagrams.
- Check whether two Strings are rotations of each other.
- Find the longest word in a sentence.
- Find the shortest word in a sentence.
- Reverse each word in a sentence.
- Reverse the order of words in a sentence.
- Capitalize the first letter of every word.
- Count the frequency of every character.
- Find the most frequently occurring character.
- Compare two Strings without using
equals(). - Remove all duplicate words from a sentence.
- Find the longest substring without repeating characters.
- Find the longest palindromic substring.
- Find the longest common prefix among multiple Strings.
- Find the longest common subsequence of two Strings.
- Implement String pattern matching without using
contains(). - Implement a basic version of
indexOf(). - Implement a basic version of
replace(). - Check whether a String is a valid palindrome after ignoring spaces, punctuation, and case.
- Compress a String using character counts.
- Find all permutations of a String.
- Find all substrings of a String.
- Implement a basic run-length encoding algorithm.
- Validate a password using suitable conditions.
- Create a word-frequency counter for a paragraph.
- Build a simple text-processing application using StringBuilder.
After completing this chapter, you should understand:
- What Strings are and how they are used in Java.
- Different ways to create String objects.
- The String Constant Pool.
- The purpose of the
intern()method. - Why Strings are immutable.
- Important built-in String methods.
- The difference between
==andequals(). - String concatenation and formatting.
- StringBuilder and StringBuffer.
- The differences between String, StringBuilder, and StringBuffer.
- String conversion and regular expressions.
- Common String programming problems.
- How to compare, search, reverse, and manipulate Strings.
- Common String interview questions.
Chapter 9: Java Exception Handling
Topics to explore:
- Introduction to Exception Handling.
- Errors vs Exceptions.
- Exception Hierarchy.
- Checked and Unchecked Exceptions.
- try and catch Blocks.
- Multiple Catch Blocks.
- Nested try Blocks.
- finally Block.
- throw Keyword.
- throws Keyword.
- Custom Exceptions.
- Exception Propagation.
- try-with-resources.
- Common Exception Handling Programs.
- Exception Handling Interview Questions.
- Practice Exercises.
Learning Tip: String questions are extremely common in Java coding interviews. Practice reversing Strings, checking palindromes, finding duplicate characters, anagrams, and character frequencies. Also understand why Strings are immutable and when to use StringBuilder instead of String.