String Flashcards
What is meant by Immutable in the context of Strings?
An immutable object cannot be modified in java. String is an immutable class in java. Once a string is created it cannot be changed.
Why a string is considered immutable?
There is a concept of string literal in java. If there are two String variables that reference to a String object “Test”, both these variables reference the same string literal.
How many ways are there to create a string?
There are two ways to create a String, one by using String literal and the other by using the “new” operator.
Why does java use string literals?
To make java more efficient in memory. If a string already exists in the string constant pool, it can be reused.
What is the main difference between a String and StringBuffer object.
String is an immutable object, its value cannot change after creation. StringBuffer is a mutable object. We can keep modifying the contents of a StringBuffer in java.
How can you make a class immutable in java?
Mark it as final to prevent it from being extended. Add private modifier to all the fields to prevent direct access. Do not provide setter methods.
What is the use of toString() in java?
Object class has a toString() method. This can be used to return the string representation of an object. Java provides default implementation for the toString method, but it can be overridden.
Arrange String, stringbuffer and stringbuilder in order of efficiency?
StringBuilder is the most efficient class, then StringBuffer, then String.