+ 2
String and References
If i say String text1 = "Hello World"; String text2 = "Hello World"; and then System.out.println(text1 == text2); is it true because both texts are stored in the same reference because they contain the same String? And with System.out.println(text1.equals(text2)); I would compare the String itself? Thanks for your help
10 Answers
+ 11
⢠Requirement of String Pool
String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
String str1 = "Hi there..";
String str2 = "Hi there..";
If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
⢠https://code.sololearn.com/clfOay4iwY7p/?ref=app
+ 5
In Java, strings are immutable đ
It means, you cannot use 2 strings with same values but different reference (without using new)
== checks for reference and as told above the strings with same value will have same reference but as you see the "new" keyword it becomes clear that a new reference is created
.equals checks for the value and not the reference so both the cases i.e. without "new" and with "new" will output the same.
+ 4
The SCP or the String Constant Pool doesn't store duplicate string. So when you create text1, it gets stored in SCP and when you create text2 with the same value then you just point to the same string with a new reference variable.
Since both point the same string, text1==text2 returns true. And yes the equals method compares the string content.
+ 3
Only one string object was created so both variables are given the same reference to the same object in string pool, if you wanted to create 2 seprate string objects you need to use the new keyword
String str= new String("hello");
String str2 = new String("hello");
0
what is java ? please explain
tell tamil and english
0
Thank you for your answers:-)
0
I studying java only
- 1
Java meaning
- 1
Tell
- 1
How to sound recognition by HTML code????