Saturday, May 11, 2019

what will be the console output of the following code? Explain why?

Problem statement:
what will be output and explain why?
  1. public class ExecutionFive {
  2.     public static void main(String[] args) {
  3.         String s1 = "Cat";
  4.         String s2 = "Cat";
  5.         System.out.println(s1 == s2);
  6.     }
  7. }
Output:
true
Explanation - whenever we create an object of String class using 'string literal', string literal means using double quotation mark(" "), then that object stores in a place called string constant pool of heap. So, what JVM does, it checks the object in the string constant pool area, if that object is not available there, then it stores the new object. if the object is already available in string constant pool, then instead of creating new object, it points to the existing object, in this way we are saving the space, time and ultimately good performance.

Below is the memory diagram for string constant pool


No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...