The `String` Class in Java

The String class in Java represents a sequence of characters. A String object is immutable, which means that it cannot be modified once it is created.

Here are some of the key features of the String class:

  • A String object is created using a string literal, which is a sequence of characters surrounded by double quotes: "Hello, World!".
  • You can concatenate two strings using the + operator: "Hello, " + "World!" will result in a new String object with the value "Hello, World!".
  • You can access individual characters in a String using the charAt() method, which takes an index as an argument and returns the character at that position: "Hello".charAt(1) will return 'e'.
  • You can compare two strings using the equals() method, which returns true if the two strings have the same characters in the same order, and false otherwise: "Hello".equals("Hello") will return true, while "Hello".equals("World") will return false.
  • You can convert a String object to an array of characters using the toCharArray() method: "Hello".toCharArray() will return an array of characters {'H', 'e', 'l', 'l', 'o'}.
  • You can search for a substring within a String using the indexOf() method, which returns the index of the first occurrence