Java Technical Interviews - Wrox Press Java Programming 24-Hour Trainer 2nd (2015)

Wrox Press Java Programming 24-Hour Trainer 2nd (2015)

Lesson 37. Java Technical Interviews

Technical job interviewing is a game with well-defined rules. I’ve worn the hats of both interviewer and interviewee many times over my Java career. In this lesson I share with you my views on hiring Java developers and on preparing for technical interviews.

Regardless of whether the IT job market is hot or not at any given time, there are some rules and techniques that can increase your interview success rate. The process of getting a job consists of three separate activities:

1. Getting the interview

2. Interviewing successfully

3. Considering the offer

I can’t stress enough how important it is to work on each of these tasks separately, one step at a time! Let’s discuss them one by one.

Getting the Interview

Your résumé is the most important thing in the first step. Unless you are a well-known Java guru (if you were, you wouldn’t read this book) your résumé is your main weapon for getting an interview. Adjust the résumé for each position you are applying for. No, I’m not asking you to lie, but you have to highlight your skills that match each particular job opening you’re applying to. Make sure it’s short and to the point (not more than two pages long).

If you are applying for a Java developer’s position, nobody needs to know the details of that Visual Basic project from 10 years ago. Always update your résumé based on the feedback you receive from recruiters or more experienced programmers.

There is a summary section on each résumé, and many people waste this space with some junk like, “I’m looking for a challenging position that will let me improve my talents.” What a waste! Use this summary line to show your relevant skills.

Say you’ve been specializing in Java messaging during the last two years, but this job posting requires web developers. Add a phrase that the messaging architecture was able to support both Java and web clients. Recruiters are not too technical—they do a quick résumé scan to find the presence of the required keywords. Also, chances are that you’ve developed web applications before; highlight your web experience in the summary section of your résumé. The same day you may be responding to another ad seeking people who know Java messaging.

Modify your summary section accordingly and send a version of your résumé that emphasizes your experience with messaging; your understanding of the web principle is not that important here.

Job requirements are more involved these days, and recruiting companies don’t even want to submit your résumé to the client if you have “only” 8 out of 10 required skills. Read the requirements and highlight all the relevant skills you have. Do not be lazy; work with your résumé.

Networking is another great way to get an interview. This time I’m not talking about Java networking; I’m talking about meeting other IT people who may be hiring or know people who are hiring. Attend your local Java Users Group meetings, join online meetups, follow Java developers on Twitter, and go to professional conferences and seminars.

Doing Well at the Interview

OK. The interview is scheduled, and now your main goal is to ace it. Remember, your interviewer has a difficult task: He needs to assess your technical skills within 30 to 60 minutes, so help him! In advance of the interview, try to get as many technical details about the job as possible from your recruiter. If the position you are applying for requires knowledge of Java sockets, research working with non-blocking sockets. If the company is building Java EE applications, find out which application server they use and read up on it.

Do your homework and prepare a short talk about some interesting and challenging technical problems you might have experienced in one of your college or real-world projects. If you didn’t have any super-complex projects, just pick up a topic from one of the multiple online programmers’ forums and research it. Another great source of Java tips and tricks is a hugely popular online resource called Stackoverlow. This is a place where software developers ask and answer questions about different programming languages and technologies. Check out the Java section at Stackoverflow.

For example, if you have prepared a talk on concurrent collections, you’re not allowed to leave the interview without talking about this. But what if the interviewer won’t ask you about Java concurrency? It doesn’t really matter. Find a way to switch the conversation to the prepared topic and do your best. The interviewer will be happy because he doesn’t need to think about what to ask next, and you’re happy because you’ve had a chance to talk about a well-prepared subject.

Will this technique work all the time? No. But it’ll work most of the time. Obviously you need to research the selected subject well, or you’ll get burned. You must talk about technical challenges you’ve resolved. You need to remember that your interviewers face a challenging task of figuring out your technical abilities in just 30 minutes. So, you need to help them out. Be in charge.

