0% found this document useful (0 votes)
7 views7 pages

Understanding Java String Immutability

In Java, strings are sequences of characters represented by double quotes and are objects of the String class. Common operations on strings include finding their length, concatenating them, and comparing them using methods like length(), concat(), and equals(). Strings in Java are immutable, meaning once created, they cannot be changed, and can be instantiated either using string literals or the new keyword, with the latter always creating a new object in memory.

Uploaded by

gyashika198
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Understanding Java String Immutability

In Java, strings are sequences of characters represented by double quotes and are objects of the String class. Common operations on strings include finding their length, concatenating them, and comparing them using methods like length(), concat(), and equals(). Strings in Java are immutable, meaning once created, they cannot be changed, and can be instantiated either using string literals or the new keyword, with the latter always creating a new object in memory.

Uploaded by

gyashika198
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Strings

In Java, a string is a sequence of characters. For example, "hello" is a


string containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .

We use double quotes to represent a string in Java. For example,

// create a string
String type = "Java programming";

Example: Create a String in Java


class Main {
public static void main(String[] args) {

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
}
}
Run Code

In the above example, we have created three strings named first , second ,

and third .

Here, we are directly creating strings like primitive types.


However, there is another way of creating Java strings (using
the new keyword).
Note: Strings in Java are not primitive types (like int , char , etc). Instead,
all strings are objects of a predefined class named String .

And all string variables are instances of the String class.

Java String Operations


Java provides various string methods to perform different operations on
strings. We will look into some of the commonly used string operations.

1. Get the Length of a String


To find the length of a string, we use the length() method. For example,
class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
[Link]("String: " + greet);

// get the length of greet


int length = [Link]();

[Link]("Length: " + length);


}
}
Run Code

Output

String: Hello! World


Length: 12

In the above example, the length() method calculates the total number of
characters in the string and returns it.
2. Join Two Java Strings
We can join two strings in Java using the concat() method. For example,
class Main {
public static void main(String[] args) {

// create first string


String first = "Java ";
[Link]("First String: " + first);

// create second
String second = "Programming";
[Link]("Second String: " + second);

// join two strings


String joinedString = [Link](second);

[Link]("Joined String: " + joinedString);


}
}
Run Code

Output

First String: Java


Second String: Programming
Joined String: Java Programming

In the above example, we have created two strings


named first and second . Notice the statement,

String joinedString = [Link](second);

Here, the concat() method joins the second string to the first string and
assigns it to the joinedString variable.
We can also join two strings using the + operator in Java.
3. Compare Two Strings
In Java, we can make comparisons between two strings using
the equals() method. For example,
class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = [Link](second);

[Link]("Strings first and second are equal: " +


result1);

// compare first and third strings


boolean result2 = [Link](third);

[Link]("Strings first and third are equal: " +


result2);
}
}
Run Code

Output

Strings first and second are equal: true


Strings first and third are equal: false

In the above example, we have created 3 strings named first , second ,

and third .
Here, we are using the equal() method to check if one string is equal to
another.
The equals() method checks the content of strings while comparing them.

Escape Character in Java Strings

Java Strings are Immutable


In Java, strings are immutable. This means once we create a string, we
cannot change that string.
To understand it more thoroughly, consider an example:

// create a string
String example = "Hello! ";

Here, we have created a string variable named example . The variable holds
the string "Hello! " .

Now, suppose we want to change the string.

// add another string "World"


// to the previous tring example
example = [Link](" World");

Here, we are using the concat() method to add another string "World" to
the previous string.
It looks like we are able to change the value of the previous string.
However, this is not true .
Let's see what has happened here:

1. JVM takes the first string "Hello! "

2. creates a new string by adding "World" to the first string


3. assigns the new string "Hello! World" to the example variable
4. The first string "Hello! " remains unchanged

Creating Strings Using the New Keyword


So far, we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using


the new keyword as well. For example,

