Strings Flashcards
1.What is a String
1.String is a special class in Java and it is immutable in nature.
2. Immutable means the strings once created it cannot be modified or changed it is constant
3.It is not like any other primitive data type , string is a Object.
2.What is String Constant Pool?
1.String Constant pool is a special memory space allocated inside the heap memory.
2.The Strings literals are stored in the string constant pool.
3.When a string is created jvm first checks in scp , if the string with the same value exists a reference to that string is returned, Otherwise, a new string object is created in the pool, and a reference to this new object is returned. This process is called “interning.”
3.What intern() method will do ?
1.Interna() method will add the exact copy of the string values in the heap memory and store it in the string constant pool.
2.This happens to make sure that it stores in scp and reducing the memory space.
3.If the string is already present in the scp it just returns the reference to the existing string object.
- In How many ways we can create a String?
4.By using String literals “” quotes
and
By using the New Keyword.
5.What is meant by Immutable and mutable in strings?
1.Immutable means strings are unchanged and unmodifiable once it is created. Strings are immutable
2. Mutable means we can modify or do any changes in the string
eg: StringBuffer and String builder
- In which package Strings, StringBuilder and String Buffer are there?
It is in java.lang package
We don’t want to import it explicitly as it is a fundamental class it is automatically imported in the java source file.
7.Is String is a Thread safe?
Yes, string is a thread safe as it is a immutable in nature
It values are constant so it is used in Multi-threaded environment.
- D/W String and String Builder
1.String is immutable and StringBuilder is mutable
2.Strings are thread safe and string Builder is not thread safe
3.String is slower than string builder incase of multiple concatenation as in string a new object is created when we do concatenation.
4.StringBuilder class doesn’t override equals() methods
but in string we can compare two strings using equals methods
9.D/W String Builder and String buffer.
1.Both are mutable in nature
2. String builder is faster than string buffer
3.String builder is not thread-safe where as string buffer is thread safe
10.How String Buffer is Synchronized?
1.Each method in the StringBuffer class is marked as synchronized. This means that when a thread invokes a method on a StringBuffer object, it acquires a lock on the object, ensuring that no other thread can access the object’s synchronized methods simultaneously.
11.What are the methods to compare two strings in Java?
1.equals()
2.equalsIgnoreCase()
2.comapreTo()
12.Why String is a popular HashMap key java?
Since String is immutable, its hash code is cached at the time of creation and it doesn’t need to be calculated again.