Day 18: Strings:
String is a class in the java.lang package and is one of the most commonly used classes. A String in Java represents a sequence of characters. It is an immutable object, meaning once a String object is created, its content cannot be changed.
String Creation in Java
1. Using String Literals
When you create a String using double quotes (" "), it is stored in the String Pool.
What is the String Pool?
The String Pool, also known as the String Constant Pool, is a special memory region inside the Heap memory. It is used to store unique string literals and helps to optimize memory usage by reusing string objects.
2. Using the new Keyword
Creates a new object in the heap memory, even if the same value exists in the String Pool.
What is Heap Memory?
The Heap Memory is the general-purpose memory area where Java objects are created using the new keyword. Strings created in the heap are not shared and are treated as independent objects.
Java String Methods in Java
The String class in Java provides a wide range of methods to perform operations on strings, such as comparison, searching, modifying, and splitting. Let's see few commonly used string methods with examples.
1. length()
Returns the number of characters in the string.
2. charAt(int index)
Returns the character at the specified index.
Example:
3. substring(int beginIndex) and substring(int beginIndex, int endIndex)
substring(int beginIndex):Extracts the string from the mentioned index of the string till the End. Index counts starts from 0.
In below example :
System.out.println("Substring (from index 7): " + str.substring(7));
Extracts from 7th Index till end so
领英推荐
Output: World!
substring(int beginIndex, int endIndex): Extracts the string from the mentioned string till the End string mentioned. Index counts starts from 0.
In below example :
System.out.println("Substring (0 to 5): " + str.substring(0, 5));
Extracts from 0 to 5th Index
Output: Hello
4. indexOf(String str) and lastIndexOf(String str)
5. contains(CharSequence s)
Checks if the string contains the specified sequence of characters.
6. equals(Object another) and equalsIgnoreCase(String another)
7. toUpperCase() and toLowerCase()
Converts the string to uppercase or lowercase.
8. trim()
Removes leading and trailing whitespaces.
StringBuffer and StringBuilder
Why?
Since String is immutable, frequent modifications create multiple objects, which is inefficient. To handle this, StringBuffer and StringBuilder are used. Let's discuss more about StringBuffer and StringBuilder tomorrow. Happy Learning :)