Tampilkan postingan dengan label answers. Tampilkan semua postingan
Tampilkan postingan dengan label answers. Tampilkan semua postingan

Core Java Interview Questions and Answers String concatenation



It is a very common beginner level question on String concatenation. Its imperative to understand that NOT all String concatenations are  bad. It depends on how you are using it. You need to have the basic understanding that in Java, String is an immutable object and StringBuilder (not thread-safe) and StringBuffer (thread-safe) are mutable. In, Java you can concatenate strings a number of ways with the "+" operator, using the append( ) in StringBuilder and StringBuffer classes, and the other methods like concat( ) in String class.

Q1. Is anything wrong with the following code?

public class StringConcat {
public static String withStringBuilder(int count) {
String s = "Hello" + " " + " peter " + count;
return s;
}

}
 
A1. No, the compiler internally uses a StringBuilder to use two append( ) calls to append the string and converts it to a String object using the toString( ) method.

Note: you can try the javap command  described below to see why.


Q2. Is anything wrong with the following code?
public class StringConcat {
public static String withStringBuilder() {
String s = "Hello" + " " + " peter " + " how are you";
return s;
}

}
 
A2. No, the compiler is smart enough to work out that it is a static concatenation and it uses its optimization to concatenate the string during compile-time. If you verify this by using a Java decompiler like jd-gui.exe to decompile the compiled class back, you will get the source code as below.
 
public class StringConcat
 {
public static String withStringBuilder(int count)
{
String s = "Hello peter how are you";
return s;
}
}

You can also use the javap command to dissemble the compiled class file using the following command
 
C:workspacesprojTestsrc>javap -c StringConcat

Gives the following output
 
Compiled from "StringConcat.java"
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static java.lang.String withStringBuilder(int);
Code:
0: ldc #2; //String Hello peter how are you
2: astore_1
3: aload_1
4: areturn

}

The line 0 shows that it has been optimized


Q3. Is anything wrong with the following code snippet

public class StringConcat {

public static String withoutStringBuilder(int count) {
String str = "";
for (int i = 0; i < count; i++) {
str += i;
}

return str;
}

}
 
A3. Yes. it consumes more memory and can have performance implications. This is because, a String object in Java is immutable. This means, you cant modify a String. If the value of count is 100, then the above code will create 100 new StringBuilder objects, of which 99 of them will be discarded for garbage collection. Creating new objects unnecessarily is not efficient, and the garbage collector needs to clean up those unreferenced 99 objects. StringBuffer and StringBuilder: are mutable and use them when you want to modify the contents. StringBuilder was added in Java 5 and it is identical in all respects to StringBuffer except that it is not synchronized, which makes it slightly faster at the cost of not being thread-safe. The code below creates only two new objects, the StringBuilder and the final String that is returned.
public class StringConcat {

public static String withStringBuilder(int count) {
StringBuilder sb = new StringBuilder(100);
for (int i = 0; i < count; i++) {
sb.append(i);
}

return sb.toString();
}

}
 
Now, if you want to be more pedantic as to how we know that the 100 StringBuilder objects are created, we can use the javap option to our rescue. The javap is a class file dissembler. If you compile the codebase in the question and then run the javap command with the StringConcat.class file as shown below
C:workspacesproj_blueTestsrc>javap -c StringConcat

You will get an output as shown below
 
Compiled from "StringConcat.java"
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static java.lang.String withoutStringBuilder(int);
Code:
0: ldc #2; //String
2: astore_1
3: iconst_0
4: istore_2
5: iload_2
6: iload_0
7: if_icmpge 35
10: new #3; //class java/lang/StringBuilder
13: dup
14: invokespecial #4; //Method java/lang/StringBuilder."<init>":()V
17: aload_1
18: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: iload_2
22: invokevirtual #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
25: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
28: astore_1
29: iinc 2, 1
32: goto 5
35: aload_1
36: areturn

}

The dissembled looks cryptic, but if you inspect it carefully the code within the public static java.lang.String withoutStringBuilder(int);

