How to Create String in Java: Syntax and Examples
In Java, you create a string using the
String class either by assigning a string literal like String s = "Hello"; or by using the constructor like String s = new String("Hello");. The first way is simpler and preferred for most cases.Syntax
There are two main ways to create a string in Java:
- String literal: Directly assign text inside double quotes.
- String object: Use the
new String()constructor to create a new string object.
Example syntax:
java
String s1 = "Hello"; String s2 = new String("Hello");
Example
This example shows how to create strings using both methods and print them.
java
public class Main { public static void main(String[] args) { String greeting1 = "Hello, world!"; // string literal String greeting2 = new String("Hello, world!"); // string object System.out.println(greeting1); System.out.println(greeting2); } }
Output
Hello, world!
Hello, world!
Common Pitfalls
Common mistakes when creating strings include:
- Using
==to compare strings instead of.equals().==checks if two references point to the same object, not if their text is the same. - Unnecessarily using
new String()which creates a new object and wastes memory.
java
public class Pitfall { public static void main(String[] args) { String a = "test"; String b = "test"; String c = new String("test"); // Wrong: compares references System.out.println(a == b); // true because literals are interned System.out.println(a == c); // false because c is a new object // Right: compares content System.out.println(a.equals(c)); // true } }
Output
true
false
true
Quick Reference
| Method | Description | Example |
|---|---|---|
| String literal | Creates string from text directly | String s = "Hello"; |
| String constructor | Creates new string object | String s = new String("Hello"); |
| .equals() | Compares string content | s1.equals(s2) |
| == operator | Compares references (not content) | s1 == s2 |
Key Takeaways
Create strings using literals for simplicity and efficiency.
Use new String() only when you need a distinct object.
Compare strings with .equals(), not with ==.
String literals with the same text share the same object in memory.
Avoid unnecessary string object creation to save memory.