Advertisement

Google Ad Slot: content-top

Java String


In Java, a String is a sequence of characters. It is one of the most commonly used data types, and Java provides the String class to work with strings. Strings in Java are immutable, meaning their value cannot be changed once created.


You can create a string in two main ways:

  • Using String Literals
  • Using the new Keyword
Example
String str1 = "Hello, World!";
String str2 = new String("Hello, World!");
System.out.println(str1+" "+str2);
Try it yourself

String Immutability:

Strings are immutable in Java. When you modify a string, a new string object is created instead of modifying the original.

Example
public class Main {
public static void main(String[] args) {
String str = "Hello";
str = str.concat(", World!"); // Assign the modified string (original string is unchanged)
System.out.println(str); // Output: Hello, World!
}
}

StringBuilder and StringBuffer:

If you need to modify strings frequently, use StringBuilder or StringBuffer for better performance as they are mutable.

  • StringBuilder: Faster but not thread-safe.
  • StringBuffer: Thread-safe but slower.
Example
public class Main {
public static void main(String[] args) {
StringBuilder sbReverse = new StringBuilder("Java").reverse();
System.out.println(sbReverse); // Output: avaJ
StringBuffer sbReverse2 = new StringBuffer("Java").reverse();
System.out.println(sbReverse2); // Output: avaJ
}
}