What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
1 – Java code provides for class methods with both public and private access specifiers. What is the difference between these two modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables and functions to specific classes within a class hierarchy. This is accomplished using various access specifiers, and knowing the difference between these fundamental components is a very relevant java interview question.
Particularly in Java, where classes can only be declared public, or not at all – whereas member functions have four different modifiers – this is a tricky subject for beginners.
Correct answers
A public access specifier directs that the method be accessible both inside and outside of the class. This is true as long as the class, itself, is declared as public, or the calling class is within the same package. If the class does not specify a modifier then it is assumed to have default (package) access, and the declarations for its methods do not override this.
A private access specifier directs that the method be accessible only inside of the class.
Bonus
If the candidate knows that there are also specifiers for protected and package (default) then it demonstrates a good understanding of this topic.
Very bad
If the candidate is unaware of the difference between public and private then it indicates a lack of experience in both Java and other object oriented languages such as C++. Should the answer be correct, but no mention of the fact that the class modifier overrides the methods, it should be penalized.
Consider the following code that contains a class, a static variable and a public method. How many bites were taken for each apple?
public class Apple {
static int bites = 0;
public void takeBite() {
bites++;
}
public static void main(String[] args) {
// Instantiate red and green apples for our example public class
Apple macintosh = new Apple();
Apple grannySmith = new Apple();
// Take a bite out of each of the two apples
macintosh.takeBite();
grannySmith.takeBite();
// Display the contents of each class
System.out.println("The Macintosh apple has " + macintosh.bites + " bite(s) out of it.");
System.out.println("The Granny Smith apple has " + grannySmith.bites + " bite(s) out of it.");
}
}
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
The goal of this article is to help prepare the interviewer, whatever their experience with java may be. Determining which candidate among many has presented the top java interview is not an easy task. At the same time, it will not be found using purely code-related or tricky interview questions. Programming is often about the logic, as opposed to the syntax, and it would be a serious mistake to penalize candidates too heavily for not being entirely familiar with something that can easily be looked up using Google.
That said, it is important to remember that the interview is, indeed, for a Java programming position. The candidate must have knowledge of the Java runtime environment (JRE), the Java virtual machine (JVM), the Java development kit (JDK), and more. Commonly used libraries such as java lang, java util should not be a mystery. Similarly, while it has fallen out of use, the Swing library should at least ring familiar while it is OK to not know the Awt library, which is completely obsolete. Finally, candidates may not have widespread experience, but should still at least be aware of the existence of frameworks and other technologies such as Spring framework, JavaServer Pages (JSP), and Java Database Connectivity (JDBC).
Java interview questions need to be specific in some regards, yet general in others. For example, is it necessary to include specific JDBC interview questions? Not likely. However, a candidate must absolutely know what a List interface is. Similarly, one may be forgiven for not immediately knowing how to interface to Oracle using JDBC, while at the same time should have some experience with building a application making use of threads.
With so many competing goals, how does one find the ideal candidate? The answer rests with a broad set of interview questions that covers the topic from more than one perspective. This article aims to address these concerns by providing the Java interview question, the correct answer or answers, and the rationale for asking each question.
Check out the Java question below. There are multiple ways to solve it, so the candidate’s choices can reveal how they code. How would you solve it? Click on the “Instructions” tab and try it out:
Programming Questions and Answers
This article contains 14 interview questions and answers. The first 5 are at the beginner level, while the remainder vary in both topic and level of difficulty. A perfect score will not necessarily be one that comes from answering every question to some level of satisfaction. Rather, the discussion surrounding solutions will give the best indicator as to both capability and experience.
Beginner-level Programming Interview Questions
1 – Java code provides for class methods with both public and private access specifiers. What is the difference between these two modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables and functions to specific classes within a class hierarchy. This is accomplished using various access specifiers, and knowing the difference between these fundamental components is a very relevant java interview question.
Particularly in Java, where classes can only be declared public, or not at all – whereas member functions have four different modifiers – this is a tricky subject for beginners.
Correct answers
A public access specifier directs that the method be accessible both inside and outside of the class. This is true as long as the class, itself, is declared as public, or the calling class is within the same package. If the class does not specify a modifier then it is assumed to have default (package) access, and the declarations for its methods do not override this.
A private access specifier directs that the method be accessible only inside of the class.
Bonus
If the candidate knows that there are also specifiers for protected and package (default) then it demonstrates a good understanding of this topic.
Very bad
If the candidate is unaware of the difference between public and private then it indicates a lack of experience in both Java and other object oriented languages such as C++. Should the answer be correct, but no mention of the fact that the class modifier overrides the methods, it should be penalized.
Consider the following code that contains a class, a static variable and a public method. How many bites were taken for each apple?
public class Apple {
static int bites = 0;
public void takeBite() {
bites++;
}
public static void main(String[] args) {
// Instantiate red and green apples for our example public class
Apple macintosh = new Apple();
Apple grannySmith = new Apple();
// Take a bite out of each of the two apples
macintosh.takeBite();
grannySmith.takeBite();
// Display the contents of each class
System.out.println("The Macintosh apple has " + macintosh.bites + " bite(s) out of it.");
System.out.println("The Granny Smith apple has " + grannySmith.bites + " bite(s) out of it.");
}
}
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
When discussing preparation for a Java programming interview, the focus is typically on the interviewee. Candidates want to know what types of questions to expect so that they can best prepare. Yet the point at issue remains – what type of java interview questions does an employer ask potential candidates in order to best evaluate their skills?
In a software development house, regardless of whether the java programming language or even object oriented programming is standard, coming up with programming questions and answers is straightforward. It is easy to employ Google, for example, to search for language syntax to help with writing the core java interview. However, what happens in cases where (or when) the company needs to hire a contractor for a simple project? Or, similarly, the existing team is non-technical and they are expanding to include their own in-house software group?
Before starting, here is a quick definition of the term Java that should help you if you are not familiar with this language:
Java is a high-level programming language developed by Sun Microsystems. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications.
The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being more strict than C++, meaning variables and functions must be explicitly defined. This means Java source code may produce errors or “exceptions” more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types.
Christensson, P., Java Definition, techterms.com
The goal of this article is to help prepare the interviewer, whatever their experience with java may be. Determining which candidate among many has presented the top java interview is not an easy task. At the same time, it will not be found using purely code-related or tricky interview questions. Programming is often about the logic, as opposed to the syntax, and it would be a serious mistake to penalize candidates too heavily for not being entirely familiar with something that can easily be looked up using Google.
That said, it is important to remember that the interview is, indeed, for a Java programming position. The candidate must have knowledge of the Java runtime environment (JRE), the Java virtual machine (JVM), the Java development kit (JDK), and more. Commonly used libraries such as java lang, java util should not be a mystery. Similarly, while it has fallen out of use, the Swing library should at least ring familiar while it is OK to not know the Awt library, which is completely obsolete. Finally, candidates may not have widespread experience, but should still at least be aware of the existence of frameworks and other technologies such as Spring framework, JavaServer Pages (JSP), and Java Database Connectivity (JDBC).
Java interview questions need to be specific in some regards, yet general in others. For example, is it necessary to include specific JDBC interview questions? Not likely. However, a candidate must absolutely know what a List interface is. Similarly, one may be forgiven for not immediately knowing how to interface to Oracle using JDBC, while at the same time should have some experience with building a application making use of threads.
With so many competing goals, how does one find the ideal candidate? The answer rests with a broad set of interview questions that covers the topic from more than one perspective. This article aims to address these concerns by providing the Java interview question, the correct answer or answers, and the rationale for asking each question.
Check out the Java question below. There are multiple ways to solve it, so the candidate’s choices can reveal how they code. How would you solve it? Click on the “Instructions” tab and try it out:
Programming Questions and Answers
This article contains 14 interview questions and answers. The first 5 are at the beginner level, while the remainder vary in both topic and level of difficulty. A perfect score will not necessarily be one that comes from answering every question to some level of satisfaction. Rather, the discussion surrounding solutions will give the best indicator as to both capability and experience.
Beginner-level Programming Interview Questions
1 – Java code provides for class methods with both public and private access specifiers. What is the difference between these two modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables and functions to specific classes within a class hierarchy. This is accomplished using various access specifiers, and knowing the difference between these fundamental components is a very relevant java interview question.
Particularly in Java, where classes can only be declared public, or not at all – whereas member functions have four different modifiers – this is a tricky subject for beginners.
Correct answers
A public access specifier directs that the method be accessible both inside and outside of the class. This is true as long as the class, itself, is declared as public, or the calling class is within the same package. If the class does not specify a modifier then it is assumed to have default (package) access, and the declarations for its methods do not override this.
A private access specifier directs that the method be accessible only inside of the class.
Bonus
If the candidate knows that there are also specifiers for protected and package (default) then it demonstrates a good understanding of this topic.
Very bad
If the candidate is unaware of the difference between public and private then it indicates a lack of experience in both Java and other object oriented languages such as C++. Should the answer be correct, but no mention of the fact that the class modifier overrides the methods, it should be penalized.
Consider the following code that contains a class, a static variable and a public method. How many bites were taken for each apple?
public class Apple {
static int bites = 0;
public void takeBite() {
bites++;
}
public static void main(String[] args) {
// Instantiate red and green apples for our example public class
Apple macintosh = new Apple();
Apple grannySmith = new Apple();
// Take a bite out of each of the two apples
macintosh.takeBite();
grannySmith.takeBite();
// Display the contents of each class
System.out.println("The Macintosh apple has " + macintosh.bites + " bite(s) out of it.");
System.out.println("The Granny Smith apple has " + grannySmith.bites + " bite(s) out of it.");
}
}
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
When discussing preparation for a Java programming interview, the focus is typically on the interviewee. Candidates want to know what types of questions to expect so that they can best prepare. Yet the point at issue remains – what type of java interview questions does an employer ask potential candidates in order to best evaluate their skills?
In a software development house, regardless of whether the java programming language or even object oriented programming is standard, coming up with programming questions and answers is straightforward. It is easy to employ Google, for example, to search for language syntax to help with writing the core java interview. However, what happens in cases where (or when) the company needs to hire a contractor for a simple project? Or, similarly, the existing team is non-technical and they are expanding to include their own in-house software group?
Before starting, here is a quick definition of the term Java that should help you if you are not familiar with this language:
Java is a high-level programming language developed by Sun Microsystems. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications.
The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being more strict than C++, meaning variables and functions must be explicitly defined. This means Java source code may produce errors or “exceptions” more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types.
Christensson, P., Java Definition, techterms.com
The goal of this article is to help prepare the interviewer, whatever their experience with java may be. Determining which candidate among many has presented the top java interview is not an easy task. At the same time, it will not be found using purely code-related or tricky interview questions. Programming is often about the logic, as opposed to the syntax, and it would be a serious mistake to penalize candidates too heavily for not being entirely familiar with something that can easily be looked up using Google.
That said, it is important to remember that the interview is, indeed, for a Java programming position. The candidate must have knowledge of the Java runtime environment (JRE), the Java virtual machine (JVM), the Java development kit (JDK), and more. Commonly used libraries such as java lang, java util should not be a mystery. Similarly, while it has fallen out of use, the Swing library should at least ring familiar while it is OK to not know the Awt library, which is completely obsolete. Finally, candidates may not have widespread experience, but should still at least be aware of the existence of frameworks and other technologies such as Spring framework, JavaServer Pages (JSP), and Java Database Connectivity (JDBC).
Java interview questions need to be specific in some regards, yet general in others. For example, is it necessary to include specific JDBC interview questions? Not likely. However, a candidate must absolutely know what a List interface is. Similarly, one may be forgiven for not immediately knowing how to interface to Oracle using JDBC, while at the same time should have some experience with building a application making use of threads.
With so many competing goals, how does one find the ideal candidate? The answer rests with a broad set of interview questions that covers the topic from more than one perspective. This article aims to address these concerns by providing the Java interview question, the correct answer or answers, and the rationale for asking each question.
Check out the Java question below. There are multiple ways to solve it, so the candidate’s choices can reveal how they code. How would you solve it? Click on the “Instructions” tab and try it out:
Programming Questions and Answers
This article contains 14 interview questions and answers. The first 5 are at the beginner level, while the remainder vary in both topic and level of difficulty. A perfect score will not necessarily be one that comes from answering every question to some level of satisfaction. Rather, the discussion surrounding solutions will give the best indicator as to both capability and experience.
Beginner-level Programming Interview Questions
1 – Java code provides for class methods with both public and private access specifiers. What is the difference between these two modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables and functions to specific classes within a class hierarchy. This is accomplished using various access specifiers, and knowing the difference between these fundamental components is a very relevant java interview question.
Particularly in Java, where classes can only be declared public, or not at all – whereas member functions have four different modifiers – this is a tricky subject for beginners.
Correct answers
A public access specifier directs that the method be accessible both inside and outside of the class. This is true as long as the class, itself, is declared as public, or the calling class is within the same package. If the class does not specify a modifier then it is assumed to have default (package) access, and the declarations for its methods do not override this.
A private access specifier directs that the method be accessible only inside of the class.
Bonus
If the candidate knows that there are also specifiers for protected and package (default) then it demonstrates a good understanding of this topic.
Very bad
If the candidate is unaware of the difference between public and private then it indicates a lack of experience in both Java and other object oriented languages such as C++. Should the answer be correct, but no mention of the fact that the class modifier overrides the methods, it should be penalized.
Consider the following code that contains a class, a static variable and a public method. How many bites were taken for each apple?
public class Apple {
static int bites = 0;
public void takeBite() {
bites++;
}
public static void main(String[] args) {
// Instantiate red and green apples for our example public class
Apple macintosh = new Apple();
Apple grannySmith = new Apple();
// Take a bite out of each of the two apples
macintosh.takeBite();
grannySmith.takeBite();
// Display the contents of each class
System.out.println("The Macintosh apple has " + macintosh.bites + " bite(s) out of it.");
System.out.println("The Granny Smith apple has " + grannySmith.bites + " bite(s) out of it.");
}
}
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
When discussing preparation for a Java programming interview, the focus is typically on the interviewee. Candidates want to know what types of questions to expect so that they can best prepare. Yet the point at issue remains – what type of java interview questions does an employer ask potential candidates in order to best evaluate their skills?
In a software development house, regardless of whether the java programming language or even object oriented programming is standard, coming up with programming questions and answers is straightforward. It is easy to employ Google, for example, to search for language syntax to help with writing the core java interview. However, what happens in cases where (or when) the company needs to hire a contractor for a simple project? Or, similarly, the existing team is non-technical and they are expanding to include their own in-house software group?
Before starting, here is a quick definition of the term Java that should help you if you are not familiar with this language:
Java is a high-level programming language developed by Sun Microsystems. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications.
The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being more strict than C++, meaning variables and functions must be explicitly defined. This means Java source code may produce errors or “exceptions” more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types.
Christensson, P., Java Definition, techterms.com
The goal of this article is to help prepare the interviewer, whatever their experience with java may be. Determining which candidate among many has presented the top java interview is not an easy task. At the same time, it will not be found using purely code-related or tricky interview questions. Programming is often about the logic, as opposed to the syntax, and it would be a serious mistake to penalize candidates too heavily for not being entirely familiar with something that can easily be looked up using Google.
That said, it is important to remember that the interview is, indeed, for a Java programming position. The candidate must have knowledge of the Java runtime environment (JRE), the Java virtual machine (JVM), the Java development kit (JDK), and more. Commonly used libraries such as java lang, java util should not be a mystery. Similarly, while it has fallen out of use, the Swing library should at least ring familiar while it is OK to not know the Awt library, which is completely obsolete. Finally, candidates may not have widespread experience, but should still at least be aware of the existence of frameworks and other technologies such as Spring framework, JavaServer Pages (JSP), and Java Database Connectivity (JDBC).
Java interview questions need to be specific in some regards, yet general in others. For example, is it necessary to include specific JDBC interview questions? Not likely. However, a candidate must absolutely know what a List interface is. Similarly, one may be forgiven for not immediately knowing how to interface to Oracle using JDBC, while at the same time should have some experience with building a application making use of threads.
With so many competing goals, how does one find the ideal candidate? The answer rests with a broad set of interview questions that covers the topic from more than one perspective. This article aims to address these concerns by providing the Java interview question, the correct answer or answers, and the rationale for asking each question.
Check out the Java question below. There are multiple ways to solve it, so the candidate’s choices can reveal how they code. How would you solve it? Click on the “Instructions” tab and try it out:
Programming Questions and Answers
This article contains 14 interview questions and answers. The first 5 are at the beginner level, while the remainder vary in both topic and level of difficulty. A perfect score will not necessarily be one that comes from answering every question to some level of satisfaction. Rather, the discussion surrounding solutions will give the best indicator as to both capability and experience.
Beginner-level Programming Interview Questions
1 – Java code provides for class methods with both public and private access specifiers. What is the difference between these two modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables and functions to specific classes within a class hierarchy. This is accomplished using various access specifiers, and knowing the difference between these fundamental components is a very relevant java interview question.
Particularly in Java, where classes can only be declared public, or not at all – whereas member functions have four different modifiers – this is a tricky subject for beginners.
Correct answers
A public access specifier directs that the method be accessible both inside and outside of the class. This is true as long as the class, itself, is declared as public, or the calling class is within the same package. If the class does not specify a modifier then it is assumed to have default (package) access, and the declarations for its methods do not override this.
A private access specifier directs that the method be accessible only inside of the class.
Bonus
If the candidate knows that there are also specifiers for protected and package (default) then it demonstrates a good understanding of this topic.
Very bad
If the candidate is unaware of the difference between public and private then it indicates a lack of experience in both Java and other object oriented languages such as C++. Should the answer be correct, but no mention of the fact that the class modifier overrides the methods, it should be penalized.
Consider the following code that contains a class, a static variable and a public method. How many bites were taken for each apple?
public class Apple {
static int bites = 0;
public void takeBite() {
bites++;
}
public static void main(String[] args) {
// Instantiate red and green apples for our example public class
Apple macintosh = new Apple();
Apple grannySmith = new Apple();
// Take a bite out of each of the two apples
macintosh.takeBite();
grannySmith.takeBite();
// Display the contents of each class
System.out.println("The Macintosh apple has " + macintosh.bites + " bite(s) out of it.");
System.out.println("The Granny Smith apple has " + grannySmith.bites + " bite(s) out of it.");
}
}
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.
When discussing preparation for a Java programming interview, the focus is typically on the interviewee. Candidates want to know what types of questions to expect so that they can best prepare. Yet the point at issue remains – what type of java interview questions does an employer ask potential candidates in order to best evaluate their skills?
In a software development house, regardless of whether the java programming language or even object oriented programming is standard, coming up with programming questions and answers is straightforward. It is easy to employ Google, for example, to search for language syntax to help with writing the core java interview. However, what happens in cases where (or when) the company needs to hire a contractor for a simple project? Or, similarly, the existing team is non-technical and they are expanding to include their own in-house software group?
Before starting, here is a quick definition of the term Java that should help you if you are not familiar with this language:
Java is a high-level programming language developed by Sun Microsystems. It was originally designed for developing programs for set-top boxes and handheld devices, but later became a popular choice for creating web applications.
The Java syntax is similar to C++, but is strictly an object-oriented programming language. For example, most Java programs contain classes, which are used to define objects, and methods, which are assigned to individual classes. Java is also known for being more strict than C++, meaning variables and functions must be explicitly defined. This means Java source code may produce errors or “exceptions” more easily than other languages, but it also limits other types of errors that may be caused by undefined variables or unassigned types.
Christensson, P., Java Definition, techterms.com
The goal of this article is to help prepare the interviewer, whatever their experience with java may be. Determining which candidate among many has presented the top java interview is not an easy task. At the same time, it will not be found using purely code-related or tricky interview questions. Programming is often about the logic, as opposed to the syntax, and it would be a serious mistake to penalize candidates too heavily for not being entirely familiar with something that can easily be looked up using Google.
That said, it is important to remember that the interview is, indeed, for a Java programming position. The candidate must have knowledge of the Java runtime environment (JRE), the Java virtual machine (JVM), the Java development kit (JDK), and more. Commonly used libraries such as java lang, java util should not be a mystery. Similarly, while it has fallen out of use, the Swing library should at least ring familiar while it is OK to not know the Awt library, which is completely obsolete. Finally, candidates may not have widespread experience, but should still at least be aware of the existence of frameworks and other technologies such as Spring framework, JavaServer Pages (JSP), and Java Database Connectivity (JDBC).
Java interview questions need to be specific in some regards, yet general in others. For example, is it necessary to include specific JDBC interview questions? Not likely. However, a candidate must absolutely know what a List interface is. Similarly, one may be forgiven for not immediately knowing how to interface to Oracle using JDBC, while at the same time should have some experience with building a application making use of threads.
With so many competing goals, how does one find the ideal candidate? The answer rests with a broad set of interview questions that covers the topic from more than one perspective. This article aims to address these concerns by providing the Java interview question, the correct answer or answers, and the rationale for asking each question.
Check out the Java question below. There are multiple ways to solve it, so the candidate’s choices can reveal how they code. How would you solve it? Click on the “Instructions” tab and try it out:
Programming Questions and Answers
This article contains 14 interview questions and answers. The first 5 are at the beginner level, while the remainder vary in both topic and level of difficulty. A perfect score will not necessarily be one that comes from answering every question to some level of satisfaction. Rather, the discussion surrounding solutions will give the best indicator as to both capability and experience.
Beginner-level Programming Interview Questions
1 – Java code provides for class methods with both public and private access specifiers. What is the difference between these two modifiers?
Rationale
In object oriented programming it common to limit the scope of both variables and functions to specific classes within a class hierarchy. This is accomplished using various access specifiers, and knowing the difference between these fundamental components is a very relevant java interview question.
Particularly in Java, where classes can only be declared public, or not at all – whereas member functions have four different modifiers – this is a tricky subject for beginners.
Correct answers
A public access specifier directs that the method be accessible both inside and outside of the class. This is true as long as the class, itself, is declared as public, or the calling class is within the same package. If the class does not specify a modifier then it is assumed to have default (package) access, and the declarations for its methods do not override this.
A private access specifier directs that the method be accessible only inside of the class.
Bonus
If the candidate knows that there are also specifiers for protected and package (default) then it demonstrates a good understanding of this topic.
Very bad
If the candidate is unaware of the difference between public and private then it indicates a lack of experience in both Java and other object oriented languages such as C++. Should the answer be correct, but no mention of the fact that the class modifier overrides the methods, it should be penalized.
Consider the following code that contains a class, a static variable and a public method. How many bites were taken for each apple?
public class Apple {
static int bites = 0;
public void takeBite() {
bites++;
}
public static void main(String[] args) {
// Instantiate red and green apples for our example public class
Apple macintosh = new Apple();
Apple grannySmith = new Apple();
// Take a bite out of each of the two apples
macintosh.takeBite();
grannySmith.takeBite();
// Display the contents of each class
System.out.println("The Macintosh apple has " + macintosh.bites + " bite(s) out of it.");
System.out.println("The Granny Smith apple has " + grannySmith.bites + " bite(s) out of it.");
}
}
Rationale
Static variables are a feature of java that is used regularly by developers. As is the case for global variables, it is important for programmers to understand the scope of these objects in order to avoid unintended side effects and other errors. Not declaring a variable. This helps avoid mistyping a variable name as the mistyped variable will appear to be a new, undeclared variable.
Correct answer
The Apple class shares the static variable, bites, among all of its instances. Therefore, when the takeBite() method is called on each of the instances, the common variable is updated. The end result is:
The Macintosh apple has 2 bite(s) out of it.
The Granny Smith apple has 2 bite(s) out of it.
Very Bad
If the candidate answers that each of the two instances has a single bite then it indicates a lack of experience with static variables. Although this is a trivial topic that is easily learned, it is one that is frequently encountered. Being unaware of it is an indicator that the candidate is lacking practical experience with the language.
What is an exception? Briefly describe the two types of exception used in java code.
Rationale
Exceptions are unexpected events that occur at run time, and differ from errors in that “catching” them is a reasonable course of action. Errors, on the other hand, typically indicate a more serious problem. The handling of exceptions is very common and should be understood, at least at a basic level, by all java programmers.
Correct answers
The two types of exceptions in java are checked and unchecked exceptions.
A checked exception is one that is “checked” at compile time. When there is code within a method that “throws” a checked exception, the method is required to acknowledge it. This can be accomplished either by handing the exception with a try/catch block, or specifying it using the throws keyword. An unchecked exception is one that is not checked at compile time. It is up to the programmer to either specify or catch this type of exception. In contrast, all of the exceptions in C++ are unchecked.
Bonus
In java, all of the exceptions under Error and RuntimeException classes are unchecked. Everything else under Throwable is checked. If the interviewee raises this point then it demonstrates a deeper understanding of when each one is used.
Very Bad
If the candidate is unaware of exceptions then they are missing a critical part of the language that is responsible for execution control. This functionality represents a step forward from languages such as C, which does not support exception handling. While not absolutely necessary, the benefits of using exceptions are many.
What are wrapper classes? Give examples of two and their corresponding primitive. How does each relate to an object?
Rationale
Wrapper classes are fundamental in java programming. In fact, their existence implies that java is not 100% object oriented (bonus to the candidate who points this out). This is the case because java contains 8 primitive datatypes that are not, by definition, objects.
Correct answers
A wrapper class is one that contains a variable that is a primitive data type, and wraps the primitive to provide functionality for interacting with it. Essentially, it turns the primitive into an object. This is useful, for example, when a method is expecting an object to be passed in. The wrapper class is valid, whereas the primitive datatype is not. The candidate should be able to name at least two of the following pairs:
Primative
Wrapper Class
boolean
Boolean
byte
Byte
char
Char
double
Double
float
Float
int
Int
long
Long
short
Short
Very Bad
The wrapper classes are defined in java.lang, and required because there many classes that only support objects. Not having knowledge of these wrapper classes, or why they would be used, is a serious inadequacy.
Define the following terms that are common in java programming
Abstract class
Garbage collector (or garbage collection)
Autoboxing
Serialization
Rationale
This list includes terms that are used in java, as well as other languages. Interview questions for experienced programmers include such definitions because it tests for in-depth knowledge and the ability to discern between languages with similar, yet non-identical concepts.
Correct answers
An abstract class is used as a base class for subclasses that will extend or override its methods. As an example, consider a “Shape” class. A shape may contain a number of sides, faces, or even dimensions. Taken in isolation a “Shape” may be of little use. On the other hand if this abstract class will be used as a base class for a “Square”, “Triangle”, or other type of polygon, it may be helpful in place at the top of the class hierarchy. – It is not possible to instantiate an abstract class. – It may contain abstract methods, but it is not required. – Subclasses of the abstract class must implement all of the abstract methods, unless it is also an abstract class. It is not possible to instantiate an abstract class.
Not being aware of abstract classes is not critical, although they will very likely be encountered while maintaining or debugging an existing code base. In addition, experienced object oriented programmers make very efficient use of abstract classes.
Garbage collection (carried out by the garbage collector) is the process of detecting and deleting objects in memory that are no longer used or referenced. In java, garbage collection is automatic, but it can also be requested.
The commands System.gc() and Runtime.gc() will “hint” to the garbage collector that it should run, although it is not guaranteed.
Running threads are paused during garbage collection. This necessarily slows down the execution, which means that in responsive applications the garbage collection should be kept to a minimum. Having no knowledge of the garbage collector is not a make-or-break deal, especially for a junior programmer. It should be noted, however, that when coming from a language like C, where all of the memory is managed manually, the programmer should certainly be aware of this functionality.
Autoboxing is the automatic wrapping of a primitive type, as discussed in question #4. For example, it will automatically convert a float into a Float. The opposite of this is unboxing, where the primitive type is extracted from the wrapper class. This is something that the majority of java programmers should be familiar with.
Serialization refers to the encoding of objects in memory into a stream of bytes that can be easily stored or transmitted. The opposite is deserialization, which reconstructs the objects from a byte stream. There are different approaches to achieve serialization. Two common methods are converting the object to XML (eXtensible Markup Language), or JSON (JavaScript Object Notation). These are well known file types, each with widespread support. Java also supports serialization as part of the language. The language includes the Serializable interface, which can be used for both serialization and deserialization. The writeObject() method is used to encode the data, whereas the readObject() method is used to reconstruct objects.
Java defines a String class to represent arrays of characters. Answer the following questions:
A constructor initializes an object when it is created. However, constructors have no explicit return type.
Generally, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Could you name some Java frameworks?
This interview question is a basic one: any competent Java developer is able to name some frameworks written in Java language. During the interview, the interviewed candidate must mention at least three Java frameworks among this list:
JSF (Java Server Faces), a Java web framework that makes easier the construction of user interfaces for server-based applications
GWT (Google Web Toolkit), an open-source set of tools that helps programmers to create and maintain JavaScript applications in Java Spring, a Java framework which doesn’t impose any specific programming model
Struts
Hibernate
Grails
Play!
Vaadin
Maven
Mixed-level Programming Interview Questions
Java defines a String class to represent arrays of characters. Answer the following questions:
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
1/ After a string is created, is it possible to modify it? Consider the following :
public static void main(String[] args) { String name = "James gosling"; // I want to change the 'g' to a 'G'. // Will this work at compile time? name.charAt(6) = 'G'; // Print with the standard system println to see “James Gosling” System.out.println(name); }
Will this work? If not, what changes would be required in order to output the desired string?
2/ The String class has more than one Comparator. Consider the following code:
public static void main(String[] args) { // This program received 2 arguments. We want to // determine if those two strings are equal. // Compare the first argument to the second argument boolean compareResult = (XXX); if (compareResult) { System.out.println("The Strings are the same."); } else { System.out.println("The Strings are not the same."); } // Print the main string args System.out.println(args[0]); System.out.println(args[1]); }
– What does the “XXX” have to be replaced by in order for the two main string args to be compared? If the arguments are: “Sun Microsystems” and “Sun microsystems”, what will the result of the execution be? Is there are way to guarantee that it will report them as identical? – If the arguments are instead: “Sun microsystem” and “Sun microsystems”, what will the result of the execution be?
3/ What is the Java string constant pool? (Or Java string pool)? Does is reside in stack memory?
Rationale
Using string representations is common in many languages, and Java is no exception. It is important to understand how strings are created, parsed, printed, and manipulated. As an important topic it makes an important interview question for java developers.
Correct answers
No, this will fail at compile time because it is not possible to modify a string once it has been initialized. This property is known as immutable. In order to make this work, the string containing “James gosling” would have to be recreated. One approach is to use an intermediate character array (by calling the toCharArray() method on the “name”), replacing the ‘g’ with the uppercase letter, and then recreating the string before printing it. A bonus to the candidate who points out that the string replace(…) function exists to replace characters, yet cannot be used because all instances of lowercase ‘g’ would be replaced.
The exact drop-in comparator in this example is either equals(…) or equalsIgnoreCase(…). The return type of both of these methods is a boolean value. If the interviewee answers compareTo(…) or compareToIgnoreCase(…) then credit should be awarded, although the return type of these methods is an int, so it is technically not correct. It does, however, still demonstrate knowledge of the language.
In the first example, the strings are identical under equalsIgnoreCase(…), but different under equals(…). In the second example there is a trailing ‘s’, which makes the strings different regardless of case.
The Java Constant String Pool is an area in the Heap memory (so, not the stack memory) where strings are stored. This approach is behind the reason for which strings are immutable in java.
For example:
string x = “main string”;
string y = “virtual machine”;
string z = “main string”;
All three of the above strings are stored in the string pool, but the interesting part is the efficiency. Both x and y point to the same area within the string pool, therefore not requiring duplication of the space. Knowing this, it should be clear that changing the value of x is not allowed because it would have the unintended side effect of changing z.
What are the differences between Stack memory and Heap space?
Rationale
In order to improve efficiency, the JVM organizes memory for applications to run in. It creates stack space and heap space, each of which is used by different operations. Understanding memory allocation at this level can lead to more predictable garbage collection and ultimately, increased efficiency.
Correct answers
Stack memory is used for static memory allocation, such as primitive values inside a method. It is always used for the execution of a thread. The stack grows when methods are called, and shrinks when they return. If the memory allocated for the stack is exceeded then the java.lang.StackOverFlowError exception is thrown.
Heap memory is used for dynamic memory allocation, such as java objects. Specifically, the object is stored in the heap, while the reference to the object is stored in the stack. The JRE classes are also stored in the heap at runtime. Accessing data in the heap is slower than doing so in stack memory. The heap requires the action of the garbage collector in order to free up unused objects. If the memory allocated for the heap is exceeded then the java.lang.OutOfMemoryError exception is thrown.
Very Bad
Having never heard of the stack or heap would indicate a shallow knowledge of the java programming language. Moreover, the terminology is typical in a general programming culture. Diagnosing memory-related errors, such as a stack overflow caused by an incorrectly behaving recursive function, would be easier with this understanding.
Two class-related terms used in java programming are “subclass” and “nested class”. Explain the differences between them. Why choose one over the other? Which one is sometimes known as an “inner class”?
Rationale
In object oriented design there is often confusion about the placement of classes within the hierarchy. Nested classes are relatively rare compared to sub-classes, yet their use is beneficial in many situations. Knowledge of their existence and how they are used should be considered an asset.
Correct answers
A subclass is one that extends another class, and is often a specialization of the original. Subclasses inherit the public and protected members of their superclass. Subclasses can be instantiated independently of the superclass, and in fact, this is always the case when the superclass is an abstract class.
A nested class is a class within a class, which in some cases is an inner class. The scope of the inner class includes all of the members in its outer class, giving it access to these variables and methods. Because the body exists entirely within the enclosing class, it cannot be instantiated independently, without it.
Using an inner class can enhance the object oriented design by further organizing code. The purpose is limited in that it exists to serve its enclosing class. If the inner class offers functionality that is useful on a wider scale then it would make more sense to have it as a top-level class. Inner classes are commonly used as callback functions for GUI components.
Bonus
There are two types of nested classes. Specifically, there is a static nested class, which does not directly have access to other members of the enclosing class. These are not often used, which is why knowing about them is a bonus as opposed to ignorance of them earning a penalty. The other type is a non-static nested-class, which is the version that is referred to as an inner class. These indeed have access to all of the members of the enclosing class, including private methods.
Very Bad
The candidate should be forgiven for never having used a nested class. Although useful, and also likely to be seen if maintaining an existing code base, the concept is straightforward. Inner classes often make code more elegant and easier to maintain, but some designers consider this a matter of style. Subclasses, on the other hand, are a fundamental component in object oriented programming that every java developer should be aware of. Not being able to easily discuss subclasses within a class hierarchy is a serious red flag.
Two collection classes that are available in java programming are the Array and List. How do the methods differ between these two container objects, and in what circumstances would you choose one over the other?
Rationale
The usage of containers is common in Java and other programming languages. The List is a dynamic data structure, while the Array is static. It is important to recognize that each is better suited to certain applications, and as such, the candidate should be familiar with them. Having in-depth knowledge of the available datatypes and container classes will ultimately safe on development time.
Correct answers
Array
Arrays are static in size, so they cannot grow or shrink in terms of the number of elements. This means that there are methods to access and modify elements, but not to insert or delete them.
Java provides methods for performing a binary search or a sort on an array. Also, an array can be initialized using the fill() method, or compared using the equals() comparator.
The size of an array is set when it is created.
The random access of an element in an array is very efficient.
Arrays are most suitable for a fixed-length collections of elements.
All of the elements are of the same type, for example:
int[] interviewArray = new int[5];
or
int[] arrayForInterview = {3, 1, 4, 1, 5};
Both of these Arrays contain five integers.
Vector
Candidates should know when it is appropriate and possible to use these keywords. In particular they should know that async can only be placed before the function keyword on a function definition. This marks the function as returning a Promise. The await keyword can only be used inside such an asynchronous function and must be placed before a call to a function that will return a Promise.
Elements in a List can be added or deleted, meaning the size of the list can change. The methods allow for many types of manipulations, including inserting into or removing from a specific index. Ranges can be manipulated as well.
The List is an interface, so when one manipulates a List, a real class, usually ArrayList, is used behind the scene
A List relies on the methods from Collections for sorting, such as Collections.sort().
The search methods contains(), indexOf(), and lastIndexOf() are examples that can be used to search the elements. However, to perform a binary search requires calling the more general method: Collections.binarySearch(…)
Lists can store objects of mixed type, for example:
List interviewList = new ArrayList();
interviewList.add(3);
interviewList.add(1415);
interviewList.add(“Pi”);
Bonus
Arrays can store Objects, so there is a workaround available for those inclined to mix types within an array. Also, the candidate should be credited for knowing that Lists are a replacement for Vectors which are no longer commonly used in Java. The reason has to do with concurrency and the synchronization of operations. Clearly, a more detailed explanation is beyond the scope of this question – however, the mention of this issue is noteworthy.
Very Bad
Arrays and Lists, among other built-in classes and interfaces, including Collections, are very common in java programming and application development. A candidate who is not comfortable with these features is almost certainly lacking experience with the language.
Unlike C++, Java does not support multiple inheritance. How will programming with an Interface provide an answer to this problem? Is an interface part of the class hierarchy?
Rationale
While there are commonalities between languages for which many programmers will be familiar, there are also distinctions that help to define them. In a java interview, there will be core java questions that help to evaluate how well the candidate knows the specifics of the java programming language. Given the issue of the Diamond Problem in C++, it is worthwhile to test the candidate’s knowledge from a java perspective.
Correct answers
An interface is similar to a class in that it can contain different types of methods, but different because it does not hold the state. Interfaces are inherently abstract, and their methods need to be implemented by a class. The interface is not instantiated – it is implemented. Unlike in C++, a class can only extend a single parent (i.e. it can only have one superclass). An interface, on the other hand, is capable of extending more than one parent interface. For example:
public interface CheckerBoard {
public void setSize(int rowCount, int columnCount);
}
public interface Game {
public void setNumberOfPlayers();
public void play();
}
public interface ChessGame extends CheckerBoard, Game {}
In this example, the ChessGame interface inherits from both CheckerBoard and Game.
Very Bad
If the interviewee does not know what multiple inheritance is, then it suggests a lack of object oriented design experience. This is not essential for all applications, although it is important to recognize that java is inherently OO.
What is the Java Virtual Machine? What is the main purpose, and what type of code does it operate with?
Rationale
No Java interview would be complete without a question on the topic of the virtual machine. The JVM is a key component of Java, and java programmers learn about it at an early stage. While the JVM is capable of running bytecode generated by other languages, such as JRuby and Jython, it does not take away from the fact that it is essential to java itself.
Correct answers
The JVM is a virtual machine that allows the computer to run Java programs that have been compiled to bytecode. The bytecode is platform independent, and will run on any computer that hosts a JVM. It includes a just-in-time (JIT) compiler than converts the bytecode into machine language instructions, allowing applications to run as quickly as a native executable.
Very Bad
The JVM is one of the main components that make Java what it is. Having no knowledge of the JVM likely indicates a lack of experience with the language.
What are final methods and classes? Will an abstract class support final methods?
Rationale
The final keyword is common and should be well understood by java programmers. During the OO design phase, there is normally a decision made with respect to whether classes should be extendable. If not, they are marked final in order to limit potential side effects from sub-classes that were not envisioned. This is an important feature that should be utilized for more robust and maintainable code.
Correct answers
A method that is declared with the final keyword cannot be overridden in the subclasses. This is used in hierarchies where the implementation of the method should be consistent throughout. The final declaration for a class disallows sub-classing entirely. Yes, it is possible to include final methods in an abstract class. This ensures that the sub-classes cannot override the method.
Very Bad
If the candidate is unfamiliar with the final keyword, whether used at the level of class or method, then it suggests relative inexperience with the language. Even for inexperienced programmers that have been involved with object oriented design, the concept of a final class should be familiar.
Java programming allows for different ways to create a thread. What are they and which is the preferred method? Explain.
Rationale
Unlike C++, java contains built-in support for multithreading. This is a rich and powerful feature that is both relevant and useful in many applications. As such, the candidate should be familiar with the basics.
Correct answers
What happens in the case that reduce is called on an empty array without providing the optional initial accumulator value?
public class JavaInterviewClass implements Runnable {
public void run() {
System.out.println(“My example public class prints this line from a thread.”);
}
}
To execute the run() method, pass an instance of the class into a Thread, as follows:
Thread interviewThread = new Thread(new JavaInterviewClass ());
interviewThread.start();
The second way to create a thread is to extend the Thread class. The subclass will override the run() method. After this, simply create an instance of the class.
public class JavaInterviewClass extends Thread {
public void run() {
System.out.println(“My example public class extends the Thread class.”);
}
}
To execute the thread, simple instantiate the class and call start(), as follows:
JavaInterviewClass myInterview = new JavaInterviewClass (); myInterview.start();
Bonus
While implementing the runnable interface and extending the Thread class are two popular ways to create a thread, it is also possible using the Executor framework. This allows for working with threads directly, but is less well-known. It includes methods such as newSingleThreadExecutor(), newFixedThreadPool(), and submit() to create a run tasks. Knowledge of how to use the Executor framework implies that the candidate is very comfortable with creating and using threads in java.
Very Bad
If the candidate is uncomfortable with using threads then they are missing out on a powerful and significant feature of the language. It is important because understanding multithreading is more than just looking up the syntax for a few commands. Rather, it is an approach that should be considered when an application is being designed and developed.
Java code has built-in support for concurrency in its Thread class. Concurrency has its own set of problems such as deadlock and race conditions. Briefly describe Atomic variables in Java and how they are used. Next, it is given that the start() method is used to create a separate call stack before the run() method is used to execute a thread. What do the yield(), sleep(), and join() methods do?
Rationale
Java’s support for multithreading can lead to concurrency-related problems. The candidate’s knowledge with respect to these issues should be evaluated and considered.
Correct answers
An Atomic variable is one that is “atomically updated”, meaning that data integrity is ensured through the use of non-blocking algorithms. This functionality is typically implemented at the machine code level. Java supports several atomic variables, most commonly AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference. There are also several methods that support the retrieval and modification of these variables, including get(), set(), lazySet(), compareAndSet(), and weakCompareAndSet(). Used properly, atomic variables can be used to implement thread safe (multithreading safe) methods that effectively deal with certain concurrency-related issues.
yield(): This method informs the environment that the current thread is not completing a task of high priority, and is prepared to pause execution. Provided that the underlying environment supports pre-emptive scheduling, it will suspend the thread if there is another one that needs to run. If there is not a second thread, or once the second thread terminates, the current thread will regain control and continue executing.
sleep(): This method will cause the current thread to sleep, or pause execution, for a specified number of milliseconds. Alternatively, a specified number of milliseconds and nanoseconds combined. While the current thread is sleeping, another thread will run, or otherwise the CPU will remain idle. Subject to the accuracy of the system clock and timers, the thread will regain control once the countdown has expired.
join(): This method is used to join two the execution of two threads together. To clarify, if Thread A calls join() on Thread B, then A will begin waiting. Once B has completed, or a pre-specified timer has expired, A will regain control and continue executing.
Very Bad
Being knowledgeable with respect to Java threads, but not conscious of problems related to concurrency can lead to serious errors. The majority of devices from desktops to mobile devices to single board computers now generally support multithreading and concurrency. It is important to understand the proper use of threads, and be aware of the methods provided by java in support of them.
Conclusion
The questions in this article are useful for evaluating the competency of a prospective Java programmer. On the topic of interview questions to prepare for a Java developer, it is important to remember that specifics of the language can be easily referenced using online help and documentation. The subtle points of a language are not nearly as important as how one applies logic. That said, candidates for such a position are expected to know the language and not be in need of extensive training before the real work begins. The skills required will be dictated by the job that needs to be done, and the variation in questions given above will assist in making this assessment. Don’t forget that one of the best ways to evaluate the candidate’s skills for your project is to perform a hands-on programming assessment, which is much more efficient than oral interview questions to hire a highly-qualified Java programmer.