String Basics
Java Strings
In Java, the String
class is used to represent strings or sequences of characters. Strings in Java are objects, and instances of the String
class are immutable, meaning that their values cannot be changed after they are created.
Declaring and Initializing Strings:
You can declare and initialize strings in several ways:
- Using String Literal:
- Using
new
Keyword:
String greeting = "Hello, World!";
String greeting = new String("Hello, World!");
Note: Using string literals is more common and convenient.
String Concatenation:
String concatenation in Java is the process of combining two or more strings. This can be done using the +
operator:
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
In this example, fullName
will be the string "John Doe".
String Methods:
The String
class provides a variety of methods for manipulating strings. Some commonly used methods include:
length()
charAt(int index)
substring(int beginIndex)
substring(int beginIndex, int endIndex)
equals(String anotherString)
equalsIgnoreCase(String anotherString)
indexOf(String str)
toUpperCase()
andtoLowerCase()
String Comparison:
When comparing strings for equality, it's recommended to use the equals()
method, as the ==
operator compares object references, not the content of the strings.
String s1 = "Hello";
String s2 = new String("Hello");
boolean areEqual = s1.equals(s2);
String Literals and String Pool:
String literals (e.g., "Hello") are automatically interned and stored in a special memory area called the "string pool." This means that if two string literals have the same content, they will refer to the same memory location.
String a = "Hello";
String b = "Hello";
boolean areSame = (a == b);
StringBuilder and StringBuffer:
The StringBuilder
and StringBuffer
classes provide mutable sequences of characters, making them more efficient for concatenating multiple strings within a loop or in scenarios where frequent modifications are needed.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
String result = sb.toString();
Note: StringBuilder
is not thread-safe, while StringBuffer
is thread-safe but may have performance implications due to synchronization.
Understanding these basic concepts will help you effectively work with strings in Java. The immutability of strings is an important aspect to keep in mind when designing and optimizing your code.