If you’re a junior developer, spend some time answering the multiple-choice computer tests that are usually required for certification exams. You don’t need to get certified, but all these books and online mock tests will help you pass similar tests offered by some job agencies. Find some sample interview questions online.

A technical interview is a game with known rules, but in many cases the interviewers are not prepared to run the interviews. Sometimes they just go by a prepared list of questions. Some interviewees take advantage of this and just spend some time studying introductory courses, and then memorize questions and answers for technical interviews. Believe it or not, in many cases this works.

What does a good enterprise Java developer have to know in addition to understanding the difference between abstract classes and interfaces? Usually employers are looking for people with knowledge of the following: Java Servlets, JSP, Spring framework, JMS, any commercial message-oriented middleware, JDBC, JNDI, HTML, XML, Hibernate, build tools, SQL, one of the major application servers, and a couple of relational database management systems.

Understanding why a particular Java EE component is being used in your current project is equally important. If the interviewer asks you, “Why did you use EJB in this project?” please do not answer, “That decision was made before I joined the project.” Even if it was, have your own opinion and explain why you think it was a good or bad choice for this particular project.

Here’s another tip: Don’t critique the application architecture of your potential employer. You’ll have plenty of chances to provide technical advice if you’re hired, so just focus on getting an offer. Remember, one step at a time!

Be energetic during the interview and show your interest in the job. Even if you are a technical guru, don’t behave as if you’re doing the interviewer a favor just by showing up. Personality matters. People don’t like prima donnas.

Be prepared to write code on a whiteboard and practice that skill. The interviewer may not ask you to do this, but it may be a good idea to start illustrating your thoughts on the board if there is one in the room. If there is no board, use your own notepad. Often interviewers are trying to judge how well you think and approach a problem more than how effectively you’ve memorized an algorithm, class name, or method arguments.

No need to rush. If you start writing a code fragment on a board, don’t be afraid of making mistakes. Think aloud. It may be even beneficial for the interviewer to see how you can identify the wrong approach and then pick the right one. Practice explaining little code fragments to your friends or relatives; they don’t need to know Java to participate in these role-playing games.

Questions of data structures and collections are pretty popular during the interviews. For example, you need to be able to explain when using LinkedList is better than using ArrayList. Some people fail the interview on simple task like “write a program to reverse letters in a word.” Get a book on data structures and algorithms and skim through it before going to the interview.

After the interview, as soon as you leave the building, take notes about what just happened. Don’t postpone it until you get home; you may forget important details. Make a note to work on the questions you might have not answered correctly. These questions require your attention and research. Improve your technical skills after each interview.

Considering the Offer

You’ve got an offer! Now think hard about whether you want to accept it. Have I mentioned that you should look for a new job not when your employer decides to let you go or your contract ends, but when you have a stable job, the sky is blue, and the grass is green? This gives you a tremendous advantage: You can consider the offer without being under pressure from unpaid bills.

Don’t accept an offer just because the new job pays an extra $5,000 a year, which comes to less than $300 a month after taxes. Do accept the offer that gives you a chance to work with interesting technologies or business applications even if it won’t pay you an extra dime.

Other nonmonetary factors of an offer are health benefits, flexible work hours, ease of commute, or simply a kinship that you feel with the people working for the potential employer. Believe it or not, some people won’t accept offers from employers who require you to wear suit and tie. Just make a decision about what’s more important for you—having an interesting job or being able to show off your latest tattoos.

No matter what your preferences are, take charge of your career and actively build it the way you want.

Interviewing Enterprise Developers

When the job market is healthy, major online job search engines show thousands of openings, and people are competing for these jobs. These days a seasoned developer has to know about 10 different tools or technologies to find a good job and feel relatively secure for a couple of years. Over the last several years I’ve interviewed lots of Java developers, and this is what I’ve noticed:

· People do not call themselves Java developers or programmer-analysts anymore; most of them prefer the title Java architect. Unfortunately, only some of them really understand how Java EE components operate and can suggest design solutions. Of course, knowledge of Java EE is not all that a Java architect should know.

