Java String Basics
Introduction
Strings are one of the most commonly used data types in Java programming.
Understanding how to create and manipulate strings is essential for any Java developer.
Strings are the building blocks of text processing in Java.
What is a String in Java?
In Java, a String is an object that represents a sequence of characters.
Strings are immutable, meaning once created, their values cannot be changed.
- Strings are instances of the java.lang.String class.
- They can store letters, numbers, symbols, and whitespace.
- Immutability helps with security and performance.
Creating Strings
There are multiple ways to create strings in Java.
The most common methods are using string literals or the String constructor.
- Using string literal: String s = "Hello";
- Using constructor: String s = new String("Hello");
Common String Methods
Java provides many useful methods to work with strings.
These methods allow you to inspect, modify, and manipulate string data.
- length() - returns the length of the string.
- charAt(int index) - returns the character at the specified index.
- substring(int beginIndex, int endIndex) - extracts a part of the string.
- toLowerCase() and toUpperCase() - change case of the string.
- equals(Object obj) - compares two strings for equality.
- trim() - removes leading and trailing whitespace.
String Immutability and Concatenation
Because strings are immutable, operations that seem to modify a string actually create a new string.
Concatenation combines strings using the + operator or concat() method.
- Using + operator: String s = "Hello" + " World";
- Using concat(): String s = "Hello".concat(" World");
- Repeated concatenation can be inefficient; consider StringBuilder for many modifications.
Examples
public class Main {
public static void main(String[] args) {
String greeting = "Hello, Java!";
System.out.println("Length: " + greeting.length());
System.out.println("Character at 7: " + greeting.charAt(7));
System.out.println("Substring (7-11): " + greeting.substring(7, 11));
System.out.println("Uppercase: " + greeting.toUpperCase());
}
}This example demonstrates creating a string and using common methods like length(), charAt(), substring(), and toUpperCase().
public class Main {
public static void main(String[] args) {
String first = "Hello";
String second = "World";
String combined = first + " " + second;
System.out.println(combined);
}
}This example shows how to concatenate two strings using the + operator.
Best Practices
- Use string literals when possible for better performance.
- Avoid using new String() unnecessarily to prevent extra objects.
- Use StringBuilder for concatenating strings inside loops.
- Always check for null before calling string methods to avoid NullPointerException.
Common Mistakes
- Modifying strings expecting the original string to change (strings are immutable).
- Using == operator to compare strings instead of equals() method.
- Ignoring case sensitivity when comparing strings if not intended.
- Concatenating strings repeatedly inside loops without StringBuilder.
Hands-on Exercise
String Method Practice
Write a Java program that takes a string input and prints its length, first character, last character, and a substring from index 2 to 5.
Expected output: Correctly displays requested string information.
Hint: Use length(), charAt(), and substring() methods.
Interview Questions
Why are strings immutable in Java?
InterviewStrings are immutable to improve security, synchronization, and performance by allowing string literals to be shared safely.
How do you compare two strings for equality in Java?
InterviewUse the equals() method to compare the content of two strings, not the == operator which compares references.
Summary
Java strings are immutable objects representing sequences of characters.
You can create strings using literals or constructors, but literals are preferred.
Common methods like length(), charAt(), substring(), and equals() help manipulate strings.
Remember to use equals() for string comparison and StringBuilder for efficient concatenation in loops.
FAQ
Can I change a character in a Java string?
No, strings are immutable. To change characters, create a new string or use StringBuilder.
What is the difference between == and equals() for strings?
== checks if two string references point to the same object, while equals() checks if their contents are the same.
