Intern
What is a string in Java?
sobes.tech AI
Answer from AI
A string in Java is a sequence of characters. It is represented by the String class.
Key features:
- Immutability: After creating a
Stringobject, its contents cannot be changed. Any operation that appears to modify the string (e.g., concatenation) actually creates a newStringobject. String Pool: Java uses theString Poolfor efficient management of string literals. When a string literal (e.g.,"hello") is created, the JVM first searches for it in the pool. If it exists, a reference to the existing object is returned. If not, a new object is created in the pool, and a reference to it is returned.- Creation:
- Using a string literal:
String s1 = "hello";(uses theString Pool). - Using the
newoperator:String s2 = new String("world");(creates a new object on the heap, even if"world"already exists in the pool).
- Using a string literal:
- Comparison: To compare the contents of strings, use the
equals()method, not the==operator. The==operator compares object references.
Example:
// Creating a string using a literal (from the pool)
String s1 = "Java";
// Creating a string using new (a new object on the heap)
String s2 = new String("Java");
// Comparing contents (correct)
boolean contentEquals = s1.equals(s2); // true
// Comparing references (not correct for content comparison)
boolean referenceEquals = (s1 == s2); // false
System.out.println("Contents are the same: " + contentEquals);
System.out.println("References are the same: " + referenceEquals);