String and String pool in java

To do :

  • What is the use of String Object in java?
  • 1.How many objects are created while
  • String s = new String(“ABC”);
  • 3.Java Stack + Heap with Reference & Instance Variables
  • 4.String Constant Pool in Java || String Object Creation in Java
  • 5.Java interview question on hashcode() and equals() || Jav
  1. String object creation behind the scenes ||
  2. Why is string immutable in java?
  3. String Literal vs String Object
  4. How substring method works internally ?
    10.Stack and Heap memory in java basic knowledge
    11.String and Stringbuffer in java basic knowledge
  5. Difference Between “== Operator” And “equals()
    13.Explain how String intern() method works in java with example?

Proof String is immutable :

public class ProofStringIsImmutable {
	public static void main(String[] args) {
		String s1 = "ABC";
		String s2 = s1;
		System.out.println(s1.hashCode());
		s1="XYZ";
		System.out.println(s1.hashCode());
		System.out.println(s2.hashCode());
	}
}

Concatenation (+ operator)

The + operator can be used in two ways within the same line of code, Rules of using + operator :

  • If both operands are numeric, + means numeric addition.
  • If either operand is a String , + means concatenation.
  • The expression is evaluated left to right.
public class ConcatOperator {
	public static void main(String[] args) {
		System.out.println(1+2); //3
		System.out.println("a"+"b"); //ab
		System.out.println("a"+"b"+3); //ab3
		System.out.println(1+2+"c"); //3c
	}
}

Immutability

  • Study final first
  • Making a class immutable

How many objects are created while String s = new String(“ABC”); ?

Inside java heap memory there is a string constant pool.
When String s = new String("ABC"); 
Since new is used here the object has to be created in the heapmemory itself but it checkes if the entry of "ABC" exist in the String constant pool as well, and if it does not exist then it will make an entry into the string constant pool. But it will refear to the Object created in the heap only.

Leave a Comment