Java String Class Methods

Java String Class Methods

Java String Class Methods

Java String Class Methods:

The java.lang.String class in Java provides a wide range of methods to work with Strings. Here are some of the most commonly used methods:

  1. length(): Returns the length of the String.
				
					String str = "Hello";
int length = str.length(); // returns 5

				
			
  1. charAt(): Returns the character at the specified index.
				
					String str = "Hello";
char c = str.charAt(1); // returns 'e'

				
			
  1. substring(): Returns a substring of the String.
				
					String str = "Hello, World!";
String subStr = str.substring(7); // returns "World!"

				
			
  1. concat(): Concatenates two Strings.
				
					String str1 = "Hello";
String str2 = "World";
String concatStr = str1.concat(str2); // returns "HelloWorld"

				
			
  1. indexOf(): Returns the index of the first occurrence of a character or substring.
				
					String str = "Hello, World!";
int index = str.indexOf("World"); // returns 7

				
			
  1. startsWith() and endsWith(): Returns true if the String starts or ends with the specified prefix or suffix.
				
					String str = "Hello, World!";
booleanstartsWith = str.startsWith("Hello"); // returns true
booleanendsWith = str.endsWith("World!"); // returns true

				
			
  1. toLowerCase() and toUpperCase(): Converts the String to lowercase or uppercase.
				
					String str = "Hello, World!";
String lowerStr = str.toLowerCase(); // returns "hello, world!"
String upperStr = str.toUpperCase(); // returns "HELLO, WORLD!"

				
			
  1. trim(): Removes leading and trailing whitespace from the String.
				
					String str = "  Hello, World!  ";
String trimStr = str.trim(); // returns "Hello, World!"

				
			
  1. replace(): Replaces all occurrences of a character or substring with another character or substring.
				
					String str = "Hello, World!";
String replaceStr = str.replace("o", "e"); // returns "Helle, Werld!"

				
			

These are just a few examples of the many methods available in the String class. By using these methods, you can manipulate and process Strings in a variety of ways in your Java programs.

Spread the love