· Job applicants are more senior, and I barely see any college graduates or junior programmers. Many of the junior positions are being outsourced and the number of graduates with computer science degrees has declined over the past several years.

· Having software certification does not make a résumé stand out. Actually, if a résumé starts with a list of certifications, most likely it’s a beginner’s. I’m not against certifications, as they help you learn a language or a tool, and show that you are willing to and can study. But a certificate doesn’t make someone a skilled professional.

· With the introduction of middle-tier object-relational mapping frameworks such as Hibernate, many people don’t even bother learning how database management systems work or how to write a SQL query that performs well — they just map Java classes to database tables.

· On multiple occasions I’ve interviewed enterprise Java developers who were trained to use certain frameworks, but without understanding how things work under the hood. A simple question to explain in details what happens between the moments when the user click the button Get Data on a web page and when the data arrive often results in a description of how a certain web framework does it. But what if there is no frameworks, but just a web page and a servlet. Not many programmers can describe such a data flow.

· In a slow economy, be prepared to pass at least four interviews to get hired. Back in 1999 two good interviews would be enough; in 2001 it was very difficult to even get an interview, let alone a job!

· Today large portions of development is done in India. Even though the total cost of development is not low despite the lower hourly rates of offshore developers, Western hiring managers unfortunately have an impression that local candidates must be flexible in their rates, too. Being a native English speaker is not enough for you to charge top dollar. Always be technically current, otherwise the more motivated guys from overseas will leave you in the dust.

Good knowledge of the business terminology of your potential employer is also important. I’m not sure about the Silicon Valley or Europe, but here in New York just being a techie may not be good enough to get you a senior job. Of course, interviewing with Google or Microsoft is an exception.

For example, if you’re applying for a Java position in a financial brokerage company and don’t know what a short sale is, this may be a deal breaker. If you are a senior developer you should be able to hit the ground running: Try to find out from your recruiter as many details as possible about the business. Do your homework, and you’ll get the job! Recruiters are desperately looking for good programmers, and you can be one of them.

To Get or Not to Get Certified?

Any certification program is a business for the vendor that wants to sell training to award certificates. Oracle is no exception; you can find various certification programs to rate your Java skills. The following website offers various certification programs in Java SE and EE technologies:http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=651#5.

Although most certification programs require you to pass a multiple-choice computer test, some of them (such as those for Java EE architects) give you a challenging task to design and program.

Overall I think it’s a good idea to prepare yourself and go through the certification process because it will definitely improve your understanding of the Java language or a specific enterprise technology or framework. In some areas it may also improve the perception of your résumé. It’ll also help you slip through computer screening tests that are used by job placement agencies. Just check job postings from your potential employers to see if they insist on having certificates.

I also want to caution you against overestimating the importance of getting Java certification. When I see a résumé that starts with a list of certificates, it tells me that this candidate is good... at passing multiple-choice tests. Having practical hands-on experience working on open-source or enterprise projects is a lot more valuable than any certificate you might have earned. It’s fine if you have certificates, but keep them somewhere at the end of your résumé rather than trying to present them as a major achievement.

Technical Questions and Answers

Suggesting a list of technical questions for an interview is a risky business. Seasoned Java developers have different views on what’s fair and what’s not fair to ask. But junior developers who just completed a Java tutorial can definitely benefit from some guidance in preparing for Java job interviews.

The following are suggested technical interview questions and expected brief answers on various Java-related topics. The questions included in this section are those that I had to answer while working on various projects. In no way is this a complete list of possible questions, but it definitely gives you an idea of what to expect at an interview. Most of the answers to these questions can be found in this book, but some require additional research.

Q:

What’s the difference between an interface and an abstract class?

A:

Prior to Java 8 I’d answered that an abstract class may contain code in method bodies, which is not allowed in an interface. But with introduction of the defender and static methods in interfaces the answer should be different. Abstract classes can implement state in member variables, but interfaces can’t. You can extend from one abstract class, but implement multiple interfaces.With abstract classes you have to inherit your class from the abstract one because Java does not allow multiple inheritance.

