String handling complete notes
String handling complete notes
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 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"
Key Points:
// 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
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
2. Empty String
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:
Copy
Summary Table:
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
// Using + operator
String result1 = str1 + " " + str2; // "Hello World"
System.out.println(result1);
System.out.println(result2);
2. Substring Extraction
System.out.println(sub1);
System.out.println(sub2);
3. Trimming Whitespace
4. Splitting Strings
System.out.println(newStr1);
System.out.println(newStr2);
6. Changing Case
// 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
// Check prefix
boolean startsWithHello = str.startsWith("Hello"); // true
// Check suffix
boolean endsWithWorld = str.endsWith("World!"); // true
System.out.println(startsWithHello);
System.out.println(endsWithWorld);
System.out.println(firstIndex);
System.out.println(lastIndex);
Summary Table:
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.
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.
You can also use the String constructor to convert primitive data types to a string.
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"
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.
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;
Note: The parse() method can throw a ParseException, so it needs to be handled with a try-
catch block.
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;
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
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
Here are some additional common methods used for string conversion in Java:
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
1. Constructors
2. Appending Data
3. Inserting Data
4. Deleting Data
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"
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
// 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"
// Convert to String
String result = sb.toString();