Line 5 to 32: is the code within the for loop. The "goto 5" indicates looping back.
Line 10: creates a new StringBuilder object every time
Line 18: uses the StringBuilders append method to concatenate the String.
Line 25: uses the toString( ) method to convert the StringBuilder back to the existing String reference via toString( ) method.

If you run the improved code snippet in the answer through javap, you get the following output
Compiled from "StringConcat.java"
public class StringConcat extends java.lang.Object{
public StringConcat();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static java.lang.String withStringBuilder(int);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: bipush 100
6: invokespecial #3; //Method java/lang/StringBuilder."<init>":(I)V
9: astore_1
10: iconst_0
11: istore_2
12: iload_2
13: iload_0
14: if_icmpge 29
17: aload_1
18: iload_2
19: invokevirtual #4; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
22: pop
23: iinc 2, 1
26: goto 12
29: aload_1
30: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
33: areturn

}

As you could see

Line 0 to 6: initializes one StringBuilder object outside the for loop.
Line 12 to 26: is the for loop.
Line 19: indicates that since the StringBuilder is mutable, the string is appended via the append method.


Important: The creation of extra strings is not limited to the overloaded mathematical operator "+", but there are several other methods like concat( ), trim( ), substring( ), and replace( ) in the String class that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations to get better performance. Experiment with javap for the String methods like concat( ), trim( ), substring( ), and replace( ) .

Note: So, javap and jd-gui.exe are handy tools for debugging your application for certain issues. For example, the java decompiler is handy for debugging generics to see how the java source code with generics is converted after compilation by decompiling the .class file back to source code.
Read More..

Top 10 Google Interview Questions Answers for Software Engineer Books Resources

These Google interview questions are some of my favorites collected from different sources. Every Programmer know that Google is one of the best technology company and its dream for many software developer to work for google, but at same time interview process at google is very tough and only few genuine intelligent programmers get through there interview process. Google interview questions are always been a good topic of discussion when few young software developer gathered around, I can still remember when one of my friend got call from google for interview then how whole bunch was got excited. We have searched a lot on internet on google interview questions and answers for him and us and then make a note of some of the best questions for preparation. I am listing down some google interview questions from that list. Apart from the popular questions asked in various Google Interview for software engineers or developers, books on algorithm and data structure plays a lot more important roles. Books like Algorithms for Interviews and Introduction to Algorithms are must read for any Programmer, who is serious about converting Google interview or similar companies like Facebook, Amazon and Microsoft. Once you start preparing for Google, rest of them become very easy.
Read more »
Read More..

Source control system and subversion aka SVN questions and answers

Q. Why do you need a source control system?
A. Source Control systems like subversion is a must if you are writing Java code by yourself or as a team. It allows multiple streams of coding, tracks the changes in your code and allows you to roll back to previous versions.  Here are the benefits of a source control system.

  • Have you ever realized that you have made a mistake and wanted to revert back to your previous revision? You also dont lose your code. You can experiment with things., and if things dont work as expected, you can revert your code.
  • Multiple streams or projects can work simultaneously on the same code base by branching the code from trunk, and then merging the code back to trunk and then tagging it prior to releasing and deploying the code.
  • Versioning helps you look at previous versions of the code to find out when and where bugs were introduced. You can compare two different versions of code side by side.
  • You can also create patches and apply patches.

Q. What are the differences between trunk, branch, and a tag in relation to a source control system like SVN?
A. There are many source control systems like Git, Clearcase, Subversion (aka SVN), etc, and SVN is a very popular open source source control system. You can use it via its command line commands or via GUI based client tools like TortosieSVN.

  • A trunk in SVN is main development area, where major development happens. Like a tree, trunk is a tree’s central superstructure. All branches come out of the trunk.
  • A branch in SVN is sub development area where parallel development on different features happens. Branches are created for adding new features/enhancements, bug fixes, and maintenance. After completion of a functionality, a branch is usually merged back into trunk. Tools like TortoiseSVN and IDE plugins for SVN simplifies the code merging task.
  • A tag in SVN is a read only copy of source code from branch or trunk at any point of time. A tag is mostly used to create a copy of released source code so that it can be rolled back.
  • A head is the latest version in the repository. That is either in the trunk or branch.

