In the world of programming, strings are fundamental data types used extensively for storing and manipulating text. In Java, the String class provides a rich set of methods to perform various operations on string data. Understanding these methods is crucial for any developer working with Java, as they allow you to manipulate text efficiently and effectively.
In this tutorial, we will explore the most commonly used String methods in Java, providing examples and explanations for each. Whether you're a beginner or an experienced developer, this guide will equip you with the knowledge needed to handle strings more proficiently.
The length() method returns the number of characters in a string.
1public class LengthExample {2public static void main(String[] args) {3String str = "Hello, World!";4int length = str.length();5System.out.println("Length of the string: " + length);6};7}
Length of the string: 13
The charAt(int index) method returns the character at the specified index in a string.
1public class CharAtExample {2public static void main(String[] args) {3String str = "Hello, World!";4char ch = str.charAt(7);5System.out.println("Character at index 7: " + ch);6}7}
Character at index 7: W
The concat(String str) method concatenates the specified string to the end of this string.
1public class ConcatExample {2public static void main(String[] args) {3String str1 = "Hello";4String str2 = " World!";5String result = str1.concat(str2);6System.out.println("Concatenated string: " + result);7}8}
Concatenated string: Hello World!
The + operator can also be used to concatenate strings.
1public class PlusOperatorExample {2public static void main(String[] args) {3String str1 = "Hello";4String str2 = " World!";5String result = str1 + str2;6System.out.println("Concatenated string: " + result);7}8}
Concatenated string: Hello World!
The substring(int beginIndex) method returns a new string that is a substring of this string.
1public class SubstringExample {2public static void main(String[] args) {3String str = "Hello, World!";4String subStr = str.substring(7);5System.out.println("Substring from index 7: " + subStr);6}7}
Substring from index 7: World!
The substring(int beginIndex, int endIndex) method returns a new string that is a substring of this string.
1public class SubstringRangeExample {2public static void main(String[] args) {3String str = "Hello, World!";4String subStr = str.substring(0, 5);5System.out.println("Substring from index 0 to 5: " + subStr);6}7}
Substring from index 0 to 5: Hello
The equals(Object anObject) method compares this string to the specified object.
1public class EqualsExample {2public static void main(String[] args) {3String str1 = "Hello";4String str2 = "Hello";5boolean isEqual = str1.equals(str2);6System.out.println("Are the strings equal? " + isEqual);7}8}
Are the strings equal? true
The compareTo(String anotherString) method compares two strings lexicographically.
1public class CompareToExample {2public static void main(String[] args) {3String str1 = "Apple";4String str2 = "Banana";5int result = str1.compareTo(str2);6System.out.println("Comparison result: " + result);7}8}
Comparison result: -1
The toUpperCase() method converts all the characters in this string to uppercase.
1public class ToUpperCaseExample {2public static void main(String[] args) {3String str = "Hello, World!";4String upperCaseStr = str.toUpperCase();5System.out.println("Uppercase string: " + upperCaseStr);6}7}
Uppercase string: HELLO, WORLD!
The toLowerCase() method converts all the characters in this string to lowercase.
1public class ToLowerCaseExample {2public static void main(String[] args) {3String str = "Hello, World!";4String lowerCaseStr = str.toLowerCase();5System.out.println("Lowercase string: " + lowerCaseStr);6}7}
Lowercase string: hello, world!
The trim() method removes leading and trailing whitespace from this string.
1public class TrimExample {2public static void main(String[] args) {3String str = " Hello, World! ";4String trimmedStr = str.trim();5System.out.println("Trimmed string: '" + trimmedStr + "'");6}7}
Trimmed string: 'Hello, World!'
The replace(char oldChar, char newChar) method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
1public class ReplaceExample {2public static void main(String[] args) {3String str = "Hello, World!";4String replacedStr = str.replace('o', 'a');5System.out.println("Replaced string: " + replacedStr);6}7}
Replaced string: Hella, Warld!
The replace(CharSequence target, CharSequence replacement) method returns a new string resulting from replacing all occurrences of the literal target sequence in this string with the specified literal replacement.
1public class ReplaceSequenceExample {2public static void main(String[] args) {3String str = "Hello, World!";4String replacedStr = str.replace("World", "Java");5System.out.println("Replaced string: " + replacedStr);6}7}
Replaced string: Hello, Java!
The split(String regex) method splits this string around matches of the given regular expression.
1public class SplitExample {2public static void main(String[] args) {3String str = "Hello,World,This,Is,Java";4String[] parts = str.split(",");5for (String part : parts) {6System.out.println(part);7}8}9}
Hello World This Is Java
Let's create a practical example that demonstrates the use of several string methods to process user input.
1import java.util.Scanner;23public class StringManipulationExample {4public static void main(String[] args) {5Scanner scanner = new Scanner(System.in);6System.out.println("Enter a sentence:");7String input = scanner.nextLine();89// Length of the string10int length = input.length();11System.out.println("Length of the input: " + length);1213// Convert to uppercase and lowercase14String upperCaseInput = input.toUpperCase();15String lowerCaseInput = input.toLowerCase();16System.out.println("Uppercase: " + upperCaseInput);17System.out.println("Lowercase: " + lowerCaseInput);1819// Trim whitespace20String trimmedInput = input.trim();21System.out.println("Trimmed Input: '" + trimmedInput + "'");2223// Replace a character24String replacedInput = input.replace('a', 'e');25System.out.println("Replaced 'a' with 'e': " + replacedInput);2627// Split the string into words28String[] words = input.split("s+");29System.out.println("Words in the sentence:");30for (String word : words) {31System.out.println(word);32}3334scanner.close();35}36}
| Method | Description |
|---|---|
length() | Returns the length of the string. |
charAt(int index) | Returns the character at the specified index. |
concat(String str) | Concatenates the specified string to this string. |
substring(int beginIndex) | Returns a substring from the specified index. |
equals(Object anObject) | Compares this string with the specified object. |
compareTo(String anotherString) | Compares two strings lexicographically. |
toUpperCase() | Converts all characters to uppercase. |
toLowerCase() | Converts all characters to lowercase. |
trim() | Removes leading and trailing whitespace. |
replace(char oldChar, char newChar) | Replaces occurrences of a character. |
split(String regex) | Splits the string around matches of a regular expression. |
In the next tutorial, we will explore Java Math Methods, which provide various mathematical operations and functions. These methods are essential for performing calculations in your Java programs. Stay tuned!