In Java, a String is a sequence of characters that is used to represent text. Strings in Java are objects of the java.lang.String
class and are immutable, which means that once a String object is created, its value cannot be changed.
Here’s an example of how to create a String object in Java:
String greeting = "Hello, world!";
In this example, we create a new String object called greeting
with the value “Hello, world!” using a string literal. A string literal is a sequence of characters enclosed in double quotes, and it is a shorthand way of creating a String object.
You can also create a String object using the new
keyword:
String name = new String("John");
In this example, we create a new String object called name
with the value “John” using the new
keyword.
Java Strings provide several useful methods for working with text. Here are some commonly used methods:
length()
: returns the length of the string.
String str = "Hello, world!"; int len = str.length(); // len will be 13
charAt(index)
: returns the character at the specified index in the string.
String str = "Hello, world!"; char ch = str.charAt(1); // ch will be 'e'
substring(beginIndex, endIndex)
: returns a new string that is a substring of the original string, starting from beginIndex
and ending at endIndex - 1
.
String str = "Hello, world!"; String substr = str.substring(7, 12); // substr will be "world"
toLowerCase()
: returns a new string with all characters converted to lowercase.
String str = "Hello, world!"; String lowerStr = str.toLowerCase(); // lowerStr will be "hello, world!"
toUpperCase()
: returns a new string with all characters converted to uppercase.
String str = "Hello, world!"; String upperStr = str.toUpperCase(); // upperStr will be "HELLO, WORLD!"
indexOf(str)
: returns the index of the first occurrence of the specified substring str
in the string.
String str = "Hello, world!"; int index = str.indexOf("world"); // index will be 7
replace(oldStr, newStr)
: returns a new string where all occurrences of oldStr
are replaced with newStr
.
String str = "Hello, world!"; String newStr = str.replace("world", "Java"); // newStr will be "Hello, Java!"
Strings in Java can also be concatenated using the +
operator or the concat()
method. Here are some examples:
String firstName = "John"; String lastName = "Doe"; String fullName = firstName + " " + lastName; // fullName will be "John Doe" String greeting = "Hello".concat(" ").concat("world!"); // greeting will be "Hello world!"