Q:

How do you deploy a web application in the application server that you currently use?

A:

In most Java EE application servers you create a web archive (war file) and copy it to the assigned directory per the application server documentation. (You should be able to explain the directory structure in a war file.)

Q:

Why were the defender methods introduced in Java 8?

A:

Oracle’s software engineers wanted to include new methods in the existing interfaces. If they would just add new method declarations, lots of existing code would break because classes that implement those interfaces didn’t implement newly introduced methods. The keyword defaultallowed them to add new methods in the interfaces without forcing existing classes implement them.

Q:

What’s the usage of the keyword static?

A:

It’s used in declarations of methods and variables to make them available without creating an instance of the class. For example, the main() method is a static one. If a variable is static, its value is shared by all instances of the class.

Q:

How can you force garbage collection?

A:

You can’t force garbage collection, but you can request it, because JVM does not guarantee that it’ll be started immediately. Invoking System.gc() requests Java garbage collection.

Q:

Why would you use lambda expression in your code?

A:

Lambda expression makes the code more concise and in some cases allows developers to flatten the class hierarchies and eliminate certain classes. For more details read about eliminating polymorphism in Lesson 13.

Q:

How do you decide if explicit casting is needed?

A:

If you assign a superclass object to a variable of a subclass’s data type, you need to use explicit casting. For example:

Object a;

Customer b;

b = (Customer) a;

Java generics can eliminate the need for explicit casting. For subclass-to-superclass assignments, the casting is performed automatically. You can also cast to interfaces that a class implements.

Q:

Can you perform casting between objects of different types?

A:

No, you can’t. The objects can have a superclass-subclass relationship, or you can cast to interfaces implemented by a class.

Q:

Can a Java class be inherited from two classes?

A:

No, Java does not allow multiple inheritance, but a class can implement multiple interfaces, which, to some extent, can be used as a workaround.

Q:

What’s the difference between constructors and regular methods?

A:

Constructors must have the same name as the class and cannot return a value. They are invoked only once, while regular methods can be invoked many times.

Q:

What’s a cookie? Which Java components create them?

A:

A cookie is an object that represents a name/value pair. Servlets, JSP, and third-party Java frameworks can create and send cookies to a web browser that saves them on the user’s disk in a special directory. Cookies help the server-side code to identify a user and implement session tracking.

Q:

Does each abstract class have at least one abstract method?

A:

Not necessarily. If a class is declared with the abstract keyword, it can be instantiated even if it has no abstract methods. For example, you can declare an abstact class Animal, which should never be instantiated, while one can create instances its concrete subclasses Cat and Dog.

Q:

Explain the use of Java packages.

A:

Packages offer a way to organize multifile projects. They also help in resolving naming conflicts when different packages have classes with the same names. Package access level also enables you to protect data from being used by unauthorized classes, permitting only the classes from the same package to see each other’s member variables.

Q:

Explain the usage of the keyword transient.

A:

The transient keyword indicates that the value of this member variable does not have to be serialized with the object. When the class gets deserialized, transient variables are initialized with the default values of the variable data types (such as 0 for integers).

Q:

What do you know about thread synchronization? Explain the difference between

public void synchronized myMethod() { ... }

and

public void myMethod() {

...

synchronized (some_object) {... }

}

A:

The keyword synchronized is used to prevent race conditions when more than one thread tries to update some values. Synchronized blocks are preferable to synchronized methods because they place locks for shorter periods. The package java.util.concurrent includes a class ReentrantLock, which can be a better solution than using the synchronized keyword.

Q:

What’s the difference between the methods sleep() and wait()?

A:

The code sleep(1000) puts the thread aside for exactly one second. The code wait(1000) makes the thread wait for up to one second. A thread can stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object, but sleep() is defined in the class Thread.

Q:

What’s the difference between creating threads subclassing the class Thread and implementing the Runnable interface?

A:

