Strings in Java are objects that represent sequences of characters. The String
class provides various methods for string manipulation, such as concatenation, substring, and length.
public class StringExample { public static void main(String[] args { String str1 = "Hello"; String str2 = "World"; // Concatenate strings String result = str1 + " " + str2; System.out.println("Concatenated String: " + result); } }
In this example, the +
operator is used to concatenate two strings str1
and str2
.
public class StringExample { public static void main(String[] args) { String str = "Hello, World!"; // Get the length of the string int length = str.length(); System.out.println("Length of the string: " + length); } }
The length()
method returns the number of characters in the string, including spaces and punctuation.
public class StringExample { public static void main(String[] args) { String str = "Hello, World!"; // Extract a substring String subStr = str.substring(7, 12); // Extracts "World" System.out.println("Substring: " + subStr); } }
The substring()
method is used to extract a part of the string. In this example, it extracts the substring starting from index 7 to 12.