Goldman Sachs Interview Question
Java DevelopersCountry: India
Interview Type: Phone Interview
Buddy will it not create any object at all or it will not create any String object?
I am asking this question because i am sure this will create some StringBuilder Objects in memory. Strings concatenated with + symbol internally uses StringBuilders to create the String object. Let me know if i am wrong.
This code will allocate memory to store string constant "ABC" and will create One "String" Object ( as mentioned in byte code - astore_1 local stack varaible ) and assign the String Constant Reference to String Object's instance varaiable "value" char array.
So the answer is It did creates one String Object ( allocates memory to keep the String Object's instance varaible such as count , offset , hash and the "value" char array will point to the String Constant Pool.
Assume , String are mutable , in other words the value char can be changed . So the Compiler cannot be used the same memory for all similar values.
for example:
String s = "ABC"
String a = "ABC"
If the String are mutable , then the jvm should allocate two value char[] memory to hold same char sequence ,
if the Strings are immutable , then the jvm can use the property and save the memory allocation. Note** When we do substring / any method invocation in String it is allocating memory for all other instance variables, but for value char array it try to look the constant pool and if exists it picks from there.
One more info, Strings can be mutable if you are using Reflection
See the sample for how to make mutable and risk and why it is not mutable by default.
public class StringTest {
public static void main(String args[]){
String a = "test213";
String s = new String("test213");
try {
System.out.println("Before Modification:"+a);
System.out.println("Before Modification:"+s);
char[] value = (char[])getFieldValue(s, "value");
value[1] = 'z';
System.out.println("After Modification:"+a);
System.out.println("After Modification:"+s);
} catch (Exception e) {
e.printStackTrace();
}
}
static Object getFieldValue(String s,String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Object chars = null;
Field innerCharArray = String.class.getDeclaredField(fieldName);
innerCharArray.setAccessible(true);
chars = innerCharArray.get(s);
return chars;
}
}
Results
Before Modification:test213
Before Modification:test213
After Modification:tzst213
After Modification:tzst213
Q. why strings are immutable ?
A. Immutable objects are those which state can't be change. That is , the class is final and cannot be extended. Immutable objects are more thread safe. String works like with pools.
If we create two or more String objects and assign the same value, lets say "Test", in case String wouldn't be immutable than it would be possible to change the value of "Test" and it would have impact on other objects having the same value too.
Q. how many objects will be created in String temp = "A" + "B" + "C" ; explain your answer in detail.
4 objects will be created with the values "A", "B", "C" and "ABC"
Only two objects will be created. "A", "B", "C" are string constants, they will be put into constant pool in .class file at compile time, not in the heap. One object is created for intermediate result "A" + "B", another one is temp.
Hey can you please explain what you mean by being put into the constant pool in the .class file and when this happens. The first thing I said to myself after looking at the question was 5 objects would be created. Clearly I am missing out on something conceptual here.
There are many reasons why strings are immutable in Java.
One of the primary reasons is security. Strings used as parameter in many methods, for example for opening database connection, files, network connections. It can be easily attacked if it is mutable.
Another reason is that immutability makes String thread safe.
To calculate hashcode only once and cash it, which makes better performance for hashMaps, when Strings are used as a key.
4 objects will be created, three for storing "A", "B" , "C" and one for "ABC" (temp)
I too feel 4 objects will be created. But would like to understand how the answer can be zero?
See below code. Here 8 objects are created.
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
Answer: The result of this code fragment is spring winter spring summer.
There are two reference variables, s1 and s2. There were a total of eight String objects
created as follows: "spring", "summer " (lost), "spring summer", "fall" (lost), "spring
fall" (lost), "spring summer spring" (lost), "winter" (lost), "spring winter" (at this point
"spring" is lost). Only two of the eight String objects are not lost in this process.
String temp="A"+"B"+"C";
3 Object will created here.
Why Sting is immutable..?
String is immutable because of String pooling.
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference...
I think the answer is 6. 3 choose 2 is 6. We have 6 combinations for A B C order of object creation.
According to me,its just one object which would be created.
String temp="ABC"
One string object and ABC would be left out in the pool.
If it were String temp=new String("ABC");
it would have lead to the creation of two string objects.
Strings are immutable because they are stored in a constant pool and before any string object is created,as in here,temp="abc",abc would first be checked in the pool.If its already present,temp will simply be made to refer it.Else,a new abc is created.In such cases,there would be many references to abc already present.So,if your program was able to chance that String object,it would have deferenced all those previously referring variables.
String is immutable correct because This not a primitive type. This is also one of the Class this string value reference only stored in stack but string is stored only heap. more than one reference create same value , reference create the how many of them created in programs all references are create in stack but value same on the already stored value cant create,
temp= "a" + "b" + "c" here only one object only created.
String temp = "A" + "B" + "C" ;
In this, Instead of creating multiple temporary objects in the Heap, here strings appended to string buffer .
String temp=new Stringbuffer().append("A").append("B").append("C").toString();
Stringbuffer , instead of creating a new String objects, it will expand the capacity and stores the string objects in that. This happens as part of JIT compiler optimization , so one object will be created.
---> Java developers made Strings immutable in order to make it thread safe. Assume that it was not immutable, in that case two different threads executing same string would have created problem because if one threads modifies the string it affects the output of second thread. So by making it immutable, it is made sure that whenever one thread changes the string, it results in complete different string without affecting the previous one.
---> I think number of string generated will be ONE because "a","b","c" being constant will be changed to "abc" at compile time so result ("abc") will be assigned to a string variable temp.
Immutable means that unary operators cannot be applied to change the values of the immutable variable. You have to reference the variable and assign the new value to it as a binary operation.
string str = "1";
++str (not valid)
--str (not valid)
str = Integer.parse(str) + 1; or in your case
str = "A" str1 = "AB"
str = str + str1; so,
str = "ABC"
String class is final it never make use of stringbuilder, here 3 object is created
A ,AB,ABC since strings are immutable when you change it creates another object without destroying previous,previous just become unreachable. example for strings are immutable is like licking plastic choclate.
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method
check it out here
"http" + "://docs.oracle.com/javase/7/docs/api/java/lang/String.html"
A string builder object is created right but what about "A" "B" "C" are they all not objects,are they not allocated memory ???...
After a string builder object is created the string "A',"B","C" are appended to it fine.
after that inorder to convert a string builder to string stringbuilder.toString method is called which again creates a string object and is returned as a reference
so totally 5 objects "A","B","C",stringBuilder,String objects are created but only the final string objects reference is used .
Am I right or wrong??
Actually, this code will create no objects at all. "A" + "B" + "C" will be optimized by a compiler to "ABC". Now, if we are going to use this constant in a smart way (e.g. append an integer value), then objects will be created. Proof:
- Zygis November 11, 2013