0% found this document useful (0 votes)
10 views

String Class

The document provides a comprehensive overview of string handling in Java, detailing the String class, its constructors, and various methods for string manipulation, comparison, and modification. It covers topics such as character extraction, string searching, and the StringBuffer class, highlighting key methods and their functionalities with examples. Additionally, it explains data conversion, case manipulation, and additional string methods, emphasizing the immutability of strings in Java.

Uploaded by

Santhosh Sgrao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

String Class

The document provides a comprehensive overview of string handling in Java, detailing the String class, its constructors, and various methods for string manipulation, comparison, and modification. It covers topics such as character extraction, string searching, and the StringBuffer class, highlighting key methods and their functionalities with examples. Additionally, it explains data conversion, case manipulation, and additional string methods, emphasizing the immutability of strings in Java.

Uploaded by

Santhosh Sgrao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Okay, here's a breakdown of String handling in Java, covering all the topics you listed, with

explanations and examples:


I. The String Class
 The String class represents character strings in Java. Strings are immutable, meaning
their values cannot be changed after they are created. Any operation that appears to
modify a string actually creates a new String object.
A. String Constructors
 There are several ways to create String objects:
1. String Literal: The simplest way is to use a string literal enclosed in double
quotes:
2. String str1 = "Hello";

content_copy download
Use code with caution.Java
3. new String() (Empty String): Creates an empty string.
4. String str2 = new String();

content_copy download
Use code with caution.Java
5. new String(String): Creates a new string that is a copy of an existing string.
6. String str3 = new String("World");

content_copy download
Use code with caution.Java
7. new String(char[]): Creates a string from an array of characters.
8. char[] chars = {'J', 'a', 'v', 'a'};
9. String str4 = new String(chars); // str4 will be "Java"

content_copy download
Use code with caution.Java
10. new String(byte[]): Creates a string from an array of bytes. You can also
specify the character encoding.
11. byte[] bytes = {65, 66, 67}; // ASCII values for A, B, C
12. String str5 = new String(bytes); // str5 will be "ABC"
13. String str6 = new String(bytes, "UTF-8"); // Explicitly specify UTF-8
encoding

content_copy download
Use code with caution.Java
14. new String(StringBuffer) or new String(StringBuilder): Creates a string
from a StringBuffer or StringBuilder object.
15. StringBuffer sb = new StringBuffer("StringBuffer Example");
16. String str7 = new String(sb);

content_copy download
Use code with caution.Java
B. String Length
 The length() method returns the number of characters in the string.
 String str = "Example";
 int len = str.length(); // len will be 7
content_copy download
Use code with caution.Java
C. Special String Operations
1. String Literals: Strings enclosed in double quotes are string literals. They are
instances of the String class.
2. String Concatenation:
o The + operator concatenates two strings.
o String str1 = "Hello";
o String str2 = "World";
o String str3 = str1 + " " + str2; // str3 will be "Hello World"

content_copy download
Use code with caution.Java
o You can also use the concat() method (less common).
o String str4 = str1.concat(" ").concat(str2); // str4 will be "Hello World"

content_copy download
Use code with caution.Java
3. String Concatenation with Other Data Types: The + operator automatically
converts other data types to strings and concatenates them.
4. ```java
5. String name = "Alice";
6. int age = 30;
7. String message = "Name: " + name + ", Age: " + age; // message will be "Name:
Alice, Age: 30"
8. ```

content_copy download
Use code with caution.
9. String Conversion and toString():
o Every Java object has a toString() method. This method returns a string
representation of the object. The default implementation in Object returns a
string containing the class name and hash code.
o You can override toString() in your custom classes to provide a more
meaningful string representation.
o class Person {
o String name;
o int age;
o
o public Person(String name, int age) {
o this.name = name;
o this.age = age;
o }
o
o @Override
o public String toString() {
o return "Person[name=" + name + ", age=" + age + "]";
o }
o }
o
o Person person = new Person("Bob", 25);
o String personString = person.toString(); // personString will be
"Person[name=Bob, age=25]"
o System.out.println(person); // Prints the result of person.toString() implicitly

content_copy download
Use code with caution.Java
II. Character Extraction
 The String class provides methods for extracting characters or arrays of characters
from a string.
A. charAt()
 Returns the character at the specified index. The index is zero-based.
 String str = "Java";
 char ch = str.charAt(0); // ch will be 'J'

content_copy download
Use code with caution.Java
B. getChars()
 Copies a range of characters from a string into an array of characters.
 String str = "This is a string";
 char[] dest = new char[5];
 str.getChars(5, 10, dest, 0); // Copies "is a " to dest
 // dest now contains {'i', 's', ' ', 'a', ' '}

content_copy download
Use code with caution.Java
C. getBytes()
 Converts a string into an array of bytes using the platform's default character encoding
