Goldman Sachs Interview Question for Java Developers


Country: India
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
8
of 10 vote

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:

$ cat Test.java 
public class Test {
    public void simplyPrint() {
        String temp = "A" + "B" + "C";
        System.out.println(temp);
    }

    public void concatWithInt() {
        String temp = "A" + "B" + "C";
        String inty = temp + 1;
        System.out.println(temp);
    }

    public static void main(String[] args) {
    }
}
$ javac Test.java
$ javap -c Test.class
Compiled from "Test.java"
public class Test {
  public Test();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        

  public void simplyPrint();
    Code:
       0: ldc           #2                  // String ABC
       2: astore_1      
       3: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
       6: aload_1       
       7: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      10: return        

  public void concatWithInt();
    Code:
       0: ldc           #2                  // String ABC
       2: astore_1      
       3: new           #5                  // class java/lang/StringBuilder
       6: dup           
       7: invokespecial #6                  // Method java/lang/StringBuilder."<init>":()V
      10: aload_1       
      11: invokevirtual #7                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      14: iconst_1      
      15: invokevirtual #8                  // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      18: invokevirtual #9                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      21: astore_2      
      22: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
      25: aload_1       
      26: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      29: return        

  public static void main(java.lang.String[]);
    Code:
       0: return        
}

- Zygis November 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 2 votes

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.

- Anup November 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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

- welcometotalk December 02, 2013 | Flag
Comment hidden because of low score. Click to expand.
3
of 5 vote

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"

- Lousianastar November 26, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
2
of 4 vote

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.

- bo November 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

+1. Correct. Only 2 objects would be created. :)

- Stupid Developer November 11, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

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.

- teli.vaibhav November 11, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Only 2 Objects will be created that is correct,
compiled code is : String temp = new StringBuffer().append("A").append("B").append("C").toString();

Object 1: Intermediate StringBuffer object which is used for concatenation.
Object 2: String object which will be returned.

- zack June 24, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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)

- aramkirakosyan89 November 11, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hey nice explanation about why the strings are immutable. However 4 objects won't be created. Nice explanation by "bo" below.

- Stupid Developer November 11, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.

- kaps November 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I found this old resource

http : // www . javaranch . com /journal/200408/ScjpTipLine-javap.html

Explains the situation pretty well :)

- Zygis November 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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...

- PRASHANTGAURAV November 12, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nice Explanation!! Thank you

- Ilavarasan November 16, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think the answer is 6. 3 choose 2 is 6. We have 6 combinations for A B C order of object creation.

- Stupid Developer November 13, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

hahaha

- Jais March 20, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.

- Pooja November 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string buffers are used to concat binary operators +.
so
temp= "a" + "b" + "c"
is compiled to the equivalent of:
temp = new StringBuffer().append("a").append("b").append("c")
.toString();
here one string buffer will be created which is freed immediately after. and only temp is used

- neha November 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.

- Nirmal November 14, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object .If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in Java.

- Ilavarasan November 16, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.

- lal November 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

4 object created

- vikash.choudhary10 December 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think it will create one object, because "A","B","C" is constant, so they just store in the constant pool, just one object will create is temp

- hashiqi January 13, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

5 - > "A" ,"B" , "C" , "AB", "ABC"

- Ashish January 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

total 5 objects..

- hydabckumar March 12, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

1 object will be created, which you can easily verify by testing the code for object equality.

String temp="A"+"B"+"C";
if (temp == "ABC" && temp == "A"+"B"+"C"){
	System.out.println("QED");
}

- zack.kenyon March 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

3 objects will get created

- Bindu Mahapatra March 09, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

---> 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.

- Aman Raj March 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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"

- Kruz March 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

how many objects will be created in String temp = "A" + "B" + "C" ; explain your answer in detail.
only 1 object will get created.
String internally used stringbuilder..
in this case ...String temp = "A" + "B" + "C" ;
new StringBuilder().append("A").append("B").append("C").toString();

- sudBisht April 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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.

- jnaveen771 May 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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"

- sudBisht May 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The compiler creates 1 String per JVM start, because the compiler can determine the resulting String at compile time, it is interned and statically stored in the JVM's String Table.
so only one object will be created .

- shukad333 June 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

According to me 5 objects will get created, A, B, C, AB and ABC.

- Ajay Kumar July 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Four objects will be created string temp ="A" + "B" +"C".

- raj November 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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??

- Blah.... December 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

There are five object.
3 Objects for "A" , "B" and "C"
String temp = "A"+"B"+"C"
4th Object create when "A"+"B" Intermediate and concatination happen with step by step which is return "AB"
5th "AB"+"C";

Please let me know if anyone have suggestion on it.

- rathor.rajeev August 20, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More