For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Strings are an essential part of every Java program. Whether you are taking user input, displaying a message, or processing data, strings are everywhere. In Java, strings are objects that represent a sequence of characters. Unlike primitive types, Strings offer powerful features and methods to work with text efficiently.
In this blog, we will cover everything about Strings in Java, from creation to memory management, with simple examples and important concepts every developer should know.
Turn your Java knowledge into a tech career—enroll in a top-rated Software Engineering course.
In programming, a String is a sequence of characters used to store and manipulate text-based data, such as words, sentences, or even paragraphs. A String can include letters, numbers, symbols, and even white spaces. In Java programming languages, Strings are treated as a data type because text manipulation is a common and important part of software development.
Strings make it easy to perform operations like comparison, searching, replacing, splitting, or joining pieces of text. They are essential for tasks like taking user input, displaying messages, or processing data.
In Java, a String is an object that represents a sequence of characters. It is defined in the java.lang package and is one of the most widely used classes. Unlike primitive data types like int or char, a String is a non-primitive or reference data type.
A key feature of Java Strings is that they are immutable, meaning once a String object is created, its value cannot be changed. If you modify a String (like adding more characters), a new String object is created in memory.
Internally, a String in Java is stored as an array of characters. Java also optimizes memory usage through String Pooling, where identical String literals are stored only once and reused when needed.
Your path to becoming a modern developer starts here: • upGrad’s Full Stack Bootcamp • AI Full Stack Program – IIIT Bangalore • Cloud & DevOps Certificate – upGrad
You can create strings in two main ways:
When you directly assign a sequence of characters in double quotes, it is called a string literal.
String str = "Java Programming";
String name = "John";
System.out.println(name);
When you use a string literal, Java checks the String Pool to see if an identical string already exists. If yes, it reuses it; otherwise, it creates a new one.
Must read: Literal in Java
You can also create a string using the new keyword, which forces Java to create a new object in the heap memory.
String str = new String("Java Programming");
String course = new String("Computer Science");
System.out.println(course);
Here, even if an identical string exists in the String Pool, a new object is created separately in the heap memory.
Must read: Top Keywords in Java
Let's start with a simple program to create and print a string.
public class StringExample {
public static void main(String[] args) {
String message = "Hello, Java!";
System.out.println(message);
}
}
Hello, Java!
Here, we created a string using a string literal and printed it using System.out.println(). Java automatically treats "Hello, Java!" as an object of the String class.
Strings are closely related to several interfaces and classes in Java:
Must read: String length in Java
Example:
import java.util.StringTokenizer;
public class TokenExample {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("Java is fun", " ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Must read: StringBuffer and StringBuilder Difference in Java
In Java, Strings are immutable. Once a String object is created, it cannot be changed. If you try to modify it, a new object is created instead.
Example:
String s1 = "Java";
s1.concat(" Programming");
System.out.println(s1); // Output: Java
Even though concat() is called, s1 remains unchanged.
How strings are stored in memory depends on how you create them.
Example:
String a = "Java";
String b = "Java";
System.out.println(a == b); // true
Both a and b point to the same object in the pool.
Example:
String x = new String("Java");
String y = new String("Java");
System.out.println(x == y); // false
Here, x and y point to different objects.
Earlier in Java versions (before Java 7), the String Pool was part of the PermGen (Permanent Generation) memory. From Java 7 onwards, the String Pool was moved to the normal heap space.
java
CopyEdit
String s1 = "Java";
String s2 = "Java";
System.out.println(s1.equals(s2)); // true
java
CopyEdit
String s3 = "Hello";
String s4 = s3.concat(" World");
System.out.println(s4); // Hello World
String original = "Learn";
original.concat(" Java");
System.out.println(original); // Learn
Use literals when possible instead of creating new objects to save memory.
Strings are powerful tools in Java and form the backbone of many applications. Understanding how strings are created, stored, and managed in memory helps you write more efficient and reliable code. Whether you're using string literals or the new keyword, keeping immutability and memory allocation concepts in mind ensures your programs run faster and safer.
Mastering Java Strings is a must for every Java programmer, and with the right practices, you can handle text data smartly and efficiently.
In Java, strings can be created using string literals (e.g., "Hello") or the new keyword (e.g., new String("Hello")). The new keyword creates a new object in heap memory, while literals use the String Pool for efficient memory management.
Both StringBuffer and StringBuilder are mutable and used for string manipulation, but StringBuffer is thread-safe, while StringBuilder is not, offering better performance for single-threaded applications.
The String Pool is a special memory area where string literals are stored. It optimizes memory usage by reusing identical string values across the program, preventing redundant string objects.
You can compare strings using methods like equals(), which checks content equality, and compareTo(), which compares strings lexicographically. equalsIgnoreCase() is used for case-insensitive comparison.
Strings in Java are immutable, meaning once created, their content cannot be changed. Any modification creates a new string object. This provides thread-safety and optimizes memory management using the String Pool.
Strings are stored in two places: the String Pool for literals and the heap memory for strings created using the new keyword. The String Pool helps to save memory by reusing identical strings.
No, strings in Java are immutable. You cannot change their contents directly. Instead, any modification results in the creation of a new string object, which helps maintain security and efficiency.
The String Pool stores string literals in a shared memory area, so when a string is referenced multiple times, Java reuses the existing object rather than creating a new one, which reduces memory usage.
StringBuffer is thread-safe because it uses synchronized methods for string manipulation, ensuring that only one thread can access the string at a time. StringBuilder, on the other hand, is not synchronized and is more efficient in single-threaded contexts.
String literals are stored in the String Pool, making them memory-efficient by reusing identical strings. The new keyword creates a new object in heap memory, even if an identical string exists in the pool.
Java’s garbage collector handles memory management by cleaning up objects that are no longer referenced. However, string literals in the String Pool are never garbage collected as they are often reused across the program.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.