Q. What are the basic steps involved in merging? for example from a branch to trunk.
A. 

  • Step 1: Check out the destination stream from SVN. In this case it is the trunk.
  • Step 2: The SVN client tools like tortoiseSVN or Eclipse IDE plugin provides you with a GUI interface to select the source code to merge. In this case it is the branch. Click on the merge button to merge automatically, and where there are conflicts, you need to merge those conflicts manually. You can also use the SVN command-line option.
  • Step 3: Test the merged code locally to ensure that they compile and work as expected.
  • Step 4: Check in the merged code into the destination. In this case the trunk.

Q. What do you understand by the term rebase?
A. When developers work in parallel and commit changes to different streams of the same code base, eventually some or all of these commits have to be brought together into a shared graph, and merging and rebasing are two primary ways that let us do that.

  • Merging brings two lines of development together while preserving the ancestry of each commit history. It is like melting two different pipes  together. The pipe itself doesn’t break, it’s just combined with another pipe. So, the commit itself knows that it is a merge commit.
  • In contrast, rebasing  is like cutting off a pipe and weld it on another pipe. Rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Q. What is a sync merge and when do you perform it?
A. Say you create a new branch from a head to work some enhancements, and simultaneously some bug fixes were made on the trunk. Suppose that a month has passed since you started working on your new branch and your new feature are not finished yet, but at the same time you know that other people on your team continue to make important bug fixes on the trunk. Its in your best interest to replicate those changes to your own branch, just to make sure that they integrate well with your changes. This is done by performing a sync merge, which is a merge operation designed to bring your branch up to date with any changes made to its ancestral parent, which is the trunk in this case. The sync merge is also known as rebasing.

Q. What do you understand by the term patch or pull request?
A.A patch means change sets you want to communicate and apply to another repository. Nowadays, the GitHub pull request makes it really easy to apply patches on GitHub repos, which is useful when you arent a direct contributor. A patch is a small file that indicates what was changed in a repository. Its generally used when someone from outside your team has read-only access but had a good code change available. He then creates a patch and sends it to you. You apply it and push it to the git repository. Here is a simple example.

Create an input file named "input.txt" as shown below and check in to the repository like SVN.

  
This is line A.
This is line B.


Now modify the above code as shown below by replacing A in first line to C.

  
This is line C.
This is line B.


Now create a patch file, for example from eclipse IDE using the SVN plugin by right clicking on the file and then select Team --> Create patch. The patch file created will be

  

Index: src/test/resources/input.txt
===================================================================
--- src/test/resources/input.txt (revision 19063)
+++ src/test/resources/input.txt (working copy)
@@ -1,2 +1,2 @@
-This is line A.
+This is line C.
This is line B.
No newline at end of file


The above patch tells that

@@ -1,2 +1,2 @@ tells that in line 1 was removed and another line 1 was added and line 2 remains the same. The "-" next to "-This is line A." indicates that this line was removed. The "+" sign next to "+This is line C." indicates that this line was added. You will also get similar patch output with a Unix diff tool.

 
$ diff -u input.txt output.txt


Note: For beginners, it can be a bit overwhelming to understand version control system, and the following blog explains things visually.
Read More..

JSP Interview Questions and Answers

Q. How does JSP differ from a desk top application?
A. Desktop applications (e.g. Swing) are presentation-centric, which means when you click a menu item you know which window would be displayed and how it would look. Web applications are resource-centric as opposed to being presentation-centric. Web applications should be thought of as follows: A browser should request from a server a resource (not a page) and depending on the availability of that resource and the model state, server would generate different presentation like a regular “read-only” web page or a form with input controls, or a “page-not-found” message for the requested resource. So think in terms of resources, not pages.

Servlets and JSPs are server-side presentation-tier components managed by the web container within an application server. Web applications make use of HTTP protocol, which is a stateless request-response based paradigm. JSP technology extends the Servlet technology, which means anything you can do with a Servlet you can do with a JSP as well.



