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 newString
object with the value"Hello, World!"
. - You can access individual characters in a
String
using thecharAt()
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 returnstrue
if the two strings have the same characters in the same order, andfalse
otherwise:"Hello".equals("Hello")
will returntrue
, while"Hello".equals("World")
will returnfalse
. - You can convert a
String
object to an array of characters using thetoCharArray()
method:"Hello".toCharArray()
will return an array of characters{'H', 'e', 'l', 'l', 'o'}
. - You can search for a substring within a
String
using theindexOf()
method, which returns the index of the first occurrence