What features and string handling methods do you know in Java?
sobes.tech AI
Answer from AI
In Java, strings are represented by the String class, which is immutable. This means that once a string object is created, its contents cannot be changed. When a string is modified, a new object is created.
Main features and methods for working with strings:
-
Creating strings:
String s = "Example"; -
Concatenation: Using the
+operator or theconcat()method.String s1 = "Hello"; String s2 = "World"; String s3 = s1 + " " + s2; // "Hello World" -
String length: The
length()method returns the number of characters. -
Getting a character: The
charAt(int index)method returns the character at the specified index. -
Comparing strings:
equals()— compares content.equalsIgnoreCase()— compares without considering case.compareTo()— lexicographical comparison.
-
Searching for a substring: Methods
indexOf(),lastIndexOf(). -
Extracting a substring: The
substring(int beginIndex, int endIndex)method. -
Changing case: Methods
toLowerCase(),toUpperCase(). -
Removing spaces: The
trim()method removes spaces at the beginning and end. -
Splitting a string: The
split(String regex)method returns an array of substrings.
For frequent modifications of strings, it is recommended to use the StringBuilder or StringBuffer classes, which are mutable and efficient for concatenations in loops.