Q. Did JSPs make servlets obsolete? 
A. No. JSPs did not make Servlets obsolete. Both Servlets and JSPs are complementary technologies. You can look at the JSP technology from an HTML designer’s perspective as an extension to HTML with embedded dynamic content and from a Java developer’s as an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating HTML with out.println(“….. ”) statements, where “out” is a PrintWriter. This process of embedding HTML code with escape characters in Servlets is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.




Q. What is a model 0 pattern (i.e. model-less pattern) and why is it not recommended? What is a model-2  or MVC architecture?
A.

Problem: The example shown above is based on a “model 0” (i.e. embedding business logic within JSP) pattern.  The model 0 pattern is fine for a very basic JSP page as shown above.  But real web applications would have business logic, data access logic etc, which would make the above code hard to read, difficult to maintain, difficult to refactor, and untestable. It is also not recommended to embed business logic and data access logic in a JSP page since it is protocol dependent (i.e. HTTP protocol) and makes it unable to be reused elsewhere like a wireless application using a WAP protocol,  a standalone XML based messaging application etc.       

Solution:  You can refactor the processing code containing business logic and data access logic into Java classes, which adhered to certain standards. This approach provides better testability, reuse and reduced the size of the JSP pages.  This is known as the “model 1” pattern where JSPs retain the responsibility of a controller, and view renderer with display logic but delegates the business processing to java classes known as Java Beans. The Java Beans are Java classes, which adhere to following items:

  • Implement java.io.Serializable or java.io.Externalizable interface.
  • Provide a no-arguments constructor.
  • Private properties must have corresponding getXXX/setXXX methods.


The above model provides a great improvement from the model 0 or model-less pattern, but there are still some problems and limitations.

Problem:  In the model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the user. This architecture may be suitable for simple applications, but complex applications will end up with significant amount of Java code embedded within your JSP page, especially when there is significant amount of data processing to be performed.  This is a problem not only for java developers due to design ugliness but also a problem for web designers when you have large amount of Java code in your JSP pages. In many cases, the page receiving the request is not the page, which renders the response as an HTML output because decisions need to be made based on the submitted data to determine the most appropriate page to be displayed.   This would require your pages to be redirected (i.e. sendRedirect (…)) or forwarded to each other resulting in a messy flow of control and design ugliness for the application. So, why should you use a JSP page as a controller, which is mainly designed to be used as a template?       

Solution: You can use the Model 2 architecture (MVC – Model, View, Controller architecture), which is a hybrid approach for serving dynamic content, since it combines the use of both Servlets and JSPs. It takes advantage of the predominant strengths of both technologies where a Servlet is the target for submitting a request and performing flow-control tasks and using JSPs to generate the presentation layer. As shown in the diagram below, the servlet acts as the controller and is responsible for request processing and the creation of any beans or objects used by the JSP as well as deciding, which JSP page to forward or redirect the request to  (i.e. flow control) depending on the data submitted by the user. The JSP page is responsible for retrieving any objects or beans that may have been previously created by the servlet, and as a template for rendering the view as a response to be sent to the user as an HTML.




Q. If you set a request attribute in your JSP, would you be able to access it in your subsequent request within your servlet code?
    [This question can be asked to determine if you understand the request/response paradigm]
A. The answer is no because your request goes out of scope, but if you set a request attribute in your servlet then you would be able to access it in your JSP.



Important: Servlets and JSPs are server side technologies and it is essential to understand the HTTP request/response paradigm. A common misconception is that the Java code embedded in the HTML page is transmitted to the browser with the HTML and executed in the browser. As shown in the diagram above, this is not true. A JSP is a server side component where the page is translated into a Java servlet and executed on the server. The generated servlet (from the JSP) outputs only HTML  code to the browser.  

As shown above in the diagram, if you set a request attribute in your servlet code, it can be retrieved in your JSP code, since it is still in scope. Once the response has been sent back to the user (i.e. the browser) the current request goes out of scope. When the user makes another request, a new request is created and the request attribute set by the JSP code in your previous request is not available to the new request object.  If you set a session attribute in your JSP, then it will be available in your subsequent request because it is still in scope.  You can access it by calling session.getAttribute(“JSPText”).

Note: The above questions and answers are extracted from my book entitled Java/J2EE Job Interview Companion. Only a few JSP questions and answers are shown.
Read More..