In this tutorial, we will learn about strings in Java. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in Java is an object of the java.lang.String
class. Strings are immutable, meaning their values cannot be changed once created. Strings are used for storing and handling text data.
Strings can be created in Java using double quotes:
String str = "Hello, world!";
Strings can also be created using the String
class constructor:
String str = new String("Hello, world!");
System.out.println
.public class Main {
public static void main(String[] args) {
String str = "Hello, world!";
System.out.println(str);
}
}
Hello, world!
charAt
method.public class Main {
public static void main(String[] args) {
String str = "Hello";
System.out.println(str.charAt(0)); // Accessing using charAt()
System.out.println(str.charAt(1));
}
}
H e
public class Main {
public static void main(String[] args) {
String str = "Hello";
str = 'J' + str.substring(1); // Modifying individual character
str += " World!"; // Appending new characters
System.out.println(str);
}
}
Jello World!
+
operator or the concat
method.public class Main {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World!";
String str3 = str1 + str2; // Concatenating strings
System.out.println(str3);
}
}
Hello World!
indexOf
method to find a substring.public class Main {
public static void main(String[] args) {
String str = "Hello, world!";
int pos = str.indexOf("world"); // Finding substring
if (pos != -1) {
System.out.println("Found 'world' at position: " + pos);
} else {
System.out.println("Substring not found");
}
}
}
Found 'world' at position: 7
length
method to get the length of the string.public class Main {
public static void main(String[] args) {
String str = "Hello, world!";
System.out.println("Length of the string: " + str.length()); // Getting string length
}
}
Length of the string: 13