Sunday, 12 May 2019

Q1. What is the difference between “==” and “equals(…)” in comparing Java String objects?

When you use “==” (i.e. shallow comparison), you are actually comparing the two object references to see if they point to the same object. When you use “equals(…)”, which is a “deep comparison” that
compares the actual string values. For example:

public class StringEquals {
 public static void main(String[ ] args) {
   String s1 = "Hello";
   String s2 = new String(s1);
   String s3 = "Hello";
   System.out.println(s1 + " equals " + s2 + "--> " +  s1.equals(s2)); //true
   System.out.println(s1 + " == " + s2 + " --> " + (s1 == s2)); //false
   System.out.println(s1 + " == " + s3+ " --> " + (s1 == s3)); //true
 }
}



Create a String object as a literal without the “new” keyword for caching

The variable s1 refers to the String instance created by “Hello”. The object referred to by s2 is created with s1 as an initializer, thus the contents of the two String objects are identical, but they are 2 distinct objects having 2 distinct references s1 and s2. This means that s1 and s2 do not refer to the same object and are, therefore, not ==, but equals( ) as they have the same value “Hello”. The s1 == s3 is true, as they both point to the same object due to internal caching. The references s1 and s3 are interned and points to the same object in the string pool.

String Pool Caches and you create a String object as a literal without the "new" keyword for caching
Create a String object as a literal without the “new” keyword for caching

In Java 6 — all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool.

In Java 7 – the string pool was relocated to the heap. So, you are not restricted by the limited size.

Spring Boot @ConfigurationProperties and Properties File

 In this tutorial, you will learn to use @ConfigurationProperties to map properties files to POJO classes in Spring Boot application. Let’s ...