// create a string using the new keyword


String name = new String("Java String");

In the above example, we have created a string name using


the new keyword.
Here, when we create a string object, the String() constructor is invoked.

Note: The String class provides various other constructors to create


strings. To learn more, visit Java String (official Java documentation).

Example: Create Java Strings Using the New


Keyword
class Main {
public static void main(String[] args) {

// create a string using new


String name = new String("Java String");

[Link](name); // print Java String


}
}
Run Code

Create String Using Literals vs. New Keyword


Now that we know how strings are created using string literals and
the new keyword, let's see what is the major difference between them.
In Java, the JVM maintains a string pool to store all of its strings inside the
memory. The string pool helps in reusing the strings.
1. While creating strings using string literals,

String example = "Java";

Here, we are directly providing the value of the string ( Java ). Hence, the
compiler first checks the string pool to see if the string already exists.
 If the string already exists, the new string is not created. Instead,
the new reference, example points to the already existing string
( Java ).
 If the string doesn't exist, a new string ( Java) is created.
2. While creating strings using the new keyword,

String example = new String("Java");

Here, the value of the string is not directly provided. Hence, a


new "Java" string is created even though "Java" is already present inside
the memory pool.

Common questions

Powered by AI

During runtime, Java optimizes memory usage for strings using a string pool, a portion of the heap memory designated for storing commonly used strings. When a string literal is created, the JVM checks the pool; if the string exists, the reference is reused rather than creating a new object, thus saving memory and increasing performance .

Java calculates the length of a string by counting the number of characters it contains. The length() method is used for this purpose, which returns an integer value representing the string's character count, excluding null terminators as in other languages .

The equals() method in Java compares the actual content of two strings, whereas '==' compares references. Using equals() is crucial for accurate value comparison to determine if two strings are logically equivalent. On the other hand, '==' might yield false for logically equivalent strings stored at different memory locations if they were created differently, such as with the 'new' keyword .

Java strings are immutable, meaning their values cannot be changed once they are created. When a string operation like concatenation is performed, a new string is created and returned rather than modifying the original. For example, when 'example.concat(" World")' is executed, 'Hello! World' is a new string, while the original 'Hello!' remains unchanged .

Strings in Java are not primitive types; they are objects of the String class. This means string variables are instances of the String class, requiring memory allocation in the heap and supporting methods and operations associated with objects. Consequently, strings benefit from object-oriented features like methods for manipulation, but they also consider issues like immutability and references .

The immutability of strings in Java offers several benefits, such as thread safety and memory efficiency through reuse in the string pool. However, it can lead to excessive memory usage and processing overhead when concatenating strings since these operations create new objects. Developers need to use classes like StringBuilder for more efficient concatenations when performance is critical .

In Java, when a string is created using a string literal, the JVM first checks the string pool to see if the string already exists. If it does, the reference points to the existing string, thus saving memory. If it does not exist, a new string is created in the pool. In contrast, when a string is created using the 'new' keyword, a new string object is always created in the heap memory, regardless of the pool's existing strings .

The string pool in Java is a special memory region where the JVM stores string literals. When a string is created using literals, the JVM checks the pool for an existing string with the same content. If found, it uses the existing string reference, preventing the creation of a duplicate. This optimizes memory usage by facilitating string reuse. If no match is found, a new string is added to the pool .

String concatenation in Java can be done using the concat() method or the '+' operator. The concat() method appends the specified string to the end of another string and returns the concatenated result. For example, 'first.concat(second)' will append 'second' to 'first'. The '+' operator achieves the same purpose in a more intuitive manner, joining strings directly. Both methods result in a new string .

The equals() method is used in Java to compare strings based on their content rather than reference addresses. It is important for checking logical equality, ensuring that two strings with identical sequences of characters are considered equivalent. This method improves accuracy in string comparison operations, which is critical in applications involving string manipulation and analysis .

You might also like