🪡String
Last updated
Last updated
In Java, a string is a type of variable that is used to store a sequence of characters, such as letters, numbers, and symbols. Strings are used to represent text and are a fundamental part of many Java programs.
Strings represent sequences of characters in Java. There are some key rules and facts to keep in mind when working with Strings.
Strings are immutable - their values cannot be changed after creation
Strings have a set of useful methods like length()
, charAt()
, etc.
Strings should be compared using equals()
not ==
Concatenation is done with +
operator or concat()
method
For example:
Some rules for String literals are:
Created by surrounding characters with double quotes
Two literal Strings with same characters refer to same object
Literal strings are stored in string pool in Java memory
Should be avoided in loops due to repeated object creation
For example:
Use backslash \
to encode special characters
for new line, for tab, \"
for double quote etc.
Unicode escapes like \uFFFF
can encode any character
For example:
So these rules help in efficiently and correctly handling Strings in Java.
Strings are used in Java to perform many different tasks, such as:
Storing and manipulating text
Printing text to the console
Reading and writing text files
Communicating with databases and web services
In Java, strings are stored as objects, which means that they have properties and methods that can be used to manipulate them. When you create a string in Java, it is stored in memory as an object with its own unique properties and methods.
To use strings in Java, you first need to create a string variable and assign a value to it. For example, you can create a string variable called "name" and assign it the value "John":
Once you have created a string variable, you can use it in your program to perform tasks such as printing text to the console or reading text from a file.
Answer: Strings are immutable in Java for several reasons: 🙋♂️
If Strings were mutable, this could lead to security issues. For example, malicious code could potentially modify String variables and manipulate data.
Since Strings are immutable and cannot be changed, two threads can share String references without synchronization issues. String pooling also works because Strings don't change.
Since String objects are immutable, they can be placed in a string constant pool. This saves memory since multiple objects with the same value can refer to the same object in the pool.
Immutability makes string operations like copying, comparing, etc very easy since we are actually working with the character array inside the String.
That's why whenever we perform operations that appear to modify a String, a new String object is actually created. For example:
Here s.concat("World")
returns a new String "HelloWorld", it doesn't modify s
. So in summary, immutability brings security, performance, and easier implementation of String operations in Java.