Intern property and equals method of immutable String class in Java



//String is immutable because it always creates new object in memory.
String abc = "Ram";                                              //takes new memory
abc = "Shyam";                                                     //takes new memory
abc = "Ghanshyam";                                             //takes new memory
What is String intern?
String Interning is a property of storing only one copy of each distinct String Value, which must be immutable.
//Now Lets explain this with example:
String a1 = "cat";
String a2 = new String("cat");
String a3 = "cat";
// here (a2) reference is a new object in java memory when compared with (a1) and (a3) because we have explicitly asked java to allocate new space in memory with "new" keyword.
whereas (a1) is the same object in memory and no new object is created when compared with (a3) because both of them have same content and we have no "new" keyword. 
//For verifying all this we have (==) operator which checks object equality in java and returns boolean.
System.out.println(a1==a2);                                                  //returns false
System.out.println(a1==a3);                                                  //returns true
//equals() method
Normally Java programmers are advised to use equals() method and  not ==, to compare two strings. This is because == operator compares memory locations (object equality), while equals()method compares the content stored in two objects (content equality) and returns boolean.
System.out.println(a1.equals(a2));                                                  //returns true because content is same
***************************************************************************************
QACult Best Software Testing Courses in Chandigarh tricity.- We love to enhance your knowledge.
QACult is the premier institute catering to the requirements of experienced and fresh pass-out that gives leaders like you a new way to experience Quality engineering—while you work and giving you the flexibility to both advance your career.
Our faculty have 12+ years of industrial experience and have developed many automation testing frameworks in java using TestNG or BDD (cucumber) methodology. We expertise in developing automation testing frameworks in java, python, javascript, php, ruby(WATIR-webdriver & Capybara) and Appium.
please subscribe our channel for more such updates:  
And visit for website: www.qacult.com for various blogs and Upcoming Events.


Comments

Popular posts from this blog

Robot Framework With Python: An Open Source Framework For RPA

Robot Framework in python with RIDE

How to do copy Paste in browser using selenium using Actions class