In Java, a String is a sequence of characters enclosed in double quotes (""
). It is one of the most commonly used data types for handling text. Strings in Java are objects, even though they can be declared like primitive types.
Syntax
1 |
String variableName = "Your text"; |
Example
1 2 |
String greeting = "Hello, Java!"; System.out.println(greeting); //Output: Hello, Java! |
Declaring and Initializing Strings
In Java, you can create strings in multiple ways:
Using String Literals
1 |
String greeting = "Hello, Java!"; |
1 2 3 |
//Example String str1 = "Java"; String str2 = "Java"; |
- When you create a String using double quotes (
""
), Java checks the String Pool (a special memory area inside the heap). - If the String already exists in the pool, the new variable (
str2
) will refer to the same object instead of creating a new one. - This saves memory and makes the program more efficient.
Using the new Keyword
1 |
String message = new String("Hello, Java!"); |
1 2 3 |
//Example String str3 = new String("Java"); String str4 = new String("Java"); |
- The
new
keyword forces Java to create a new object in the heap, even if the same string already exists in the pool. - Each
new String("Java")
creates a separate object in memory, meaningstr3
andstr4
are different objects.
String Literal vs new Keyword in Java
Feature | String Literal ("" ) |
new Keyword |
---|---|---|
Memory Location | Stored in String Pool | Stored in Heap Memory |
Object Creation | Reuses existing object (if available) | Always creates a new object |
Performance | Faster (because of String Pool) | Slower (creates a new object) |
Recommended? | Yes, for efficiency | Only if a separate object is required |
Immutable Nature of Strings
Strings in Java are immutable, meaning once created, they cannot be changed. Every modification creates a new object in memory.
1 2 3 |
String name = "Alice"; name.concat(" Wonderland"); System.out.println(name); // Output: Alice (unchanged) |
If you need a mutable string, you can use StringBuilder or StringBuffer.