How To Create Strings in Java?
Learn how to create strings in Java using string literals and String constructor methods. Master Java string objects, string pool concepts, and string immutability. Essential Java programming tutorial for beginners and developers.
Strings in Java are sequences of characters. Unlike primitive data types, strings are objects. This means they have methods associated with them that can be used to manipulate and process the string data.
Strings are one of the most commonly used data types in Java programming and are widely used for storing and manipulating text. For example, "100"
(with quotes) is considered a string, while 100
(without quotes) is considered a number or falls under the integer type. Computers can perform mathematical operations on numbers but not strings.
In Java, strings are represented byString
class, part ofjava.lang
package automatically imported and widely used in Java programming to store and manipulate textual data.
How do you create a string object?
There are two main ways to create strings in Java:
- By string literals
- By string constructor
Using String literals
Java String literal is created by using double quotes. For Example:
String greeting = "Hello, world!";
Using String constructor
There are two different ways to use the string constructor to create strings:
- Using a double-quoted text with a String constructor
String name = new String("John Doe");
- Using
char[]
array of characters
char[] charArray = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'};
String newGreeting = new String(charArray); // Hello world!
String pool
Java uses a special memory in Heap called the String pool to store string literals. When you create a string literal, the JVM checks if that literal already exists in the pool. If it does, it returns a reference to the existing object; if not, it adds the new literal to the pool.
However, when using the new
keyword, the string is created in the heap memory (outside the pool), even if the exact string literal exists in the pool.
You will learn about String pool in the next lessons.
Immutability in string
Once a String
object is created, its value cannot be changed. For example, when you concatenate two strings, a new String
object is created, and the original strings remain unchanged.
Example of immutability:
String original = "Hello";
String modified = original.concat(", World!");
// original remains "Hello", and modified is "Hello, World!"