0% found this document useful (0 votes)
38 views2 pages

Java String Tricky Questions

The document discusses Java Strings and their behavior, explaining the difference between string literals and objects created using the 'new' keyword. It highlights how references to strings in the constant pool can be equal while those in the heap cannot, and notes that the string constant pool is immutable and not eligible for garbage collection. Additionally, it introduces StringBuffer as a mutable alternative to String, which is synchronized for thread safety.

Uploaded by

vimalkmr550
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views2 pages

Java String Tricky Questions

The document discusses Java Strings and their behavior, explaining the difference between string literals and objects created using the 'new' keyword. It highlights how references to strings in the constant pool can be equal while those in the heap cannot, and notes that the string constant pool is immutable and not eligible for garbage collection. Additionally, it introduces StringBuffer as a mutable alternative to String, which is synchronized for thread safety.

Uploaded by

vimalkmr550
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java String

Strings:
[Link]
String var1 = “vimal” → string literal stored in string constant pool.
String var2 = new String(”vimal”) → creates a new Object in the Heap
String var3 = “vimal”
String var4 = new String(”vimal”)

var1 == var3 → True → point the reference in string constant pool


var 2 == var3 → false → no because it is a new object in the heap so its not
equal
var 2 == var4 → false → no because its 2 new objects in the heap so it's not
equal

How man objects are created for the below


String var4 = new String(”vimal”)
TWO → one in string constant pool and one in heap. the reason is JVM creates it
for reusability.

[Link]() → will return the reference to the string

The string constant pool is not eligible for garbage collection.


its immutable reason is we have files, data connection string, objects

StringBuffer

Java String 1
StringBuffer is a class in Java that represents a mutable sequence of
characters. It provides an alternative to the immutable String class, allowing
you to modify the contents of a string without creating a new object every
time.

StringBuffer is synchronized i.e. thread safe. It means two threads can't call
the methods of StringBuffer simultaneously.

Java String 2

You might also like