Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Java strings work [duplicate]

I'm trying to understand exactly how Java strings are immutable. I get that this should probably be an easy concept, but after reading several online web pages I still don't quite understand.

I don't understand how Java Strings are "immutable". I currently have the following code:

public static void main(String[] args) {

  String name = "Jacob Perkins";

  System.out.println( name );

  name = name + "!";

  System.out.println( name );

}

My output is the following:

Jacob Perkins
Jacob Perkins!

Why is this happening if a string is supposed to be immutable? Why am I able to re-assign a value to the string?

like image 615
user2301187 Avatar asked May 08 '13 04:05

user2301187


People also ask

How are duplicate characters found in a string Java?

The duplicate characters are found in the string using a nested for loop.

Can strings have duplicates?

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.

How do you replicate a string in Java?

The string can be repeated N number of times, and we can generate a new string that has repetitions. repeat() method is used to return String whose value is the concatenation of given String repeated count times. If the string is empty or the count is zero then the empty string is returned.


2 Answers

Let an image explain this for you:

String example

On the left side, you have the variable, which in fact is a reference.

  1. String name = "Jacob Perkins;" The String "Jacob Perkins" is created, and name points to it.
  2. name = name + "!"; A new String "Jakob Perkins!" is created, and the reference now points to the new String. The old one, however, remains unchanged, because String is immutable.
like image 195
Uooo Avatar answered Oct 28 '22 02:10

Uooo


The string itself, once created, can never be changed. What your code sample does is to replace the string in name with a new string that was constructed from the previous contents of name, and an exclamation point. (The original contents of name, which are no longer referenced by any variable, will eventually be reaped by the garbage collector.)

If you were to examine the compiled code (or step through it with a debugger), you would discover that your name + "!" expression had been compiled into the creation of a StringBuilder object and a few operations on that object.

That is, the strings are immutable, but the variable name is not. Its value changes, to point to different strings. The strings themselves never change.

like image 41
Edward Falk Avatar answered Oct 28 '22 02:10

Edward Falk