(or a specified encoding).
 String str = "ABC";
 byte[] bytes = str.getBytes(); // bytes will contain {65, 66, 67} (ASCII)

 // With Encoding
 byte[] utf8Bytes = str.getBytes("UTF-8"); // specifying encoding

content_copy download
Use code with caution.Java
D. toCharArray()
 Converts a string into a new array of characters.
 String str = "Hello";
 char[] chars = str.toCharArray(); // chars will be {'H', 'e', 'l', 'l', 'o'}

content_copy download
Use code with caution.Java
III. String Comparison
 The String class provides several methods for comparing strings.
A. equals() and equalsIgnoreCase()
 equals() compares two strings for exact equality (case-sensitive).
 equalsIgnoreCase() compares two strings for equality, ignoring case.
 String str1 = "Hello";
 String str2 = "hello";
 boolean isEqual = str1.equals(str2); // isEqual will be false
 boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2); // isEqualIgnoreCase will
be true

content_copy download
Use code with caution.Java
B. regionMatches()
 Compares a specific region within two strings. You can specify whether the
comparison should be case-sensitive or not.
 String str1 = "This is a test";
 String str2 = "a test string";
 boolean areEqual = str1.regionMatches(10, str2, 2, 4); // Compares "test" from both
strings
 // areEqual will be true

 boolean areEqualIgnoreCase = str1.regionMatches(true,10, str2, 2, 4); // Case
insensitive

content_copy download
Use code with caution.Java
C. startsWith() and endsWith()
 startsWith() checks if a string starts with a specified prefix.
 endsWith() checks if a string ends with a specified suffix.
 String str = "filename.txt";
 boolean startsWithFile = str.startsWith("file"); // startsWithFile will be true
 boolean endsWithTxt = str.endsWith(".txt"); // endsWithTxt will be true

content_copy download
Use code with caution.Java
D. equals() Versus ==
 equals() compares the content of two strings.
 == compares the references of two strings (whether they are the same object in
memory).
 Important: Use equals() to compare string content. Use == only to check if two
variables refer to the exact same String object in memory (which is rarely what you
want when comparing strings for equality).
 String str1 = "Hello";
 String str2 = "Hello";
 String str3 = new String("Hello");

 boolean equals1 = str1.equals(str2); // equals1 will be true
 boolean equals2 = str1.equals(str3); // equals2 will be true

 boolean eq1 = (str1 == str2); // eq1 will likely be true (string literals are often
interned)
 boolean eq2 = (str1 == str3); // eq2 will be false (str3 is a new object)

content_copy download
Use code with caution.Java
E. compareTo()
 Compares two strings lexicographically (based on Unicode values).
 Returns:
o 0 if the strings are equal.
o A negative value if the string is lexicographically less than the other string.
o A positive value if the string is lexicographically greater than the other string.
 String str1 = "apple";
 String str2 = "banana";
 int comparison = str1.compareTo(str2); // comparison will be a negative value

content_copy download
Use code with caution.Java
IV. Searching Strings
 The String class provides methods for finding characters or substrings within a string.
A. indexOf()
 Returns the index of the first occurrence of a specified character or substring within a
string.
 Returns -1 if the character or substring is not found.
 String str = "This is a test string";
 int index1 = str.indexOf('i'); // index1 will be 2
 int index2 = str.indexOf("test"); // index2 will be 10
 int index3 = str.indexOf("xyz"); // index3 will be -1

content_copy download
Use code with caution.Java
B. lastIndexOf()
 Returns the index of the last occurrence of a specified character or substring within a
string.
 Returns -1 if the character or substring is not found.
 String str = "This is a test string";
 int index1 = str.lastIndexOf('i'); // index1 will be 18
 int index2 = str.lastIndexOf("string"); // index2 will be 15

content_copy download
Use code with caution.Java
V. Modifying a String
 Since strings are immutable, these methods create and return new String objects.
A. substring()
 Extracts a substring from a string.
 String str = "This is a string";
 String sub1 = str.substring(5); // sub1 will be "is a string"
 String sub2 = str.substring(5, 10); // sub2 will be "is a "

content_copy download
Use code with caution.Java
B. concat()
 Appends one string to the end of another. It's typically more common to use the +
operator for concatenation.
 String str1 = "Hello";
 String str2 = "World";
 String str3 = str1.concat(str2); // str3 will be "HelloWorld"

content_copy download
Use code with caution.Java
C. replace()
 Replaces all occurrences of a character or substring with another character or
substring.
 String str = "This is a test string";
 String replaced1 = str.replace('i', 'x'); // replaced1 will be "Thxs xs a test strxng"
 String replaced2 = str.replace("test", "example"); // replaced2 will be "This is a
example string"

content_copy download
Use code with caution.Java
D. trim()
 Removes leading and trailing whitespace from a string.
 String str = " Hello World ";
 String trimmed = str.trim(); // trimmed will be "Hello World"

content_copy download
Use code with caution.Java
VI. Data Conversion Using valueOf()
 The String.valueOf() methods provide a convenient way to convert various data types
