Banner_Ads

Interview Question-Answers | Tutorial For Beginners


tech4allsa2z:This blog provides you tutorial and most common Interview questions for beginners related to the following technology like java, python.

Important Java String methods



String Question And Answers

String Functions: It is used for manipulating the String.

List of commonly used String methods in Java along with examples:

1.length (): Returns the length of the string.

String str = "Hello, World!";

int length = str.length(); // length is 13

 

2.charAt(int index): Returns the character at the specified index.

char ch = str.charAt(7); // ch is 'W'

 

3.substring(int beginIndex): Returns a substring starting from the specified index.

String sub = str.substring(7); // sub is "World!"

 

 

4.substring(int beginIndex, int endIndex): Returns a substring within the specified range of indices.

String sub2 = str.substring(7, 12); // sub2 is "World"

 

5.indexOf(String str): Returns the index of the first occurrence of the specified substring.

int index = str.indexOf("World"); // index is 7

 

6.lastIndexOf(String str): Returns the index of the last occurrence of the specified substring.

int lastIndex = str.lastIndexOf("o"); // lastIndex is 8

 

 

7.toLowerCase(): Converts the string to lowercase.

String lowerCaseStr = str.toLowerCase(); // lowerCaseStr is "hello, world!"

 

8.toUpperCase(): Converts the string to uppercase.

String upperCaseStr = str.toUpperCase(); // upperCaseStr is "HELLO, WORLD!"

 

9.replace(char oldChar, char newChar): Replaces all occurrences of a specified character with another character.

String replacedStr = str.replace('l', 'z'); // replacedStr is "Hezzo, Worzd!"

 

10.replaceAll(String regex, String replacement): Replaces all occurrences of a specified regex pattern with another string.

String regexReplacedStr = str.replaceAll("[, ]", "-"); // regexReplacedStr is "Hello-World!"

 

11.startsWith(String prefix): Checks if the string starts with the specified prefix.

boolean startsWithHello = str.startsWith("Hello"); // true

 

12.endsWith(String suffix): Checks if the string ends with the specified suffix.

boolean endsWithExclamation = str.endsWith("!"); // true

 

13.trim(): Removes leading and trailing whitespace from the string.

String spacedStr = "   Hello   ";

String trimmedStr = spacedStr.trim(); // trimmedStr is "Hello"

 

14.split(String regex): Splits the string into an array of substrings based on a regex pattern.

String[] splitStr = str.split(", "); // splitStr is ["Hello", "World!"]

 

15.isEmpty(): Checks if the string is empty.

boolean empty = str.isEmpty(); // false

 

 

 


Post a Comment

0 Comments