In the world of programming, understanding how to work with text is crucial. In this guide, we will explore the java Strings - What they are What is String, how to use it, its method with an example.
What is String?
In Java, a String is a sequence of characters. The String class provides methods to manipulate these characters, like concatenating two strings, converting characters to uppercase, and so on.
Key Features of String:
Immutability: Strings are immutable in Java, meaning once created, they cannot be changed. Any modification to a string results in a new object, leaving the original string unaltered.
String pool: Java uses a special memory area known as the string pool to store string literals . This helps in saving memory, as multiple reference to the same string literally point to the same object in the pool.
String Creation: Strings can be created using either string literals or the new keyword. Creating strings literals promotes reusing existing objects from the String pool, where as the new keyword forces the new object creation.
Example:
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "selinium";
String third = "JavaScript";
// print strings
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
Output:
Java
selinium
JavaScript
Concatenation: Strings can be concatenated using the + operator or the concat() method. Concatenation creates a new string object since strings are immutable.
Comparison: Strings can be compared using the equals() method for content comparison or == for reference comparison. The equalsIgnoreCase() method can be used for case-insensitive content comparisons.
Case Handling: Methods like toLowercase() and toUpperCase() allow conversion between different cases.
Substring & Character Access: substring(), charAt(). and indexOf() it helps in accessing specific parts or characters of a string.
Trimming & Replacing: trim() is used to remove leading and trailing whitespace. replace() and repalceAll() help in replacing specific characters or sequences within a string.
Converting to Other Types: Strings can be converted to arrays of characters using toCharArray(). various parsing methods like integer.parseint() can convert a string to numerical types.
Performance Consideration: Since strings are immutable, frequent modifications can lead to performance issues. In scenarios with intense string manipulation, consider using StringBuilder or StringBuffer.
String vs StringBuffer: String is immutable in java whenever we do String manipulation like concatenation, substring . It will generate a new string and discards the older String for garbage collection . In java has provided StringBuffer and StringBuilder classes that should be used for String manipulation. StringBuffer ad StringBuilder are mutable in in java. They provide append(), insert(), delete(), and substring() methods for String manipulation.
String vs StringBuffer vs StringBuilder: String is immutable whereas stringbufferand stringbuilder are mutable classes.
StringBuffer is thread-safe and synchronized where as StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
String concatenation operator + internally uses StringBuffer or StringBuilder class.
Example of StringBuffer in java:
public class exampleofstringbuffer {
// Create a StringBuffer
StringBuffer stringBuffer = new StringBuffer("Hello, ");
// Append to the buffer
stringBuffer.append("World!");
System.out.println("After append: " + stringBuffer);
// Insert text at a specific position
stringBuffer.insert(5, "Java ");
System.out.println("After insert: " + stringBuffer);
// Replace a portion of the text
stringBuffer.replace(6, 10, "Programming");
System.out.println("After replace: " + stringBuffer);
// Delete a portion of the text
stringBuffer.delete(6, 17);
System.out.println("After delete: " + stringBuffer);
// Reverse the text
stringBuffer.reverse();
System.out.println("After reverse: " + stringBuffer);
}
}
Output:
After append: Hello, World!
After insert: HelloJava , World!
After replace: HelloJProgramming, World!
After delete: HelloJ, World!
After reverse: !dlroW ,JolleH
In the above example stringbuffer can be used in building a long string from smaller parts. Instead of using string
concatenation, which creates a new object each time, String buffer can be used to append the smaller parts together into a single mutable string.
Example for String methods:
public class string1 {
public static void main(String[] args) {
// Create a sample string
String str = "Hello, World!";
// Length of the string
int length = str.length();
System.out.println("Length of the string: " + length);
// Character at a specific index
char charAtIndex = str.charAt(7);
System.out.println("Character at index 7: " + charAtIndex);
// Substring
String substring = str.substring(7);
System.out.println("Substring from index 7 to end: " + substring);
// Substring with start and end index
String substringWithRange = str.substring(0, 5);
System.out.println("Substring from index 0 to 4: " + substringWithRange);
// Concatenation
String concatStr = str.concat(" This is a Java program.");
System.out.println("Concatenated string: " + concatStr);
// Replace
String replacedStr = str.replace("World", "Java");
System.out.println("String after replacement: " + replacedStr);
// Uppercase and lowercase
String upperCaseStr = str.toUpperCase();
String lowerCaseStr = str.toLowerCase();
System.out.println("Uppercase string: " + upperCaseStr);
System.out.println("Lowercase string: " + lowerCaseStr);
// Check if a string contains a substring
boolean containsSubstring = str.contains("World");
System.out.println("Contains 'World': " + containsSubstring);
// Split a string into an array
String[] splitArray = str.split(",");
System.out.println("Split string:");
for (String part : splitArray) {
System.out.println(part.trim());
}
// Trim leading and trailing spaces
String stringWithSpaces = " This is a string with spaces. ";
String trimmedStr = stringWithSpaces.trim();
System.out.println("Trimmed string: '" + trimmedStr + "'");
}
}
Output:
Length of the string: 13
Character at index 7: W
Substring from index 7 to end: World!
Substring from index 0 to 4: Hello
Concatenated string: Hello, World! This is a Java program.
String after replacement: Hello, Java!
Uppercase string: HELLO, WORLD!
Lowercase string: hello, world!
Contains 'World': true
Split string:
Hello
World!
Trimmed string: 'This is a string with spaces.'
Thank you for taking time to read my blog, Hope it is helpful for your study.
Comentarios