Thread creation with the class Thread requires that your class be inherited from it. Then you need to create an instance of your class and call its start() method. If a class implements the Runnable interface the procedure is different; you have to create the instance of your class, and the instance of the Thread object, passing the Runnable class to the latter. Using Runnable enables you to create threads from classes that have to be inherited from classes other than Thread classes. You can implement Runnable with lambda expressions.

Q:

How can you create a thread that can return a value from its method run()?

A:

You need to implement the Callable interface.

Q:

What would you use to compare two String variables: the equals() method or the == operator?

A:

I’d use equals() to compare the values of the Strings, and the == operator to check whether two variables point at the same String object in memory.

Q:

What do you know about the MVC design pattern?

A:

MVC stands for the model-view-controller design pattern, which is used to separate presentation modules from business logic and data ones. The model part represents the data and the business logic of the application, the view is a visual representation (for example, a UI), and the controller accepts the data from the view and passes it to the model and vice versa.

Q:

How can you reduce the time spent by JVM on creating frequently used instances of some objects?

A:

I’d create my own or configure existing object pools (for example, DataSource can be configured to use object pools of database connections).

Q:

Will the following statement create the file xyz.txt on disk?

File a = new File("xyz.txt");

A:

No, it just creates an object pointing to this file.

Q:

How can a subclass invoke a method defined in a superclass?

A:

Java has the keyword super. If a method has been overridden, but you’d like to invoke its version defined in the superclass, use the following syntax: super.myMethod();. To call a constructor of the superclass, use super(); with required parameters in the first line of the subclass’s constructor.

Q:

Can a functional interface declare more than one method?

A:

Yes as long as only one of them is abstract. For example, besides abstract methods you can have several defender and static methods in the interface.

Q:

What access level do you need to specify for members of the class Customer to ensure that only classes from the same directory can access these members?

A:

You do not need to specify any access level. In this case, Java uses the default package access level, which guarantees visibility for the Customer members only to the classes located in the same directory (package).

Q:

What’s the use of JNDI?

A:

JNDI is a Java API for naming and directory servers. It is used for finding Java objects by name in a distributed application. For example, you can use JNDI to get a reference to the DataSource or JMS objects.

Q:

Can you modify the data in the underlying collection using the Stream API?

A:

No you can’t. The underlying data set is immutable.

Q:

If you need to catch more than one exception (such as FileNotFoundException and IOException), does the order of the catch statements matter?

A:

Yes, it does. FileNotFoundException is inherited from IOException. The exception subclasses have to be caught first.

Q:

Explain in detail the data workflow between a web page and a Servlet called FindBooks after the user clicks Submit. (In this question interviewers can replace the web page and Servlet with any other client-server components. The main point is to find out if the job applicant understands the entire end-to-end data flow.)

A:

The web browser connects to the server located at the specified URL, and if FindBooks has not been started yet, the Servlet container starts it, invoking the servlet’s init() method followed by the service() method, which in turn calls doGet() or doPost(), depending on the method of HTTP request. The objects HTTPServletRequest and HTTPServletResponse are used for the interaction between the client and FindBooks. The Servlet’s output can be sent back to the user by means of one of the methods of HTTPServletResponse, for example println().

Q:

Explain the process of getting the data from a database table in a Java SE program using JDBC. Which classes and methods have to be used?

A:

First you load the appropriate JDBC driver using Class.forName(). After that you get the Connection object using either the DataSource object or DriverManager.getConnection(). Then you create a Statement object and invoke one of its methods, like executeQuery() or executeUpdate(). Process the ResultSet, if any, and close the Connection, Statement, and ResultSet objects. In some cases instead of Statement you use PreparedStatement or CallableStatement.

Q:

What are the differences among the Java keywords final, finalize, and finally?

A:

Depending on its position, the keyword final means either that the variable can be initialized only once, or that you cannot override a method, or that you cannot subclass a class. Parameters in the catch block are implicitly final.

The method finalize(), if defined in your class, is invoked by the garbage collector when it’s ready to release a memory used by the instance of your class.

The keyword finally is used in a try/catch block to place code, that must be executed whether the code in the try block succeeds or fails.