into strings.
 int num = 123;
 double pi = 3.14159;
 boolean flag = true;

 String numStr = String.valueOf(num); // numStr will be "123"
 String piStr = String.valueOf(pi); // piStr will be "3.14159"
 String flagStr = String.valueOf(flag); // flagStr will be "true"

content_copy download
Use code with caution.Java
VII. Changing the Case of Characters Within a String
A. toLowerCase()
 Converts all characters in a string to lowercase.
 String str = "Hello World";
 String lowerCase = str.toLowerCase(); // lowerCase will be "hello world"

content_copy download
Use code with caution.Java
B. toUpperCase()
 Converts all characters in a string to uppercase.
 String str = "Hello World";
 String upperCase = str.toUpperCase(); // upperCase will be "HELLO WORLD"

content_copy download
Use code with caution.Java
VIII. Additional String Methods
 isEmpty(): Returns true if the string has a length of 0, false otherwise.
 split(): Splits a string into an array of strings based on a delimiter.
 String str = "apple,banana,orange";
 String[] fruits = str.split(","); // fruits will be {"apple", "banana", "orange"}

content_copy download
Use code with caution.Java
 join() (Java 8 and later): Joins elements of an array or iterable into a single string with
a specified delimiter.
 String[] words = {"This", "is", "a", "sentence"};
 String sentence = String.join(" ", words); // sentence will be "This is a sentence"

content_copy download
Use code with caution.Java
 format(): Creates a formatted string using a format string and arguments (like printf in
C).
 String name = "Alice";
 int age = 30;
 String formatted = String.format("Name: %s, Age: %d", name, age); // formatted will
be "Name: Alice, Age: 30"

content_copy download
Use code with caution.Java
IX. StringBuffer Class
 The StringBuffer class is a mutable string class. Unlike String, you can modify
StringBuffer objects without creating new objects. StringBuffer is thread-safe
(synchronized).
A. StringBuffer Constructors
1. StringBuffer(): Creates an empty StringBuffer with an initial capacity of 16
characters.
2. StringBuffer(int capacity): Creates an empty StringBuffer with the specified initial
capacity.
3. StringBuffer(String str): Creates a StringBuffer initialized with the contents of the
specified string. The initial capacity is 16 plus the length of the string.
B. length() and capacity()
 length(): Returns the number of characters currently in the StringBuffer.
 capacity(): Returns the total amount of storage space available for characters in the
StringBuffer.
C. ensureCapacity()
 Ensures that the StringBuffer has at least the specified capacity. If the current capacity
is less than the specified capacity, a new, larger buffer is allocated.
D. setLength()
 Sets the length of the StringBuffer.
o If the new length is less than the current length, the StringBuffer is truncated.
o If the new length is greater than the current length, the StringBuffer is padded
with null characters (\u0000).
E. charAt() and setCharAt()
 charAt(): Returns the character at the specified index (same as String).
 setCharAt(): Sets the character at the specified index to a new character.
F. getChars()
 Copies a range of characters from a StringBuffer into an array of characters (same as
String).
G. append()
 Appends various data types (strings, characters, numbers, objects) to the end of the
StringBuffer. Overloaded methods are available for different data types.
H. insert()
 Inserts a string or other data type at the specified index within the StringBuffer.
Overloaded methods exist for various data types.
I. reverse()
 Reverses the order of characters in the StringBuffer.
J. delete() and deleteCharAt()
 delete(): Deletes a range of characters from the StringBuffer.
 deleteCharAt(): Deletes the character at the specified index.
K. replace()
 Replaces a range of characters in the StringBuffer with a specified string.
L. substring()
 Returns a new String object containing a substring of the StringBuffer (same as String
but returns String, not StringBuffer).
M. Additional StringBuffer Methods
 There are not too many other methods besides the ones described above. If you need
more specialized methods consider if StringBuilder meets the need.
X. StringBuilder Class
 The StringBuilder class is another mutable string class that is similar to StringBuffer.
 Key Difference: StringBuilder is not synchronized (not thread-safe).
 Performance: StringBuilder is generally faster than StringBuffer because it doesn't
have the overhead of synchronization.
 When to Use: Use StringBuilder when you are working with strings in a single-
threaded environment and need to perform frequent modifications.
 StringBuilder offers the same methods as StringBuffer (constructors, length(),
capacity(), append(), insert(), delete(), replace(), substring(), reverse(), etc.).
Summary Table
Feature String StringBuffer StringBuilder
Mutability Immutable Mutable Mutable
Thread Safety Thread-safe Thread-safe Not thread-safe
Synchronization No Synchronized No
Performance - Slower (due to sync) Faster
Read-only Multi-threaded string Single-threaded string
Usage
strings manipulation manipulation
By understanding the characteristics and methods of String, StringBuffer, and StringBuilder,
you can effectively handle strings in Java and choose the appropriate class for your specific
needs.

You might also like