Java Strings: Mutable or immutable?

Java Strings: Mutable or immutable?

I don’t understand why it is said that Strings are immutable in Java. Here is a small piece of code which shows that Strings are in fact mutable:

class TestStringStuff{public static void main (String args[]){	String name = “Bill”;	System.out.println(name);	name = name +” Clinton”;	System.out.println(name); // name has been                                   // changed from                                    // Bill to Bill                                    // Clinton}}  

First a little philosophy:

An object is mutable (i.e. variable) if some of its properties can be changed without changing its essential identity. People are mutable objects. A person can get a face lift, a sex change, dye his hair, diet, and change his name, but we still regard him as the same person. (Philosophersare still arguing about what might be considered the “essence” of aperson.)

Arrays are mutable. We can change an individual component of an array x:

x[i] = x[i] + 1;
but we still regard x as the same array.

By contrast, changing any property of a non-mutable object (i.e. aconstant) changes the object’s identity. For example, a rational number like 3/4 is non-mutable. It has two properties: a denominator and a numerator. If we change the numerator from 3 to 1, we regard the result, 1/4, as a completely different number.

Java strings are non-mutable simply because the String class fails toprovide mutators (methods that modify individual characters). Theintention is to force programmers to treat strings as constants rather than variables. Similarly, instances of the Number, Character and Boolean classes are non-mutable.

Your example raises two issues. First, an object can merge with anotherobject to form a larger object. For example, we can merge two stringsusing append:

 String first = “Bill”,          last = ” Clinton”,          both = first + last;
but no one would say that the string “Bill” mutated into the string”Bill Clinton” any more than one would say the number 3 mutated into 7 after 4 was added to it.

Second, unlike people, we don’t regard the name of an object as one of itsproperties. This is because we can always create anonymous instances of class:

new String(“Bill”);  // no name!
One might argue that the object to which a name refers is a property of the name, not the object. In this case, a name is mutable since we can always change its reference without changing its essential identity. Thus,
first = first + last;
changes the reference of first from “Bill” to “Bill Clinton,” but wedon’t regard the left-hand occurrance of first as a symbol distinctfrom the right-hand occurance.

How do we modify individual characters within a string? Java providesa mutable counterpart to the String class called StringBuffer, whichprovides a mutator called insert. For example:

StringBuffer sbfirst = new StringBuffer(first);   sbfirst.insert(1, ‘u’);  // change ‘i’ to ‘u’   first = mfirst.toString();
In fact, the expression:
 first + last
is compiled to:
new StringBuffer().append(first).append(last).toString()

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes