Strings in Java
String in Java || String Methods in Java With proper Explanation
The String
class in Java provides several methods that allow you to work with strings. Some of the most commonly used methods are:
length()
: Returns the length of the string (i.e., the number of characters in the string)charAt(int index)
: Returns the character at the specified index in the stringsubstring(int beginIndex, int endIndex)
: Returns a new string that is a substring of this string. The substring begins at the specifiedbeginIndex
and extends to the character at indexendIndex - 1
.indexOf(String str)
: Returns the index within this string of the first occurrence of the specified substring.toLowerCase()
: Converts all of the characters in this string to lower casetoUpperCase()
: Converts all of the characters in this string to upper casetrim()
: Returns a new string with leading and trailing white space omittedreplace(char oldChar, char newChar)
: Returns a new string resulting from replacing all occurrences ofoldChar
withnewChar
split(String regex)
: Splits this string around matches of the given regular expressionequals(Object anObject)
: Compares this string to the specified object. The result istrue
if and only if the argument is notnull
and is aString
object that represents the same sequence of characters as this object.
These are just some of the many methods provided by the String
class in Java. For a complete list of all the methods available, you can refer to the official Java documentation.
Example :
Part-1 :
// Import the String class from the java.lang package
import java.lang.String;
public class Main {
public static void main(String[] args) {
// Create a new String object with the value "Hello, World!"
// Time complexity: O(1)
String str = new String("Hello, World!");
// Print the length of the String
// Time complexity: O(1)
System.out.println(str.length());
// Print the first character of the String
// Time complexity: O(1)
System.out.println(str.charAt(0));
// Print the last character of the String
// Time complexity: O(1)
System.out.println(str.charAt(str.length() - 1));
// Concatenate the String with another String
// Time complexity: O(1)
String str2 = str.concat(" This is a test.");
System.out.println(str2);
}
}
In this code, we import the
String
class from thejava.lang
package, and then create a newString
object with the value "Hello, World!". We then use various methods of theString
class to manipulate the string, such aslength()
to get the length of the string,charAt()
to get the character at a specific index, andconcat()
to concatenate two strings together.
The time complexity of the operations performed on the String
object are all O(1), since they only involve a constant number of operations. The space complexity is also O(1), since the String
object only requires a constant amount of space to store its value.
Part-2:
// Import the String class from the java.lang package
import java.lang.String;
public class Main {
public static void main(String[] args) {
// Create a new String object with the value "Hello, World!"
String str = new String("Hello, World!");
// Check if the String starts with a given prefix
// Time complexity: O(m), where m is the length of the prefix
System.out.println(str.startsWith("Hello")); // true
System.out.println(str.startsWith("World")); // false
// Check if the String ends with a given suffix
// Time complexity: O(m), where m is the length of the suffix
System.out.println(str.endsWith("World!")); // true
System.out.println(str.endsWith("Hello")); // false
// Check if the String contains a given substring
// Time complexity: O(n * m), where n is the length of the String and m is the length of the substring
System.out.println(str.contains("Hello")); // true
System.out.println(str.contains("World")); // true
System.out.println(str.contains("Foo")); // false
// Replace a substring with another string
// Time complexity: O(n * m), where n is the length of the String and m is the length of the substring
String str2 = str.replace("World", "Foo");
System.out.println(str2); // "Hello, Foo!"
// Convert the String to lowercase
// Time complexity: O(n), where n is the length of the String
String str3 = str.toLowerCase();
System.out.println(str3); // "hello, world!"
// Convert the String to uppercase
// Time complexity: O(n), where n is the length of the String
String str4 = str.toUpperCase();
System.out.println(str4); // "HELLO, WORLD!"
// Split the String into an array of substrings, using a given delimiter
// Time complexity: O(n), where n is the length of the String
String[] words = str.split(",");
System.out.println(Arrays.toString(words)); // ["Hello", " World!"]
}
}
This code demonstrates how to use various methods of the
String
class to manipulate strings. These methods includestartsWith()
andendsWith()
to check if a string starts or ends with a given prefix or suffix,contains()
to check if a string contains a given substring,replace()
to replace a substring with another string,toLowerCase()
andtoUpperCase()
to convert the string to lowercase or uppercase, andsplit()
to split the string into an array of substrings using a given delimiter.
The time complexity of these operations depends on the length of the input string and, in some cases, the length of the substring or delimiter. In general, the time complexity ranges from O(1) for operations that only involve
Part-3 :
// Import the String class from the java.lang package
import java.lang.String;
public class Main {
public static void main(String[] args) {
// Create a new String object with the value "Hello, World!"
String str = new String("Hello, World!");
// Check if the String is empty
// Time complexity: O(1)
System.out.println(str.isEmpty()); // false
// Check if the String is blank (contains only whitespace characters)
// Time complexity: O(n), where n is the length of the String
System.out.println(str.trim().isEmpty()); // false
// Check if the String contains only digits
// Time complexity: O(n), where n is the length of the String
System.out.println(str.matches("\\d+")); // false
// Check if the String contains only letters
// Time complexity: O(n), where n is the length of the String
System.out.println(str.matches("[a-zA-Z]+")); // false
// Check if the String contains only letters and digits
// Time complexity: O(n), where n is the length of the String
System.out.println(str.matches("[a-zA-Z\\d]+")); // false
// Check if the String contains only alphanumeric characters
// Time complexity: O(n), where n is the length of the String
System.out.println(str.matches("[\\w]+")); // true
// Trim the whitespace characters from the beginning and end of the String
// Time complexity: O(n), where n is the length of the String
String str2 = str.trim();
System.out.println(str2); // "Hello, World!"
// Reverse the String
// Time complexity: O(n), where n is the length of the String
StringBuilder sb = new StringBuilder(str);
String str3 = sb.reverse().toString();
System.out.println(str3); // "!dlroW ,olleH"
}
}
This code demonstrates how to use various methods of the
String
class to check the contents of a string, trim whitespace characters, and reverse the string. These methods includeisEmpty()
to check if the string is empty,trim()
to remove leading and trailing whitespace characters,matches()
to check if the string matches a given regular expression, andreverse()
to reverse the string.
The time complexity of these operations depends on the length of the input string. In general, the time complexity ranges from O(1) for operations that only involve a constant number of operations, to O(n) for operations that involve iterating over the entire string. The space complexity is also O(n), since the StringBuilder
class used to reverse the string requires O(n) space to store the reversed string.
We are goanna learn StringBuilder in Separate Note/Page. [[StringBuilder in Java]]