Java Interview Questions For Candidates With Two Years Of Experience
If you have two years of experience, prepare for these Java interview questions:
- In OOP, why is composition more advantageous than inheritance?
- What is the Java thread life cycle?
- What is the advantage of an unordered array over an ordered array?
- What are marker interfaces in Java?
- What is Double Brace Initialisation in Java?
- How do you make an object eligible for garbage collection in Java?
- Have you completed a project using Java 11?
- Can you explain the working of substrings in String?
- How do you use business logic to complete an equality check?
- How do you use a numeric promotion?
- Can you estimate the time for code execution without a profiling tool?
- Why are strings made immutable in Java?
- What are the differences between interfaces and abstract classes?
- What are the differences between a HashSet and a TreeSet?
- Would you prefer the character array over string for securing information? Why?
Q23what Is An Infinite Loop In Java Explain With An Example
An infinite loop is an instruction sequence in Java that loops endlessly when a functional exit isnt met. This type of loop can be the result of a programming error or may also be a deliberate action based on the application behavior. An infinite loop will terminate automatically once the application exits.
public class InfiniteForLoopDemo}
Tell Us Something About Jit Compiler
- JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run.
- The compiler is nothing but a translator of source code to machine-executable code. But what is special about the JIT compiler? Let us see how it works:
- First, the Java source code conversion to byte code occurs with the help of the javac compiler.
- Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.
- JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.
- Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.
Recommended Reading: How To Not Be Nervous For An Interview
Landing A Job As A Java Developer
Although some new programmers might question Javas relevance in todays tech world, its an incredibly popular choice for coders looking to work as a developer. There are more than nine million Java developers worldwide, and more than three billion smart phones run on Java today. The recent success of Java8 is a promising indication that the language will dominate the software development landscape for years to come.
Hiring managers will tell a student that Java is one of the most in-demand skills they can learn. The question is how can students best prepare for the notoriously difficult interview questions when trying to land their first job?
Going in, students should know that they can be questioned on any version of Java to date, and that many developer job interviews are conducted at least partially in writing. This means the interviewee will be expected to perform the answer on a whiteboard or on paper.
Here is an example of how part of an interview might go, and suggested answers:
Q: Describe what all the different parts of the main method declaration mean, and describe what each does.
Q: What is the main difference in fail-fast and fail-safe iterators?
A: Whether the collection can be modified while its being iterated. Fail-fast iterators do not allow this and fail-safe iterators do.
Q: Why is it more secure to store sensitive data in a character array over a String?
Q What Do We Mean By Weak Reference
In Java there are four types of references differentiated on the way by which they are garbage collected.
1. Strong Reference: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection. The object is garbage collected only when the variable which was strongly referenced points to null.
StrongReferenceClass obj =newStrongReferenceClass
Here obj object is strong reference to newly created instance of MyClass, currently obj is active object so can’t be garbage collected.
2. Weak Reference: A weakly referenced object is cleared by the Garbage Collector when its weakly reachable.Weak reachability means that an object has neither strong nor soft references pointing to it. The object can be reached only by traversing a weak reference. To create such references java.lang.ref.WeakReference class is used.
/*** Java Code to illustrate Weak reference***/importjava.lang.ref.WeakReference classWeakReferenceExample } publicclassMainClass }
Weak Reference Example!Weak Reference Example!
3. Soft Reference: In Soft reference, even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory.To create such references java.lang.ref.SoftReference class is used.
Soft Reference Example!Soft Reference Example!
What Is Java Programming
Java is a powerful general-purpose programming language. It is used to develop desktop and mobile applications, big data processing, embedded systems, and so on. According to Oracle, the company that owns Java, Java runs on 3 billion devices worldwide, which makes Java one of the most popular programming languages.
Q What Are Different Scenarios Causing Exception In Thread Main
Some of the common main thread exception are as follows:
- Exception in thread main java.lang.UnsupportedClassVersionError: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version.
- Exception in thread main java.lang.NoClassDefFoundError: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found.
- Exception in thread main java.lang.NoSuchMethodError: main: This exception comes when you are trying to run a class that doesnt have main method.
- Exception in thread “main” java.lang.ArithmeticException: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message.
Recommended Reading: How To Ask Good Interview Questions
What Is The Difference Between Execute Executequery Executeupdate
Statement execute is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet to get the ResultSet and getUpdateCount method to retrieve the update count.
Statement executeQuery is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message executeQuery method can not be used for update.
Statement executeUpdate is used to execute Insert/Update/Delete statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language statements. For DDL statements, the output is 0.
You should use execute method only when you are not sure about the type of statement else use executeQuery or executeUpdate method.
Q What Is Jvm And Is It Platform Independent
Java Virtual Machine is a specification that provides runtime environment in which java bytecode can be executed. The JVM is the platform. The JVM acts as a “virtual” machine or processor. Java’s platform independence consists mostly of its Java Virtual Machine . JVM makes this possible because it is aware of the specific instruction lengths and other particularities of the platform .
The JVM is not platform independent. Java Virtual Machine provides the environment to execute the java file. So at the end it’s depends on kernel and kernel is differ from OS to OS. The JVM is used to both translate the bytecode into the machine language for a particular computer and actually execute the corresponding machine-language instructions as well.
Recommended Reading: How To Write A Follow Up Email To An Interview
How Does An Exception Propagate In The Code
When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.
Top Interview Questions For A Java Developer
To recruit Java developers you should make a list of the questions that are closely connected to the technology. However, we have prepared standard questions you can ask:
Also Check: How To Interview For A Promotion
Learn Data Structures And Algorithms
This is something you cant even think to avoid preparing before going out for a tech interview in any of the leading IT giants. Data Structures and Algorithms is the most preferred skill by these tech companies, and they significantly assess the candidates in the interview based on their understanding of Data structure and algorithm concepts. It not only allows the interviewer to assess your technical skills and knowledge but also shows your problem-solving skills to him/her. You simply can start to learn Data Structures & Algorithms from the basic concepts like Array, Stack, Queue, Searching, Sorting, etc., and then gradually move towards the advanced concepts like Hashing, Tries, Greedy Algorithms, Dynamic Programming, and others.
Also, youre not only required to learn these DSA concepts theoretically but youre recommended to implement them also by solving various programming problems for better understanding and proficiency.
What Are The Most Popular Experienced Java Developer Interview Questions
Second-round questions list must be made with regard to a Java developer experience. The higher the experience is, the harder questions should be asked. According to Interview Mocha, Java competencies can be evaluated with the help of SME questions concerning the general aspects of the entire stack or a stand-alone concept. Below is the chart that includes the Java-based stacks and frameworks that can become a subject of your face-to-face meeting with a job applicant.
Interview Mocha divides Java developer 3 years experience interview questions into the following categories:
As you see, the rounds are much the same as we mentioned above. Along with developers, candidates to a Java job position can be interviewed and screened by project managers and CEOs. Below there are some typical topics they discuss.
Also Check: How To Do An Exit Interview
Did you have a pipeline in place?
How did you normally do code deployments?
Describe the team. Did you have product managers? UI/UX designers? Testing and QA?
Talk about the ideation to completion of a feature you worked on.
Did you have code reviews? Who was responsible for them and how did they work?
What types of things do you look for when reviewing another persons code?
There is often a stigma surrounding failure and doing something the wrong way. However, the greatest way we learn is by screwing up and reflecting. Dont be afraid to discuss these situations, just make sure you take the time and care to understand what went wrong and why. That goes the same with great success as well.
Its also easy to have a massive victory and not think about what got you there. This is a good example to talk about a really tough problem you had, how you solved it, and what you think helped you do that. Maybe you tried debugging a way you hadnt thought about before, maybe you used a certain tool you hadnt known about previously. Share this experience with your interviewer and try to explain what you learned from it and how you think it will help you be successful in a new role.
What Are The Different Ways Of Threads Usage
- We can define and implement a thread in java using two ways:
- Extending the Thread class
classInterviewBitThreadExampleextendsThread publicstaticvoidmain }
- Implementing the Runnable interface
classInterviewBitThreadExampleimplementsRunnable publicstaticvoidmain }
- Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
- start method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run method for executing the thread in that call stack.
Q What Is The Difference Between Transient And Volatile Variable In Java
Transient: The transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value i.e. null for a reference type, and zero or false for a primitive type.
publictransientint limit =55 // will not persistpublicint b // will persist
Volatile: The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization.
publicclassMyRunnableimplementsRunnable }publicvoidstop }
Write A Java Program For The Fibonacci Series
This question is another specific exercise that can show your knowledge of using Java code to complete a task. The interviewer probably wants to see that you can arrive at the correct solution in an acceptable amount of time. This is an ideal time to explain your process aloud as you write your code to show the interviewer your thought process.
Q In Java How Many Ways You Can Take Input From The Console
In Java, there are three different ways for reading input from the user in the command line environment.
1. Using Buffered Reader Class: This method is used by wrapping the System.in in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.
importjava.io.BufferedReader importjava.io.IOException importjava.io.InputStreamReader publicclassTest }
2. Using Scanner Class: The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line.
importjava.util.Scanner classGetInputFromUser }
3. Using Console Class: It has been becoming a preferred way for reading users input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user the format string syntax can also be used ).
What Is Object In Java
An object is a software bundle of variables and related methods. You can represent real-world objects using software objects. You might want to represent real-world dogs as software objects in an animation program or a real-world bicycle as a software object within an electronic exercise bike. However, you can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.
Don’t Miss: How Do You Prepare For A Job Interview
Q What Are Assertions In Java
An assertion allows testing the correctness of any assumptions that have been made in the program. Assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It is mainly used for testing purposes during development.
The assert statement is used with a Boolean expression and can be written in two different ways.
// First way assert expression // Second wayassert expression1 : expression2
Container Dependency And Ioc
This topic is focused on spring container basics and the key benefits of IOC and Dependency injection and how Spring Framework implements them, here are some sample questions from this topic
By the way, you can find answers to all these questions in my book. If you want to prepare for Java and Spring Interview in a structured and guided way then you can also check my book Grokking the Spring Boot Interview, it covers all essential Spring topics and concepts so that you can prepare well in a limited time, and you can buy it for just $10.99 on GumRoad.
Here is the link to grab your copy for a special price of $10.99 Grokking the spring Boot Interview
If you like to shop on Amazon then the book is now also available on Amazon Kindle for Pre-order, if you like to order from Amazon then you can use this link