String Constructors
In Java, the String class provides several constructors to create String objects. These
constructors allow you to create strings from different sources, such as character arrays, byte
arrays, or other strings. Below is a detailed explanation of the String constructors in Java,
along with examples:
1. Default Constructor
Creates an empty String object.
Syntax:
String str = new String();
Example:
String str = new String();
System.out.println(str); // Output: "" (empty string)
2. Constructor with String Literal
Creates a String object from another string.
Syntax:
String str = new String(String original);
Example:
String original = "Hello";
String str = new String(original);
System.out.println(str); // Output: "Hello"
3. Constructor with Character Array
Creates a String object from a character array.
Syntax:
String str = new String(char[] value);
Example:
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str = new String(chars);
System.out.println(str); // Output: "Hello"
4. Constructor with Character Array (Partial)
Creates a String object from a portion of a character array.
Syntax:
String str = new String(char[] value, int offset, int count);
o value: The character array.
o offset: The starting index in the array.
o count: The number of characters to include.
Example:
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str = new String(chars, 1, 3); // Starts at index 1, takes 3 characters
System.out.println(str); // Output: "ell"
5. Constructor with Byte Array
Creates a String object from a byte array using the platform's default charset.
Syntax:
String str = new String(byte[] bytes);
Example:
byte[] bytes = {72, 101, 108, 108, 111}; // ASCII values for "Hello"
String str = new String(bytes);
System.out.println(str); // Output: "Hello"
6. Constructor with Byte Array (Partial)
Creates a String object from a portion of a byte array.
Syntax:
String str = new String(byte[] bytes, int offset, int length);
o bytes: The byte array.
o offset: The starting index in the array.
o length: The number of bytes to include.
Example:
byte[] bytes = {72, 101, 108, 108, 111}; // ASCII values for "Hello"
String str = new String(bytes, 1, 3); // Starts at index 1, takes 3 bytes
System.out.println(str); // Output: "ell"
7. Constructor with Byte Array and Charset
Creates a String object from a byte array using a specified charset.
Syntax:
String str = new String(byte[] bytes, String charsetName);
Example:
byte[] bytes = {72, 101, 108, 108, 111}; // ASCII values for "Hello"
String str = new String(bytes, "UTF-8");
System.out.println(str); // Output: "Hello"
8. Constructor with StringBuffer
Creates a String object from a StringBuffer.
Syntax:
String str = new String(StringBuffer buffer);
Example:
StringBuffer buffer = new StringBuffer("Hello");
String str = new String(buffer);
System.out.println(str); // Output: "Hello"
9. Constructor with StringBuilder
Creates a String object from a StringBuilder.
Syntax:
String str = new String(StringBuilder builder);
Example:
StringBuilder builder = new StringBuilder("Hello");
String str = new String(builder);
System.out.println(str); // Output: "Hello"
Summary Table of String Constructors:
Constructor Type Syntax
Default Constructor String()
From String Literal String(String original)
From Character Array String(char[] value)
From Partial Character Array String(char[] value, int offset, int count)
From Byte Array String(byte[] bytes)
From Partial Byte Array String(byte[] bytes, int offset, int length)
From Byte Array with
String(byte[] bytes, String charsetName)
Charset
From StringBuffer String(StringBuffer buffer)
From StringBuilder String(StringBuilder builder)
Key Points:
1. Immutability: Strings in Java are immutable, meaning their values cannot be
changed after creation.
2. Literal vs. Constructor: Prefer using string literals (e.g., String str = "Hello";) over
constructors for better performance, as literals are stored in the string pool.
3. Charset: When working with byte arrays, always specify the charset if the default
charset is not appropriate.
Example Combining Multiple Constructors:
public class Main {
public static void main(String[] args) {
// Default constructor
String str1 = new String();
System.out.println("str1: " + str1); // ""
// From string literal
String str2 = new String("Hello");
System.out.println("str2: " + str2); // "Hello"
// From character array
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(chars);
System.out.println("str3: " + str3); // "Hello"
// From partial character array
String str4 = new String(chars, 1, 3);
System.out.println("str4: " + str4); // "ell"
// From byte array
byte[] bytes = {72, 101, 108, 108, 111};
String str5 = new String(bytes);
System.out.println("str5: " + str5); // "Hello"
// From partial byte array
String str6 = new String(bytes, 1, 3);
System.out.println("str6: " + str6); // "ell"
// From StringBuffer
StringBuffer buffer = new StringBuffer("Hello");
String str7 = new String(buffer);
System.out.println("str7: " + str7); // "Hello"
// From StringBuilder
StringBuilder builder = new StringBuilder("Hello");
String str8 = new String(builder);
System.out.println("str8: " + str8); // "Hello"
}
}
Length of String
In Java, the length of a string can be determined using the length() method provided by
the String class. This method returns the number of characters in the string. Here's a detailed
explanation with examples:
length() Method
The length() method is used to find the number of characters in a string.
It returns an int value representing the length of the string.
Syntax:
int length = stringName.length();
Key Points:
1. The length() method counts all characters, including spaces and special characters.
2. For an empty string (""), the length is 0.
3. The length() method is different from the length property of arrays (e.g., array.length),
which is used to find the size of an array.
Examples:
1. Basic Usage
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
int length = str.length();
System.out.println("Length of the string: " + length); // Output: 13
}
}
2. Empty String
public class Main {
public static void main(String[] args) {
String str = "";
int length = str.length();
System.out.println("Length of the string: " + length); // Output: 0
}
}
3. String with Spaces and Special Characters
public class Main {
public static void main(String[] args) {
String str = "Java @ 2023!";
int length = str.length();
System.out.println("Length of the string: " + length); // Output: 12
}
}
4. Using length() in Conditions
public class Main {
public static void main(String[] args) {
String str = "Hello";
if (str.length() > 0) {
System.out.println("The string is not empty.");
} else {
System.out.println("The string is empty.");
}
// Output: The string is not empty.
}
}
5. Iterating Through a String Using length()
public class Main {
public static void main(String[] args) {
String str = "Hello";
for (int i = 0; i < str.length(); i++) {
System.out.println("Character at index " + i + ": " + str.charAt(i));
}
}
}
Output:
Copy
Character at index 0: H
Character at index 1: e
Character at index 2: l
Character at index 3: l
Character at index 4: o
Common Mistakes:
1. Using length instead of length():
o For strings, you must use length() (a method), not length (a property of
arrays).
o Example:
java
Copy
String str = "Hello";
int len = str.length(); // Correct
// int len = str.length; // Incorrect (compilation error)
2. Null Strings:
o If the string is null, calling length() will throw a NullPointerException.
o Example:
String str = null;
int len = str.length(); // Throws NullPointerException
Handling Null Strings
To avoid NullPointerException, always check if the string is null before calling length():
public class Main {
public static void main(String[] args) {
String str = null;
if (str != null) {
System.out.println("Length: " + str.length());
} else {
System.out.println("The string is null.");
}
// Output: The string is null.
}
}
Comparison with Arrays
For arrays, use the length property:
int[] numbers = {1, 2, 3, 4, 5};
int arrayLength = numbers.length; // 5
For strings, use the length() method:
String str = "Hello";
int stringLength = str.length(); // 5
Summary Table:
Feature String (length()) Array (length)
Type Method Property
Usage str.length() array.length
Returns Number of characters in the string Number of elements in the array
Example "Hello".length() → 5 int[] arr = {1, 2, 3}; arr.length → 3
Special String operations
n Java, the String class provides a variety of special operations for manipulating and
working with strings. These operations include concatenation, substring extraction, trimming,
splitting, and more. Below is a detailed explanation of these special string operations, along
with examples:
1. Concatenation
Combines two or more strings into a single string.
Methods:
o Using the + operator.
o Using the concat() method.
Examples:
String str1 = "Hello";
String str2 = "World";
// Using + operator
String result1 = str1 + " " + str2; // "Hello World"
// Using concat() method
String result2 = str1.concat(" ").concat(str2); // "Hello World"
System.out.println(result1);
System.out.println(result2);
2. Substring Extraction
Extracts a portion of a string.
Methods:
o substring(int startIndex): Extracts from startIndex to the end.
o substring(int startIndex, int endIndex): Extracts from startIndex to endIndex -
1.
Examples:
String str = "Hello, World!";
// Extract from index 7 to the end
String sub1 = str.substring(7); // "World!"
// Extract from index 7 to 12 (exclusive)
String sub2 = str.substring(7, 12); // "World"
System.out.println(sub1);
System.out.println(sub2);
3. Trimming Whitespace
Removes leading and trailing whitespace from a string.
Method: trim()
Example:
String str = " Hello, World! ";
String trimmed = str.trim(); // "Hello, World!"
System.out.println(trimmed);
4. Splitting Strings
Splits a string into an array of substrings based on a delimiter (regex).
Method: split(String regex)
Example:
String str = "apple,banana,orange";
String[] fruits = str.split(","); // Splits by comma
for (String fruit : fruits) {
System.out.println(fruit);
}
Output:
apple
banana
orange
5. Replacing Characters or Substrings
Replaces occurrences of a character or substring with another character or substring.
Methods:
o replace(char oldChar, char newChar)
o replace(CharSequence target, CharSequence replacement)
Examples
String str = "Hello, World!";
// Replace 'o' with 'a'
String newStr1 = str.replace('o', 'a'); // "Hella, Warld!"
// Replace "World" with "Java"
String newStr2 = str.replace("World", "Java"); // "Hello, Java!"
System.out.println(newStr1);
System.out.println(newStr2);
6. Changing Case
Converts a string to uppercase or lowercase.
Methods:
o toUpperCase()
o toLowerCase()
Examples:
String str = "Hello, World!";
// Convert to uppercase
String upper = str.toUpperCase(); // "HELLO, WORLD!"
// Convert to lowercase
String lower = str.toLowerCase(); // "hello, world!"
System.out.println(upper);
System.out.println(lower);
7. Checking Prefix and Suffix
Checks if a string starts or ends with a specific substring.
Methods:
o startsWith(String prefix)
o endsWith(String suffix)
Examples:
String str = "Hello, World!";
// Check prefix
boolean startsWithHello = str.startsWith("Hello"); // true
// Check suffix
boolean endsWithWorld = str.endsWith("World!"); // true
System.out.println(startsWithHello);
System.out.println(endsWithWorld);
8. Finding Index of a Character or Substring
Finds the index of the first or last occurrence of a character or substring.
Methods:
o indexOf(int ch) or indexOf(String str)
o lastIndexOf(int ch) or lastIndexOf(String str)
Examples:
String str = "Hello, World!";
// Find first occurrence of 'o'
int firstIndex = str.indexOf('o'); // 4
// Find last occurrence of 'o'
int lastIndex = str.lastIndexOf('o'); // 8
System.out.println(firstIndex);
System.out.println(lastIndex);
9. Checking if a String Contains a Substring
Checks if a string contains a specific substring.
Method: contains(CharSequence sequence)
Example:
String str = "Hello, World!";
boolean containsWorld = str.contains("World"); // true
System.out.println(containsWorld);
10. Joining Strings
Joins multiple strings with a delimiter.
Method: String.join(CharSequence delimiter, CharSequence... elements)
Example:
String[] words = {"Hello", "World", "Java"};
String joined = String.join(" ", words); // "Hello World Java"
System.out.println(joined);
11. Repeating a String
Repeats a string a specified number of times.
Method: repeat(int count) (introduced in Java 11)
Example:
String str = "Hello";
String repeated = str.repeat(3); // "HelloHelloHello"
System.out.println(repeated);
12. Comparing Strings
Compares two strings lexicographically.
Methods:
o compareTo(String anotherString)
o compareToIgnoreCase(String anotherString)
Examples
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2); // Negative value (apple < banana)
System.out.println(result);
Summary Table:
Operation Method/Operator Description
Concatenation +, concat() Combines strings.
Substring substring() Extracts a portion of a string.
Removes leading and trailing
Trimming trim()
whitespace.
Splits a string into an array based
Splitting split()
on a delimiter.
Replacing replace(), replaceAll() Replaces characters or substrings.
Converts a string to uppercase or
Case Conversion toUpperCase(), toLowerCase()
lowercase.
Prefix/Suffix Checks if a string starts or ends
startsWith(), endsWith()
Check with a specific substring.
Finds the index of a character or
Index Finding indexOf(), lastIndexOf()
substring.
Operation Method/Operator Description
Checks if a string contains a
Contains Check contains()
substring.
Joins multiple strings with a
Joining Strings String.join()
delimiter.
Repeating Repeats a string a specified number
repeat()
Strings of times.
compareTo(), compareToIgnoreCase(
Comparison Compares strings lexicographically.
)
Data Conversion in String
In Java, data conversion in strings refers to converting data types like int, float, double, etc.,
to String and vice versa. Java provides various methods for converting between different data
types and strings, allowing you to represent primitive data types or objects as strings and
convert strings to primitive data types.
1. Converting Other Data Types to String
There are multiple ways to convert other data types to a string in Java.
a. Using String.valueOf()
String.valueOf() is the most commonly used method for converting primitive data types (like
int, float, double, etc.) or objects to strings.
int num = 10;
String str = String.valueOf(num); // Converts int to String
System.out.println(str); // Output: "10"
boolean flag = true;
String boolStr = String.valueOf(flag); // Converts boolean to String
System.out.println(boolStr); // Output: "true"
b. Using String Constructor
You can also use the String constructor to convert primitive data types to a string.
int num = 100;
String str = new String(String.valueOf(num)); // Another way to convert int to String
System.out.println(str); // Output: "100"
c. Using + Operator
In Java, when you concatenate a primitive data type (like an integer) with a string using the +
operator, the primitive type is automatically converted to a string.
int num = 25;
String str = num + ""; // Concatenate with an empty string to convert int to String
System.out.println(str); // Output: "25"
2. Converting String to Other Data Types
To convert a String to a different data type (such as int, double, etc.), you typically use
wrapper class methods like Integer.parseInt(), Double.parseDouble(), etc.
a. Converting String to int
You can use Integer.parseInt() to convert a string to an integer
String str = "123";
int num = Integer.parseInt(str); // Converts String to int
System.out.println(num); // Output: 123
b. Converting String to double
You can use Double.parseDouble() to convert a string to a double.
String str = "12.34";
double num = Double.parseDouble(str); // Converts String to double
System.out.println(num); // Output: 12.34
c. Converting String to float
Use Float.parseFloat() to convert a string to a float.
String str = "12.34";
float num = Float.parseFloat(str); // Converts String to float
System.out.println(num); // Output: 12.34
d. Converting String to boolean
You can use Boolean.parseBoolean() to convert a string to a Boolean.
String str = "true";
boolean boolVal = Boolean.parseBoolean(str); // Converts String to boolean
System.out.println(boolVal); // Output: true
e. Converting String to long
You can use Long.parseLong() to convert a string to a long.
String str = "10000000000";
long num = Long.parseLong(str); // Converts String to long
System.out.println(num); // Output: 10000000000
f. Converting String to char
If you need to convert a string to a single character, you can use the charAt() method.
String str = "Hello";
char ch = str.charAt(0); // Extracts the first character of the string
System.out.println(ch); // Output: 'H'
3. Converting String to Date
To convert a string to a Date object, you can use SimpleDateFormat to parse the string into a
date.
import java.text.SimpleDateFormat;
import java.util.Date;
String str = "2025-02-19";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(str);
System.out.println(date); // Output: Wed Feb 19 00:00:00 GMT 2025
Note: The parse() method can throw a ParseException, so it needs to be handled with a try-
catch block.
4. Converting String to Other Objects
You can convert a string to any other object type by parsing or using specific parsing
methods for that object type. For instance, if you're dealing with a custom object, you may
need to implement a custom parsing method.
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
// Custom method to convert a String to a Person object
public static Person fromString(String str) {
String[] parts = str.split(",");
String name = parts[0].split(":")[1].trim();
int age = Integer.parseInt(parts[1].split(":")[1].trim());
return new Person(name, age);
}
}
String str = "Name: John, Age: 25";
Person p = Person.fromString(str);
System.out.println(p); // Output: Name: John, Age: 25
5. String Conversion and Formatting
Sometimes, you might want to format numbers or dates as strings using String.format() or
System.out.printf().
double pi = 3.14159;
String formatted = String.format("%.2f", pi); // Formats pi to 2 decimal places
System.out.println(formatted); // Output: 3.14
6. Common String Conversion Methods
Here are some additional common methods used for string conversion in Java:
toString(): Converts an object to a string
Integer num = 100;
String str = num.toString(); // Converts Integer to String
System.out.println(str); // Output: "100"
String.format(): Formats a string using placeholders.
double pi = 3.14159;
String formatted = String.format("Value of Pi: %.2f", pi); // Format to 2 decimal
places
System.out.println(formatted); // Output: "Value of Pi: 3.14"
String Buffer
In Java, the StringBuffer class is used to create mutable (modifiable) sequences of
characters. Unlike the String class, which is immutable, StringBuffer allows you to modify
the content of the string without creating a new object each time. This
makes StringBuffer more efficient for situations where frequent modifications to the string
are required.
Key Features of StringBuffer:
1. Mutable: The content of a StringBuffer can be changed after it is created.
2. Thread-Safe: All methods in StringBuffer are synchronized, making it thread-safe.
3. Efficient for Frequent Modifications: Ideal for scenarios where the string is
modified repeatedly.
Common Methods of StringBuffer
1. Constructors
StringBuffer(): Creates an empty StringBuffer with an initial capacity of 16
characters.
StringBuffer sb = new StringBuffer();
StringBuffer(int capacity): Creates an empty StringBuffer with the specified initial
capacity.
StringBuffer sb = new StringBuffer(100);
StringBuffer(String str): Creates a StringBuffer initialized with the specified string.
StringBuffer sb = new StringBuffer("Hello");
2. Appending Data
append(): Adds data to the end of the StringBuffer.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // "Hello World"
sb.append(123); // "Hello World123"
3. Inserting Data
insert(): Inserts data at a specified position.
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World"); // "Hello World"
sb.insert(0, 123); // "123Hello World"
4. Deleting Data
delete(int start, int end): Removes characters from start to end - 1.
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11); // "Hello"
deleteCharAt(int index): Removes the character at the specified index.
StringBuffer sb = new StringBuffer("Hello");
sb.deleteCharAt(1); // "Hllo"
5. Replacing Data
replace(int start, int end, String str): Replaces characters from start to end - 1 with
the specified string.
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java"); // "Hello Java"
6. Reversing the String
reverse(): Reverses the characters in the StringBuffer.
StringBuffer sb = new StringBuffer("Hello");
sb.reverse(); // "olleH"
7. Getting the Length and Capacity
length(): Returns the number of characters in the StringBuffer.
StringBuffer sb = new StringBuffer("Hello");
int len = sb.length(); // 5
capacity(): Returns the current capacity of the StringBuffer.
StringBuffer sb = new StringBuffer("Hello");
int cap = sb.capacity(); // 21 (default capacity is 16 + length of "Hello")
8. Setting the Length
setLength(int newLength): Sets the length of the StringBuffer. If the new length is
less than the current length, the string is truncated. If it is greater, null characters (\
u0000) are added.
StringBuffer sb = new StringBuffer("Hello");
sb.setLength(3); // "Hel"
sb.setLength(10); // "Hel " (padded with null characters)
9. Converting to a String
toString(): Converts the StringBuffer to a String.
StringBuffer sb = new StringBuffer("Hello");
String str = sb.toString(); // "Hello"
Example: Using StringBuffer
public class Main {
public static void main(String[] args) {
// Create a StringBuffer
StringBuffer sb = new StringBuffer("Hello");
// Append data
sb.append(" World"); // "Hello World"
// Insert data
sb.insert(5, ","); // "Hello, World"
// Replace data
sb.replace(7, 12, "Java"); // "Hello, Java"
// Delete data
sb.delete(5, 7); // "HelloJava"
// Reverse the string
sb.reverse(); // "avaJolleH"
// Convert to String
String result = sb.toString();
System.out.println(result); // Output: "avaJolleH"
}
}
When to Use StringBuffer
Use StringBuffer when you need to perform frequent modifications to a string in
a multi-threaded environment.
If thread safety is not a concern, prefer StringBuilder for better performance.