Q:

Can you declare fields in an interface?

A:

You can only declare final and static variables in an interface.

Q:

Can an inner class, declared inside a method, access local variables of this method?

A:

It’s possible only if the method’s variables are final.

Q:

What could be used to keep track of sessions in web applications?

A:

You can use cookies, URL rewriting, and the HTTPSession object.

Q:

Will session management with cookies always work?

A:

No, if a user disables cookies in the web browser, it won’t work. In such cases application servers usually automatically switch to URL rewriting.

Q:

How can you stop a long-running thread?

A:

The class Thread has a deprecated method called stop(), but this method does not guarantee that the thread will be stopped. Depending on the process that is run by this thread, you could try to close connections or open streams, if any, or use the method interrupt().

Q:

When could a Java class be called a bean?

A:

You call the class a bean if it has a no-argument constructor, implements the Serializable interface, and has public setter/getter methods for its private properties.

Q:

What are the advantages of using JSP rather than Servlets?

A:

JSP enables you to separate presentation from business logic and the resulting web page can be modified by people who do not know Java.

Q:

Give an example that shows the difference between the use of the operators && and &.

A:

In the following code snippet, the second expression in the if statement is not even evaluated if variable a is null. If a single ampersand were used here you’d get a NullPointerException.

String a=null;

if (a != null && a.length()>10) {...}

Q:

Name some predefined JSP variables.

A:

request, response, out, session...

Q:

How do you deploy a JSP?

A:

You can place .jsp files in a document root directory of the Servlet container or application server, or create a war file and put a JSP in the document root there.

Q:

What’s the default port number that web servers use for HTTP-based communications?

A:

HTTP requests go through port 80; HTTPS ones go through port 443.

Q:

What method of the Servlet class is an equivalent of a constructor in a regular Java class?

A:

The Servlet’s method init() plays a similar role, but because all clients use the same instance of the Servlet, you should initialize only those variables that are allowed to have the same value for each user’s request, such as the name of the database server.

Q:

Which is faster: array or ArrayList?

A:

In most cases arrays are faster. An array can be used if you know in advance the number of elements in the array. ArrayList is an API on top of an array. You do not need to know its size in advance; new elements can be added as needed. Arrays work faster because JVM allocates memory only once for all elements. But to give you a better answer I’d have to write an appropriate benchmark in context to find out.

Q:

What do you know about Java reflection?

A:

Reflection is a way of finding information about a Java class internals during run time. For example, you can find out the constructors and the method signatures of a particular class. The class Class has such methods as getConstructor(), getFields(), getMethods(), and others.

Q:

What would you do if your Java program crashed during the run time with an “out of memory” error?

A:

I’d try to increase the size of the JVM’s dynamic memory (heap) on program start-up using command-line parameters. For example, you can request the minimum heap size of 512 MB and the maximum heap size of 1024 MB as follows:

java –Xms512 –Xmx1024 MyProgram

Q:

How can you ensure that only one instance of some class can be created in your application?

A:

You need to implement the singleton design pattern. Create a class with a private constructor and provide a public getter method that returns the only instance of this class—for example MyClass.getInstance().

Q:

What’s the major difference between a Hashtable and a HashMap?

A:

The Hashtable class is internally synchronized, whereas the HashMap is not.

Q:

Name some design patterns.

A:

Singleton, MVC, data transfer object, facade... While preparing to answer this question, refer to the article on design patterns at Wikipedia.

Q:

The word stateless is used to describe a session EJB as well as HTTP protocol. What’s the meaning of the word stateless in these two cases?

A:

HTTP protocol is page-based, meaning that the web browser does not hold the connection between requests, but in the case of an EJB, stateless means that the session bean cannot be used to store the state of a particular client.

Q:

Are Java objects passed by value or by reference?

A:

Objects are passed by reference, but their reference variables are passed by value.

Q:

How can a Java client access a message-driven bean?

A:

Java clients don’t access MDBs directly; they just place messages into a queue or publish them to topics, and the MDB retrieves them from there.