Learn Java Basics
About Lesson

A string is a sequence of characters. Strings in Java are represented by the String class, which is part of the Java standard library. Here are some common string manipulation functions in Java:

  1. length(): Returns the length of the string.
  2. charAt(int index): Returns the character at the specified index in the string.
  3. substring(int beginIndex, int endIndex): Returns a new string that is a substring of the original string, starting at beginIndex and ending at endIndex (exclusive).
  4. concat(String str): Concatenates the specified string to the end of the original string.
  5. indexOf(String str): Returns the index of the first occurrence of the specified string within the original string, or -1 if the specified string is not found.
  6. replace(char oldChar, char newChar): Returns a new string where all occurrences of the oldChar character are replaced with the newChar character.

Here’s an example of how to use these functions:

String str = "Hello, world!";
int length = str.length(); // length is 13
char firstChar = str.charAt(0); // firstChar is 'H'
String substr = str.substring(7, 12); // substr is "world"
String newStr = str.concat(" Goodbye!"); // newStr is "Hello, world! Goodbye!"
int index = str.indexOf("world"); // index is 7
String replacedStr = str.replace('o', 'a'); // replacedStr is "Hella, warld!"

I hope that helps! Let me know if you have any further questions.

Join the conversation