In Java, a String is much more than just a collection of characters—it is an immutable object with special memory handling in the String Pool.
What is a Character?
A Character is a single letter, number, or symbol enclosed within a single quote (' '). For example:
char ch = 'A';
What is a String?
A String is a sequence of characters enclosed within double quotes (" "). For example:
String str = "Hello";
In Java, Strings are treated as objects, not just a simple collection of characters.
Ways to Compare Strings
Using == operator: Compares the memory locations (references) of the strings.
Using equals() method: Compares the actual content of the strings.
Using compareTo() method: Compares strings character by character and returns an integer value.
Using equalsIgnoreCase() method: Compares strings while ignoring upper and lower case differences.
Additional String Concepts
Before writing code with strings, it is important to understand:
String Pool: Java optimizes memory usage by storing string literals in a common pool.
String Mutability: Since strings are immutable, modifying a string creates a new object instead of changing the original one.
StringBuffer and StringBuilder: These classes allow creating and modifying strings efficiently when frequent changes are needed.
By understanding these concepts, you will be able to work efficiently with strings in Java.