Strings
In Java, a String is a sequence of characters used to represent text. Strings are one of the most commonly used data types and are essential for handling text in Java programs. In Java, String is an object, and the String class provides several helpful methods for manipulating text.
Creating Strings
You can create strings in a couple of ways:
- Using Double Quotes (most common way):
String greeting = "Hello, World!";
Using the new Keyword:
String message = new String("Hello, Java!");
Using double quotes directly is recommended, as Java optimizes memory by reusing string literals with the same value. This process is called string interning.
String Immutability
In Java, strings are immutable, which means that once a string is created, it cannot be changed. For example:
String original = "Hello"; String modified = original + " World!"; System.out.println(original); // Prints "Hello" System.out.println(modified); // Prints "Hello World!"
Instead of modifying original, Java creates a new string for modified. This immutability makes strings safer to use, especially in multi-threaded applications.
Common String Methods
- Length: Get the length of a string.
String text = "Java"; int length = text.length(); // Returns 4
- CharAt: Get a character at a specific index.
char firstChar = text.charAt(0); // Returns 'J'
- Substring: Extract a part of the string.
String part = text.substring(1, 3); // Returns "av"
- ToUpperCase and ToLowerCase: Change the case of the string.
String upper = text.toUpperCase(); // Returns "JAVA" String lower = text.toLowerCase(); // Returns "java"
- Trim: Remove whitespace from the beginning and end of the string.
String spaced = " Hello "; String trimmed = spaced.trim(); // Returns "Hello"
- Replace: Replace characters or substrings.
String replaced = text.replace('a', 'o'); // Returns "Jovo"
Comparing Strings
Java provides several ways to compare strings:
- equals(): Checks if two strings have the same content.
String a = "Java"; String b = "Java"; boolean isEqual = a.equals(b); // Returns true
- equalsIgnoreCase(): Ignores case when comparing.
boolean isEqualIgnoreCase = a.equalsIgnoreCase("java"); // Returns true
- compareTo(): Compares two strings lexicographically (alphabetically).
int result = a.compareTo("Python"); // Returns a negative number because "Java" comes before "Python"
Concatenating Strings
You can combine strings in several ways:
- Using + Operator:
String first = "Hello, "; String second = "World!"; String result = first + second; // Returns "Hello, World!"
- Using concat() Method:
String result = first.concat(second); // Also returns "Hello, World!"
StringBuilder and StringBuffer for Performance
Since strings are immutable, creating many strings (e.g., in loops) can be inefficient. Java provides StringBuilder and StringBuffer classes for efficient string manipulation.
- StringBuilder: Faster but not thread-safe.
StringBuilder sb = new StringBuilder("Hello"); sb.append(", World!"); System.out.println(sb.toString()); // Prints "Hello, World!"
- StringBuffer: Thread-safe, but slightly slower than StringBuilder.
String Formatting
You can format strings with String.format():
String name = "Java"; int version = 17; String formatted = String.format("Welcome to %s version %d!", name, version); System.out.println(formatted); // Prints "Welcome to Java version 17!"