Search This Blog

Sunday, 30 May 2021

Difference between a tuple and collection in scala

 

Difference between Tuple and Collections in Scala :


1. Tuple store heterogenous data, means it can store different data types at a time. Where as collection stores same data type.

2. If we want to return two values from a function, lets say, we would like to return 1 and "Scala" at a time from a function we can use Tuple.

3. At max tuple can store 22 elements, But Collection can store more than 22 elements ( No restriction).



Wednesday, 5 May 2021

Differences between creation of string in java string s = "abc" and String s= new String("abc")

 

 

String s = “abc”

String s = new String(“abc”)

Why?

Creation of string literals are the preferred way in java

At times, we may wish to create separate instance for each separate string in memory. We can create one string object per string value using new keyword.

If we create many strings with same char sequence assume

String s = “abc”

String s1 =”abc”

String s2 = “abc”

All these variables will have same reference, we will not create the string again with same value in memory , this will save lot of memory in runtime.

If we create

String s = new String(“abc”)

String s1 = new String(“abc”)

String s2 = new String(“abc”), then we will create different objects/instances in heap memory.

The strings that are created with string literals are stored in special memory in heap memory called string pool. String literals are stored in String pool, a special memory area created by JVM

The strings created with new operator will be stored in heap memory but not in string pool

 

String s1 =”abc”, If we try to create same object , will have the reference of first string stored in string pool Which is existing in pool already.

String s1= new string (“abc”)

String s2 = new String (“abc”)

Different objects with different references will be created in heap momory.

 

String literals are stored in string pool

String objects are stored in head memory.

 

A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored.

When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap

 

 

 

 

 

 

 

 

 

 

String str1 = "Hello";

Lightbox

 

 

String str1 = "Hello";
String str2 = "Hello";

Lightbox

 

 

 

 

String str1 = "Hello";
String str2 = "Hello";
String str3 = "Class";

 

 

String str1 = new String("John");
String str2 = new String("Doe");

 

Regards,

Swathi.