String
A String in Java represents a sequence of characters, like a word or sentence. Unlike primitive types, String is a class, and once created, a String object's content cannot be changed (it is "immutable").
1. What is a String?
A String in Java represents a sequence of characters, like a word or sentence. Unlike primitive types, String is a class, and once created, a String object's content cannot be changed (it is "immutable").
2. Why is it used?
Almost every program deals with text in some way — names, messages, addresses. String is the standard way Java represents and works with this kind of text data.
3. Real-Life Example
Think of a printed name tag. Once printed, you can't directly edit the letters on it — you'd need to print an entirely new tag to show a different name. A Java String behaves the same way; any "change" actually creates a brand-new String.
4. Syntax
javaString text = "Hello, Java!";
5. Example Program
javapublic class StringDemo { public static void main(String[] args) { String name = "Java Learner"; System.out.println("Welcome, " + name); } }
Output:
Welcome, Java Learner6. Key Points to Remember
- Strings in Java are immutable — every "modification" actually creates a new
Stringobject. Stringcan be created using double quotes directly, or with thenew String()constructor.Stringcomparison should use.equals(), not==, to compare actual content correctly.