Last time there were some notes regarding the size of data and primitive types of data in Java.
Now we’ll talk about the String.
The String occupies a very special niche in the Java language; it’s not a type like the integers, or doubles: it is an object. But you can have Strings in java without having any Object-related syntax. In fact, you can represent a String in code just like any other constant value.
Some facts about strings in java:
- They are immutable, which means they have special behavior to make them much like primitive data types
- They respond to the sum operator + (by having Java transform every value involved into a String representation, then concatenate them)
- If two variables have the same string literal assigned to them, they actually point to the same memory address
Some details about the meaning of string immutability:
If you assign a variable a particular String, then change the value stored in the variable, then the memory address the variable points to changes, and a new string is created.
As a corollary of having multiple variables point to the same memory address if assigned to the same String literal, if you change the data in memory (supposedly you can’t but sun.misc.Unsafe exists), all the string variable’s data changes together.
If a two variables contain parts of the same string (ie: String a = “babcdol”; String b = “bab”;) then both strings point to the same spot – but the length changes. Playing with sun.misc.Unsafe helps shed light on the matter. This is because of a mechanism called the String Pool.
Strings are, perhaps, the weirdest data type in java thanks to these features. Shenanigans ensue when used as parameters, if you expect them to function like other Java objects.
Next time we’ll talk about casting, or converting variables from a type to another.