Creating Strings Using Literals and Constructors in Java
Course: Core Java Training
Topic: Creating Strings Using Literals and Constructors
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Strings in Java
A string is a sequence of characters used to represent text in a Java application. Strings can contain letters, numbers, symbols, whitespace, and other characters. Java provides the built-in String class in the java.lang package to create and manipulate text.
Strings are commonly used for names, addresses, messages, file paths, user input, application configuration, and data received from databases or APIs.
Java provides two common ways to create strings:
- String literals: Create a string by placing text inside double quotation marks.
- String constructors: Create a string object using the
new keyword and a constructor of the String class.
String language = "Java";
String framework = new String("Spring");
Both statements create strings containing text, but they can differ in object creation and memory usage.
2. Learning Objectives
After completing this topic, you should be able to:
- Understand the purpose of the Java String class.
- Create strings using string literals.
- Create strings using the
String constructor.
- Explain the String Pool and its role in memory management.
- Differentiate between string references and string objects.
- Compare strings using
equals() and ==.
- Create strings from character arrays and byte arrays.
- Identify common mistakes when creating strings.
3. What Is the String Class?
The String class represents an immutable sequence of characters. Immutable means that once a String object has been created, its content cannot be changed. String methods that appear to modify text return a new string rather than changing the original object.
public class StringExample {
public static void main(String[] args) {
String message = "Hello";
message.concat(" Java");
System.out.println(message);
}
}
Output:
Hello
The concat() method returns a new string, but the returned value is not assigned to message. Therefore, the original variable still refers to "Hello".
To retain the combined text, assign the returned string:
String message = "Hello";
message = message.concat(" Java");
System.out.println(message);
Output:
Hello Java
4. Creating Strings Using Literals
A string literal is a sequence of characters enclosed in double quotation marks. Java allows you to assign a literal directly to a variable of type String.
Syntax
String variableName = "text";
Example
public class StringLiteralExample {
public static void main(String[] args) {
String name = "Rahul";
String course = "Core Java";
String message = "Welcome to Java Programming";
System.out.println(name);
System.out.println(course);
System.out.println(message);
}
}
Output:
Rahul
Core Java
Welcome to Java Programming
Explanation
"Rahul" is a string literal assigned to name.
"Core Java" is assigned to course.
"Welcome to Java Programming" is assigned to message.
- The Java compiler recognizes these quoted text values as string literals.
5. Understanding the String Pool
The String Pool is a special area associated with the JVM's heap memory where Java can reuse string objects representing the same interned literal value. Reusing pooled strings can reduce unnecessary duplicate objects.
Consider the following example:
public class StringPoolExample {
public static void main(String[] args) {
String first = "Java";
String second = "Java";
System.out.println(first == second);
System.out.println(first.equals(second));
}
}
Output:
true
true
Explanation:
first and second refer to the same pooled string object in this example.
- The
== operator returns true because both references point to the same object.
- The
equals() method returns true because the character contents are equal.
String pooling is an optimization. For ordinary string literals with the same contents, Java normally reuses the pooled object.
6. Creating Strings Using Constructors
A constructor initializes an object when it is created. The String class provides several constructors for creating strings from different sources, including another string, a character array, or a byte array.
A commonly demonstrated constructor uses the new keyword:
String variableName = new String("text");
Example
public class StringConstructorExample {
public static void main(String[] args) {
String language = new String("Java");
String greeting = new String("Hello World");
System.out.println(language);
System.out.println(greeting);
}
}
Output:
Java
Hello World
Explanation:
new String("Java") explicitly creates a new String object.
- The constructor initializes that object with the characters from the supplied string.
- The variable stores a reference to the resulting object.
- Using
new String(...) is usually unnecessary when a literal alone is sufficient.
7. Difference Between String Literals and Constructors
| Feature |
String Literal |
String Constructor |
| Example |
String s = "Java"; |
String s = new String("Java"); |
| Object creation |
Uses a pooled literal when applicable |
Explicitly creates a new String object |
| Memory behavior |
Can reuse an existing pooled object |
Normally creates a distinct object for the constructor call |
| Readability |
Short and easy to read |
More explicit but usually more verbose |
| Performance |
Generally preferred for fixed text |
May introduce unnecessary object creation |
| Content |
Immutable |
Immutable |
| Typical usage |
Most ordinary text values |
When an explicit object or a particular constructor is needed |
8. Comparing String References and Contents
One important concept when creating strings is the difference between reference comparison and content comparison.
== checks whether two reference variables point to the same object.
equals() checks whether two strings contain the same sequence of characters.
Example
public class StringComparisonExample {
public static void main(String[] args) {
String first = "Java";
String second = "Java";
String third = new String("Java");
System.out.println(first == second);
System.out.println(first == third);
System.out.println(first.equals(third));
}
}
Output:
true
false
true
Explanation:
first == second is true because both variables refer to the same pooled literal.
first == third is false because third refers to a separately created object.
first.equals(third) is true because both strings contain "Java".
Best practice: Use equals() to compare string contents in most application logic.
9. Creating a String from a Character Array
The String class provides constructors that accept character arrays. This is useful when text is stored as individual characters and needs to be converted into a string.
Syntax
char[] characters = {'J', 'a', 'v', 'a'};
String text = new String(characters);
Example
public class CharArrayStringExample {
public static void main(String[] args) {
char[] letters = {'H', 'e', 'l', 'l', 'o'};
String result = new String(letters);
System.out.println(result);
}
}
Output:
Hello
The constructor creates a string containing the characters supplied in the array. Subsequent changes to the original character array do not change the created string.
Creating a String from Part of a Character Array
You can also specify an offset and a length to select a section of the array.
public class PartialCharArrayExample {
public static void main(String[] args) {
char[] letters = {'J', 'a', 'v', 'a', ' ', 'S', 'E'};
String text = new String(letters, 0, 4);
System.out.println(text);
}
}
Output:
Java
In this example, the offset is 0 and the length is 4, so only the first four characters are included.
10. Creating a String from a Byte Array
A string can be constructed from a byte array. This is useful when working with encoded text received from a file, network, or other data source.
When converting bytes into text, choose the correct character encoding. UTF-8 is a common choice for text data.
Example Using UTF-8
import java.nio.charset.StandardCharsets;
public class ByteArrayStringExample {
public static void main(String[] args) {
byte[] data = {74, 97, 118, 97};
String text = new String(data, StandardCharsets.UTF_8);
System.out.println(text);
}
}
Output:
Java
The byte values correspond to the UTF-8 encoded characters in the word "Java".
Important: Avoid relying on the platform's default character encoding when the encoding of the data is known. Specify the appropriate charset to ensure consistent results.
11. Creating a String from Another String
The String constructor can accept another string as its argument.
public class CopyStringExample {
public static void main(String[] args) {
String original = "Core Java";
String copied = new String(original);
System.out.println(original);
System.out.println(copied);
System.out.println(original.equals(copied));
System.out.println(original == copied);
}
}
Output:
Core Java
Core Java
true
false
The new object has the same content as the original, but the constructor creates a distinct String object. Since strings are immutable, a separate copy is rarely necessary.
12. Creating an Empty String
An empty string is a valid string containing zero characters. It is not the same as null.
public class EmptyStringExample {
public static void main(String[] args) {
String first = "";
String second = new String();
System.out.println(first.length());
System.out.println(second.length());
System.out.println(first.equals(second));
}
}
Output:
0
0
true
Both variables refer to strings whose length is zero. The no-argument constructor creates an empty string, but the empty literal is the simpler choice for most situations.
Empty String vs. Null
| Value |
Meaning |
Can Call String Methods? |
"" |
A valid string with no characters |
Yes |
null |
No object reference is present |
No; calling a method on it causes a NullPointerException |
" " |
A string containing one space |
Yes |
13. Creating Strings with Escape Sequences
String literals can include special characters using escape sequences. An escape sequence begins with a backslash.
| Escape Sequence |
Meaning |
Example |
\n |
New line |
"Hello\nJava" |
\t |
Tab |
"Name\tAge" |
\" |
Double quotation mark |
"He said \"Hello\"" |
\\ |
Backslash |
"C:\\Java" |
\' |
Single quotation mark |
"It\'s Java" |
\r |
Carriage return |
"A\rB" |
Example
public class EscapeSequenceExample {
public static void main(String[] args) {
String message = "Welcome to\nCore Java";
String quote = "Java says: \"Hello!\"";
String path = "C:\\Java\\Programs";
System.out.println(message);
System.out.println(quote);
System.out.println(path);
}
}
Output:
Welcome to
Core Java
Java says: "Hello!"
C:\Java\Programs
14. Creating Multiline Strings with Text Blocks
Java supports text blocks for writing multiline strings. Text blocks became a standard language feature in Java 15. They begin and end with three double quotation marks and are useful for longer formatted text.
public class TextBlockExample {
public static void main(String[] args) {
String details = """
Course: Core Java
Topic: Strings
Level: Beginner
""";
System.out.println(details);
}
}
Text blocks preserve a readable multiline layout and handle many quotation-mark cases more conveniently than traditional string literals. They are still instances of the String class.
15. String Immutability and Object Creation
String immutability means that the contents of an existing String object cannot be changed after creation. Operations such as concatenation, replacement, or converting case return a result rather than modifying the original object.
public class StringImmutabilityExample {
public static void main(String[] args) {
String text = "java";
String upper = text.toUpperCase();
System.out.println(text);
System.out.println(upper);
}
}
Output:
java
JAVA
The variable text still refers to the original string. The variable upper refers to the result returned by toUpperCase().
Immutability makes strings easier to share safely, helps the String Pool work effectively, and prevents accidental changes to text values.
16. Understanding the Interned String
The intern() method returns the canonical pooled representation of a string. If a matching interned string already exists, that pooled reference is returned; otherwise, the string is added to the pool.
public class InternExample {
public static void main(String[] args) {
String first = "Java";
String second = new String("Java");
String third = second.intern();
System.out.println(first == second);
System.out.println(first == third);
}
}
Output:
false
true
The first comparison is false because second is a distinct object. The second is true because intern() returns the pooled representation corresponding to the literal "Java".
Use intern() only when there is a clear reason to canonicalize strings. It is not necessary for ordinary string creation.
17. String Concatenation During Creation
You can create strings by joining existing strings and other values using the + operator. Java converts supported operands to text as part of concatenation.
public class StringConcatenationExample {
public static void main(String[] args) {
String firstName = "Amit";
String lastName = "Sharma";
String fullName = firstName + " " + lastName;
System.out.println(fullName);
}
}
Output:
Amit Sharma
For simple expressions, the + operator is readable and convenient. For repeated modifications inside a large loop, consider using StringBuilder to avoid creating many intermediate string results.
18. Common String Creation Mistakes
| Mistake |
Problem |
Correct Approach |
| Using single quotes for a string |
Single quotes represent a character literal, not a String |
Use double quotes: "Java" |
Comparing contents with == |
Checks reference identity, not general content equality |
Use equals() |
Assuming concat() changes the original |
String is immutable |
Assign the returned result |
Using new String() for every literal |
Can create unnecessary objects |
Prefer literals when appropriate |
| Ignoring byte encoding |
Text may be decoded incorrectly |
Specify the correct charset |
| Calling methods on null |
Can throw NullPointerException |
Check for null before method calls |
| Using incorrect constructor offsets |
Can cause an index-related exception |
Verify offset and length bounds |
19. Troubleshooting String Creation Problems
Problem 1: Compilation Error with Single Quotes
// Incorrect
String language = 'Java';
// Correct
String language = "Java";
Single quotes are intended for character literals such as 'J'. A string must use double quotes.
Problem 2: Unexpected Result from Reference Comparison
String a = "Java";
String b = new String("Java");
System.out.println(a == b);
The result is false because the two references point to different objects. To compare their contents, use a.equals(b).
Problem 3: Original String Does Not Change
String text = "Hello";
text.concat(" World");
System.out.println(text);
The output is Hello. Assign the returned value to preserve the concatenated result:
text = text.concat(" World");
Problem 4: Invalid Character Array Range
char[] letters = {'J', 'a', 'v', 'a'};
String text = new String(letters, 2, 5);
This constructor call is invalid because the requested range exceeds the array's bounds. The offset and length must select a valid range within the array.
20. Best Practices for Creating Strings
- Prefer string literals for ordinary fixed text.
- Use
equals() or equalsIgnoreCase() when comparing string contents.
- Use
new String(...) only when explicitly creating a separate object is useful.
- Remember that String objects are immutable.
- Specify a charset when decoding bytes into text if the encoding is known.
- Use meaningful variable names such as
firstName, email, and courseName.
- Validate null values before invoking methods on references that might be null.
- Use
StringBuilder for repeated string modifications in loops.
- Use text blocks for readable multiline text when the project targets Java 15 or later.
- Avoid relying on the String Pool for application logic; compare string contents explicitly.
21. Practical Example: Creating Student Details
The following program demonstrates string literals, constructors, content comparison, and concatenation in a single example.
public class StudentDetails {
public static void main(String[] args) {
String firstName = "Priya";
String lastName = "Patel";
String course = new String("Core Java");
String fullName = firstName + " " + lastName;
System.out.println("Student Name: " + fullName);
System.out.println("Course: " + course);
System.out.println("Course is Core Java: "
+ course.equals("Core Java"));
}
}
Output:
Student Name: Priya Patel
Course: Core Java
Course is Core Java: true
What this example demonstrates:
- String literals store the student's first and last names.
- A constructor explicitly creates the course string.
- The
+ operator combines the first and last names.
- The
equals() method compares the course string's contents.
22. Practical Example: Converting User Data into a String
Sometimes a program needs to convert numeric or character data into text. Java provides conversion methods and constructors for different data types.
public class StringConversionExample {
public static void main(String[] args) {
int age = 22;
double score = 87.5;
char[] gradeLetters = {'A', 'B', 'C'};
String ageText = String.valueOf(age);
String scoreText = String.valueOf(score);
String grades = new String(gradeLetters);
System.out.println(ageText);
System.out.println(scoreText);
System.out.println(grades);
}
}
Output:
22
87.5
ABC
The String.valueOf() method converts supported values to their string representation, while the character-array constructor creates a string from the supplied characters.
23. String Creation and Memory Considerations
Understanding how strings are created helps developers write efficient Java programs.
- Literals: Identical interned literals can share a pooled object.
- Constructors: Explicit construction normally creates a distinct String object.
- Immutability: String content cannot be changed after object creation.
- Concatenation: Combining strings produces a result string; compiler optimizations may simplify constant expressions.
- Interning: The
intern() method provides a pooled canonical representation.
For example, String a = "Java"; and String b = "Java"; normally share the pooled literal. By contrast, String c = new String("Java"); explicitly creates a separate object. The exact physical memory layout and optimizations depend on the JVM implementation, so focus on the language-level behavior rather than assuming every implementation detail.
24. Exercises for Practice
Exercise 1: Create Basic Strings
- Create a string literal containing your name.
- Create another string literal containing your favorite programming language.
- Print both values.
Exercise 2: Compare Literal and Constructor Strings
- Create a literal containing
"Java".
- Create another string using
new String("Java").
- Print the results of
== and equals().
- Explain why the results differ.
Exercise 3: Create a String from a Character Array
- Declare a character array containing the letters of
"Python".
- Convert the array into a string.
- Print the string and its length.
Exercise 4: Create a String from Bytes
- Declare a byte array representing a short ASCII-compatible word.
- Convert it into a string using
StandardCharsets.UTF_8.
- Print the result.
Exercise 5: Create a Student Profile
- Store a student's name, course, and city in separate strings.
- Use concatenation to create a profile message.
- Use
equals() to verify the student's course.
25. Mini Project: Student Information Formatter
Project objective: Build a simple console program that creates and formats student information using string literals and constructors.
Requirements
- Create a student name using a string literal.
- Create a course name using a String constructor.
- Build a full profile message using concatenation.
- Compare the course name with an expected value using
equals().
- Print each value in a readable format.
Sample Solution
public class StudentInformationFormatter {
public static void main(String[] args) {
String studentName = "Neha";
String courseName = new String("Core Java");
String city = "Mumbai";
String profile = "Student: " + studentName
+ ", Course: " + courseName
+ ", City: " + city;
System.out.println(profile);
if (courseName.equals("Core Java")) {
System.out.println("Course verified successfully.");
} else {
System.out.println("Course does not match.");
}
}
}
Sample Output:
Student: Neha, Course: Core Java, City: Mumbai
Course verified successfully.
26. Interview Questions and Answers
Q1. What is a String in Java?
Answer: A String is an object of the String class that represents an immutable sequence of characters.
Q2. How can you create a string in Java?
Answer: Common approaches include assigning a string literal, using a String constructor, or creating a string from character or byte arrays.
Q3. What is a string literal?
Answer: A string literal is text enclosed in double quotation marks, such as "Hello".
Q4. What is the String Pool?
Answer: The String Pool enables Java to reuse canonical string objects, particularly for literals, instead of creating duplicate pooled representations unnecessarily.
Q5. What is the difference between a literal and new String()?
Answer: A literal can refer to a pooled string object. A constructor call using new String(...) explicitly creates a distinct String object.
Q6. What is the difference between == and equals()?
Answer: The == operator compares references for object identity, while equals() compares the contents of strings.
Q7. Are strings mutable in Java?
Answer: No. String objects are immutable. Methods that transform a string return a result instead of changing the existing object's content.
Q8. Can a string be created from a character array?
Answer: Yes. The constructor new String(charArray) creates a string from the characters in an array.
Q9. How can you create a string from bytes?
Answer: Use a suitable constructor such as new String(bytes, StandardCharsets.UTF_8), selecting the encoding appropriate for the data.
Q10. What does intern() do?
Answer: It returns the canonical pooled representation of a string.
Q11. Is an empty string the same as null?
Answer: No. An empty string is a valid object with zero characters. Null indicates that a reference does not refer to an object.
Q12. Why should you avoid unnecessary String constructors?
Answer: They can create extra objects without providing any benefit when a literal or existing string is sufficient.
Q13. Why is String immutability useful?
Answer: It supports safe sharing, predictable behavior, and string pooling, and prevents a string's contents from changing unexpectedly.
Q14. How do you create a multiline string in modern Java?
Answer: Use a text block with triple double quotation marks. Text blocks became a standard feature in Java 15.
Q15. Which method should you use to compare string content?
Answer: Use equals() for case-sensitive content comparison or equalsIgnoreCase() when case should be ignored.
27. Quick Revision Checklist
- Understand that String represents immutable text.
- Know how to create strings using double-quoted literals.
- Understand how
new String(...) creates an explicit object.
- Know the purpose of the String Pool.
- Distinguish reference identity from string content equality.
- Use
equals() to compare text.
- Know how to construct strings from character and byte arrays.
- Specify a suitable character encoding when converting bytes to text.
- Understand empty strings, null references, and escape sequences.
- Avoid unnecessary object creation and remember string immutability.
28. Conclusion
Creating strings is a fundamental skill in Core Java. String literals provide a simple and efficient way to represent fixed text, while constructors support creating String objects from existing strings, character arrays, byte arrays, and other sources. Understanding the String Pool, object identity, immutability, and content comparison helps you write reliable and maintainable Java programs.
Practice both approaches and pay particular attention to the difference between == and equals(). These concepts form the foundation for more advanced Java topics, including string manipulation, collections, file handling, and application development.
Explore More: Learn about Core Java through the JustAcademy Core Java Training Course, register for a course demo, or visit the JustAcademy website.