Introduction to Java

  • What Is Java? A Beginner's Guide to Java and Its Evolution
  • Why Java is a Popular Programming Language?
  • Top 10 Reasons Why You Should Learn Java
  • Why Java is a Secure language?
  • What are the different Applications of Java?
  • Java for Android: Know the importance of Java in Android
  • What is the basic Structure of a Java Program?
  • What is the difference between C, C++ and Java?

Java 9 Features and Improvements

  • Top 10 Java Frameworks You Should Know
  • Netbeans Tutorial: What is NetBeans IDE and how to get started?

Environment Setup

  • How To Set Path in Java?

How to Write Hello World Program in Java?

  • How to Compile and Run your first Java Program?
  • Learn How To Use Java Command Line Arguments With Examples

Control Statements

  • What is for loop in java and how to implement it?
  • What is a While Loop in Java and how to use it?
  • What is for-each loop in Java?
  • What is a Do while loop in Java and how to use it?
  • What is a Switch Case In Java?

Java Core Concepts

  • Java Tutorial For Beginners – Java Programming Made Easy!
  • What are the components of Java Architecture?
  • What are Comments in Java? – Know its Types
  • What are Java Keywords and reserved words?
  • What is a Constructor in Java?
  • What is the use of Destructor in Java?
  • Know About Parameterized Constructor In Java With Examples
  • What are Operators in Java and its Types?
  • What Are Methods In Java? Know Java Methods From Scratch
  • What is Conditional Operator in Java and how to write it?

What is a Constant in Java and how to declare it?

  • What is JIT in Java? – Understanding Java Fundamentals
  • What You Should Know About Java Virtual Machine?
  • What is the role for a ClassLoader in Java?
  • What is an Interpreter in Java?
  • What is Bytecode in Java and how it works?
  • What is a Scanner Class in Java?
  • What is the Default Value of Char in Java?
  • this Keyword In Java – All You Need To Know
  • What is Protected in Java and How to Implement it?
  • What is a Static Keyword in Java?
  • What is an Array Class in Java and How to Implement it?
  • What is Ternary Operator in Java and how can you use it?
  • What is Modulus in Java and how does it work?
  • What is the difference between Method Overloading And Overriding?
  • Instance variable In Java: All you need to know
  • Know All About the Various Data Types in Java
  • What is Typecasting in Java and how does it work?
  • How to Create a File in Java? – File Handling Concepts
  • File Handling in Java – How To Work With Java Files?
  • What is a Comparator Interface in Java?
  • Comparable in Java: All you need to know about Comparable & Comparator interfaces
  • What is Iterator in Java and How to use it?
  • Java Exception Handling – A Complete Reference to Java Exceptions
  • All You Need to Know About Final, Finally and Finalize in Java
  • How To Implement Volatile Keyword in Java?
  • Garbage Collection in Java: All you need to know
  • What is Math Class in Java and How to use it?
  • What is a Java Thread Pool and why is it used?
  • Synchronization in Java: What, How and Why?
  • Top Data Structures & Algorithms in Java That You Need to Know
  • Java EnumSet: How to use EnumSet in Java?
  • How to Generate Random Numbers using Random Class in Java?
  • Generics in Java – A Beginners Guide to Generics Fundamentals
  • What is Enumeration in Java? A Beginners Guide
  • Transient in Java : What, Why & How it works?
  • What is Wait and Notify in Java?

Swing In Java : Know How To Create GUI With Examples

  • Java AWT Tutorial – One Stop Solution for Beginners
  • Java Applet Tutorial – Know How to Create Applets in Java
  • How To Implement Static Block In Java?
  • What is Power function in Java? – Know its uses
  • Java Array Tutorial – Single & Multi Dimensional Arrays In Java
  • Access Modifiers in Java: All you need to know
  • What is Aggregation in Java and why do you need it?
  • How to Convert Int to String in Java?
  • What Is A Virtual Function In Java?
  • Java Regex – What are Regular Expressions and How to Use it?
  • What is PrintWriter in Java and how does it work?
  • All You Need To Know About Wrapper Class In Java : Autoboxing And Unboxing
  • How to get Date and Time in Java?
  • What is Trim method in Java and How to Implement it?
  • How do you exit a function in Java?
  • What is AutoBoxing and unboxing in Java?
  • What is Factory Method in Java and how to use it?
  • Threads in Java: Know Creating Threads and Multithreading in Java
  • Join method in Java: How to join threads?
  • What is EJB in Java and How to Implement it?
  • What is Dictionary in Java and How to Create it?
  • Daemon Thread in Java: Know what are it's methods
  • How To Implement Inner Class In Java?
  • What is Stack Class in Java and how to use it?

Java Strings

  • What is the concept of String Pool in java?
  • Java String – String Functions In Java With Examples
  • Substring in Java: Learn how to use substring() Method
  • What are Immutable String in Java and how to use them?
  • What is the difference between Mutable and Immutable In Java?
  • BufferedReader in Java : How To Read Text From Input Stream
  • What are the differences between String, StringBuffer and StringBuilder?
  • Split Method in Java: How to Split a String in Java?
  • Know How to Reverse A String In Java – A Beginners Guide
  • What is Coupling in Java and its different types?
  • Everything You Need to Know About Loose Coupling in Java

Objects and Classes

  • Packages in Java: How to Create and Use Packages in Java?
  • Java Objects and Classes – Learn how to Create & Implement
  • What is Object in Java and How to use it?
  • Singleton Class in Java – How to Use Singleton Class?
  • What are the different types of Classes in Java?
  • What is a Robot Class in Java?
  • What is Integer class in java and how it works?
  • What is System Class in Java and how to implement it?
  • Char in Java: What is Character class in Java?
  • What is the Boolean Class in Java and how to use it?
  • Object Oriented Programming – Java OOPs Concepts With Examples
  • Inheritance in Java – Mastering OOP Concepts
  • Polymorphism in Java – How To Get Started With OOPs?
  • How To Implement Multiple Inheritance In Java?
  • Java Abstraction- Mastering OOP with Abstraction in Java
  • Encapsulation in Java – How to master OOPs with Encapsulation?
  • How to Implement Nested Class in Java?
  • What is the Use of Abstract Method in Java?
  • What is Association in Java and why do you need it?
  • What is the difference between Abstract Class and Interface in Java?
  • What is Runnable Interface in Java and how to implement it?
  • What is Cloning in Java and its Types?
  • What is Semaphore in Java and its use?

What is Dynamic Binding In Java And How To Use It?

Java collections.

  • Java Collections – Interface, List, Queue, Sets in Java With Examples
  • List in Java: One Stop Solution for Beginners
  • Java ArrayList: A Complete Guide for Beginners
  • Linked List in Java: How to Implement a Linked List in Java?
  • What are Vector in Java and how do we use it?
  • What is BlockingQueue in Java and how to implement it?
  • How To Implement Priority Queue In Java?
  • What is Deque in Java and how to implement its interface?
  • What are the Legacy Classes in Java?
  • Java HashMap – Know How to Implement HashMap in Java
  • What is LinkedHashSet in Java? Understand with examples
  • How to Implement Map Interface in Java?
  • Trees in Java: How to Implement a Binary Tree?
  • What is the Difference Between Extends and Implements in Java?
  • How to Implement Shallow Copy and Deep Copy in Java
  • How to Iterate Maps in Java?
  • What is an append Method in Java?
  • How To Implement Treeset In Java?
  • Java HashMap vs Hashtable: What is the difference?
  • How to Implement Method Hiding in Java
  • How To Best Implement Concurrent Hash Map in Java?
  • How To Implement Marker Interface In Java?

Java Programs

  • Palindrome in Java: How to check a number is palindrome?
  • How to check if a given number is an Armstrong number or not?
  • How to Find the largest number in an Array in Java?
  • How to find the Sum of Digits in Java?
  • How To Convert String To Date In Java?
  • Ways For Swapping Two Numbers In Java
  • How To Implement Addition Of Two Numbers In Java?
  • How to implement Java program to check Leap Year?

How to Calculate Square and Square Root in Java?

  • How to implement Bubble Sort in Java?
  • How to implement Perfect Number in Java?
  • What is Binary Search in Java? How to Implement it?
  • How to Perform Merge Sort in Java?
  • Top 30 Pattern Program in Java: How to Print Star, Number and Character
  • Know all about the Prime Number program in Java
  • How To Display Fibonacci Series In Java?
  • How to Sort Array, ArrayList, String, List, Map and Set in Java?
  • How To Create Library Management System Project in Java?
  • How To Practice String Concatenation In Java?
  • How To Convert Binary To Decimal In Java?
  • How To Convert Double To Int in Java?
  • How to convert Char to Int in Java?
  • How To Convert Char To String In Java?
  • How to Create JFrame in Java?
  • What is Externalization in Java and when to use it?
  • How to read and parse XML file in Java?
  • How To Implement Matrix Multiplication In Java?
  • How To Deal With Random Number and String Generator in Java?
  • Basic Java Programs for Practice With Examples

Advance Java

  • How To Connect To A Database in Java? – JDBC Tutorial
  • Advanced Java Tutorial- A Complete Guide for Advanced Java
  • Servlet and JSP Tutorial- How to Build Web Applications in Java?
  • Introduction to Java Servlets – Servlets in a Nutshell
  • What Is JSP In Java? Know All About Java Web Applications
  • How to Implement MVC Architecture in Java?
  • What is JavaBeans? Introduction to JavaBeans Concepts
  • Know what are the types of Java Web Services?
  • JavaFX Tutorial: How to create an application?
  • What is Executor Framework in Java and how to use it?
  • What is Remote Method Invocation in Java?
  • Everything You Need To Know About Session In Java?
  • Java Networking: What is Networking in Java?
  • What is logger in Java and why do you use it?
  • How To Handle Deadlock In Java?
  • Know all about Socket Programming in Java
  • Important Java Design Patterns You Need to Know About
  • What is ExecutorService in Java and how to create it?
  • Struts 2 Tutorial – One Stop Solution for Beginners
  • What is Hibernate in Java and Why do we need it?
  • What is Maven in Java and how do you use it?
  • What is Machine Learning in Java and how to implement it?

Career Opportunities

  • Java Developer Resume: How to Build an Impressive Resume?
  • What is the Average Java Developer Salary?

Interview Questions

Java interview questions and answers.

  • Top MVC Interview Questions and Answers You Need to Know in 2024
  • Top 50 Java Collections Interview Questions You Need to Know in 2024
  • Top 50 JSP Interview Questions You Need to Know in 2024
  • Top 50 Hibernate Interview Questions That Are A Must in 2024

Programming & Frameworks

  • 38 Comments

In this blog, I am going to list some of the most important Java programming Interview Questions that will set you apart in the interview process. Java is used by approximately 10 Million developers worldwide to develop applications for 15 Billion devices supporting Java. It is also used to create applications for trending technologies like Big Data on household devices like Mobiles and DTH boxes. And hence, today, Java is used everywhere! This is the reason why Java Certification is the most in-demand certification in the programming domain.

Java Interview Questions and Answers | Java Tutorial | Java Online Training | Edureka

This Edureka Java tutorial video will help you to prepare yourself for Java Interviews

This Edureka Java Interview Questions and Answers video will help you to prepare yourself to clear Java Interviews on your first attempt Let us start by taking a look at some of the most frequently asked Java interview questions, Q1. What is Java? Q2. List the features of Java programming language Q3. How is Java different from C++? Q4. Explain JDK, JRE and JVM? Q5. Explain public static void main(String args[]) in Java. Q6. What is classLoader in Java? Q7. Why Java is platform independent? Q8. Why Java is not 100% Object-oriented? Q9. What are wrapper classes in Java? Q10. What are constructors in Java?

  • Basic Java  Interview Questions
  • Java OOPs Interview Questions
  • JDBC Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • JSP Interview Questions
  • Java Exception and Thread Interview Questions

As a Java professional, it is essential to know the right buzzwords, learn the right technologies and prepare the right answers to commonly asked Java Programming Interview Questions. Here’s a definitive list of top Java Interview Questions that will guarantee a breeze-through to the next level.

In case you attended any Java interview recently, or have additional questions beyond what we covered, we encourage you to post them in our Java community questions . Our expert team will get back to you at the earliest.   

So let’s get started with the first set.

Basic Java Interview Questions for Freshers

Q1. what is java.

Java is a class-based, object-oriented programming language with minimal implementation dependencies. A general-purpose programming language, Java allows programmers to write once and run anywhere (WORA), meaning compiled Java code can execute on all Java-supported platforms without recompilation. Java applications are usually compiled to bytecode that works on any JVM, regardless of computer architecture.

Q2. List the features of Java programming language

  • Java is a language that is considered simple to learn. One fundamental notion of OOP Java must be understood.
  • Java offers a secure feature that aids in the development of a virus-free and tamper-proof system for users.
  • OOP is an abbreviation for Object-Oriented Programming language. OOP denotes that everything in Java is considered an object.
  • Java is not compiled into a platform-specific machine; rather, it is compiled into platform-independent bytecode. The Virtual Machine that
  • operates the platform interprets this code.

Q3. How is Java different from C++?

Java and C++ are both object-oriented programming languages, but they have some key differences.

  • Platform independence: Java is a platform-independent language, while C++ is a platform-dependent language. This means that Java code can run on any platform that has a Java virtual machine (JVM), while C++ code can only run on the platform that it was compiled for.
  • Memory management: Java uses automatic memory management, while C++ requires manual memory management. This means that Java programmers do not need to worry about allocating and freeing memory, while C++ programmers need to be careful to manage memory correctly to avoid memory leaks.
  • Safety: Java is a safer language than C++. This is because Java has built-in security features that help to protect applications from malicious code. For example, Java does not allow direct access to the operating system, which makes it more difficult for attackers to exploit security vulnerabilities.
  • Performance: Java is typically not as fast as C++. This is because Java uses a virtual machine, which adds an extra layer of abstraction between the code and the hardware. However, Java applications are typically more portable and secure than C++ applications.

In general, Java is a good choice for developing portable, secure, and easy-to-maintain applications. C++ is a good choice for developing high-performance applications that require direct access to the operating system.

Q4. Explain JDK, JRE and JVM?

Q5. explain public static void main(string args[]) in java..

main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args) .

  • public : Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static : It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main () is called by the JVM before any objects are made and only static methods can be directly invoked via the class. 
  • void : It is the return type of the method. Void defines the method which will not return any value.
  • main : It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[] : It is the parameter passed to the main method.

Q6. What is classLoader in Java?

The Java ClassLoader subset of JVM loads class files. The classloader loads Java programs first. Three classloaders are built into Java:

  • Bootstrap ClassLoader
  • Extension ClassLoader
  • System/Application ClassLoader

Q7. Why Java is platform independent?

Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.

Upskill for Higher Salary with Java certification training course

Q8. Why Java is not 100% Object-oriented?

Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.

Q9. What are wrapper classes in Java?

Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.

Q10. What are constructors in Java?

In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:

  • Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation. 
  • Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.

Q11. What is singleton class in Java and how can we make a class singleton?

Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

Q12. What is the difference between Array list and vector in Java?

Q13. Write a Java program to rotate arrays 90 degrees clockwise by taking matrices from user input.

Here’s an example Java program that takes a matrix as user input and rotates it 90 degrees clockwise:

Q14. What is the difference between equals() and == in Java?

Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic.

“==” or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. public boolean equals(Object o) is the method provided by the Object class. The default implementation uses == operator to compare two objects. For example: method can be overridden like String class. equals() method is used to compare the values of two objects.

Q15. Implement Binary Search in Java using recursion .

Here’s an example Java program that implements the binary search algorithm using recursion:

This program uses binary search to find a target value `target` in a sorted array `arr`. Calling the `binarySearch` function triggers the `binarySearchRecursive` function. The `binarySearchRecursive` function executes the binary search algorithm through the utilization of recursion.

The `binarySearchRecursive` function takes the array, target value, and indices for the low and high boundaries of the search range. It compares the target value with the middle element of the current range. If they match, the function returns the index. If the target is smaller, it recursively calls itself with the left half of the range. If the target is larger, it recursively calls itself with the right half of the range. The process continues until the element is found or the low index becomes greater than the high index.

The program outputs the index where the element is found or a message indicating that the element was not found in the array.

Note: The program assumes that the array is sorted in ascending order.

Q16. When can you use the super keyword?

In Java, the super keyword is a reference variable that refers to an immediate parent class object.

When you create a subclass instance, you’re also creating an instance of the parent class, which is referenced to by the super reference variable.

The uses of the Java super Keyword are- 

  • To refer to an immediate parent class instance variable, use super.
  • The keyword super can be used to call the method of an immediate parent class.
  • Super() can be used to call the constructor of the immediate parent class.

Q17. What makes a HashSet different from a TreeSet?

Q18. What are the differences between HashMap and HashTable in Java?

Q19. How does HashMap work in Java?

A HashMap in Java stores key-value pairs. The HashMap requires a hash function and uses hashCode and equals methods in order to put and retrieve elements to and from the collection. When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists then its value is updated with the new value. Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.

Q20. What are the differences between wait() and sleep()?

  • Wait() is a method of Object class. Sleep() is a method of Thread class.
  • Sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.
  • Wait() allows the thread to release the lock and go to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object.

Q21. What are the uses of synchronized keywords?

Synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a lock on the object and thus prevents race condition.

Q22. What does the ‘static’ keyword mean? Is it possible to override private or static method in Java?

The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class to which it belongs. You cannot override static methods in Java, because method overriding is based upon dynamic binding at runtime and static methods are statically binded at compile time. A static method is not associated with any instance of a class, so the concept is not applicable.

Q23. What is the default value of the local variables?

The local variables are not initialized to any default value; neither primitives nor object references.

Q24. What is the importance of reflection in Java?

Reflection is a runtime API for inspecting and changing the behavior of methods, classes, and interfaces. Java Reflection is a powerful tool that can be really beneficial. Java Reflection allows you to analyze classes, interfaces, fields, and methods during runtime without knowing what they are called at compile time. Reflection can also be used to create new objects, call methods, and get/set field values. External, user-defined classes can be used by creating instances of extensibility objects with their fully-qualified names. Debuggers can also use reflection to examine private members of classes.

Q25. How to not allow serialization of attributes of a class in Java?

The Non-Serialized attribute can be used to prevent member variables from being serialized. You should also make an object that potentially contains security-sensitive data non-serializable if possible. Apply the Non-Serialized attribute to certain fields that store sensitive data if the object must be serialized. If you don’t exclude these fields from serialization, the data they store will be visible to any programs with serialization permission.

Q26. Can you call a constructor of a class inside another constructor?

Yes, we can call a constructor of a class inside another constructor. This is also called as constructor chaining. Constructor chaining can be done in 2 ways-

  • Within the same class: For constructors in the same class, the this() keyword can be used.
  • From the base class: The super() keyword is used to call the constructor from the base class. The constructor chaining follows the process of inheritance. The constructor of the sub class first calls the constructor of the super class. Due to this, the creation of sub class’s object starts with the initialization of the data members of the super class. The constructor chaining works similarly with any number of classes. Every constructor keeps calling the chain till the top of the chain.

Q27. Write a Java program to reverse a string.

Here’s an example Java program that reverses a string:

This program prompts the user to enter a string. It then calls the `reverseString` function to reverse the string using the `reverse()` method of the `StringBuilder` class. The reversed string is then printed to the console.

Here’s a sample output of the program:

Enter a string: Hello, World!

Reversed string: !dlroW ,olleH

Q28. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

An array generally contains elements of the primitive data types such as int, float, etc. In such cases, the array directly stores these elements at contiguous memory locations. While an ArrayList does not contain primitive data types. An arrayList contains the reference of the objects at different memory locations instead of the object itself. That is why the objects are not stored at contiguous memory locations.

Q29. How is the creation of a String using new() different from that of a literal? When we create a string using new(), a new object is created. Whereas, if we create a string using the string literal syntax, it may return an already existing object with the same name.

Q30. Why is synchronization necessary? Explain with the help of a relevant example.

Java allows multiple threads to execute. They may be accessing the same variable or object. Synchronization helps to execute threads one after another. It is important as it helps to execute all concurrent threads while being in sync. It prevents memory consistency errors due to access to shared memory. An example of synchronization code is-

As we have synchronized this function, this thread can only use the object after the previous thread has used it.

Q31. Explain the term “Double Brace Initialization” in Java?

Double Brace Initialization is a Java term that refers to the combination of two independent processes. There are two braces used in this. The first brace creates an anonymous inner class. The second brace is an initialization block. When these both are used together, it is known as Double Brace Initialization. The inner class has a reference to the enclosing outer class, generally using the ‘this’ pointer. It is used to do both creation and initialization in a single statement. It is generally used to initialize collections. It reduces the code and also makes it more readable.

Q32. Why is it said that the length() method of String class doesn’t return accurate results?

The length() method of String class doesn’t return accurate results because it simply takes into account the number of characters within in the String. In other words, code points outside of the BMP (Basic Multilingual Plane), that is, code points having a value of U+10000 or above, will be ignored.

The reason for this is historical. One of Java’s original goals was to consider all text as Unicode; yet, Unicode did not define code points outside of the BMP at the time. It was too late to modify char by the time Unicode specified such code points.

Q33. What are the differences between Heap and Stack Memory in Java?

The major difference between Heap and Stack memory are:

Q34. What is a package in Java? List down various advantages of packages.

Packages in Java, are the collection of related classes and interfaces which are bundled together. By using packages, developers can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and reused. Below I have listed down a few of its advantages:

  • Packages help in avoiding name clashes
  • They provide easier access control on the code
  • Packages can also contain hidden classes which are not visible to the outer classes and only used within the package
  • Creates a proper hierarchical structure which makes it easier to locate the related classes

Q35. Why pointers are not used in Java?

Java doesn’t use pointers because they are unsafe and increases the complexity of the program. Since, Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.

Q36. What is JIT compiler in Java?

JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.

Q37. What are access modifiers in Java?

In Java, access modifiers are special keywords which are used to restrict the access of a class, constructor, data member and method in another class. Java supports four types of access modifiers:

Q38. Define a Java Class.

A class in Java is a blueprint which includes all your data.  A class contains fields (variables) and methods to describe the behavior of an object. Let’s have a look at the syntax of a class.

Q39. What is an object in Java and how is it created?

An object is a real-world entity that has a state and behavior. An object has three characteristics:

An object is created using the ‘new’ keyword. For example:

ClassName obj = new ClassName();

Q40. What is Object Oriented Programming?

Object-oriented programming, or OOP, is a programming model or approach in which programs are organized around objects rather than logic and functions. In other words, OOP mainly focuses on the objects that need to be manipulated instead of logic. This approach is ideal for large and complex programs and needs to be actively updated or maintained.

Q41. What are the main concepts of OOPs in Java?

Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

  • Inheritance: Inheritance is a process where one class acquires the properties of another.
  • Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
  • Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. 
  • Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.

Q42. What is the difference between a local variable and an instance variable?

In Java, a  local variable is typically used inside a method, constructor, or a block  and has only local scope. Thus, this variable can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable.

Whereas, an  instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within a  class , but outside a method. Every object of that class will create it’s own copy of the variable while using it. Thus, any changes made to the variable won’t reflect in another instances of that class and will be bound to that particular instance only.

Q43. Differentiate between the constructors and methods in Java?

Q44. what is final keyword in java.

final is a special keyword in Java that is used as a non-access modifier. A final variable can be used in different contexts such as:

  • final variable

When the final keyword is used with a variable then its value can’t be changed once assigned. In case the no value has been assigned to the final variable then using only the class constructor a value can be assigned to it.

final method

When a method is declared final then it can’t be overridden by the inheriting class.

final class

When a class is declared as final in Java, it can’t be extended by any subclass class but it can extend other class.

Q45. What is the difference between break and continue statements?

Q46. what 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 isn’t 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.

For example:

Q47. What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor. 

Q48. What is Java String Pool?

Java String pool refers to a collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not. If it is present, then the same reference is returned to the variable else new object will be created in the String pool and the respective reference will be returned.

Q49. Differentiate between static and non-static methods in Java.

Q50. what is constructor chaining in java.

In Java, constructor chaining is the process of calling one constructor from another with respect to the current object. Constructor chaining is possible only through legacy where a subclass constructor is responsible for invoking the superclass’ constructor first. There could be any number of classes in the constructor chain. Constructor chaining can be achieved in two ways:

  • Within the same class using this()
  • From base class using super()

Q51. Difference between String, StringBuilder, and StringBuffer.

Q52. Why Java Strings are immutable in nature?

In Java, string objects are immutable in nature which simply means once the String object is created its state cannot be modified. Whenever you try to update the value of that object instead of updating the values of that particular object, Java creates a new string object. Java String objects are immutable as String objects are generally cached in the String pool. Since String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security, caching, synchronization, and performance of the application. 

Q53. What is the difference between an array and an array list?

Q54. what is a map in java.

In Java, Map is an interface of Util package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface: 

  • Map doesn’t contain duplicate keys.

Each key can map at max one value.

Q55. What is collection class in Java? List down its methods and interfaces.

In Java, the collection is a framework that acts as an architecture for storing and manipulating a group of objects. Using Collections you can perform various tasks like searching, sorting, insertion, manipulation, deletion, etc. Java collection framework includes the following:

The below image shows the complete hierarchy of the Java Collection.

The above Java Interview questions for freshers are designed to gauge the basic understanding, familiarity, and practical skills with one of the world’s most popular programming languages. For those new to the Java landscape, preparation by understanding these key areas, practicing coding problems, and embracing the logic and philosophy of Java can make the journey into the professional world smoother and more rewarding. If you find our Java programming questions interesting, we would recommend you to check out Java Collection Interview Questions here!

Java OOPS Interview Questions

Q56. what is polymorphism.

  • Compile time polymorphism
  • Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.

Q57. What is runtime polymorphism or dynamic method dispatch?

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.

Q58. What is abstraction in Java?

Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing the essential things to the user. Thus you can say that abstraction in Java is the process of hiding the implementation details from the user and revealing only the functionality to them. Abstraction can be achieved in two ways:

  • Abstract Classes (0-100% of abstraction can be achieved)
  • Interfaces (100% of abstraction can be achieved)

Q59. What do you mean by an interface in Java?

An interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Thus, interface basically is a group of related methods with empty bodies. Example:

Q60. What is the difference between abstract classes and interfaces?

Q61. What is inheritance in Java?

Inheritance in Java is the concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes. Inheritance is performed between two types of classes:

  • Parent class (Super or Base class)
  • Child class (Subclass or Derived class)

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.

Q62. What are the different types of inheritance in Java?

Java supports four types of inheritance which are:

  • Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as well as one child class.
  • Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.
  • Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.
  • Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.

Q63. What is method overloading and method overriding?

Method overloading :.

  • In Method Overloading, Methods of the same class shares the same name but each method must have a different number of parameters or parameters having different types and order.
  • Method Overloading is to “add” or “extend” more to the method’s behavior.
  • It is a compile-time polymorphism.
  • The methods must have a different signature.
  • It may or may not need inheritance in Method Overloading.

Let’s take a look at the example below to understand it better.

Method Overriding:  

  • In Method Overriding, the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.
  • Method Overriding is to “Change” existing behavior of the method.
  • It is a run time polymorphism.
  • The methods must have the same signature.
  • It always requires inheritance in Method Overriding.

Q64. Can you override a private or static method in Java?

You cannot override a private or static method in Java. If you create a similar method with the same return type and same method arguments in child class then it will hide the superclass method; this is known as method hiding. Similarly, you cannot override a private method in subclass because it’s not accessible there. What you can do is create another private method with the same name in the child class. Let’s take a look at the example below to understand it better.

Q65. What is multiple inheritance? Is it supported by Java?

The problem with multiple inheritance is that if multiple parent classes have the same method name, then at runtime it becomes difficult for the compiler to decide which method to execute from the child class.

Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as Diamond Problem.

Q66. What is encapsulation in Java?

Encapsulation is a mechanism where you bind your data(variables) and code(methods) together as a single unit. Here, the data is hidden from the outer world and can be accessed only via current class methods. This helps in protecting the data from any unnecessary modification. We can achieve encapsulation in Java by:

  • Declaring the variables of a class as private.
  • Providing public setter and getter methods to modify and view the values of the variables.

Q67. What is an association?

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to many, many to one and many to many.

Q68. What do you mean by aggregation?

An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not destroy. 

Q69. What is composition in Java?

Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of a relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically delete.

Q70. What is a marker interface?

In Java, a marker interface is an interface that does not declare any methods or fields. Its sole purpose is to mark or tag a class as having a certain characteristic or capability. By implementing a marker interface, a class indicates that it possesses specific behavior or qualifies for a particular treatment.

Marker interfaces are purely a convention and serve as a form of metadata. They provide a way for developers or frameworks to identify classes that meet certain criteria without requiring any additional methods or fields.

Some common examples of marker interfaces in Java include:

  • Serializable: The Serializable interface is a marker interface that indicates a class can be serialized, allowing objects of that class to be converted into a byte stream for storage or transmission.
  • Cloneable: The Cloneable interface is a marker interface that indicates a class can be cloned using the `clone()` method. Implementing this interface allows for creating a copy of an object.
  • Remote: The Remote interface is a marker interface used in Java’s Remote Method Invocation (RMI) framework. It marks an interface that can be invoked remotely, enabling the execution of methods across different JVMs.

Marker interfaces can be useful in various scenarios, such as:

– Providing hints to the Java runtime or frameworks about special handling or optimizations for certain classes.

– Enabling conditional behavior based on the presence of a marker interface during runtime.

– Supporting integration with external libraries or frameworks that recognize and operate on marker interfaces.

It’s important to note that with the introduction of annotations in Java, the use of marker interfaces has become less common. Annotations offer a more flexible and expressive way to attach metadata to classes and methods. However, marker interfaces still have their place in certain contexts and are part of the Java language’s design and heritage.

Q71 .  What is object cloning in Java?

Object cloning in Java is the process of creating an exact copy of an object. It basically means the ability to create an object with a similar state as the original object. To achieve this, Java provides a method clone ()  to make use of this functionality. This method creates a new instance of the class of the current object and then initializes all its fields with the exact same contents of corresponding fields. To object clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime exceptions. One thing you must note is Object clone() is a protected method, thus you need to override it.

Q72. What is a copy constructor in Java?

Copy constructor is a member function that is used to initialize an object using another object of the same class. Though there is no need for copy constructor in Java since all objects are passed by reference. Moreover, Java does not even support automatic pass-by-value.

Q73. What is a constructor overloading in Java?

In Java, constructor overloading is a technique of adding any number of constructors to a class each having a different parameter list. The compiler uses the number of parameters and their types in the list to differentiate the overloaded constructors.

Servlets Java Technical Interview Questions

Q74. what is a servlet.

  • Java Servlet is server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.
  • The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
  • All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
  • Most of the times, web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class. Servlet API hierarchy is shown in below image.

Q75. What are the differences between Get and Post methods?

Q76. what is request dispatcher.

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response.

There are two methods defined in this interface:

1.void forward()

2.void include()

Q77. What are the differences between forward() method and sendRedirect() methods?

Q78. what is the life-cycle of a servlet.

  • Servlet is loaded
  • Servlet is instantiated
  • Servlet is initialized
  • Service the request
  • Servlet is destroyed

Q79. How does cookies work in Servlets?

  • Cookies are text data sent by server to the client and it gets saved at the client local machine.
  • Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
  • HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.
  • Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

Q80. What are the differences between ServletContext vs ServletConfig?

The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.

Q81. What are the different methods of session management in servlets?

Session is a conversational state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

  • User Authentication
  • HTML Hidden Field
  • URL Rewriting
  • Session Management API

Apart from this blog, if you want to get trained by professionals on this technology, you can opt for structured training from edureka! Click below to know more.

JDBC – Java Basic Interview Questions 

Q82. what is jdbc driver.

JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:

  • JDBC-ODBC bridge driver
  • Native-API driver (partially java driver)
  • Network Protocol driver (fully java driver)
  • Thin driver (fully java driver)

Q83. What are the steps to connect to a database in java?

  • Registering the driver class
  • Creating connection
  • Creating statement
  • Executing queries
  • Closing connection

Q84. What are the JDBC API components?

The java.sql package contains interfaces and classes for JDBC API.

Interfaces:

  • PreparedStatement
  • ResultSetMetaData
  • DatabaseMetaData
  • CallableStatement etc.
  • DriverManager
  • SQLException etc.

Q85. What is the role of JDBC DriverManager class?

The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

Q86. What is JDBC Connection interface?

The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

Q87.  What is the purpose of JDBC ResultSet interface?

The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

Q88. What is JDBC ResultSetMetaData interface?

The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

Q89. What is JDBC DatabaseMetaData interface?

The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

Q90. What do you mean by batch processing in JDBC?

Batch processing helps you to group related SQL statements into a batch and execute them instead of executing a single query. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.

Q91. What is the difference between execute, executeQuery, executeUpdate?

Statement execute(String query) 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(String query) 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(String query ) is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) 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.

Q92. What do you understand by JDBC Statements?

JDBC statements are basically the statements which are used to send SQL commands to the database and retrieve data back from the database. Various methods like execute(), executeUpdate(), executeQuery, etc. are provided by JDBC to interact with the database.

JDBC supports 3 types of statements:

  • Statement: Used for general purpose access to the database and executes a static SQL query at runtime.
  • PreparedStatement: Used to provide input parameters to the query during execution.
  • CallableStatement: Used to access the database stored procedures and helps in accepting runtime parameters.

Spring Framework Java Interview Questions 

Q93. what is spring.

Wikipedia defines the Spring framework as “an application framework and inversion of control container for the Java platform. The framework’s core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform.” Spring is essentially a lightweight, integrated framework that can be used for developing enterprise applications in java.

Q94. Name the different modules of the Spring framework.

Some of the important Spring Framework modules are:

  • Spring Context – for dependency injection.
  • Spring AOP – for aspect oriented programming.
  • Spring DAO – for database operations using DAO pattern
  • Spring JDBC – for JDBC and DataSource support.
  • Spring ORM – for ORM tools support such as Hibernate
  • Spring Web Module – for creating web applications.
  • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

Q95. List some of the important annotations in annotation-based Spring configuration.

The important annotations are:

  • @PostConstruct
  • @PreDestroy

Q96. Explain Bean in Spring and List the different Scopes of Spring bean.

Beans are objects that form the backbone of a Spring application. They are managed by the Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

There are five Scopes defined in Spring beans.

  • Singleton : Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
  • Prototype : A new instance will be created every time the bean is requested.
  • Request : This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
  • Session : A new bean will be created for each HTTP session by the container.
  • Global-session : This is used to create global session beans for Portlet applications.

Q97. How we can set the spring bean scope? And what supported scopes does it have?

In Spring framework, the scope of a bean determines the lifecycle and visibility of the bean instance within the container. You can set the scope of a Spring bean using the `@Scope` annotation or the XML configuration.

To set the scope using the `@Scope` annotation, you can specify it on the bean class or the bean definition method within a configuration class. Here’s an example:

In this example, the `singletonBean` method is annotated with `@Scope(“singleton”)`, indicating that the bean will have a singleton scope. The `prototypeBean` method is annotated with `@Scope(“prototype”)`, specifying a prototype scope.

Alternatively, you can configure bean scopes using XML configuration. Here’s an example:

The supported bean scopes in Spring are:

  • Singleton (default): Only one instance of the bean is created per Spring container. It is cached and reused for subsequent requests.
  • Prototype: A new instance of the bean is created every time it is requested.
  • Request: A new instance of the bean is created for each HTTP request in a web application context.
  • Session: A new instance of the bean is created for each HTTP session in a web application context.
  • Global session: Similar to the session scope, but used in a Portlet context (not commonly used).
  • Application: A single instance of the bean is created per ServletContext in a web application context (not commonly used).
  • Websocket: A new instance of the bean is created for each WebSocket connection in a web application context.

Note that the availability of certain scopes depends on the type of application context you are using (e.g., web application context).

Q98. Explain the role of DispatcherServlet and ContextLoaderListener.

DispatcherServlet is basically the front controller in the Spring MVC application as it loads the spring bean configuration file and initializes all the beans that have been configured. If annotations are enabled, it also scans the packages to configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

Q99. What is the best way to inject dependency? Also, state the reason

The best way to inject dependencies in an application is through constructor injection. Constructor injection involves passing dependencies as parameters to a class’s constructor. Here are the reasons why constructor injection is considered the best approach:

  • Explicit dependencies: Constructor injection makes dependencies explicit, as they are clearly defined as constructor parameters. This improves code readability and makes it easier to understand the class’s dependencies.
  • Compile-time safety: With constructor injection, dependencies are resolved at compile-time rather than runtime. This allows for early detection of missing or incorrect dependencies, reducing the chances of runtime errors.
  • Testability: Constructor injection facilitates easy testing of classes by allowing for the injection of mock or stub dependencies during unit testing. By providing test doubles through the constructor, you can isolate the class under test and verify its behavior without relying on real dependencies.
  • Immutability: Constructor injection promotes immutability as dependencies can be declared as final or read-only. Immutable objects are generally easier to reason about and less prone to bugs related to state changes.
  • Dependency inversion principle: Constructor injection adheres to the Dependency Inversion Principle (DIP) of the SOLID principles. DIP states that high-level modules should not depend on low-level modules, but both should depend on abstractions. Constructor injection allows for the injection of abstractions rather than concrete implementations, enabling flexibility and loose coupling between classes.

While other dependency injection techniques like setter injection and field injection exist, they have certain drawbacks compared to constructor injection. Setter injection can lead to optional dependencies or unexpected null values, while field injection tightly couples classes and makes it harder to identify dependencies. Hence, constructor injection is generally recommended as the best way to inject dependencies.

Q100. What are the differences between constructor injection and setter injection?

Q101. what is autowiring in spring what are the autowiring modes.

Autowiring enables the programmer to inject the bean automatically. We don’t need to write explicit injection logic.  Let’s see the code to inject bean using dependency injection.

  • <bean id= “emp” class = “com.javatpoint.Employee” autowire= “byName” />  

The autowiring modes are given below:

Q102. How to handle exceptions in Spring MVC Framework?

Spring MVC Framework provides the following ways to help us achieving robust exception handling.

Controller Based:

We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.

Global Exception Handler:

Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.

HandlerExceptionResolver implementation:

For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

Q103. What are some of the important Spring annotations which you have used?

Some of the Spring annotations that I have used in my project are:

@Controller – for controller classes in Spring MVC project.

@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples

@ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.

@PathVariable – for mapping dynamic values from the URI to handler method arguments.

@Autowired – for autowiring dependencies in spring beans.

@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.

@Service – for service classes.

@Scope – for configuring the scope of the spring bean.

@Configuration, @ComponentScan and @Bean – for java based configurations.

AspectJ annotations for configuring aspects and advices , @Aspect, @Before, @After, @Around, @Pointcut, etc.

Check out JavaScript Interview Questions as well.

Q104. How to integrate Spring and Hibernate Frameworks?

We can use Spring ORM module to integrate Spring and Hibernate frameworks if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.

Also, Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management.

Q105. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

  • Programmatic transaction management:  In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.
  • Declarative transaction management:  In this, transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.

Hibernate – Java Interview Questions for Experienced Professionals

Q106. what is hibernate framework.

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.

Hibernate provides a reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use the Hibernate persistence API for CRUD operations. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.

Similarly, hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

Q107. What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

  • Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
  • Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
  • Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism, and association.
  • Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentation and help is easily available in forums.
  • Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
  • Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
  • Hibernate cache helps us in getting better performance.
  • For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

Q108. Explain Hibernate architecture.

The Hibernate architecture is categorized in four layers.

  • Java application layer
  • Hibernate framework layer
  • Backhand API layer
  • Database layer

Q109. What are the differences between get and load methods?

The differences between get() and load() methods are given below.

Q103. What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

  • Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
  • Hibernate supports inheritance, associations, and collections. These features are not present with JDBC API.
  • Hibernate implicitly provides transaction management, in fact, most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. 
  • JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throw JDBCException or HibernateException un-checked exception, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
  • Hibernate Query Language (HQL) is more object-oriented and close to Java programming language. For JDBC, we need to write native SQL queries.
  • Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
  • Hibernate provides option through which we can create database tables too, for JDBC tables must exist in the database.
  • Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for the connection pool. This is a very important feature in enterprise application and completely missing in JDBC API.
  • Hibernate supports JPA annotations, so the code is independent of the implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.

JSP – Core Java Interview Questions

Q110. what are the life-cycle methods for a jsp, q111. what are the jsp implicit objects.

JSP provides 9 implicit objects by default. They are as follows:

Q112. What are the differences between include directive and include action?

Q113. how to disable caching on back button of the browser, q114. what are the different tags provided in jstl.

There are 5 type of JSTL tags.

  • internationalization tags
  • functions tags

Q115. How to disable session in JSP?

  • < %@ page session = “false” % >

Q116.  How to delete a Cookie in a JSP?

The following code explains how to delete a Cookie in a JSP :

Q117. Explain the jspDestroy() method.

jspDestry() method is invoked from javax.servlet.jsp.JspPage interface whenever a JSP page is about to be destroyed. Servlets destroy methods can be easily overridden to perform cleanup, like when closing a database connection.

Q118.  How is JSP better than Servlet technology?

JSP is a technology on the server’s side to make content generation simple. They are document-centric, whereas servlets are programs. A Java server page can contain fragments of Java program, which execute and instantiate Java classes. However, they occur inside an HTML template file. It provides the framework for the development of a Web Application.

Q119. What are the different categories of Java Design patterns?

Java Design patterns can be broadly categorized into three main categories: creational patterns, structural patterns, and behavioral patterns. Let’s explore each category in more detail:

  • Creational Patterns: These patterns deal with object creation mechanisms, providing ways to create objects in a flexible and reusable manner. Some common creational patterns include:

   – Singleton: Ensures that only one instance of a class is created and provides a global point of access to it.

   – Factory Method: Defines an interface for creating objects, but lets subclasses decide which class to instantiate.

   – Abstract Factory: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

  • Structural Patterns: These patterns focus on the composition of classes and objects, defining how they can be structured to form larger structures while keeping the system flexible and efficient. Some examples of structural patterns include:

   – Adapter: Converts the interface of a class into another interface that clients expect.

   – Decorator: Dynamically adds new behaviors or responsibilities to an object.

   – Composite: Treats a group of objects as a single object, allowing clients to treat individual objects and compositions uniformly.

  • Behavioral Patterns: These patterns address the interaction and communication between objects, defining how they collaborate and fulfill their responsibilities. Some common behavioral patterns are:

   – Observer: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

   – Strategy: Defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.

   – Command: Encapsulates a request as an object, allowing you to parameterize clients with queues, requests, and operations.

These divisions offer a methodical approach to categorize and comprehend many Java design patterns. It is noteworthy that certain design patterns might fall into more than one category or have variants and combinations, and that these categories are not exclusive of one another. Other design patterns that fall outside of these categories include concurrency patterns and architectural patterns, both of which are applicable to Java programming.

Q120. Why should we not configure JSP standard tags in web.xml?

We don’t need to configure JSP standard tags in web.xml because when container loads the web application and find TLD files, it automatically configures them to be used directly in the application JSP pages. We just need to include it in the JSP page using taglib directive.

Q121. How will you use JSP EL in order to get the HTTP method name?

Using pageContext JSP EL implicit object you can get the request object reference and make use of the dot operator to retrieve the HTTP method name in the JSP page. The JSP EL code for this purpose will look like ${pageContext.request.method}.

 Exception and Thread Java Interview Questions for Experienced Professionals

Q122. what is the difference between error and exception.

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.

While exceptions are conditions that occur because of bad input or human error etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving the user feedback for entering proper values etc.

Q123. How can you handle Java exceptions?

There are five keywords used to handle exceptions in Java: 

Q124. What are the differences between Checked Exception and Unchecked Exception?

Checked exception.

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. 
  • Checked exceptions are checked at compile-time.
  • Example: IOException, SQLException etc.

Unchecked Exception

  • The classes that extend RuntimeException are known as unchecked exceptions. 
  • Unchecked exceptions are not checked at compile-time.
  • Example: ArithmeticException, NullPointerException etc.

Q125. What are the different ways of thread usage?

There are two ways to create a thread:

  • Extending Thread class

This creates a thread by creating an instance of a new class that extends the Thread class. The extending class must override the run() function, which is the thread’s entry point.

  • Implementing Runnable interface

This is the easiest way to create a thread, by creating a class that implements the runnable interface. After implementing the runnable interface, the class must implement the public void run() method ()

The run() method creates a parallel thread in your programme. When run() returns, the thread will come to an end.

Within the run() method, you must specify the thread’s code.

Like any other method, the run() method can call other methods, use other classes, and define variables.

Q126. Java works as “pass by value” or “pass by reference” phenomenon?

Java is always pass-by-value. This means that it creates a copy of the contents of the parameter in memory. In Java, object variables always refer to the memory heap’s real object.

Q126. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

The finally block always gets executed even hen the return statement is written at the end of the try block and the catch block. It always executes , whether there is an exception or not. There are only a few situations in which the finally block does not execute, such as VM crash, power failure, software crash, etc. If you don’t want to execute the finally block, you need to call the System.exit() method explicitly in the finally block.

Q127. How does an exception propagate in the code?

If an exception is not caught, it is thrown from the top of the stack and falls down the call stack to the previous procedure. If the exception isn’t caught there, it falls back to the previous function, and so on, until it’s caught or the call stack reaches the bottom. The term for this is Exception propagation.

Q128. Can you explain the Java thread lifecycle?

The java thread lifecycle has the following states-

When a thread is created, and before the program starts the thread, it is in the new state. It is also referred to as a born thread.

 Runnable

When a thread is started, it is in the Runnable state. In this state, the thread is executing its task.

Sometimes, a thread goes to the waiting state, where it remains idle because another thread is executing. When the other thread has finished, the waiting thread again comes into the running state.

Timed Waiting

In timed waiting, the thread goes to waiting state. But, it remains in waiting state for only a specified interval of time after which it starts executing.It remains waiting either till the time interval ends or till the other thread has finished.

A thread is said to be in this state once it terminates. It may be because the thread has completed its task or due to any other reason.

Q129. What purpose do the keywords final, finally, and finalize fulfill? 

Final is used to apply restrictions on class, method, and variable. A final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed. Let’s take a look at the example below to understand it better.

Finally is used to place important code, it will be executed whether the exception is handled or not. Let’s take a look at the example below to understand it better.

Finalize is used to perform clean up processing just before the object is garbage collected. Let’s take a look at the example below to understand it better.

Q130. What are the differences between throw and throws? 

Q131. what is exception hierarchy in java.

The hierarchy is as follows:

Throwable is a parent class of all Exception classes. There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of exceptions extends Exception class whereas errors are further classified into Virtual Machine error and Assertion error.

Q132. How to create a custom Exception?

To create you own exception extend the Exception class or any of its subclasses.

  • class New1Exception extends Exception { }               // this will create Checked Exception
  • class NewException extends IOException { }             // this will create Checked exception
  • class NewException extends NullPonterExcpetion { }  // this will create UnChecked exception

Q133. What are the important methods of Java Exception Class?

Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.

  • String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor.
  • String getLocalizedMessage( ) – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
  • Synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown.
  • String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.
  • void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as an argument to write the stack trace information to the file or stream.

Q134. What are the differences between processes and threads?

Q135. what is a finally block is there a case when finally will not execute.

Finally block is a block which always executes a set of statements. It is always associated with a try block regardless of any exception that occurs or not.  Yes, finally will not be executed if the program exits either by calling System.exit() or by causing a fatal error that causes the process to abort.

Q136. What is synchronization?

Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As Java supports execution of multiple threads, two or more threads may access the same fields or objects. Synchronization is a process which keeps all concurrent threads in execution to be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory. When a method is declared as synchronized the thread holds the monitor for that method’s object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor. 

Q137. Can we write multiple catch blocks under single try block? 

Yes we can have multiple catch blocks under single try block but the approach should be from specific to general. Let’s understand this with a programmatic example.

Methods are defined in the base class Throwable. Some of the important methods of Java exception class are stated below. 

  • String getMessage() – This method returns the message String about the exception. The message can be provided through its constructor.
  • public StackTraceElement[] getStackTrace() – This method returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack whereas the last element in the array represents the method at the bottom of the call stack.

Synchronized Throwable getCause() – This method returns the cause of the exception or null id as represented by a Throwable object.

  • String toString() – This method returns the information in String format. The returned String contains the name of Throwable class and localized message.
  • void printStackTrace() – This method prints the stack trace information to the standard error stream. 

Q138. What is OutOfMemoryError in Java?

OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

Q139. What is a Thread?

A thread is the smallest piece of programmed instructions which can be executed independently by a scheduler. In Java, all the programs will have at least one thread which is known as the main thread. This main thread is created by the JVM when the program starts its execution. The main thread is used to invoke the main() of the program.

Q140. What are the two ways to create a thread?

In Java, threads can be created in the following two ways:- 

  • By implementing the Runnable interface.
  • By extending the Thread

Q141. Why does the java array index start with 0?

The decision to start array indexing from 0 in Java (and many other programming languages) is rooted in the design and implementation of these languages.

Imagine you have a list of items, like a grocery shopping list. In Java, when you store those items in an array (a container to hold multiple values), the first item in the list is referred to as item 0, the second item as item 1, and so on. The numbering starts from 0 instead of 1.

There are a few reasons for this. First, it helps keep things consistent and predictable. By starting from 0, it forms a clear pattern where each item’s position corresponds directly to its index. It’s like counting how many steps you take to reach a certain item, where the first step is step 0.

Another reason is that starting from 0 simplifies how arrays are stored in computer memory. It allows for efficient calculations and direct access to the memory location where an item is stored.

Finally, many programming languages, including Java, follow this convention because it’s familiar to developers who have worked with other languages like C and C++. It helps with compatibility and makes it easier to understand and share code across different languages.

So, while it might seem a bit unusual at first, starting array indexing from 0 is a convention that has been widely adopted in programming languages to provide simplicity, consistency, and efficiency.

Q142. What are the different types of garbage collectors in Java?

Garbage collection in Java a program which helps in implicit memory management. Since in Java, using the new keyword you can create objects dynamically, which once created will consume some memory. Once the job is done and there are no more references left to the object, Java using garbage collection destroys the object and relieves the memory occupied by it. Java provides four types of garbage collectors:

  • Serial Garbage Collector
  • Parallel Garbage Collector
  • CMS Garbage Collector
  • G1 Garbage Collector

Q143. Write a Java program to print a Fibonacci sequence using recursion.

If you want to write a Java program to generate the Fibonacci series using recursion, you’ll need to create a method that can call itself to figure out the next number in the series. Here’s a simple example:

public class Fibonacci {

public static void main(String[] args) {

int n = 10; // Number of elements in Fibonacci series

for (int i = 0; i < n; i++) {

System.out.print(fibonacci(i) + ” “);

public static int fibonacci(int n) {

if (n <= 1) {

return fibonacci(n – 1) + fibonacci(n – 2);

In this program:

  • The main method sets the number of elements to be printed in the Fibonacci series (in this case, 10).
  • If n is 0 or 1, it returns n itself as per the Fibonacci series definition.
  • Otherwise, it calls itself with the values n – 1 and n – 2, and sums up their results.

When you run this program, it’ll display the initial 10 numbers from the Fibonacci sequence. If you want to print a different number of elements, you can tweak the value of n in the main method. Just keep in mind, this recursive method isn’t the best choice for large n values because it recalculates the same values repeatedly. For bigger series, it’s better to use an iterative approach or memoization.

Q144. Write a Java program to count the number of digits in a number.

If you want to create a Java program that tallies up the digits in a number, you can follow a straightforward approach. Start by repeatedly dividing the number by 10 until it reaches zero. Each time you divide, you essentially discard one digit from the number. By keeping track of how many times you’ve divided, you’ll know how many digits were originally in the number. Here’s an example implementation:

public class DigitCounter {

    public static void main(String[] args) {

        int number = 123456; // Example number

        int count = 0;

        while (number != 0) {

            number /= 10;  // Remove the last digit

            count++;       // Increment the count

        }

        System.out.println(“Number of digits: ” + count);

    }

  • number is the variable that holds the number whose digits you want to count. You can change this to any integer.
  • The while loop continues to execute as long as number is not zero.
  • Inside the loop, number /= 10; removes the last digit from number.
  • count is incremented each time a digit is removed.

When the number becomes zero, the loop terminates, and the total number of digits is output using System.out.println.

Q145. Write a Java program that counts how many times digit ‘D’ occurs within a given number ‘N’. You have to take N and D as inputs from the user.

Here’s a Java program that takes a number ‘N’ and a digit ‘D’ as input from the user and counts how many times digit ‘D’ occurs within the given number ‘N’:

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

// Taking input for N and D from the user

System.out.print(“Enter the number (N): “);

long N = scanner.nextLong();

System.out.print(“Enter the digit (D): “);

int D = scanner.nextInt();

// Converting N to a string for easier manipulation

String numberAsString = String.valueOf(N);

// Counting the occurrences of D in N

int count = 0;

for (int i = 0; i < numberAsString.length(); i++) {

if (numberAsString.charAt(i) – ‘0’ == D) {

// Displaying the result

System.out.println(“The digit ” + D + ” occurs ” + count + ” times in the number ” + N);

This program relies on Java’s Scanner class to gather input from the user. After receiving the input, it transforms the number ‘N’ into a string so that it can analyze each digit individually. It goes through each digit and compares it with the specified digit ‘D’, counting how many times ‘D’ appears. Once it completes this process, it displays the total count of occurrences of ‘D’ in ‘N’.

To get this program up and running, you’ll need first to compile it using a Java compiler and then execute the compiled class. Once you do that, it’ll ask you to input values for N and D, and then it’ll show you the result.

Q146. Write a Java program to calculate xn (x raised to the power of n) by using recursion. The solution can have O(N) time but is not allowed to use any additional space other than the recursion call stack space.

Here’s a Java program that calculates xn (x raised to the power of n) using recursion. It’s designed to keep the time complexity at O(N) and utilizes only the recursion call stack space, without needing any additional space.

public class PowerCalculator {

        double x = 2; // example base

        int n = 5; // example exponent

        double result = power(x, n);

        System.out.println(x + ” raised to the power of ” + n + ” is ” + result);

    public static double power(double x, int n) {

        // Base case: any number raised to the power of 0 is 1

        if (n == 0) {

            return 1;

        // If n is negative, compute the power for -n and take reciprocal

        if (n < 0) {

            return 1 / power(x, -n);

        // Recursive call

        return x * power(x, n – 1);

This program has a function called power which calculates the result of raising a given number x to the power of another number n. It works with both positive and negative values of n. In the main part of the program, there’s an example demonstrating how to use the power function.

When dealing with recursion, it’s crucial to keep in mind that for extremely large values of n, can cause a stack overflow error. In real-world scenarios, it’s wise to explore alternative solutions that don’t rely on recursion or to optimize through tail recursion (if your language and compiler allow it). This can greatly enhance the performance and reliability of your code in a production setting.

Q147. Write a Java program to calculate pow(x,n) using recursion.

To write a Java program that calculates x raised to the power of n using recursion, you can follow these steps:

  • Base Case: If n is 0, return 1, as any number raised to the power of 0 is 1.
  • Recursive Case: Otherwise, multiply x with the result of pow(x, n – 1).

Here’s how you can implement this:

        int x = 2; // Example value for x

        int n = 5; // Example value for n

        int result = pow(x, n);

    public static int pow(int x, int n) {

        // Base case

        return x * pow(x, n – 1);

  • The pow method is a recursive method that calculates x^n.
  • If n is 0, it returns 1.
  • Otherwise, it returns x multiplied by pow(x, n – 1), effectively computing the power recursively.

This approach works well for small values of n. However, for very large values, you may encounter a stack overflow error due to too many recursive calls. In such cases, an iterative approach or optimizing the recursion with memoization might be more efficient.

When dealing with small values of n, this method performs effectively. However, for very large values, you may encounter a stack overflow error, which happens when there are too many recursive calls. In these situations, it’s better to use an iterative method or enhance the recursion with memoization to improve efficiency.

So this brings us to the end of the blog. The topics that you learned in this Core Java Interview Questions blog are the most sought-after skill sets that recruiters look for in a Java Professional. This set of Interview Questions will definitely help you ace your job interview. Good luck with your interview!

Got a question for us? Please mention it in the comments section of this  and we will get back to you as soon as possible or you can also join our Java Training in Bangalore .

Recommended videos for you

Microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, introduction to java/j2ee & soa, microsoft sharepoint 2013 : the ultimate enterprise collaboration platform, mastering regex in perl, effective persistence using orm with hibernate, building application with ruby on rails framework, learn perl-the jewel of scripting languages, node js express: steps to create restful web app, nodejs – communication and round robin way, implementing web services in java, responsive web app using cakephp, php and mysql : server side scripting for web development, microsoft .net framework : an intellisense way of web development, create restful web application with node.js express, hibernate-the ultimate orm framework, service-oriented architecture with java, a day in the life of a node.js developer, hibernate mapping on the fly, node js : steps to create restful web app, recommended blogs for you, javascript validation : all you need to know about validating forms and email, node.js docker tutorial – know how to use node with docker, top 45 bootstrap interview questions and answers in 2024, understanding java input and output, understanding java hashmaps, string concatenation in javascript: all you need to know about string concat(), how to implement queue in c, a guide for planning a career as ruby on rails developer, everything about data retrieval in php, how to decrypt md5 password in php, removing elements from an array in javascript, a complete roadmap to learn data structures and algorithms (dsa), top 60+ javascript interview questions and answers for 2024, important javascript loops you need to know.

Nice article. Thank for your dedicate to make all of this.

In Question 10, describing the difference between heap and stack, the last comparison is not totally accurate. starting from Java 6 we have something called Escape Analysis made by the JVM. This is not only primitives and references are stored but also Objects that has no hope of being referenced outof scope are stored in the Stack Memory. This is efficient because the garbage collector shouldn’t care about local variables that end their lifetime in side the same scope.

Hey Tessema, thank you for reading our blogs and for pointing this out. We are glad to have avid learners like you on our channel. Cheers :)

In qn 18, isnt the parent method foo supposed to be hidden? so that all outputs belong to child class..

Hey Greshma, we would definitely like to help. May we know which question are you talking about? We can’t find a qn18. Thanks!

Q3 1st and 3rd row are wrong. Interfaces have been able to provide code via default methods for years (Java 8, 2014).

Question no 13 of exception where question says some methods of Exception class , toString() is method of Object class not of Exception class. Throwable class override this method from Object class. Throwable is parent of Exception class, that’s why Exception is able to use it. Correct it.

Hey Neha, thak you for pointing this out. We will definitely look into this. Cheers :)

Hi, Kindly provide explanation for DAO and parallel programming implementation in java.

Hi. Section OOPS Java Interview Questions: Q5 example is not valid in terms of syntax you missed curly braces.

Hey Bhargav, this was mostly probably a typo. We regret the mistake and thank you for pointing it out. Do browse through our other blogs and let us know how you liked it. Cheers :)

what are the modifiers applicable in java main method

thank you need sum advance concept

explain very well excepted with image good

Join the discussion Cancel reply

Trending courses in programming & frameworks, full stack web development internship program.

  • 29k Enrolled Learners
  • Weekend/Weekday

Java Certification Training Course

  • 76k Enrolled Learners

Python Scripting Certification Training

  • 14k Enrolled Learners

Flutter Application Development Course

  • 12k Enrolled Learners

Node.js Certification Training Course

  • 10k Enrolled Learners

Spring Framework Certification Course

Advanced java certification training.

  • 7k Enrolled Learners

Data Structures and Algorithms using Java Int ...

  • 31k Enrolled Learners

PHP & MySQL with MVC Frameworks Certifica ...

  • 5k Enrolled Learners

Microsoft .NET Framework Certification Traini ...

  • 6k Enrolled Learners

Browse Categories

Subscribe to our newsletter, and get personalized recommendations..

Already have an account? Sign in .

20,00,000 learners love us! Get personalised resources in your inbox.

At least 1 upper-case and 1 lower-case letter

Minimum 8 characters and Maximum 50 characters

We have recieved your contact details.

You will recieve an email from us shortly.

The Java Interview Prep Handbook – 50 Questions Solved + Code Examples

Vahe Aslanyan

If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable.

Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level.

This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring you're well-prepared for the challenges ahead.

This guide serves as a comprehensive Java review tutorial, bridging the gap between foundational Java knowledge and the sophisticated expertise sought by industry leaders like Google. And it'll help you deepen your understanding and practical application of Java, preparing you for professional success in the tech industry.

Table of Contents

  • What is Java?
  • What's the difference between the JDK, JRE, and JVM?
  • How does the 'public static void main(String[] args)' method work?
  • What is bytecode in Java?
  • Differentiate between overloading and overriding
  • What is the Java ClassLoader?
  • Can we override static methods in Java?
  • How does the 'finally' block differ from the 'finalize' method in Java?
  • What is the difference between an abstract class and an interface?
  • Explain the concept of Java packages
  • What are Java annotations?
  • How does multi-threading work in Java?
  • Use throw to raise an exception
  • Use throws to declare exceptions
  • What is the significance of the transient keyword?
  • How do you ensure thread safety in Java?
  • Explain the Singleton pattern
  • What are Java Streams?
  • What are the primary differences between ArrayList and LinkedList?
  • How do HashSet, LinkedHashSet, and TreeSet differ?
  • Differentiate between HashMap and ConcurrentHashMap
  • Describe the contract between hashCode() and equals() methods
  • What is Java reflection?
  • How do you create a custom exception in Java?
  • What is the difference between a checked and unchecked exception?
  • What are generics? Why are they used?
  • Explain the concept of Java Lambda Expressions
  • What is the diamond problem in inheritance?
  • Describe the difference between fail-fast and fail-safe iterators
  • What is type erasure in Java generics?
  • Describe the differences between StringBuilder and StringBuffer
  • What is the volatile keyword in Java?
  • Explain the Java memory model
  • What is the purpose of the default keyword in interfaces?
  • How does switch differ in Java 7 and Java 8?
  • Explain the concept of Autoboxing and Unboxing
  • Describe the @FunctionalInterface annotation
  • How can you achieve immutability in Java?
  • What is the decorator pattern?
  • Explain the Java I/O streams
  • How does the garbage collector work in Java?
  • What are the benefits of using Java NIO?
  • Explain the Observer pattern
  • What is the purpose of Java's Optional?
  • Explain Java's try-with-resources
  • Explain the difference between C++ and Java
  • What is polymorphism? Provide an example
  • How can you avoid memory leaks in Java?
  • Explain the purpose of Java's synchronized block
  • Explain the concept of modules in Java

image-23

1. What is Java?

Java is a high-level, object-oriented programming language known for its platform independence. It allows developers to write code once and run it anywhere using the Java Virtual Machine (JVM).

2. What's the Difference between the JDK, JRE, and JVM?

  • JDK (Java Development Kit): This is a software package that provides developers with the tools and utilities necessary to develop, compile, and run Java applications.
  • JRE (Java Runtime Environment): A subset of the JDK, the JRE contains the essential components, including the JVM, to run Java applications but not to develop them.
  • JVM (Java Virtual Machine): An abstract computing machine, the JVM enables Java bytecode to be executed, providing the platform independence Java is known for.

3. How Does the public static void main(String[] args) Method Work?

This method is the entry point for Java applications. The public modifier means it's accessible from other classes, static denotes it's a class-level method, and void indicates it doesn't return any value. The argument String[] args allows command-line arguments to be passed to the application.

4. What is bytecode in Java?

Bytecode is an intermediate, platform-independent code that Java source code is compiled into. It is executed by the JVM, enabling the "write once, run anywhere" capability.

5. Differentiate between overloading and overriding

  • Overloading: This occurs when two or more methods in the same class share the same name but have different parameters. It's a compile-time concept.
  • Overriding: In this case, a subclass provides a specific implementation for a method already defined in its superclass. It's a runtime concept.

image-24

6. What is the Java ClassLoader?

The Java ClassLoader is a part of the JRE that dynamically loads Java classes into the JVM during runtime. It plays a crucial role in Java's runtime environment by extending the core Java classes.

7. Can We Override Static Methods in Java?

No, we cannot override static methods. While a subclass can declare a method with the same name as a static method in its superclass, this is considered method hiding, not overriding.

8. How Does the finally Block Differ from the finalize Method in Java?

Understanding the distinction between the finally block and the finalize method in Java is crucial for effective resource management and exception handling in your programs.

Finally Block:

  • Purpose and Usage: The finally block is a key component of Java's exception handling mechanism. It is used in conjunction with try-catch blocks.
  • Execution Guarantee: Regardless of whether an exception is thrown or caught within the try or catch blocks, the code within the finally block is always executed. This ensures that it runs even if there’s a return statement in the try or catch block.
  • Common Uses: It is typically utilized for cleaning up resources, such as closing file streams, database connections, or releasing any system resources that were acquired in the try block. This helps in preventing resource leaks.

Finalize Method:

  • Definition: The finalize method is a protected method of the Object class in Java. It acts as a final resort for objects garbage collection.
  • Garbage Collector Call: It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. However, its execution is not guaranteed, and it's generally unpredictable when, or even if, the finalize method will be invoked.
  • Resource Release: The finalize method is designed to allow an object to clean up its resources before it is collected by the garbage collector. For example, it might be used to ensure that an open file owned by an object is closed.
  • Caution in Use: It's important to note that relying on finalize for resource cleanup is generally not recommended due to its unpredictability and potential impact on performance.

Access Modifiers in Java:

  • Private: This modifier makes a member accessible only within its own class. Other classes cannot access private members of a different class.
  • Default (no modifier): When no access modifier is specified, the member has package-level access. This means it is accessible to all classes within the same package.
  • Protected: A protected member is accessible within its own package and also in subclasses. This is often used in inheritance.
  • Public: Public members are accessible from any class in the Java program. It provides the widest level of access.

Understanding these distinctions and access levels is vital for effective Java programming, ensuring resource management, security, and encapsulation are handled appropriately in your software development endeavors.

9. What is the Difference between an Abstract Class and an Interface?

An abstract class in Java is used as a base for other classes. It can contain both abstract methods (without an implementation) and concrete methods (with an implementation).

Abstract classes can have member variables that can be inherited by subclasses. A class can extend only one abstract class due to Java's single inheritance property.

Example of an Abstract Class:

An interface in Java, on the other hand, is a completely "abstract class" that is used to group related methods with empty bodies.

From Java 8 onwards, interfaces can have default and static methods with a body. A class can implement any number of interfaces.

Example of an Interface:

Both abstract classes and interfaces are foundational concepts in Java, used for achieving abstraction and supporting design patterns like Strategy and Adapter. The use of these concepts depends on the specific requirements and design considerations of your software project.

image-25

10. Explain the Concept of Java Packages

Java packages are a way of organizing and structuring classes and interfaces in Java applications. They provide a means to group related code together. Packages help prevent naming conflicts, enhance code readability, and facilitate code reusability.

For example, consider a banking application. You might have packages like com.bank.accounts , com.bank.customers , and com.bank.transactions . These packages contain classes and interfaces specific to their respective functionalities.

In essence, Java packages are like directories or folders in a file system, organizing code and making it more manageable.

11. What are Java Annotations?

Java annotations are metadata that can be added to Java source code. They provide information about the code to the compiler or runtime environment. Annotations do not directly affect the program's functionality – instead, they convey instructions to tools or frameworks.

A common use of annotations is for marking classes or methods as belonging to a specific framework or for providing additional information to tools like code analyzers, build tools, or even custom code generators.

For example, the @Override annotation indicates that a method is intended to override a method from a superclass, helping catch coding errors during compilation. Another example is @Deprecated , which indicates that a method or class is no longer recommended for use.

12. How Does Multi-threading Work in Java?

Multi-threading in Java allows a program to execute multiple threads concurrently. Threads are lightweight processes within a program that can run independently. Java provides a rich set of APIs and built-in support for multi-threading.

Threads in Java are typically created by either extending the Thread class or implementing the Runnable interface. Once created, threads can be started using the start() method, causing them to run concurrently.

Java's multi-threading model ensures that threads share resources like memory and CPU time efficiently while providing mechanisms like synchronization and locks to control access to shared data.

Multi-threading is useful for tasks such as improving application responsiveness, utilizing multi-core processors, and handling concurrent operations, as often seen in server applications.

13. Use throw to Raise an Exception

In Java programming, the throw keyword is crucial for handling exceptions deliberately and responsively. This approach to exception management allows developers to enforce specific conditions in their code and maintain control over the program flow.

In this example, an IllegalArgumentException is thrown if the age parameter is less than 18. This method of raising an exception ensures that the program behaves predictably under defined conditions, enhancing both the security and reliability of the code.

14. Use throws to Declare Exceptions

The throws keyword in Java serves to declare that a method may cause an exception to be thrown. It signals to the method's caller that certain exceptions might arise, which should be either caught or further declared.

In this scenario, the readDocument method declares that it might throw a FileNotFoundException . This declaration requires the caller of this method to handle this exception, ensuring that appropriate measures are in place to deal with potential errors, and thus improving the robustness of the application.

Both throw and throws are integral to managing exceptions in Java. throw is used for actively raising an exception in the code, while throws declares possible exceptions that a method might produce, thereby mandating their handling by the caller. This distinction is essential for writing error-resistant and well-structured Java programs.

image-26

15. What is the Significance of the transient Keyword?

The transient keyword in Java is used to indicate that a field should not be serialized when an object of a class is converted to a byte stream (for example, when using Java Object Serialization).

This is significant when you have fields in a class that you do not want to include in the serialized form, perhaps because they are temporary, derived, or contain sensitive information.

16. How Do You Ensure Thread Safety in Java?

Thread safety in Java is achieved by synchronizing access to shared resources, ensuring that multiple threads can't simultaneously modify data in a way that leads to inconsistencies or errors.

You can ensure thread safety through synchronization mechanisms like synchronized blocks, using thread-safe data structures, or utilizing concurrent utilities from the java.util.concurrent package.

In the code above, we have a SharedCounter class with a synchronized increment method, ensuring that only one thread can increment the count variable at a time. This synchronization mechanism prevents data inconsistencies when multiple threads access and modify the shared count variable.

We create two threads ( thread1 and thread2 ) that concurrently increment the counter. By using synchronized methods or blocks, we guarantee thread safety, and the final count will be accurate, regardless of thread interleaving.

17. Explain the Singleton Pattern

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is achieved by making the constructor of the class private, creating a static method to provide a single point of access to the instance, and lazily initializing the instance when needed.

Implementation without Singleton:

Let's imagine a scenario where you want to establish a database connection. Without the Singleton pattern, every time you'd need a connection, you might end up creating a new one.

Now, imagine initializing this connection multiple times in different parts of your application:

For the above code, "Establishing a new database connection..." would be printed twice, implying two separate connections were created. This is redundant and can be resource-intensive.

Implementation with Singleton:

With the Singleton pattern, even if you attempt to get the connection multiple times, you'd be working with the same instance.

Initializing this connection multiple times:

For the above code, "Establishing a single database connection..." would be printed just once, even though we've called getInstance() twice.

18. What are Java Streams?

Java Streams are a powerful abstraction for processing sequences of elements, such as collections, arrays, or I/O channels, in a functional and declarative style. They provide methods for filtering, mapping, reducing, and performing various transformations on data.

Streams can significantly simplify code and improve readability when working with data collections.

19. What Are the Primary Differences between ArrayList and LinkedList?

ArrayList and LinkedList are both implementations of the List interface. The primary differences between them lie in their internal data structures.

ArrayList uses a dynamic array to store elements, offering fast random access but slower insertions and deletions. LinkedList uses a doubly-linked list, which provides efficient insertions and deletions but slower random access.

image-27

20. How do HashSet , LinkedHashSet , and TreeSet Differ?

  • HashSet stores elements in an unordered manner, offering constant-time complexity for basic operations.
  • LinkedHashSet maintains the order of insertion, providing ordered iteration of elements.
  • TreeSet stores elements in a sorted order (natural or custom), offering log(n) time complexity for basic operations.

In this code, we add a large number of elements to each type of set ( HashSet , LinkedHashSet , and TreeSet ) and measure the time it takes to perform this operation. This demonstrates the performance characteristics of each set type.

Typically, you will observe that HashSet performs the fastest for adding elements since it doesn't maintain any specific order, followed by LinkedHashSet , and TreeSet , which maintains a sorted order.

This output demonstrates the time taken (in nanoseconds) to add one million elements to each of the three sets: HashSet , LinkedHashSet , and TreeSet . As you can see, HashSet is the fastest, followed by LinkedHashSet , and TreeSet is the slowest due to its need to maintain elements in sorted order.

21. Differentiate between HashMap and ConcurrentHashMap

HashMap is not thread-safe and is suitable for single-threaded applications. ConcurrentHashMap , on the other hand, is designed for concurrent access and supports multiple threads without external synchronization. It provides high concurrency and performance for read and write operations.

22. Describe the Contract between the hashCode() and equals() Methods

The contract between hashCode() and equals() methods states that if two objects are equal ( equals() returns true), their hash codes ( hashCode() ) must also be equal.

However, the reverse is not necessarily true: objects with equal hash codes may not be equal. Adhering to this contract is crucial when using objects as keys in hash-based collections like HashMap .

23. What is Java Reflection?

Java reflection is a feature that allows you to inspect and manipulate the metadata of classes, methods, fields, and other program elements at runtime. It enables you to perform tasks such as dynamically creating objects, invoking methods, and accessing fields, even for classes that were not known at compile time.

24. How Do You Create a Custom Exception in Java?

You can create a custom exception in Java by extending the Exception class or one of its subclasses. By doing so, you can define your exception with specific attributes and behaviors tailored to your application's needs.

image-28

25. What is the Difference between a Checked and Unchecked Exception?

Checked exceptions are exceptions that must be either caught using a try-catch block or declared in the method signature using the throws keyword.

Unchecked exceptions (usually subclasses of RuntimeException ) do not require such handling.

Checked exceptions are typically used for recoverable errors, while unchecked exceptions represent programming errors or runtime issues.

Here is a code example to illustrate checked and unchecked exceptions.

In this code, we attempt to read a file using FileReader, which may throw a checked exception called IOException .

To handle this exception, we enclose the file reading code in a try-catch block specifically catching IOException . This is an example of how you handle checked exceptions, which are typically used for recoverable errors like file not found or I/O issues.

Now, let's take a look at an example of an unchecked exception:

In this code, we attempt to divide an integer by zero, which leads to an unchecked exception called ArithmeticException . Unchecked exceptions do not require explicit handling using a try-catch block. However, it's good practice to catch and handle them when you anticipate such issues. These exceptions often represent programming errors or runtime issues.

26. What Are Generics? Why Are They Used?

Generics in Java are a powerful feature that allows you to create classes, interfaces, and methods that operate on types. They provide a way to define classes or methods with a placeholder for the data type that will be used when an instance of the class is created or when a method is called.

Generics are used to make your code more reusable, type-safe, and less error-prone by allowing you to write generic algorithms that work with different data types. They help eliminate the need for typecasting and enable compile-time type checking.

For example, consider the use of a generic class to create a List of integers:

Generics ensure that you can only add integers to the list and that you don't need to perform explicit typecasting when retrieving elements from the list.

27. Explain the Concept of Java Lambda Expressions

Lambda expressions in Java are a concise way to express instances of single-method interfaces (functional interfaces) using a more compact syntax. They facilitate functional programming by allowing you to treat functions as first-class citizens.

Lambda expressions consist of a parameter list, an arrow (->), and a body. They provide a way to define and use anonymous functions.

For example, consider a functional interface Runnable that represents a task to be executed. With a lambda expression, you can define and execute a runnable task as follows:

We will talk about a more practical example later down the post.

28. What is the Diamond Problem in Inheritance?

The diamond problem in inheritance is a common issue in object-oriented programming languages that support multiple inheritance. It occurs when a class inherits from two classes that have a common ancestor class, resulting in ambiguity about which superclass's method or attribute to use.

Java solves the diamond problem by not supporting multiple inheritance of classes (that is, a class cannot inherit from more than one class).

But Java allows multiple inheritance of interfaces, which doesn't lead to the diamond problem because interfaces only declare method signatures, and the implementing class must provide concrete implementations. In case of method conflicts, the implementing class must explicitly choose which method to use.

Here's a simplified example to illustrate the diamond problem (even though Java doesn't directly encounter it):

In Java, the diamond problem is avoided through interface implementation and explicit method choice when conflicts arise.

29. Describe the Difference between Fail-fast and Fail-safe Iterators

In Java, fail-fast and fail-safe are two strategies for handling concurrent modification of collections during iteration.

Fail-fast iterators throw a ConcurrentModificationException if a collection is modified while being iterated. Fail-safe iterators, on the other hand, do not throw exceptions and allow safe iteration even if the collection is modified concurrently.

Fail-Fast Iterator Example:

In this example, when we attempt to remove an element from the list while iterating, it leads to a ConcurrentModificationException , which is characteristic of fail-fast behavior. Fail-fast iterators immediately detect and throw an exception when they detect that the collection has been modified during iteration.

Fail-Safe Iterator Example:

In this example, a ConcurrentHashMap is used, which supports fail-safe iterators. Even if we modify the map concurrently while iterating, there is no ConcurrentModificationException thrown. Fail-safe iterators continue iterating over the original elements and do not reflect changes made after the iterator is created.

image-29

30. What is Type Erasure in Java Generics?

Type erasure is a process in Java where type parameters in generic classes or methods are replaced with their upper bound or Object during compilation. This erasure ensures backward compatibility with pre-generic Java code. But it means that the type information is not available at runtime, which can lead to issues in some cases.

31. Describe the Differences between StringBuilder and StringBuffer

Thread safety:.

StringBuffer is thread-safe. This means it is synchronized, so it ensures that only one thread can modify it at a time. This is crucial in a multithreaded environment where you have multiple threads modifying the same string buffer.

StringBuilder , on the other hand, is not thread-safe. It does not guarantee synchronization, making it unsuitable for use in scenarios where a string is accessed and modified by multiple threads concurrently. But this lack of synchronization typically leads to better performance under single-threaded conditions.

Performance:

Because StringBuffer operations are synchronized, they involve a certain overhead that can impact performance negatively when high-speed string manipulation is required.

StringBuilder is faster than StringBuffer because it avoids the overhead of synchronization. It's an excellent choice for string manipulation in a single-threaded environment.

Use Case Scenarios:

Use StringBuffer when you need to manipulate strings in a multithreaded environment. Its thread-safe nature makes it the appropriate choice in this scenario.

Use StringBuilder in single-threaded situations, such as local method scope or within a block synchronized externally, where thread safety is not a concern. Its performance benefits shine in these cases.

API Similarity:

Both StringBuilder and StringBuffer have almost identical APIs. They provide similar methods for manipulating strings, such as append() , insert() , delete() , reverse() , and so on.

This similarity means that switching from one to the other in your code is generally straightforward.

Memory Efficiency:

Both classes are more memory efficient compared to using String for concatenation. Since String is immutable in Java, concatenation with String creates multiple objects, whereas StringBuilder and StringBuffer modify the string in place.

Introduced Versions:

StringBuffer has been a part of Java since version 1.0, whereas StringBuilder was introduced later in Java 5. This introduction was primarily to offer a non-synchronized alternative to StringBuffer for improved performance in single-threaded applications.

You should make the choice between StringBuilder and StringBuffer based on the specific requirements of your application, particularly regarding thread safety and performance needs.

While StringBuffer provides safety in a multithreaded environment, StringBuilder offers speed and efficiency in single-threaded or externally synchronized scenarios.

32. What is the volatile Keyword in Java?

Basic Definition: The volatile keyword is used to modify the value of a variable by different threads. It ensures that the value of the volatile variable will always be read from the main memory and not from the thread's local cache.

Visibility Guarantee: In a multithreading environment, threads can cache variables. Without volatile, there's no guarantee that one thread's changes to a variable will be visible to another. The volatile keyword guarantees visibility of changes to variables across threads.

Happens-Before Relationship: volatile establishes a happens-before relationship in Java. This means that all the writes to the volatile variable are visible to subsequent reads of that variable, ensuring a consistent view of the variable across threads.

Usage Scenarios: volatile is used for variables that may be updated by multiple threads. It's often used for flags or status variables. For example, a volatile boolean running variable can be used to stop a thread.

Limitations: Volatile cannot be used with class or instance variables. It's only applicable to fields. It doesn't provide atomicity.

For instance, volatile int i; i++; is not an atomic operation. For atomicity, you might need to resort to AtomicInteger or synchronized methods or blocks. It's not a substitute for synchronization in every case, especially when multiple operations on the volatile variable need to be atomic.

Avoiding Common Misconceptions: A common misconception is that volatile makes the whole block of statements atomic, which is not true. It only ensures the visibility and ordering of the writes to the volatile variable.

Another misconception is that volatile variables are slow. But while they might have a slight overhead compared to non-volatile variables, they are generally faster than using synchronized methods or blocks. Performance Considerations: volatile can be a more lightweight alternative to synchronization in cases where only visibility concerns are present. It doesn't incur the locking overhead that synchronized methods or blocks do. Best Practices: Use volatile sparingly and only when necessary. Overusing it can lead to memory visibility issues that are harder to detect and debug. Always assess whether your use case requires atomicity, in which case other concurrent utilities or synchronization might be more appropriate.

volatile use case:

We will create a simple program where one thread modifies a volatile boolean flag, and another thread reads this flag. This flag will be used to control the execution of the second thread.

Code Example:

Key points in the comments:.

  • Visibility of volatile variable: The most crucial aspect of using volatile here is ensuring that the update to the running variable in one thread (main thread) is immediately visible to another thread ( thread1 ). This is what allows thread1 to stop gracefully when running is set to false .
  • Use in a Simple Flag Scenario: The example demonstrates a common scenario for using volatile , that is as a simple flag to control the execution flow in a multithreaded environment.
  • Absence of Compound Operations: Note that we are not performing any compound operations (like incrementing) on the running variable. If we were, additional synchronization would be needed because volatile alone does not guarantee atomicity of compound actions.
  • Choice of volatile Over Synchronization: The choice to use volatile over other synchronization mechanisms (like synchronized blocks or Locks ) is due to its lightweight nature when dealing with the visibility of a single variable. It avoids the overhead associated with acquiring and releasing locks.

33. Explain the Java Memory Model

The JMM defines how Java threads interact through memory. Essentially, it describes the relationship between variables and the actions of threads (reads and writes), ensuring consistency and predictability in concurrent programming.

Happens-Before Relationship:

At the heart of the JMM is the 'happens-before' relationship. This principle ensures memory visibility, guaranteeing that if one action happens-before another, then the first is visible to and affects the second.

For example, changes to a variable made by one thread are guaranteed to be visible to other threads only if a happens-before relationship is established.

Memory Visibility:

Without the JMM, threads might cache variables, and changes made by one thread might not be visible to others. The JMM ensures that changes made to a shared variable by one thread will eventually be visible to other threads.

Synchronization:

The JMM utilizes synchronization to establish happens-before relationships. When a variable is accessed within synchronized blocks, any write operation in one synchronized block is visible to any subsequent read operation in another synchronized block.

Additionally, the JMM governs the behavior of volatile variables, ensuring visibility of updates to these variables across threads without synchronization.

Thread Interleaving and Atomicity:

The JMM defines how operations can interleave when executed by multiple threads. This can lead to complex states if not managed correctly.

Atomicity refers to operations that are indivisible and uninterrupted. In Java, operations on most primitive types (except long and double ) are atomic. However, compound operations (like incrementing a variable) are not automatically atomic.

Reordering:

The JMM allows compilers to reorder instructions for performance optimization as long as happens-before guarantees are maintained. However, this can lead to subtle bugs if not properly understood.

Use of Volatile Keyword:

The volatile keyword plays a significant role in the JMM. It ensures that any write to a volatile variable establishes a happens-before relationship with subsequent reads of that variable, thus ensuring memory visibility without the overhead of synchronization.

Locking Mechanisms:

Locks in Java (implicit via synchronized blocks/methods or explicit via ReentrantLock or others) also adhere to the JMM, ensuring that memory visibility is maintained across threads entering and exiting locks.

Safe Publication:

The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.

High-Level Implications:

Understanding the JMM is critical for writing correct and efficient multi-threaded Java applications. It helps developers reason about how shared memory is handled, especially in complex applications where multiple threads interact and modify shared data.

Best Practices:

  • Always use the appropriate synchronization mechanism to ensure memory visibility and atomicity.
  • Be cautious about memory visibility issues; even simple operations can lead to visibility problems in a multi-threaded context.
  • Understand the cost of synchronization and use volatile variables where appropriate.

34. What is the Purpose of the default Keyword in Interfaces?

The default keyword in Java interfaces, introduced in Java 8, marks a significant evolution in the Java language, especially in how interfaces are used and implemented. It serves several key purposes:

Adding Method Implementations in Interfaces:

Prior to Java 8, interfaces in Java could only contain method signatures (abstract methods) without any implementation.

The default keyword allows you to provide a default implementation for a method within an interface. This feature bridges a gap between full abstraction (interfaces) and concrete implementations (classes).

Enhancing Interface Evolution:

One of the primary motivations for introducing the default keyword was to enhance the evolution of interfaces.

Before Java 8, adding a new method to an interface meant breaking all its existing implementations. With default methods, you can add new methods to interfaces with default implementations without breaking the existing implementations.

This is particularly useful for library designers, ensuring backward compatibility when interfaces need to be expanded.

Facilitating Functional Programming:

\The introduction of default methods played a crucial role in enabling functional programming features in Java, such as Lambda expressions. It allowed for richer interfaces (like java.util.stream.Stream ) which are fundamental to functional-style operations in Java.

Multiple Inheritance of Behavior:

While Java does not allow multiple inheritance of state (that is, you cannot inherit from multiple classes), the default keyword enables multiple inheritance of behavior.

A class can implement multiple interfaces, and each interface can provide a default implementation of methods, which the class inherits.

Reducing Boilerplate Code:

default methods can be used to reduce the amount of boilerplate code by providing a general implementation that can be shared across multiple implementing classes, while still allowing individual classes to override the default implementation if a more specific behavior is required.

Example Usage:

In this example, any class implementing the Vehicle interface must provide an implementation for cleanVehicle , but it's optional for startEngine . The default implementation of startEngine can be used as is, or overridden by the implementing class.

Best Practices and Considerations:

  • Use Sparingly: Default methods should be used judiciously. They are best suited for gradually evolving interfaces or for methods that have a common implementation across most implementing classes.
  • Design With Care: When designing interfaces with default methods, consider how they might be used or overridden. It's important to document the expected behavior and interactions between default methods and other abstract methods in the interface.
  • Overriding Default Methods: Just like any inherited method, default methods can be overridden in the implementing class. This should be done to provide a specific behavior different from the default implementation.

image-30

35. How Does switch Differ in Java 7 and Java 8?

Limited Case Types: In Java 7, the switch statement supports limited types for the case labels, namely byte , short , char , int , and their corresponding Wrapper classes, along with enum types and, as of Java 7, String .

Traditional Structure: The structure of the switch statement in Java 7 follows the conventional C-style format, with a series of case statements and an optional default case. Each case falls through to the next unless it ends with a break statement or other control flow statements like return .

No Lambda Expressions: Java 7 does not support lambda expressions, and thus, they cannot be used within a switch statement or case labels.

Lambda Expressions: While the basic syntax and supported types for the switch statement itself did not change in Java 8, the introduction of lambda expressions in this version brought a new paradigm in handling conditional logic.

This doesn’t directly change how switch works, but it offers alternative patterns for achieving similar outcomes, especially when used in conjunction with functional interfaces.

Functional Programming Approach: Java 8 promotes a more functional programming style, encouraging the use of streams, lambda expressions, and method references. This can lead to alternatives for traditional switch statements, like using Map of lambdas for conditional logic, which can be more readable and concise.

Enhanced Readability and Maintainability: Although not a direct change to the switch statement, the use of lambda expressions and functional programming practices in Java 8 can lead to more readable and maintainable code structures that might otherwise use complex switch or nested if-else statements.

Practical Considerations:

  • When to Use switch in Java 8: Despite the advancements in Java 8, the switch statement remains a viable and efficient method for controlling complex conditional logic. It is particularly useful when dealing with a known set of possible values, such as enum constants or strings.
  • Combining switch with Lambdas: While you cannot use lambdas directly in a switch statement, Java 8 allows for more elegant ways to handle complex conditional logic that might traditionally have been a use case for switch . For example, using a Map with lambdas or method references can sometimes replace a complex switch statement.
  • Performance Considerations: The performance of a switch statement is generally better than a series of if-else statements, especially when dealing with a large number of cases, due to its internal implementation using jump tables or binary search.

36. Explain the Concept of Autoboxing and Unboxing

What is autoboxing.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer , a double to a Double , and so on.

When to use autoboxing

This feature is commonly used when working with collections, like ArrayList or HashMap , which can only store objects and not primitive types.

It simplifies the code by allowing direct assignment of a primitive value to a variable of the corresponding wrapper class.

Behind the Scenes:

When autoboxing, the compiler essentially uses the valueOf method of the respective wrapper class to convert the primitive to its wrapper type.

For example, Integer.valueOf(int) is used for converting int to Integer .

Performance Considerations:

  • While convenient, autoboxing can introduce performance overhead, especially in scenarios with extensive boxing and unboxing in tight loops, due to the creation of additional objects.

What is unboxing?

Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.

When to use unboxing

It is often used when performing arithmetic operations or comparisons on objects of wrapper classes, where primitive types are required.

During unboxing, the compiler uses the corresponding wrapper class's method to extract the primitive value. For instance, it uses Integer.intValue() to get the int from an Integer .

Null Pointer Exception:

A crucial point to consider is that unboxing a null object reference will throw a NullPointerException . This is a common bug in code that relies heavily on autoboxing and unboxing.

  • Be Aware of Implicit Conversions: It's important to be aware that these conversions are happening, as they can sometimes lead to unexpected behavior, especially with regards to NullPointerExceptions during unboxing of null references.
  • Consider Performance: In performance-sensitive applications, prefer using primitives to avoid the overhead of autoboxing and unboxing.
  • Null Safety: Always check for null before unboxing, to avoid potential NullPointerExceptions .
  • Readability vs Efficiency: While autoboxing and unboxing significantly improve code readability and reduce boilerplate, be mindful of their impact on performance and choose wisely based on the application's context.

37. Describe the @FunctionalInterface Annotation

The @FunctionalInterface annotation in Java is a key feature that dovetails with the language's embrace of functional programming concepts, particularly since Java 8. It serves a specific purpose in defining and enforcing certain coding patterns, making it a vital tool for developers focusing on functional-style programming.

Definition and Purpose

@FunctionalInterface is an annotation that marks an interface as a functional interface.

A functional interface in Java is an interface that contains exactly one abstract method. This restriction makes it eligible to be used in lambda expressions and method references, which are core components of Java's functional programming capabilities.

Enforcing Single Abstract Method

The primary role of @FunctionalInterface is to signal the compiler to enforce the rule of a single abstract method. If the annotated interface does not adhere to this rule, the compiler throws an error, ensuring the interface's contract is not accidentally broken by adding additional abstract methods.

Usage and Implications:

  • Lambda Expressions: Functional interfaces provide target types for lambda expressions and method references. For example, Java's standard java.util.function package contains several functional interfaces like Function<T,R> , Predicate<T> , Consumer<T> , which are widely used in stream operations and other functional programming scenarios.
  • Optional but Recommended: While the @FunctionalInterface annotation is not mandatory for an interface to be considered a functional interface by the Java compiler, using it is considered best practice. It makes the developer's intention clear and ensures the contract of the functional interface is not inadvertently broken.
  • Existing Interfaces: Many existing interfaces from earlier versions of Java naturally fit the definition of a functional interface. For example, java.lang.Runnable and java.util.concurrent.Callable are both functional interfaces as they have only one abstract method.

In this example, SimpleFunction is a functional interface with one abstract method execute() . The @FunctionalInterface annotation ensures that no additional abstract methods are inadvertently added.

  • Clarity and Documentation: Use @FunctionalInterface to communicate your intention clearly both to the compiler and to other developers. It serves as a form of documentation.
  • Design with Care: When designing a functional interface, consider its general utility and how it fits into the broader application architecture, especially if it's intended to be used across different parts of the application.
  • Avoid Overuse: While functional programming in Java can lead to more elegant and concise code, be cautious of overusing lambdas and functional interfaces, as they can make the code harder to read and debug if used excessively or inappropriately.
  • Compatibility with Older Java Versions: Be aware that @FunctionalInterface is a Java 8 feature. If you're working on applications that need to be compatible with earlier Java versions, you won’t be able to use this feature.

38. How Can You Achieve Immutability in Java?

Achieving immutability in Java is a fundamental practice, particularly useful for creating robust, thread-safe applications.

An immutable object is one whose state cannot be modified after it is created. Here's a detailed and precise explanation of how to achieve immutability in Java:

Core Principles of Immutability:

  • No Setters: Immutable objects do not expose any methods to modify their state after construction. This typically means not providing any setter methods.
  • Final Class: The class should be declared as final to prevent subclassing. Subclasses could add mutable state, undermining the immutability of the parent class.
  • Final Fields: All fields should be final , ensuring they are assigned only once, typically within the constructor, and cannot be re-assigned.
  • Private Fields: Fields should be private to prevent external modification and to encapsulate the data.
  • No Direct Access to Mutable Objects:
  • If your class has fields that are references to mutable objects (like arrays or collections), ensure these fields are not directly exposed or modified:
  • Do not provide methods that modify mutable objects.
  • Do not share references to the mutable objects. Provide copies of mutable objects when needed.

How to Create an Immutable Class:

  • Defensive Copies: When dealing with mutable objects passed to the constructor or returned by methods, create defensive copies. This practice prevents external code from modifying the internal state of the immutable object.
  • Immutable Collections: Utilize immutable collections (like those provided in Java 9 and later) to simplify the creation of classes with immutable collection fields.
  • Performance Considerations: Be mindful of the performance implications of creating defensive copies, especially in performance-critical applications.
  • Use in Multi-threaded Environments: Immutable objects are inherently thread-safe, making them ideal for use in multi-threaded environments.
  • String and Wrapper Types: Leverage the immutability of String and wrapper types (Integer, Long, and so on) as part of your immutable objects.
  • Design Strategy: Consider immutability as a design strategy, especially for objects representing values that are not expected to change, such as configuration data, constants, or natural data types.

Advantages of Immutability:

  • Simplicity and Clarity: Immutable objects are easier to understand and use. There's no need to track changes in state, reducing cognitive load.
  • Thread Safety: Immutability eliminates issues related to concurrency and synchronization, as immutable objects can be freely shared between threads without synchronization.
  • Caching and Reuse: Immutable objects can be cached and reused, as they are guaranteed not to change, reducing the overhead of object creation.
  • Hashcode Caching: Immutable objects are great candidates for caching their hashcode, which can be beneficial in collections like HashMaps and HashSets .

39. What is the Decorator Pattern?

The Decorator Pattern is a structural design pattern used in object-oriented programming, and it's particularly useful for extending the functionality of objects at runtime. It is a robust alternative to subclassing, providing a more flexible approach to add responsibilities to objects without modifying their underlying classes.

Purpose of decorator pattern

The Decorator Pattern allows you to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The pattern involves a set of decorator classes that are used to wrap concrete components. Each decorator class has a reference to a component object and adds its own behavior either before or after delegating the task to the component object.

How to implement the decorator pattern

It typically involves an abstract decorator class that implements or extends the same interface or superclass as the objects it will dynamically add functionality to. Concrete decorators then extend the abstract decorator.

Key Components:

  • Component: An interface or abstract class defining the operations that can be altered by decorators.
  • Concrete Component: A class implementing or extending the Component, defining an object to which additional responsibilities can be attached.
  • Decorator: An abstract class that extends or implements the Component interface and has a reference to a Component.
  • Concrete Decorator: A class that extends the Decorator and adds functionalities to the Component it decorates.

Decorator example in Java:

Usage and advantages:.

  • Flexibility: The Decorator Pattern provides a more flexible way to add responsibilities to objects compared to subclassing. New functionalities can be added at runtime.
  • Avoid Class Explosion: It helps in avoiding an extensive hierarchy of subclasses when you need multiple combinations of functionalities.
  • Single Responsibility Principle: Decorators allow functionalities to be divided into simple classes with single responsibilities.

Considerations:

  • Complexity: Overuse of the decorator pattern can lead to complexity, making the code harder to understand and maintain.
  • Instantiation Management: Managing the instantiation of decorated objects can be challenging, especially when dealing with multiple layers of decoration.

The Decorator Pattern is a powerful tool in a software developer's toolkit, offering a dynamic and flexible solution for extending object functionality. Understanding and applying this pattern can greatly enhance the design of software, particularly in situations where adding responsibilities to objects at runtime is necessary.

This pattern is highly valued in software development, as it showcases an ability to effectively manage and extend object functionalities without altering existing codebases, aligning with principles of maintainability and scalability.

40. Explain Java I/O Streams

Java I/O (Input/Output) streams are a fundamental part of the Java I/O API, providing a robust framework for handling input and output operations in Java. Understanding these streams is crucial for efficient data handling in Java applications.

Overview of Java I/O Streams

I/O streams in Java are used to read data from an input source and to write data to an output destination. The Java I/O API is rich and provides various classes to handle different types of data, like bytes, characters, objects, etc.

Stream Types:

Java I/O streams are broadly categorized into two types:

  • Byte Streams: Handle I/O of raw binary data.
  • Character Streams: Handle I/O of character data, automatically handling character encoding and decoding.

Byte Streams:

  • Classes: InputStream and OutputStream are abstract classes at the hierarchy's root for byte streams.
  • Usage: They are used for reading and writing binary data, such as image or video files.
  • Example Classes: FileInputStream , FileOutputStream , BufferedInputStream , BufferedOutputStream , etc.

Character Streams:

  • Classes: Reader and Writer are abstract classes for character streams.
  • Usage: Suitable for handling textual data, ensuring correct interpretation of characters according to the default character encoding.
  • Example Classes: FileReader , FileWriter , BufferedReader , BufferedWriter , etc.

Key Features of Java I/O Streams:

  • Stream Hierarchy: Java uses a hierarchy of classes to manage different types of I/O operations, allowing for flexibility and reusability of code.
  • Decorators: Java I/O uses decorators, where one stream wraps another and adds additional capabilities, like buffering, data conversion, and so on.
  • Buffering: Buffering is a common practice in I/O streams to enhance I/O efficiency, allowing for the temporary storage of data in memory before it's written to or read from the actual I/O source.
  • Exception Handling: I/O operations in Java are prone to errors like file not found, access denied, etc. Hence, most I/O operations throw IOException , which must be properly handled using try-catch blocks or thrown further.
  • Use Buffered Streams: Always use buffered streams ( BufferedInputStream , BufferedOutputStream , BufferedReader , BufferedWriter ) for efficient I/O operations, as they reduce the number of actual I/O operations by buffering chunks of data.
  • Close Streams: Ensure streams are closed after their operation is complete to free up system resources. This is typically done in a finally block or using try-with-resources introduced in Java 7.
  • Error Handling: Implement robust error handling. I/O operations are susceptible to many issues, so proper exception handling is crucial.
  • Character Encoding: Be mindful of character encoding while using character streams. Incorrect handling of encoding can lead to data corruption.

Practical Example:

In this example, BufferedReader and BufferedWriter are used for reading from and writing to a text file, demonstrating the use of character streams with buffering for efficiency.

Java I/O streams form the backbone of data handling in Java applications. Understanding the distinction between byte and character streams, along with the proper use of buffering and exception handling, is essential for writing efficient, robust, and maintainable Java code.

This knowledge is vital for Java developers and is often a subject of interest in technical interviews, showcasing one's capability to handle data proficiently in Java applications.

image-31

41. How Does the Garbage Collector Work in Java?

In Java, garbage collection (GC) is a critical process of automatically freeing memory by reclaiming space from objects that are no longer in use, ensuring efficient memory management.

Understanding how the garbage collector works in Java is essential for writing high-performance applications and is a key area of knowledge in professional Java development.

Overview of Garbage Collection in Java

The primary function of garbage collection in Java is to identify and discard objects that are no longer needed by a program. This prevents memory leaks and optimizes memory usage.

Automatic Memory Management

Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.

How the Garbage Collector Works

Object creation and heap storage:.

In Java, objects are created in a heap memory area. This heap is divided into several parts – Young Generation, Old Generation (or Tenured Generation), and Permanent Generation (replaced by Metaspace in Java 8).

  • Young Generation: Newly created objects reside in the Young Generation, which is further divided into three parts: one Eden space and two Survivor spaces (S0 and S1). Most objects die young. When the Eden space fills up, a minor GC is triggered, moving surviving objects to one of the Survivor spaces (S0 or S1) and clearing Eden.
  • Aging of Objects: As objects survive more garbage collection cycles, they age. After surviving certain cycles, they are moved to the Old Generation.
  • Old Generation: The Old Generation stores long-living objects. A more comprehensive form of GC, known as major GC, occurs here, which is generally more time-consuming.
  • Metaspace (Java 8 and above): Metaspace stores metadata of classes. Unlike the PermGen (Permanent Generation) space in earlier Java versions, Metaspace uses native memory, and its size is not fixed but can be configured.

Types of Garbage Collectors in Java:

  • Serial GC: Suitable for single-threaded environments. It freezes all application threads during garbage collection.
  • Parallel GC: Also known as Throughput Collector, it uses multiple threads for young generation garbage collection but stops all application threads during major GC.
  • Concurrent Mark Sweep (CMS) GC: Minimizes pauses by doing most of its work concurrently with application threads but requires more CPU resources.
  • G1 Garbage Collector: Designed for large heap memory areas, it divides the heap into regions and prioritizes GC on regions with the most garbage first.

Garbage Collection Processes

The process starts by marking all reachable objects. Reachable objects are those that are accessible directly or indirectly through references from root objects (like local variables, static fields, etc.).

Unreachable objects (those not marked as reachable) are considered for deletion .

To prevent fragmentation and optimize memory usage, some garbage collectors perform compaction , moving surviving objects closer together.

  • Avoid Memory Leaks: Despite automatic garbage collection, memory leaks can still occur (for example, through static references). It's crucial to be mindful of object references and their lifecycles.
  • GC Tuning: For high-performance applications, GC tuning can be essential. Understanding different garbage collector types and their configuration parameters allows for optimal tuning according to application needs.
  • Monitoring and Profiling: Regular monitoring of garbage collection and memory usage is important, especially for applications with high throughput or large heaps.

Garbage collection in Java is a sophisticated system designed to efficiently manage memory in the Java Virtual Machine (JVM). An in-depth understanding of how garbage collection works, its types, and its impact on application performance is essential for Java developers, particularly those working on large-scale, high-performance applications.

This knowledge not only helps in writing efficient and robust applications but also is a valuable skill in troubleshooting and performance tuning, aspects highly regarded in the field of software development.

42. What Are the Benefits of Using Java NIO?

Java NIO (New Input/Output), introduced in JDK 1.4, marks a substantial advancement in Java's approach to I/O operations. It was developed to address the constraints of traditional I/O methods, leading to improved scalability and efficiency.

This makes Java NIO particularly advantageous in scenarios demanding high throughput and concurrent access.

Let’s discuss the key benefits of using Java NIO in detail.

1. Channels and Buffers: Enhanced Data Handling

  • Channels : These are bi-directional conduits allowing both reading and writing operations. Unlike traditional unidirectional streams, channels simplify I/O patterns, especially for network sockets, by enabling two-way communication within a single channel.
  • Buffers : Acting as fixed-size data containers, buffers allow batch processing of data. This is more efficient compared to the byte-by-byte processing in traditional I/O, as it enables handling data in larger, more manageable blocks.

2. Non-blocking and Asynchronous I/O

Java NIO supports non-blocking and asynchronous I/O operations, a stark contrast to the blocking nature of traditional I/O where a thread remains idle until an operation completes.

This feature of NIO means a thread can initiate an I/O operation and continue performing other tasks without waiting for the I/O process to finish. This capability significantly enhances the scalability and responsiveness of applications, making them more efficient in handling multiple concurrent I/O requests.

3. Practical Applications

Java NIO is particularly effective in environments that require high-performance and low latency, such as:

  • Web and Application Servers : Managing high-volume network traffic efficiently.
  • Real-time Systems : Like trading platforms where quick data processing is critical.
  • Big Data Applications : Benefiting from efficient handling of large datasets.
  • File-based Database Systems : Where efficient file I/O operations are crucial.

4. Channels: The Foundation of NIO’s Architecture

Channels serve as the backbone of NIO, providing a more unified and simplified interface for various I/O operations. They come in different types, each catering to specific needs:

  • FileChannel : For file operations.
  • SocketChannel and ServerSocketChannel : For TCP network communications.
  • DatagramChannel : For UDP operations.
  • Pipes : For inter-thread communication. Particularly in network operations, the ability of channels to operate in a non-blocking mode allows a single thread to handle multiple connections, enhancing the application’s scalability.

5. Buffers: Central to NIO’s Data Transfer

Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:

  • Put and Get : For writing and reading data.
  • Flip : To switch modes between reading and writing.
  • Clear and Compact : Preparing the buffer for new data. Different buffer types (like ByteBuffer, CharBuffer, IntBuffer) cater to various data primitives, enhancing the flexibility and efficiency of data handling. Notably, direct buffers, which are allocated outside of the JVM heap, can provide faster I/O operations, though they come with higher allocation and deallocation costs.

6. Selectors: Streamlining Scalable I/O Operations

Selectors are a unique NIO feature enabling a single thread to monitor multiple channels for readiness, thus efficiently managing numerous I/O operations. This reduces the need for multiple threads, cutting down on resource usage and context switching, which is particularly advantageous in high-performance environments.

7. Improved Performance and Scalability

The amalgamation of channels, buffers, and selectors provides a substantial performance boost. The non-blocking nature of NIO minimizes idle thread time, and managing multiple channels with a single thread significantly improves the scalability. This is pivotal in server environments dealing with numerous simultaneous connections.

Java NIO offers a robust, scalable, and efficient framework for handling I/O operations, addressing many of the limitations of traditional I/O. Its design is particularly advantageous for high-throughput and concurrent-processing systems.

While the complexity of NIO might be higher compared to traditional I/O, the performance and scalability benefits it provides make it an indispensable tool for developers working on large-scale, I/O-intensive Java applications.

43. Explain the Observer Pattern

The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It's particularly useful in the scenario where a single object needs to notify an array of objects about a change in its state. In the context of a newsletter system, the Observer pattern can be effectively used to notify subscribers whenever a new post is available.

How to Implement the Observer Pattern for a Newsletter System

Let's break down the implementation using the Observer pattern in the context of a newsletter system:

  • Subject (Newsletter) : This is the entity being observed. It will notify all attached observers when a new post is available.
  • Observer (Subscriber) : These are the observers who wish to be notified about new posts in the newsletter.
  • Client : This will use both the Subject and Observers.

Step 1: Create the Subject Class (Newsletter)

Step 2: create the observer abstract class (subscriber), step 3: create concrete observer classes.

EmailSubscriber.java

SMSSubscriber.java

Step 4: Use the Newsletter and Concrete Subscriber Objects

Step 5: output verification.

When running NewsletterSystemDemo , the output will be something like:

This output indicates that both the email and SMS subscribers are notified whenever the newsletter has a new post.

The Observer pattern provides a clean and straightforward way to implement a subscription mechanism in a newsletter system, ensuring that all subscribers are automatically updated with the latest posts.

This pattern enhances modularity and separation of concerns, making the system easier to understand, maintain, and extend.

44. Explain the Purpose of the this Keyword.

The this keyword in Java serves a very specific and useful purpose. It refers to the current instance of the class in which it is used. This is particularly valuable in scenarios where you need to distinguish between class fields (instance variables) and parameters or variables within a method that have the same name. Let's break it down:

Reference to Instance Variables: When a class’s field is shadowed by a method or constructor parameter, this can be used for referencing the class's field. For instance, in a setter method, this helps differentiate between the instance variable and the parameter passed to the method.

Calling One Constructor from Another: In a class with overloaded constructors, this can be used to call one constructor from another, avoiding code duplication.

Returning the Current Instance: Methods can return this to return the current class instance. This is often used in method chaining.

Passing the Current Instance to Another Method: this can be passed as an argument in the method call or constructor call. This is common in event handling.

Disambiguation: It eliminates ambiguity when instance variables and parameters or local variables share the same name.

image-33

45. Explain Java's try-with-resources.

Java's try-with-resources, introduced in Java 7, is a mechanism that ensures more efficient handling of resources, like files or sockets, in Java. Its primary purpose is to simplify the cleanup of resources which must be closed after their operations are completed.

Key Characteristics:

Automatic Resource Management: In try-with-resources, resources declared within the try clause are automatically closed at the end of the statement, even if exceptions are thrown. This reduces boilerplate code significantly as compared to traditional try-catch-finally blocks.

Syntax: The resources that implement java.lang.AutoCloseable or java.io.Closeable are declared and initialized within parentheses just after the try keyword.

  • Here, the BufferedReader instance is automatically closed when the try block exits, regardless of whether it exits normally or due to an exception.
  • Exception Handling: Any exception thrown by the automatic closure of resources is suppressed if an exception is thrown in the try block. These suppressed exceptions can be retrieved using Throwable.getSuppressed() method.
  • Improved Readability and Reliability: This structure enhances code readability and reliability. It reduces the risk of resource leaks, as the closing of resources is handled automatically.
  • Use in Custom Resources: Custom classes can also utilize this mechanism by implementing the AutoCloseable interface and overriding the close method.

Practical Implications:

In real-world applications, try-with-resources ensures that resources like file streams, database connections, or network sockets are closed properly, preventing resource leaks which could lead to performance issues and other bugs. It is especially valuable in large-scale applications where resource management is critical for efficiency and reliability.

46. Explain the Difference between C++ and Java.

When distinguishing between C++ and Java, it's important to understand that both are powerful programming languages with their unique characteristics and use cases.

They share some similarities, as both are object-oriented and have similar syntax (being influenced by C), but there are key differences that set them apart.

Language Nature and Design Philosophy:

C++ is a multi-paradigm language that supports both procedural and object-oriented programming. It's often chosen for system-level programming due to its efficiency and fine-grained control over memory management.

Java , on the other hand, is primarily object-oriented and designed with a simpler approach to avoid common programming errors (like pointer errors in C++). Java's design principle "Write Once, Run Anywhere" (WORA) emphasizes portability, which is achieved through the Java Virtual Machine (JVM).

Memory Management:

In C++ , memory management is manual. Programmers have direct control over memory allocation and deallocation using operators like new and delete .

Java abstracts away the complexity of direct memory management through its Automatic Garbage Collection, which periodically frees memory that's no longer in use, reducing the likelihood of memory leaks but at the cost of less control and potential overhead.

Platform Dependency and Portability:

C++ is platform-dependent. A C++ program needs to be compiled for each specific platform it's intended to run on, which can lead to more work when targeting multiple platforms.

Java is platform-independent at the source level. Java programs are compiled into bytecode, which can run on any device equipped with a JVM, making it highly portable.

Runtime and Performance:

C++ generally offers higher performance than Java. It compiles directly to machine code, which the CPU executes, resulting in faster execution suitable for performance-critical applications.

Java may have slower performance due to the added abstraction layer of the JVM. But improvements in Just-In-Time (JIT) compilers within the JVM have significantly narrowed this performance gap.

Pointers and Memory Safety:

C++ supports both pointers and references, allowing for powerful, albeit potentially risky, memory manipulation.

Java has references but does not support pointers (at least not in the traditional sense), reducing the risk of memory access errors, thereby increasing program safety.

Exception Handling:

C++ supports exception handling but does not enforce error handling (uncaught exceptions can lead to undefined behavior).

Java has a robust exception handling mechanism, requiring checked exceptions to be caught or declared in the method signature, promoting better error management practices.

Multi-Threading:

C++ has more complex approaches to multi-threading and requires careful management to ensure thread safety.

Java provides built-in support for multi-threading with synchronized methods and blocks, making concurrent programming more manageable.

Standard Template Library (STL) vs. Java Standard Library:

C++ 's STL is a powerful library that offers containers, algorithms, iterators, and so on for efficient data manipulation.

Java 's Standard Library provides a rich set of APIs, including collections, streams, networking, and so on with a focus on ease of use.

Legacy and Use Cases:

C++ is often chosen for system/software development, game development, and applications where hardware access and performance are critical.

Java is widely used in enterprise environments, web services, and Android app development due to its portability and robust libraries.

Both C++ and Java have their strengths and are chosen based on the requirements of the project.

C++ is preferred for scenarios where performance and memory control are crucial, while Java is ideal for applications where portability and ease of use are more important.

Understanding these differences is key in selecting the right language for a particular task or project, and adapting to the strengths of each can lead to more efficient and effective programming practices.

47. What is Polymorphism? Provide an Example.

Polymorphism, a fundamental concept in object-oriented programming, allows objects to be treated as instances of their parent class or interface. It’s a Greek word meaning “many shapes” and in programming, it refers to the ability of a single function or method to work in different ways based on the object it is acting upon.

There are two primary types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.

Compile-Time Polymorphism : This is achieved through method overloading and operator overloading. It’s called compile-time polymorphism because the decision about which method to call is made by the compiler.

Method Overloading involves having multiple methods in the same scope, with the same name but different parameters.

In this example, the operate method is overloaded with different parameter types, allowing it to behave differently based on the type of arguments passed.

Runtime Polymorphism : This is mostly achieved through method overriding, which is a feature of inheritance in object-oriented programming. In runtime polymorphism, the method to be executed is determined at runtime.

Method Overriding involves defining a method in a subclass that has the same name, return type, and parameters as a method in its superclass.

In this example, the speak method in the subclass Dog overrides the speak method in its superclass Animal . When the speak method is called on an object of type Dog , the overridden method in the Dog class is executed, demonstrating runtime polymorphism.

Why Polymorphism is Important

  • Flexibility and Extensibility : Polymorphism allows for flexible and extensible code. You can create a more generalized code that works on the superclass type, and it automatically adapts to the specific subclass types.
  • Code Reusability : It enables the reuse of code through inheritance and the ability to override or overload methods.
  • Loose Coupling : By using polymorphic behavior, components can be designed loosely coupled, which means a change in one part of the system causes minimal or no effect on other parts of the system.
  • Simplifies Code Maintenance : With polymorphism, developers can write more maintainable and manageable code, as changes to a superclass are inherited by all subclasses, reducing the need for changes across multiple classes.

Polymorphism is a cornerstone in the world of object-oriented programming, enabling more dynamic and flexible code. It allows objects to interact in a more abstract manner, focusing on the shared behavior rather than the specific types.

Understanding and effectively using polymorphism can lead to more robust and maintainable code, a crucial aspect for any software developer looking to excel in their field.

48. How Can You Avoid Memory Leaks in Java?

Avoiding memory leaks in Java, despite its automated garbage collection mechanism, requires a deep understanding of how memory allocation and release work in Java, alongside meticulous coding practices and effective use of analysis tools.

Let’s delve into some advanced and specific strategies for preventing memory leaks in Java applications:

Understand Object Lifecycle and Scope:

  • Scope Management : Ensure objects are scoped as narrowly as possible. For instance, use local variables within methods rather than class-level variables if the data does not need to persist beyond the method’s execution context.
  • Reference Management : Be cautious with static references. Static fields can keep objects alive for the lifetime of the class, potentially leading to memory leaks.

Efficient Use of Collections:

  • WeakHashMap : For cache implementations, consider using WeakHashMap . It uses weak references for keys, which allows keys (and their associated values) to be garbage-collected when no longer in use.
  • Data Structure Choice : Be mindful of the choice of data structure. For example, use ArrayList over LinkedList for large lists of data where frequent access is required, as LinkedList can consume more memory due to the storage of additional node references.

Leveraging WeakReferences and SoftReferences :

  • SoftReferences for Caches : Use SoftReference for memory-sensitive caches. The garbage collector will only remove soft-referenced objects if it needs memory, making them more persistent than weak references.
  • WeakReferences for Listeners : Utilize WeakReference for listener patterns where listeners might not be explicitly removed.

Managing Resources and I/O:

  • AutoCloseable and Try-with-Resources : For resources like streams, files, and connections, use try-with-resources for automatic closure. Ensure that objects implementing AutoCloseable are closed properly to release resources.

Inner Classes Handling:

  • Static Inner Classes : Prefer static inner classes over non-static to avoid the implicit reference to the outer class instance, which can prevent the outer instance from being garbage-collected.

Profiling and Leak Detection:

  • Heap Dump Analysis : Regularly analyze heap dumps in tools like Eclipse Memory Analyzer (MAT) to detect large objects and potential memory leaks.
  • Java Flight Recorder : Use Java Flight Recorder for runtime analysis and monitoring, which can help identify memory leaks.

ThreadLocal Variables Management:

  • Explicit Removal : Always remove ThreadLocal variables after use, particularly in thread-pooled environments like servlet containers or application servers.

ClassLoader Leaks:

  • ClassLoader Lifecycle : In environments with dynamic class loading/unloading (for example, web servers), ensure that class loaders are garbage collected when not needed. This involves ensuring that classes loaded by these class loaders are no longer referenced.

Garbage Collection Tuning:

  • GC Analysis : Analyze GC logs to understand the garbage collection behavior and identify potential memory leaks.
  • GC Algorithm Choice : Choose an appropriate garbage collection algorithm based on application needs, which can be tuned with JVM options for optimal performance.

String Interning:

  • Selective Interning : Be cautious with the String.intern() method. Unnecessary interning of strings can lead to a bloated String pool.

Static Analysis Tools:

Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.

Developer Training and Code Reviews:

Regularly train developers on best practices in memory management and conduct thorough code reviews with a focus on potential memory leak patterns.

Memory leak prevention in Java is a sophisticated practice that involves a thorough understanding of Java memory management, careful coding, diligent use of analysis tools, and regular monitoring.

By adopting these advanced practices, developers can significantly mitigate the risk of memory leaks, leading to more robust, efficient, and scalable Java applications.

49. Explain the Purpose of Java's Synchronized Block

The purpose of Java's synchronized block is to ensure thread safety in concurrent programming by controlling access to a shared resource among multiple threads.

In a multithreaded environment, where multiple threads operate on the same object, there's a risk of data inconsistency if the threads simultaneously modify the object. A synchronized block in Java is used to lock an object for exclusive access by a single thread.

Thread Safety and Data Consistency:

When different threads access and modify shared data, it can lead to unpredictable data states and inconsistencies. The synchronized block ensures that only one thread can execute a particular block of code at a time, thus maintaining data integrity.

Lock Mechanism:

In Java, each object has an intrinsic lock or monitor lock. When a thread enters a synchronized block, it acquires the lock on the specified object. Other threads attempting to enter the synchronized block on the same object are blocked until the thread inside the synchronized block exits, thereby releasing the lock.

Syntax and Usage:

The synchronized block is defined within a method, and you must specify the object that provides the lock:

The lockObject is a reference to the object whose lock the synchronized block acquires. It can be this to lock the current object, a class object for class-level locks, or any other object.

Advantages Over Synchronized Methods:

Compared to synchronized methods, synchronized blocks provide finer control over the scope and duration of the lock.

While a synchronized method locks the entire method, a synchronized block can lock only the part of the method that needs synchronization, potentially improving performance.

Avoiding Deadlocks:

Take care to avoid deadlocks, a situation where two or more threads are blocked forever, each waiting for the other's lock. This usually occurs when multiple synchronized blocks are locking objects in an inconsistent order.

Synchronized blocks also solve memory visibility problems. Changes made by one thread in a synchronized block are visible to other threads entering subsequent synchronized blocks on the same object.

Best Practices

  • Minimize Lock Contention : Keep the synchronized sections as short as possible to minimize lock contention and avoid performance bottlenecks.
  • Consistent Locking Order : Always acquire locks in a consistent order to prevent deadlocks.
  • Avoid Locking on Public Objects : Locking on public objects can lead to accidental and uncontrolled access to the lock, increasing the deadlock risk. Prefer private objects as lock targets.
  • Complement with Other Concurrency Tools : In some cases, using higher-level concurrency tools like ReentrantLock , Semaphore , or concurrent collections from java.util.concurrent package might be more appropriate.

Java's synchronized block is a critical tool for achieving thread safety in concurrent applications. Its proper use ensures data integrity and consistency by controlling access to shared resources. But, it requires careful consideration to avoid common pitfalls like deadlocks and performance issues due to excessive lock contention.

Understanding and applying these concepts is essential for developers working in a multithreaded environment to create robust and efficient Java applications.

50. Explain the Concept of Modules in Java

Modules in Java, introduced in Java 9 with the Java Platform Module System (JPMS), represent a fundamental shift in organizing Java applications and their dependencies.

Understanding modules is essential for modern Java development, as they offer improved encapsulation, reliable configuration, and scalable system architectures.

What are Java modules?

A module in Java is a self-contained unit of code and data, with well-defined interfaces for communicating with other modules. Each module explicitly declares its dependencies on other modules.

Modules enable better encapsulation by allowing a module to expose only those parts of its API which should be accessible to other modules, while keeping the rest of its codebase hidden. This reduces the risk of unintended usage of internal APIs.

Key Components of modules:

module-info.java : Each module must have a module-info.java file at its root, which declares the module's name, its required dependencies, and the packages it exports.

  • Here, com.example.myapp is the module name, java.sql is a required module, and com.example.myapp.api is the exported package.
  • Exports and Requires: The exports keyword specifies which packages are accessible to other modules, while requires lists the modules on which the current module depends.
  • Improved Application Structure: Modules encourage a cleaner, more organized code structure, helping in maintaining large codebases and improving code quality.
  • Reduced Memory Footprint: By only loading the required modules, applications can reduce their memory footprint and start-up time, enhancing performance.
  • Enhanced Security and Maintenance: Modules reduce the surface area for potential security vulnerabilities. They also simplify dependency management, making it easier to update and maintain libraries without affecting the entire system.

Consider a scenario where you are developing a large-scale application with various functionalities like user management, data processing, and reporting. By organizing these functionalities into separate modules (like usermodule , dataprocessmodule , reportmodule ), you can maintain them independently, avoiding the complexities of a monolithic application structure.

Modules in Java are a powerful feature for building scalable, maintainable, and efficient applications. They offer clear boundaries and contracts between different parts of a system, facilitating better design and architecture.

For developers and teams aiming to build robust Java applications, understanding and leveraging modules is not just a technical skill but a strategic approach to software development.

This modular architecture aligns with modern development practices, enabling Java applications to be more scalable and easier to manage in the long term.

image-34

As we wrap up this roundup of Java interview questions, I want to take a moment to thank the freeCodeCamp team. This platform is a fantastic resource for people learning to code, and it's great to have such a supportive community in the tech world.

I also want to thank the editorial team for their help in making this guide possible. Working together has been a great experience, and it's been rewarding to combine our efforts to help others learn Java.

It's important to reflect on the journey we've undertaken together. Java's robustness in Object-Oriented Programming (OOP) is a critical asset for developers at all levels, especially those aspiring to join top-tier tech firms. This handbook has aimed to provide a clear pathway to mastering Java interviews, focusing on the insights and techniques that matter most in the competitive landscape of big tech.

From the fundamentals to the more complex aspects of Java, I've sought to bridge the gap between basic Java knowledge and the sophisticated expertise that industry leaders like Google value. This resource is crafted not just for those new to Java, but also for those revisiting key concepts, offering a comprehensive understanding of the language in a practical context.

As you continue to explore the depths of Java, remember that mastering this language is not just about enhancing coding skills, but also about expanding your professional horizons. Java's significant role in IoT and its presence in billions of devices worldwide make it a language that can truly shape your career.

In closing, I hope this handbook has provided you with valuable insights and a strong foundation for your future endeavors in Java programming and beyond. Whether you're preparing for a big tech interview or simply looking to refine your software development skills, this guide is a stepping stone towards achieving those goals.

If you're keen on furthering your Java knowledge, here's a guide to help you conquer Java and launch your coding career . It's perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  • Java Data Structures Mastery - Ace the Coding Interview : A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  • Foundations of Java Data Structures - Your Coding Catalyst : Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech's website for these resources and more information on the bootcamp .

Connect with Me:

  • Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI
  • Visit my Personal Website
  • Subscribe to my The Data Science and AI Newsletter

About the Author

I'm Vahe Aslanyan, deeply engaged in the intersecting worlds of computer science, data science, and AI. I invite you to explore my portfolio at vaheaslanyan.com, where I showcase my journey in these fields. My work focuses on blending full-stack development with AI product optimization, all fueled by a passion for innovative problem-solving.

6539302e3cd34bb5cbabe5f9_Vahe%20Aslanyan%20(256%20x%20256%20px)

I've had the privilege of contributing to the launch of a well-regarded data science bootcamp and collaborating with some of the best minds in the industry. My goal has always been to raise the bar in tech education, making it accessible and standard for everyone.

As we conclude our journey here, I want to thank you for your time and engagement. Sharing my professional and academic experiences in this book has been a rewarding experience. I appreciate your involvement and look forward to seeing how it helps you advance in the tech world.

I'm Vahe Aslanyan, dedicated to making AI and data science education inclusive and accessible. I guide developers towards clear tech understanding in software engineering.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

DEV Community

DEV Community

Posted on Aug 6, 2019 • Updated on Apr 4

Java Interview Questions for Experienced 50+ Core Java Interview Questions with Answers for Programmers

Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.

Hello, Java programmers! Over the past few years, I have been sharing a lot of Java Interview questions , answers, and discussion individually. Many of my readers have requested that I bring them together so that they can have them in the same spot for their interview preparation.

This post is the result of that.

This article contains more than 50 Java Interview questions and answers covering all important topics like Core Java fundamentals, Java Collection Framework , Java Multithreading and Concurrency , Java IO , JDBC , JVM Internals , Coding Problems , Object-Oriented programming , etc.

These questions are picked up from various Java interviews which I have given and few are shared by my friends, readers, and other people from their own experience. They are, by no means, very difficult. You might have seen them already in your phone or face-to-face round of interviews.

The questions are also very useful to review important Java topics like core Java concepts, multithreading, lambdas, Streams, and collections.

I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass course on Udemy which you can join to brush up and fill gaps in your Java skills.

I have also written books on Java Interview preparation like "Grokking the Java Interview" , and Grokking the Spring Boot Interviews , where I have shared a lot of questions for Java developers.

If you are preparing for Java interviews this year you can also get my Java + Spring Interview + SQL Bundle on Gumroad , use code friends20 to get a 20% discount also

Java and Spring Interview books

So what are we waiting for? Here is the list of some of the most frequently asked Java questions in interviews for both beginner and experienced Java developers.

Top 50 Java Interview Questions for 2 to 3 years Experienced Programmers

So, without wasting any more of your time, here is my list of some of the frequently asked Core Java Interview Question s for beginner programmers. This list focuses on beginners and less experienced devs, like someone with 2 to 3 years of experience in Java.

1) How does Java achieve platform independence? ( answer ) hint: bytecode and Java Virtual Machine answer - Java achieves platform independence by producing bytecode and then running on Java virtual Machine which convert these bytecode to planform dependent machine code. Since JVM is different for different platform, I mean for Windows you have separate JRE (Which includes JVM) and for Linux you will have separate JRE. Since Java code are not compiled to native machine code instead they compiled to bytecode which makes them platform independent.

2) What is **ClassLoader** in Java? ( answer ) hint: part of JVM that loads bytecodes for classes. You can write your own. answer: In Java, code is encapsulated inside class because Java is an object oriented programming. Your program is written inside class and in order to execute them JVM loads these classes which contains your code. The JVM component which is responsible for loading classes are called classloaders. They are three main classloaders exists in, the bootstrap classloader, the extension classloader and the application classloader.

Here is a nice diagram which shows the function of each of these classloader Java:

classloaders in Java

3) Write a Java program to check if a number is Even or Odd? ( answer ) hint: you can use the bitwise operator, like bitwise AND, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.

4) Difference between **ArrayList** and **HashSet** in Java? ( answer ) hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc. See Java Fundamentals: Collections by Richard Warburton to learn more about ArrayList, HashSet and other important Collections in Java.

java essay questions and answers

5) What is double checked locking in Singleton? ( answer ) hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6) How do you create thread-safe Singleton in Java? ( answer ) hint: many ways, like using Enum or by using double-checked locking pattern or using a nested static class.

7) Difference between Serializable and Externalizable in Java? ( answer ) hint: Externalizable gives you more control over the Serialization process.

8) When to use a transient variable in Java? ( answer ) hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don't want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9) Difference between the transient and volatile variable in Java? ( answer ) hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) When to use the volatile variable in Java? ( answer ) hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

11) Can we override the private method in Java? ( answer ) hint: No, because it's not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between **Hashtable** and **HashMap** in Java? ( answer **) **hint: several but most important is Hashtable , which is synchronized, while HashMap is not. It's also legacy and slow as compared to HashMap .

13) Difference between **List** and **Set** in Java? ( answer ) hint: List is ordered and allows duplicate. Set is unordered and doesn't allow duplicate elements.

14) Difference between **ArrayList** and **Vector** in Java ( answer ) hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It's also legacy class like Hashtable .

15) Difference between **Hashtable** and **ConcurrentHashMap** in Java? ( answer ) hint: more scalable. See Java Fundamentals: Collections by Richard Warburton to learn more.

16) How does **ConcurrentHashMap** achieve scalability? ( answer ) hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an **Object** to be used as **Key** in **HashMap** ? ( answer ) hint: equals and hashcode

18) Difference between wait and sleep in Java? ( answer ) \ hint: The wait() method releases the lock or monitor, while sleep doesn't.

19) Difference between **notify** and **notifyAll** in Java? ( answer ) hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify , or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with **equals()** in Java? ( answer ) hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList .

21) What is the load factor of **HashMap** means? ( answer ) hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it's 75 percent full.

22) Difference between **ArrayList** and **LinkedList** in Java? ( answer ) hint: same as an array and linked list, one allows random search while other doesn't. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections , Richard Warburton's course on Pluralsight, to learn more about essential Collection data structure in Java.

23) Difference between **CountDownLatch** and **CyclicBarrier** in Java? ( answer ) hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch after the count reaches to zero.

24) When do you use **Runnable** vs **Thread** in Java? ( answer ) hint: always

25) What is the meaning of Enum being type-safe in Java? ( answer ) hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? ( answer ) hint: By using the valueOf() method in Java.

27) Difference between **PATH** and **Classpath** in Java? ( answer ) hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATH , Classpath , and other Java environment variable.

java essay questions and answers

28) Difference between method overloading and overriding in Java? ( answer ) hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? ( answer ) \ hint: just make its constructor private

30) How do you restrict your class from being used by your client? ( answer ) \ hint: make the constructor private or throw an exception from the constructor

31) Difference between **StringBuilder** and **StringBuffer** in Java? ( answer ) hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? ( answer ) hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Object Oriented Java Programming: Data Structures and Beyond Specialization on Coursera, to learn more about OOP features. One of the most in-depth course for beginners.

java essay questions and answers

By the way, if you find Coursera courses useful, which they are because they are created by reputed companies and universities around the world, I suggest you join the Coursera Plus , a subscription plan from Coursera which gives you unlimited access to their most popular courses, specialization, professional certificate, and guided projects. It cost around $399/year but its complete worth of your money as you get unlimited certificates.

33) Can we override static method in Java? ( answer ) \ hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? ( answer ) \ hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? ( answer ) hint: from Java 8 , the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? ( answer ) \ hint: DOM loads whole XML File in memory while SAX doesn't. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? ( answer ) \ hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

java essay questions and answers

38) Difference between fail-safe and fail-fast iterators in Java? ( answer ) hint: fail-safe doesn't throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? ( answer ) hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn't allow that.

40) What is **IdentityHashMap** in Java? ( answer ) hint: A Map , which uses the == equality operator to check equality instead of the equals() method.

41) What is the **String** pool in Java? ( answer ) hint: A pool of String literals. Remember it's moved to heap from perm gen space in JDK 7.

42) Can a **Serializable** class contains a non-serializable field in Java? ( answer **) **hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? ( answer ) hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between **Comparator** and **Comparable** in Java? ( answer ) \ hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String . See The Complete Java MasterClass to learn more about sorting in Java.

java essay questions and answers

45) Difference between **java.util.Date** and **java.sql.Date** in Java? ( answer ) hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in **Object** class in Java? ( answer ) hint: because they require lock which is only available to an object.

47) Why Java doesn't support multiple inheritances? ( answer ) hint: It doesn't support because of a bad experience with C++, but with Java 8, it does in some sense --- only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? ( answer ) hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it's up to you; compile will not bother you.

49) Difference between Error and Exception in Java? ( answer ) hint: I am tired of typing please check the answer

50) Difference between Race condition and Deadlock in Java? ( answer ) hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding. See Multithreading and Parallel Computing in Java to learn more about deadlock, Race Conditions, and other multithreading issues.

Additional Resources

  • Java Interview Guide: 200+ Interview Questions and Answers
  • Spring Framework Interview Guide --- 200+ Questions & Answers
  • Preparing For a Job Interview By John Sonmez
  • Java Programming Interview Exposed by Markham
  • Cracking the Coding Interview --- 189 Questions and Answers
  • Data Structure and Algorithms Analysis for Job Interviews
  • 130+ Java Interview Questions of Last 5 Years
  • Grokking the Java Interview - FREE Sample PDF
  • Grokking the Spring Boot Interview - FREE Sample PDF

Closing Notes

Thanks, You made it to the end of the article ... Good luck with your programming interview! It's certainly not going to be easy, but these questions will certainly help you. It will also encourage you to learn more.

If you like this article, then please share with your friends and colleagues, and don't forget to follow javinpaul on Twitter!

P.S. --- If you need some FREE resources to learn Java, you can check out this list of my favorite free Java courses to start your preparation. P. S. S. --- I have not provided the answer to the interview questions shared in the image " How many String objects are created in the code?" can you guess and explain?

And, If you are preparing for Java interviews this year you can also get my Java + Spring Interview + SQL Bundle on Gumroad , use code friends20 to get a 20% discount also

Top comments (11)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

helenanders26 profile image

  • Location Wellington, New Zealand
  • Pronouns she/her
  • Joined Jun 19, 2017

Hi @javinpaul ,

Please read through the updated #beginner tag guidelines.

Promotional Guidelines

Articles should NOT primarily promote an external work, such as a Udemy course, website, or book (yours or someone else's). This is what Listings is for. It IS acceptable to include a brief (1-2 sentence) plug for another resource at the bottom of your article, so long as the article contains complete and substantial content in its own right. If you want to write up a list of resources (paid or free) for beginners, this IS acceptable on the following conditions: Resources should be by at least three different distinct authors/creators. (Don't just make a list all of one person's work.) Clearly indicate which resources are FREE (no cost or data whatsoever), which require personally identifiable information PII, and which cost money. Do not use personal affiliate links to monetize. Use the exact same URLs that anyone else could provide. It should be clear at the first paragraph that the article contains promotional links.
  • Joined Sep 16, 2018

Hello Helen,

Thx for the reminder, I have added the disclosure as "Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article."

Does it suffice? Or, do I need to remove the beginner tag altogether?

Regards Javin

codemouse92 profile image

  • Email [email protected]
  • Location Time Vortex
  • Pronouns he/him
  • Work Director of Community at OWASP Foundation
  • Joined Jan 31, 2017

Affiliate links are allowed on DEV as long as they're disclosed, but we strongly discourage them on #beginners . Is there any way you can change them to "the exact same URLs that anyone else could provide"?

Hi Jason, I have taken note of this for future posting. thx

Don't forget, you can also edit your post. (Don't leave things as they are please.)

Hello Yuma's Papa, Thanks for the comment. Well, I have blogged about it before on my blog, you may like to check Weak reference vs soft reference vs phantom reference

lprakashv profile image

  • Location Bangalore, India
  • Work Software Engineer 3 at Walmart Labs IDC
  • Joined Aug 7, 2019

30 -> It should be final class instead of private constructor.

salyadav profile image

  • Email [email protected]
  • Location Atlanta
  • Education MS in CS, Georgia Tech
  • Work Ex-SWE @ Oracle | Vimeo
  • Joined Apr 3, 2020

Love this compilation! The 49th answer was lit! Hahaha. Nice one, and thanks for writing this article. Bliss.

kadiyakashyap profile image

  • Joined Dec 23, 2020

How many String objects are created in the code?

Two String objects are created there. 1) String pool and 2) Heap memory.

conaxinfotech profile image

  • Location Allahabad
  • Work Digital Marketing Expert
  • Joined Feb 17, 2023

Thanks for sharing these important quetions. also practice core java interview questions for freshers.

belverus profile image

  • Location Istanbul
  • Education Software Engineering, MS
  • Joined Feb 14, 2019

Gold mine here! Thank you for the share.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

mdarifulhaque profile image

2000. Reverse Prefix of Word

MD ARIFUL HAQUE - May 1

weseek-inc profile image

Building a Docker Development Environment (Part 1)

Weseek-Inc - Apr 30

Building a Docker Development Environment (Part 2)

alisdairbr profile image

A Software Engineer's Tips and Tricks #2: Template Databases in PostgreSQL

alisdairbr - Apr 30

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Download Interview guide PDF

  • Java Interview Questions

Download PDF

Do you have what it takes to ace a Java Interview? We are here to help you in consolidating your knowledge and concepts in Java . Before we begin, let's understand what Java is all about.

What is Java? 

Java is a high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications. 

The following article will cover all the popular Core Java interview questions, String Handling interview questions, Java 8 interview questions, Java multithreading interview questions, Java OOPs interview questions, Java exception handling interview questions, collections interview questions, and some frequently asked Java coding interview questions.

Go through all the important questions to enhance your chances of performing well in the Java Interviews. The questions will revolve around the basic, core & advanced fundamentals of Java.

So, let’s dive deep into the plethora of useful Java Technical Interview Questions and Answers categorised into the following sections:

  • Java interview questions for Freshers

Java Intermediate Interview Questions

Java interview questions for experienced, java programming interview questions.

Join our community and share your recent Java interview experiences.

Java Interview Questions for Freshers

1. why is java a platform independent language.

Java language was developed so that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

  • The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

2. Why is Java not a pure object oriented language?

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language .

3. Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.

Java Utilizes this memory as - 

  • When we write a java program then all the variables, methods, etc are stored in the stack memory.
  • And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Example- Consider the below java program :

For this java program. The stack and heap memory occupied by java is -

java essay questions and answers

Main and PrintArray is the method that will be available in the stack area and as well as the variables declared that will also be in the stack area. 

And the Object (Integer Array of size 10) we have created, will be available in the Heap area because that space will be allocated to the program during runtime. 

4. Can java be said to be the complete object-oriented programming language?

It is not wrong if we claim that Java is the complete object-oriented programming language because everything in Java is under the classes and we can access them by creating the objects.

But we can even say that Java is not a completely object-oriented programming language because it has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is Java a completely object-oriented programming language? We can say that - Java is not a pure object-oriented programming language, because it has direct access to primitive data types. And these primitive data types don't directly belong to the Integer classes.

5. How is Java different from C++?

  • C++ is only a  compiled language, whereas Java is compiled as well as an interpreted language.
  • Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. 
  • C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers. 
  • C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

Learn via our Video Courses

6. pointers are used in c/ c++. why does java not make use of pointers.

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

7. What do you understand by an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

java essay questions and answers

8. What are the default values assigned to variables and instances in java?

  • There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of ( Variable might not be initialized ). 
  • But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. 
  • If it is a reference, then it will be assigned to null. 
  • If it is numeric, then it will assign to 0.
  • If it is a boolean, then it will be assigned to false. Etc.

9. What do you mean by data encapsulation?

  • Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit.
  • It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
  • It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

java essay questions and answers

10. 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.
  • First, the Java source code (.java) conversion to byte code (.class) 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.

java essay questions and answers

11. Can you tell the difference between equals() method and equality operator (==) in Java?

We are already aware of the (==) equals operator. That we have used this to compare the equality of the values. But when we talk about the terms of object-oriented programming, we deal with the values in the form of objects. And this object may contain multiple types of data. So using the (==) operator does not work in this case. So we need to go with the . equals() method.

Both [(==) and .equals()] primary functionalities are to compare the values, but the secondary functionality is different. 

So in order to understand this better, let’s consider this with the example -

This code will print true. We know that both strings are equals so it will print true. But here (==) Operators don’t compare each character in this case. It compares the memory location. And because the string uses the constant pool for storing the values in the memory, both str1 and str2 are stored at the same memory location. See the detailed Explanation in Question no 73: Link .

java essay questions and answers

Now, if we modify the program a little bit with -

java essay questions and answers

Then in this case, it will print false. Because here no longer the constant pool concepts are used. Here, new memory is allocated. So here the memory address is different, therefore ( == ) Operator returns false. But the twist is that the values are the same in both strings. So how to compare the values? Here the .equals() method is used.

.equals() method compares the values and returns the result accordingly.  If we modify the above code with - 

Then it returns true.

  • In the cases where the equals method is not overridden in a class, then the class uses the default implementation of the equals method that is closest to the parent class.
  • Object class is considered as the parent class of all the java classes. The implementation of the equals method in the Object class uses the == operator to compare two objects. This default implementation can be overridden as per the business logic.

12. How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
  • Using while loop:
  • Using do-while loop:

13. Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

java essay questions and answers

Three constructors are defined here but they differ on the basis of parameter type and their numbers.

14. Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class. 

Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

15. Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - 

Consider the below code snippets: 

16. Comment on method overloading and overriding by citing relevant examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability.

The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it.

java essay questions and answers

Both the functions have the same name but differ in the number of arguments. The first method calculates the area of the rectangle, whereas the second method calculates the area of a cuboid.

Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding. Let’s give a look at this example:

java essay questions and answers

Both class methods have the name walk and the same parameters, distance, and time. If the derived class method is called, then the base class method walk gets overridden by that of the derived class.

17. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same:

Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

18. Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.

  • When a variable is declared as final in Java, the value can’t be modified once it has been assigned.
  • If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
  • A method declared as final cannot be overridden by its children's classes.
  • A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here
  • No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

19. Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example:

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example:

20. Is it possible that the ‘finally’ block will not be executed? If yes then list the case.

 Yes. It is possible that the ‘finally’ block will not be executed. The cases are-

  • Suppose we use System.exit() in the above statement.
  • If there are fatal errors like Stack overflow, Memory access error, etc.

21. Identify the output of the java program and state the reason.

The above code will generate a compile-time error at Line 7 saying - [error: variable i might already have been initialized] . It is because variable ‘i’ is the final variable. And final variables are allowed to be initialized only once, and that was already done on line no 5.

22. When can you use super keyword?

  • The super keyword is used to access hidden fields and overridden methods or attributes of the parent class.
  • Accessing data members of parent class when the member names of the class and its child subclasses are same.
  • To call the default and parameterized constructor of the parent class inside the child class.
  • Accessing the parent class methods when the child classes have overridden them.
  • The following example demonstrates all 3 cases when a super keyword is used.

23. Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

24. Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.

Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static. 

25. Can the static methods be overridden?

  • No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
  • Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

26. Difference between static methods, static variables, and static classes in java.

  • For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method.  And Similarly static variables we have used like (length) for the array to get the length. So that is the static method.
  • Static classes - A class in the java program cannot be static except if it is the inner class. If it is an inner static class, then it exactly works like other static members of the class.

27. What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

28. What is a ClassLoader?

  • Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. 
  • Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

29. What part of memory - Stack or Heap - is cleaned in garbage collection process?

30. what are shallow copy and deep copy in java.

To copy the object's data, we have several methods like deep copy and shallow copy. 

Object for this Rectangle class - Rectangle obj1 = new Rectangle();

  • Shallow copy - The shallow copy only creates a new reference and points to the same object. Example - For Shallow copy, we can do this by -

Now by doing this what will happen is the new reference is created with the name obj2 and that will point to the same memory location.

  • Deep Copy - In a deep copy, we create a new object and copy the old object value to the new object. Example -

Both these objects will point to the memory location as stated below -

java essay questions and answers

Now, if we change the values in shallow copy then they affect the other reference as well. Let's see with the help of an example - 

We can see that in the above code, if we change the values of object1, then the object2 values also get changed. It is because of the reference.

Now, if we change the code to deep copy, then there will be no effect on object2 if it is of type deep copy. Consider some snippets to be added in the above code.

The above snippet will not affect the object2 values. It has its separate values. The output will be

Now we see that we need to write the number of codes for this deep copy. So to reduce this, In java, there is a method called clone().  

The clone() will do this deep copy internally and return a new object. And to do this we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone();

1. Apart from the security aspect, what are the reasons behind making strings immutable in Java?

A String is made immutable due to the following reasons:

  • String Pool: Designers of Java were aware of the fact that String data type is going to be majorly used by the programmers and developers. Thus, they wanted optimization from the beginning. They came up with the notion of using the String pool (a storage area in Java heap) to store the String literals. They intended to decrease the temporary String object with the help of sharing. An immutable class is needed to facilitate sharing. The sharing of the mutable structures between two unknown parties is not possible. Thus, immutable Java String helps in executing the concept of String Pool.

java essay questions and answers

  • Multithreading : The safety of threads regarding the String objects is an important aspect in Java. No external synchronization is required if the String objects are immutable. Thus, a cleaner code can be written for sharing the String objects across different threads. The complex process of concurrency is facilitated by this method.
  • Collections : In the case of Hashtables and HashMaps, keys are String objects. If the String objects are not immutable, then it can get modified during the period when it resides in the HashMaps. Consequently, the retrieval of the desired data is not possible. Such changing states pose a lot of risks. Therefore, it is quite safe to make the string immutable.

2. What is a singleton class in Java? And How to implement a singleton class?

Singleton classes are those classes, whose objects are created only once. And with only that object the class members can be accessed. 

Understand this with the help of an example-:

Consider the water jug in the office and if every employee wants that water then they will not create a new water jug for drinking water. They will use the existing one with their own reference as a glass. So programmatically it should be implemented as -

In the above class, the Constructor is private so we cannot create the object of the class. But we can get the object by calling the method getInstance() . And the getInstance is static so it can be called without creating the object. And it returns the object. Now with that object, we can call getWater() to get the water.

We can get the single object using this getInstance(). And it is static, so it is a thread-safe singleton class. Although there are many ways to create a thread-safe singleton class. So thread-safe classes can also be:

  • When singletons are written with double-checked locking, they can be thread-safe.
  • We can use static singletons that are initialized during class loading. Like we did in the above example.
  • But the most straightforward way to create a thread-safe singleton is to use Java enums.

3. Which of the below generates a compile-time error? State the reason.

  • int[] n1 = new int[0];
  • boolean[] n2 = new boolean[-200];
  • double[] n3 = new double[2241423798];
  • char[] ch = new char[20];

We get a compile-time error in line 3. The error we will get in Line 3 is - integer number too large . It is because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number ( 2241423798 ) is beyond the capacity of the integer. The maximum array size we can declare is - ( 2147483647 ).

Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The program will compile fine. But we get the runtime exception in line 2. The exception is - NegativeArraySizeException . 

Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.

4. How would you differentiate between a String, StringBuffer, and a StringBuilder?

  • Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area.
  • Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable.
  • Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.)
  • Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads. Syntax:

5. Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types : Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

Interface example:

6. Is this program giving a compile-time error? If Yes then state the reason and number of errors it will give. If not then state the reason.

The above program will give a compile-time error. The compiler will throw 2 errors in this.

  • [Illegal Combination of modifiers: abstract and final] at line 1.
  • [Cannot inherit from final ‘InterviewBit’] at line 4.

It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.

7. What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values. 

8. In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

9. What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

10. Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

11. What do we get in the JDK file?

  • JDK - For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
  • JRE -  To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes +  JVM. What are JAVA Classes?  It contains some predefined methods that help Java programs to use that feature, build and execute. For example - there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
  • JVM - (Java Virtual Machine) JVM  is a part of JRE that executes the Java program at the end.  Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.

java essay questions and answers

12. What are the differences between JVM, JRE and JDK in Java?

13. what are the differences between hashmap and hashtable in java, 14. what is the importance of reflection in java.

  • The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
  • Consider an example where we have an object of unknown type and we have a method ‘fooBar()’ which we need to call on the object. The static typing system of Java doesn't allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called “fooBar()” and only then call the method if needed.
  • Speed — Method invocations due to reflection are about three times slower than the direct method calls.
  • Type safety — When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
  • Traceability — Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke() and proxy() method logs to identify the root cause.
  • Hence, it is advisable to follow solutions that don't involve reflection and use this method as a last resort.

15. What are the different ways of threads usage?

  • Extending the Thread class
  • Implementing the Runnable interface
  • 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.

16. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

There are a total of 3 different types of priority available in Java. 

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5.

In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM. 

17. What is the difference between the program and the process?

  • A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. 
  • A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

18. What is the difference between the ‘throw’ and ‘throws’ keyword in java?

  • The ‘ throw ’ keyword is used to manually throw the exception to the calling method.
  • And the ‘ throws ’ keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

Here in the above snippet, the method testExceptionDivide throws an exception. So if the main method is calling it then it must have handled the exception. Otherwise, the main method can also throw the exception to JVM.

And the method testExceptionDivide 'throws’ the exception based on the condition.

19. What are the differences between constructor and method of a class in Java?

20. identify the output of the below java program and justify your answer..

The above code will throw the compilation error. It is because the super() is used to call the parent class constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the same block.

21. Java works as “pass by value” or “pass by reference” phenomenon?

Java always works as a “pass by value”. There is nothing called a “pass by reference” in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location. 2 cases might happen inside the method:

  • Case 1: When the object is pointed to another location: In this case, the changes made to that object do not get reflected the original object before it was passed to the method as the reference points to another location.

For example:

  • Case 2: When object references are not modified: In this case, since we have the copy of reference the main object pointing to the same memory location, any changes in the content of the object get reflected in the original object.

22. What is the ‘IS-A ‘ relationship in OOPs java?

‘IS-A’ relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an ‘IS-A’ Relationship.

Example - Consider a Television (Typical CRT TV). Now another Smart TV  that is inherited from television class. So we can say that the Smart iv is also a TV. Because CRT TV things can also be done in the Smart TV.

java essay questions and answers

So here ‘IS-A’ Relationship formed. [ SmartTV ‘IS-A’ TV ] .

23. Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

24. How to not allow serialization of attributes of a class in Java?

  • In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
  • In the above example, all the fields except someInfo can be serialized.

25. What happens if the static modifier is not included in the main method signature in Java?

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError” error at the runtime.

26. Consider the below program, identify the output, and also state the reason for that.

The output of the above program will be Hello. Main Method . This is because JVM will always call the main method based on the definition it already has. Doesn't matter how many main methods we overload it will only execute one main method based on its declaration in JVM.

27. Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

28. What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

29. What do you understand by Object Cloning and how do you achieve it in Java?

  • It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:
  • In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

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

java essay questions and answers

31. How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users.  This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.

32. Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters ‘System.exit()’ method anywhere in try/catch block.

34. Can you call a constructor of a class inside the another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this() .

java essay questions and answers

35. Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations.

java essay questions and answers

However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

java essay questions and answers

36. Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.

Example - Consider the array and assume each element takes 4-byte memory space. Then the address will be like this -

java essay questions and answers

Now if we want to access index 4. Then internally java calculates the address using the formula-

[Base Address + (index * no_of_bytes)] . So according to this. The starting address of the index 4 will be - [100 + (4*4)] = 116 . And exactly that's what the address is calculated.  Now consider the same with 1 index Array -

java essay questions and answers

Now if we apply the same formula here. Then we get - 116 as the starting address of the 4th index. Which is wrong. Then we need to apply formula - [ Base Address + ((index-1) * no_of_bytes)] .

And for calculating this, an extra arithmetic operation has to be performed. And consider the case where millions of addresses need to be calculated, this causes complexity. So to avoid this, ) the index array is supported by java.

37. Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Example - To Delete from the front of the linked list, internally the references adjustments happened like this.

java essay questions and answers

The only thing that will change is that the head pointer will point to the head’s next node. And delete the previous node. That is the constant time operation.

Whereas in the ArrayList, internally it should work like this-

java essay questions and answers

For deletion of the first element, all the next element has to move to one place ahead. So this copying value takes time. So that is the reason why removing in ArrayList is slower than LinkedList.

38. How many overloaded add() and addAll() methods are available in the List interface? Describe the need and uses.

There are a total of 4 overloaded methods for add() and addAll() methods available in List Interface. The below table states the description of all.

39. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

ArrayList is implemented in such a way that it can grow dynamically. We don't need to specify the size of ArrayList. For adding the values in it, the methodology it uses is -

1. Consider initially that there are 2 elements in the ArrayList. [2, 3] .

java essay questions and answers

2. If we need to add the element into this. Then internally what will happen is-

  • ArrayList will allocate the new ArrayList of Size (current size + half of the current size). And add the old elements into the new. Old - [2, 3],    New - [2, 3, null].

java essay questions and answers

  • Then the new value will be inserted into it. [2, 3, 4, null]. And for the next time, the extra space will be available for the value to be inserted.

java essay questions and answers

3. This process continues and the time taken to perform all of these is considered as the amortized constant time. 

This is how the ArrayList grows dynamically. And when we delete any entry from the ArrayList then the following steps are performed -

1. It searches for the element index in the array. Searching takes some time. Typically it’s O(n) because it needs to search for the element in the entire array.

java essay questions and answers

2. After searching the element, it needs to shift the element from the right side to fill the index.

java essay questions and answers

So this is how the elements are deleted from the ArrayList internally. Similarly, the search operations are also implemented internally as defined in removing elements from the list (searching for elements to delete).

1. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance lags behind composition in the following scenarios:

  • Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members.
  • Composition assists in attaining high flexibility and prevents breaking of encapsulation.
  • Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance.
  • The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance.

Let’s take an example:

In the above example, inheritance is followed. Now, some modifications are done to the Top class like this:

If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem:

2. What is the difference between ‘>>’ and ‘>>>’ operators in java?

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators.

  • ‘>>’ Bitwise Right Shift Operator - This operator shifts each bit to its right position. And this maintains the signed bit.
  • ‘>>>’ Bitwise Right Shift Operator with trailing zero - This operator also shifts each bit to its right. But this doesn’t maintain the signed bit. This operator makes the Most significant bit to 0.

Example- Num1 = 8, Num2 = -8.

So the binary form of these numbers are - 

Num1 = 00000000 00000000 00000000 00001000  Num2 = 11111111 11111111 11111111  11111000

‘>>’ Operator : 8 >> 1 (Shift by one bit) : 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 11111111 11111111 11111111  11111100

‘>>>’ Operator : 8 >>> 1 (Shift by one bit) = 

Num1 = 00000000 00000000 00000000 00000100 Num2 = 01111111 11111111 11111111 11111100

3. What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let’s understand with the help of an example. 

  • Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically.  So here we can say that there is a strong association between the objects. So this Strong Association is called Composition .
  • Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor’s). So here is the weak association between the objects. And this weak association is called Aggregation .

4. How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them.

The checking() function will return true as the same content is referenced by both the variables.

java essay questions and answers

Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

The checking() function will return false as the same content is not referenced by both the variables.

java essay questions and answers

5. How is the ‘new’ operator different from the ‘newInstance()’ operator in java?

Both ‘ new ’ and ‘ newInstance() ’ operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don’t know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the ‘ newInstance() ’ operator.

The ‘ newInstance() ’ keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn’t exist, and we get the class name from runtime. So it will throw an exception.

6. Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them.

In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects.

Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

Let’s take a look at the following example:

7. Why is synchronization necessary? Explain with the help of a relevant example.

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource.

Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let’s take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

No synchronization:

java essay questions and answers

If a thread Thread1 views the count as 10, it will be increased by 1 to 11. Simultaneously, if another thread Thread2 views the count as 10, it will be increased by 1 to 11. Thus, inconsistency in count values takes place because the expected final value is 12 but the actual final value we get will be 11.

Now, the function increase() is made synchronized so that simultaneous accessing cannot take place.

With synchronization:

java essay questions and answers

If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus, consistency in count values takes place.

8. In the given code below, what is the significance of ... ?

  • Ability to provide ... is a feature called varargs (variable arguments) which was introduced as part of Java 5.
  • The function having ... in the above example indicates that it can receive multiple arguments of the datatype String.
  • For example, the fooBarMethod can be called in multiple ways and we can still have one method to process the data as shown below:

9. What will be the output of the below java program and define the steps of Execution of the java program with the help of the below code?

The Output we get by executing this program will be

Static Block 1. Value of j = 0 Static method.  Static Block 2. Value of j = 10 Instance Block 1. Value of i = 0 Instance Block 2. Value of i = 5 Instance method.  Welcome to InterviewBit

This is a java tricky interview question frequently asked in java interviews for the experienced. The output will be like this because, when the java program is compiled and gets executed, then there are various steps followed for execution. And the steps are - 

  • Identification of Static Members from top to bottom.
  • Execution of Static variable assignment and a Static block from top to bottom.
  • Execution of the main method.
  • Identification of Instance Members from top to bottom.
  • Execution of Instance variable assignment and Instance block from top to bottom.
  • Execution of Constructor.

In above steps from 4 to 6, will be executed for every object creation. If we create multiple objects then for every object these steps will be performed.

Now from the above code, the execution will happen like this - 

1. In the step of identification of static members. It is found that -

  • static int j.
  • static block.
  • main method.
  • static method_2.

During identification, the JVM will assign the default value in the static int j variable. Then it is currently in the state of reading and indirectly writing. Because the original value is not assigned.

2. In the next step, it will execute the static block and assign the value in static variables.

  • First static block it will print and because execution from top to bottom and original value in j is not assigned. So it will print the default value of 0.
  • After executing static block 1. It will execute the static method_1 because it is called from the static block 1.
  • Then it will assign the original value of 5 in the j variable. And executes the remaining static block.

3. Now it will execute the main method. In which it will create an object for the class InterviewBit. And then the execution of instances will happen.

4. Identify the instance variables and blocks from top to bottom. 

  • Instance block 1.
  • Instance method_1.

Like a static variable, the instance variable also has been initialized with the default value 0 and will be in the state of reading and writing indirectly.

5. It will execute the instance methods and assign the original value to the instance variable.

  • Prints the Instance block 1. And the current value of i is not assigned till now, so it will print 0.
  • Assign the original value to i. Then print instance block 2. And after that instance method will be called and printed because it is being called in the instance block.

6. And at the last step, the constructor will be invoked and the lines will be executed in the constructor.

This is how the java program gets executed.

10. Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package . Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

11. Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:

  • New – When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state.
  • Runnable – Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread.
  • Running – When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received.
  • Terminated – Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

The following flowchart clearly explains the lifecycle of the thread in Java.

java essay questions and answers

12. What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

  • The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n) .
  • The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1).
  • Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

13. Is it possible to import the same class or package twice in Java and what happens to it during runtime?

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

14. In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

15. Will the finally block be executed if the code System.exit(0) is written at the end of try block?

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

16. What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

17. Explain the term “Double Brace Initialisation” in Java?

This is a convenient means of initializing any collections in Java. Consider the below example.

In the above example, we see that the stringSets were initialized by using double braces.

  • The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class’s behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet.
  • The second braces do the task of initializing the instances.

Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

18. Why is it said that the length() method of String class doesn't return accurate results?

  • The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below.
  • Code Point: This represents an integer denoting a character in the code space.
  • Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
  • The code points from the first plane are encoded using one 16-bit code unit
  • The code points from the remaining planes are encoded using two code units.

Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected.

In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

19. What is the output of the below code and why?

“bit” would have been the result printed if the letters were used in double-quotes (or the string literals). But the question has the character literals (single quotes) being used which is why concatenation wouldn't occur. The corresponding ASCII values of each character would be added and the result of that sum would be printed. The ASCII values of ‘b’, ‘i’, ‘t’ are:

98 + 105 + 116 = 319

Hence 319 would be printed.

20. What are the possible ways of making object eligible for garbage collection (GC) in Java?

First Approach: Set the object references to null once the object creation purpose is served.

Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC.

Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC.

21. In the below Java Program, how many objects are eligible for garbage collection?

In the above program, a total of 7 objects will be eligible for garbage collection. Let’s visually understand what's happening in the code.

java essay questions and answers

In the above figure on line 3, we can see that on each array index we are declaring a new array so the reference will be of that new array on all the 3 indexes. So the old array will be pointed to by none. So these three are eligible for garbage collection. And on line 4, we are creating a new array object on the older reference. So that will point to a new array and older multidimensional objects will become eligible for garbage collection.

22. What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - 

Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

23. How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes:

  • Global-session

24. What are the different categories of Java Design patterns?

Java Design patterns are categorized into the following different types. And those are also further categorized as 

Structural patterns:

Behavioral patterns:

  • Interpreter
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Strategy pattern
  • Visitor pattern

J2EE patterns:

  • MVC Pattern
  • Data Access Object pattern
  • Front controller pattern
  • Intercepting filter pattern
  • Transfer object pattern

Creational patterns:

  • Factory method/Template
  • Abstract Factory

25. What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Example - Consider a linked list like the structure below -

java essay questions and answers

In the above image, there are unused objects that are not referenced. But then also Garbage collection will not free it. Because it is referencing some existing referenced object. So this can be the situation of memory leak.

Some common causes of Memory leaks are - 

  • When there are Unbounded caches.
  • Excessive page swapping is done by the operating system.
  • Improper written custom data structures.
  • Inserting into a collection object without first deleting it. etc.

26. Assume a thread has a lock on it, calling the sleep() method on that thread will release the lock?

A thread that has a lock won't be released even after it calls sleep(). Despite the thread sleeping for a specified period of time, the lock will not be released.

1. Check if a given string is palindrome using recursion.

/* * Java program to check if a given inputted string is palindrome or not using recursion. */ import java.util.*; public class InterviewBit { public static void main (String args[]) { Scanner s = new Scanner(System.in); String word = s.nextLine(); System.out.println( "Is " +word+ " palindrome? - " +isWordPalindrome(word)); } public static boolean isWordPalindrome (String word) { String reverseWord = getReverseWord(word); //if word equals its reverse, then it is a palindrome if (word.equals(reverseWord)){ return true ; } return false ; } public static String getReverseWord (String word) { if (word == null || word.isEmpty()){ return word; } return word.charAt(word.length()- 1 ) + getReverseWord(word.substring( 0 , word.length() - 1 )); } }

2. Write a Java Program to print Fibonacci Series using Recursion.

In the above code, we are printing the base 2 Fibonacci values 0 and 1. And then based on the length of Fibonacci to be printed, we are using the helper function to print that.

3. Write a Java program to check if the two strings are anagrams.

The main idea is to validate the length of strings and then if found equal, convert the string to char array and then sort the arrays and check if both are equal.

4. Write a Java Program to find the factorial of a given number.

public class FindFactorial { public static void main (String[] args) { int num = 10 ; long factorialResult = 1l ; for ( int i = 1 ; i <= num; ++i) { factorialResult *= i; } System.out.println( "Factorial: " +factorialResult); } }

5. Given an array of non-duplicating numbers from 1 to n where one number is missing, write an efficient java program to find that missing number.

Idea is to find the sum of n natural numbers using the formula and then finding the sum of numbers in the given array. Subtracting these two sums results in the number that is the actual missing number. This results in O(n) time complexity and O(1) space complexity.

6. Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1.

Example, consider the number:

  • Step 1: 163 => 1+6+3 = 10
  • Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number

7. Write a Java program to create and throw custom exceptions.

We have created the exception class named with CustomException and called the base exception constructor with the error message that we want to print. And to avoid handling exceptions in the main method, we have used the throws keyword in the method declaration.

8. Write a Java program to reverse a string.

In the above code, we are storing the last character from the string to the first and the first value to the last in the output character array. And doing the same thing in the loop for the remaining 2nd to n-1 characters. This is how the string will be reversed.

9. Write a Java program to rotate arrays 90 degree clockwise by taking matrices from user input.

In the above code, for rotating the matrix to  90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.

10. Write a java program to check if any number given as input is the sum of 2 prime numbers.

18 = 13 + 5 18 = 11 + 7

In the above code, for any number n , we find all the 2 pairs of numbers that are added together resulting in n . And each checking number if it is prime. If it is prime then we are printing that.

11. Write a Java program for solving the Tower of Hanoi Problem.

In the above code we are first moving the n-1 disk from Tower A to Tower B , then moving that nth disk from Tower A to Tower C , and finally, the remaining n-1 disk from Tower B to Tower C . And we are doing this recursively for the n-1 disk.

12. Implement Binary Search in Java using recursion.

In the above code, we are finding the middle element each time and checking if the element is in the middle or not. If it is not, then we check on which side from the middle it exists. And Recursively searching on the particular subarray. So this way we are reducing the search space by 2 every time. So the search time is very low.

1. Conclusion

Java is one of the simple high-level languages that provides powerful tools and impressive standards required for application development. It was also one of the first languages to provide amazing threading support for tackling concurrency-based problems. The easy-to-use syntax and the built-in features of Java combined with the stability it provides to applications are the main reasons for this language has ever-growing usage in the software community.

Interview Preparation Resources

  • How to Become a Java Developer?
  • How much does a Java Developer earn in India?
  • Java Projects
  • Java Programming Questions for Interview
  • Java 8 Interview Questions
  • Java String Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • Java Collections Interview Questions
  • Array Interview Questions
  • Design Patterns Interview Questions
  • Multithreading Interview Questions
  • Java Tutorial
  • Advance Java MCQ
  • Difference Between C++ and Java
  • Difference Between C and Java
  • Difference Between Java and Javascript
  • Hashmap vs Hashtable in Java
  • Kotlin Vs Java
  • Java Vs Python
  • Features of Java 9
  • Java 8 Features
  • Java Frameworks
  • Java Developer Skills
  • Java 11 Features
  • Additional Technical Interview Questions
  • JAVA SE Download

Coding Problems

What is the component used for compiling, debugging, and executing java programs?

What component does the task of bytecode to machine code conversion?

Which of the following is the functionality of the java interpreter?

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called?

What is the output of the below piece of code?

What is the output of the following code?

Which of the following happens when the garbage collection process kicks off during the execution of the thread?

What is the output of the below code?

What is the functionality of Class.getInstance() ?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Java Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

21 Essential Java Interview Questions  *

Toptal sourced essential questions that the best java developers and engineers can answer. driven from our community, we encourage experts to submit questions and offer feedback..

java essay questions and answers

Interview Questions

Describe and compare fail-fast and fail-safe iterators. Give examples.

The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not.

Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException . Some examples include ArrayList , HashSet , and HashMap (most JDK1.4 collections are implemented to be fail-fast).

Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList .

ArrayList , LinkedList , and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of.

Of the three, LinkedList is generally going to give you the best performance. Here’s why:

ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector.

LinkedList , on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed.

However, it is worth noting that if performance is that critical, it’s better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC .

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you’re done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it.

In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Apply to Join Toptal's Development Network

and enjoy reliable, steady, remote Freelance Java Developer Jobs

What is the ThreadLocal class? How and why would you use it?

A single ThreadLocal instance can store different values for each thread independently. Each thread that accesses the get() or set() method of a ThreadLocal instance is accessing its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or transaction ID). The example below, from the ThreadLocal Javadoc , generates unique identifiers local to each thread. A thread’s id is assigned the first time it invokes ThreadId.get() and remains unchanged on subsequent calls.

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

What is the volatile keyword? How and why would you use it?

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM “Warning, this variable may be modified in another Thread”.

In all versions of Java, the volatile keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variable’s current value instead of (potentially) using a cached value.

In Java 5 or later, volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.

Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.

The volatile keyword is also useful for 64-bit types like long and double since they are written in two operations. Without the volatile keyword you risk stale or invalid values.

One common example for using volatile is for a flag to terminate a thread. If you’ve started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true ). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block. For example:

Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait() , on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll() , to achieve synchronization and avoid race conditions.

Tail recursion is functionally equivalent to iteration. Since Java does not yet support tail call optimization, describe how to transform a simple tail recursive function into a loop and why one is typically preferred over the other.

Here is an example of a typical recursive function, computing the arithmetic series 1, 2, 3…N. Notice how the addition is performed after the function call. For each recursive step, we add another frame to the stack.

Tail recursion occurs when the recursive call is in the tail position within its enclosing context - after the function calls itself, it performs no additional work. That is, once the base case is complete, the solution is apparent. For example:

Here you can see that a plays the role of the accumulator - instead of computing the sum on the way down the stack, we compute it on the way up, effectively making the return trip unnecessary, since it stores no additional state and performs no further computation. Once we hit the base case, the work is done - below is that same function, “unrolled”.

Many functional languages natively support tail call optimization, however the JVM does not. In order to implement recursive functions in Java, we need to be aware of this limitation to avoid StackOverflowError s. In Java, iteration is almost universally preferred to recursion.

How can you swap the values of two numeric variables without using any other variables?

You can swap two values a and b without using any other variables as follows:

How can you catch an exception thrown by another thread in Java?

This can be done using Thread.UncaughtExceptionHandler .

Here’s a simple example:

What is the Java Classloader? List and explain the purpose of the three types of class loaders.

The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web.

When the JVM is started, three class loaders are used: 1. Bootstrap Classloader: Loads core java API file rt.jar from folder. 2. Extension Classloader: Loads jar files from folder. 3. System/Application Classloader: Loads jar files from path specified in the CLASSPATH environment variable.

Is a finally block executed when an exception is thrown from a try block that does not have a catch block, and if so, when?

A finally block is executed even if an exception is thrown or propagated to the calling code block.

Output can vary, being either:

When designing an abstract class, why should you avoid calling abstract methods inside its constructor?

This is a problem of initialization order. The subclass constructor will not have had a chance to run yet and there is no way to force it to run it before the parent class. Consider the following example class:

This seems like a good start for an abstract Widget: it allows subclasses to fill in width and height , and caches their initial values. However, look when you spec out a typical subclass implementation like so:

Now we’ve introduced a subtle bug: Widget.cachedWidth and Widget.cachedHeight will always be zero for SquareWidget instances! This is because the this.size = size assignment occurs after the Widget constructor runs.

Avoid calling abstract methods in your abstract classes’ constructors, as it restricts how those abstract methods can be implemented.

What variance is imposed on generic type parameters? How much control does Java give you over this?

Java’s generic type parameters are invariant . This means for any distinct types A and B , G<A> is not a subtype or supertype of G<B> . As a real world example, List<String> is not a supertype or subtype of List<Object> . So even though String extends (i.e. is a subtype of) Object , both of the following assignments will fail to compile:

Java does give you some control over this in the form of use-site variance . On individual methods, we can use ? extends Type to create a covariant parameter. Here’s an example:

Even though longs is a List<Long> and not List<Number> , it can be passed to sum .

Similarly, ? super Type lets a method parameter be contravariant . Consider a function with a callback parameter:

forEachNumber allows Callback<Object> to be a subtype of Callback <Number> , which means any callback that handles a supertype of Number will do:

Note, however, that attempting to provide a callback that handles only Long (a subtype of Number ) will rightly fail:

Liberal application of use-site variance can prevent many of the unsafe casts that often appear in Java code and is crucial when designing interfaces used by multiple developers.

What are static initializers and when would you use them?

A static initializer gives you the opportunity to run code during the initial loading of a class and it guarantees that this code will only run once and will finish running before your class can be accessed in any way.

They are useful for performing initialization of complex static objects or to register a type with a static registry, as JDBC drivers do.

Suppose you want to create a static, immutable Map containing some feature flags. Java doesn’t have a good one-liner for initializing maps, so you can use static initializers instead:

Within the same class, you can repeat this pattern of declaring a static field and immediately initializing it, since multiple static initializers are allowed.

If one needs a Set , how do you choose between HashSet vs. TreeSet ?

At first glance, HashSet is superior in almost every way: O(1) add , remove and contains , vs. O(log(N)) for TreeSet .

However, TreeSet is indispensable when you wish to maintain order over the inserted elements or query for a range of elements within the set.

Consider a Set of timestamped Event objects. They could be stored in a HashSet , with equals and hashCode based on that timestamp. This is efficient storage and permits looking up events by a specific timestamp, but how would you get all events that happened on any given day? That would require a O(n) traversal of the HashSet , but it’s only a O(log(n)) operation with TreeSet using the tailSet method:

If Event happens to be a class that we cannot extend or that doesn’t implement Comparable , TreeSet allows us to pass in our own Comparator :

Generally speaking, TreeSet is a good choice when order matters and when reads are balanced against the increased cost of writes.

What are method references, and how are they useful?

Method references were introduced in Java 8 and allow constructors and methods (static or otherwise) to be used as lambdas. They allow one to discard the boilerplate of a lambda when the method reference matches an expected signature.

For example, suppose we have a service that must be stopped by a shutdown hook. Before Java 8, we would have code like this:

With lambdas, this can be cut down considerably:

However, stop matches the signature of Runnable.run ( void return type, no parameters), and so we can introduce a method reference to the stop method of that specific SomeBusyService instance:

This is terse (as opposed to verbose code) and clearly communicates what is going on.

Method references don’t need to be tied to a specific instance, either; one can also use a method reference to an arbitrary object, which is useful in Stream operations. For example, suppose we have a Person class and want just the lowercase names of a collection of people:

A complex lambda can also be pushed into a static or instance method and then used via a method reference instead. This makes the code more reusable and testable than if it were “trapped” in the lambda.

So we can see that method references are mainly used to improve code organization, clarity and terseness.

How are Java enums more powerful than integer constants? How can this capability be used?

Enums are essentially final classes with a fixed number of instances. They can implement interfaces but cannot extend another class.

This flexibility is useful in implementing the strategy pattern, for example, when the number of strategies is fixed. Consider an address book that records multiple methods of contact. We can represent these methods as an enum and attach fields, like the filename of the icon to display in the UI, and any corresponding behaviour, like how to initiate contact via that method:

We can dispense with switch statements entirely by simply using instances of ContactMethod :

This is just the beginning of what can be done with enums. Generally, the safety and flexibility of enums means they should be used in place of integer constants, and switch statements can be eliminated with liberal use of abstract methods.

What does it mean for a collection to be “backed by” another? Give an example of when this property is useful.

If a collection backs another, it means that changes in one are reflected in the other and vice-versa.

For example, suppose we wanted to create a whitelist function that removes invalid keys from a Map . This is made far easier with Map.keySet , which returns a set of keys that is backed by the original map. When we remove keys from the key set, they are also removed from the backing map:

retainAll writes through to the backing map, and allows us to easily implement something that would otherwise require iterating over the entries in the input map, comparing them against allowedKey , etcetera.

Note, it is important to consult the documentation of the backing collection to see which modifications will successfully write through. In the example above, map.keySet().add(value) would fail, because we cannot add a key to the backing map without a value.

What is reflection? Give an example of functionality that can only be implemented using reflection.

Reflection allows programmatic access to information about a Java program’s types. Commonly used information includes: methods and fields available on a class, interfaces implemented by a class, and the runtime-retained annotations on classes, fields and methods.

Examples given are likely to include:

  • Annotation-based serialization libraries often map class fields to JSON keys or XML elements (using annotations). These libraries need reflection to inspect those fields and their annotations and also to access the values during serialization.
  • Model-View-Controller frameworks call controller methods based on routing rules. These frameworks must use reflection to find a method corresponding to an action name, check that its signature conforms to what the framework expects (e.g. takes a Request object, returns a Response ), and finally, invoke the method.
  • Dependency injection frameworks lean heavily on reflection. They use it to instantiate arbitrary beans for injection, check fields for annotations such as @Inject to discover if they require injection of a bean, and also to set those values.
  • Object-relational mappers such as Hibernate use reflection to map database columns to fields or getter/setter pairs of a class, and can go as far as to infer table and column names by reading class and getter names, respectively.

A concrete code example could be something simple, like copying an object’s fields into a map:

Such tricks can be useful for debugging, or for utility methods such as a toString method that works on any class.

Aside from implementing generic libraries, direct use of reflection is rare but it is still a handy tool to have. Knowledge of reflection is also useful for when these mechanisms fail.

However, it is often prudent to avoid reflection unless it is strictly necessary, as it can turn straightforward compiler errors into runtime errors.

Nested classes can be static or non-static (also called an inner class). How do you decide which to use? Does it matter?

The key difference between is that inner classes have full access to the fields and methods of the enclosing class. This can be convenient for event handlers, but comes at a cost: every instance of an inner class retains and requires a reference to its enclosing class.

With this cost in mind, there are many situations where we should prefer static nested classes. When instances of the nested class will outlive instances of the enclosing class, the nested class should be static to prevent memory leaks. Consider this implementation of the factory pattern:

At a glance, this design looks good: the WidgetParserFactory hides the implementation details of the parser with the nested class WidgetParserImpl . However, WidgetParserImpl is not static, and so if WidgetParserFactory is discarded immediately after the WidgetParser is created, the factory will leak, along with all the references it holds.

WidgetParserImpl should be made static, and if it needs access to any of WidgetParserFactory ’s internals, they should be passed into WidgetParserImpl ’s constructor instead. This also makes it easier to extract WidgetParserImpl into a separate class should it outgrow its enclosing class.

Inner classes are also harder to construct via reflection due to their “hidden” reference to the enclosing class, and this reference can get sucked in during reflection-based serialization, which is probably not intended.

So we can see that the decision of whether to make a nested class static is important, and that one should aim to make nested classes static in cases where instances will “escape” the enclosing class or if reflection on those nested classes is involved.

What is the difference between String s = "Test" and String s = new String("Test") ? Which is better and why?

In general, String s = "Test" is more efficient to use than String s = new String("Test") .

In the case of String s = "Test" , a String with the value “Test” will be created in the String pool. If another String with the same value is then created (e.g., String s2 = "Test" ), it will reference this same object in the String pool.

However, if you use String s = new String("Test") , in addition to creating a String with the value “Test” in the String pool, that String object will then be passed to the constructor of the String Object (i.e., new String("Test") ) and will create another String object (not in the String pool) with that value. Each such call will therefore create an additional String object (e.g., String s2 = new String("Test") would create an addition String object, rather than just reusing the same String object from the String pool).

There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .

Tired of interviewing candidates? Not sure what to ask to get you a top hire?

Let Toptal find the best people for you.

Our Exclusive Network of Java Developers

Looking to land a job as a Java Developer?

Let Toptal find the right job for you.

Job Opportunities From Our Network

Submit an interview question

Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.

Looking for Java Developers?

Looking for Java Developers ? Check out Toptal’s Java developers.

Julie Wetherbee, Freelance Java Programmer for Hire.

Julie Wetherbee

Julie has over 20 years of experience building software applications and leading engineering teams for businesses of all sizes. She has expertise in Java, JavaScript, C, C++, and Perl, and is familiar with many popular frameworks. Recently, Julie designed and implemented a large-scale Oracle database sharding solution for Walmart.com.

Jean-François Savard, Freelance Java Engineer.

Jean-François Savard

Jean-François is a passionate developer who started coding in Java when he was 14 years old and has rarely passed a day without writing code since then. Notwithstanding his unique experience with Java and its related frameworks, his thirst for knowledge led him to explore several aspects of computer science, such as machine learning, data science, software architecture, and cloud-based development.

Claudio Aldana, Java Engineer.

Claudio Aldana

Claudio is a seasoned IT specialist focused on business outcomes, along with having a solid engineering background. He's applied data science to optimize customer satisfaction, product personalization, and customer churn. Claudio is also a certified SharePoint expert and has worked with prominent Microsoft customers, helping them to maximize security, performance, and usability.

Toptal Connects the Top 3% of Freelance Talent All Over The World.

Join the Toptal community.

The complete guide to Java interview questions and interview prep

java essay questions and answers

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

While an older language, Java remains one of the most popular high-level programming languages today. It entered the landscape as a high-level language designed for simplicity and platform independence . Java is running on most of our mobile devices and laptops, and Java developers remain in high demand.

Whether you’re preparing for a role in game development or Android development, mastering Java might take you closer to finding a developer job you love .

Today, we present you with this complete guide to preparing for Java interviews.

We’ll cover :

Common Java interview questions

Core Java interview questions for beginners

Is Java an object-oriented programming language?

Does java support multiple inheritances for classes, what is jdk, method overloading: which method will be invoked, what is a default constructor, resources for common java interview questions, advanced java interview questions and answers for experienced developers, can enum implement an interface in java, what are garbage collection (gc) roots, what are the three phases of garbage collection, rest api questions, resources for advanced java interview questions, java coding interviews, java algorithm interview questions, java data structure interview questions, java collections interview questions and answers, what are collections, what is the collection interface, what are collection interface bulk operations.

  • What are the collection types in the Java Collections Framework?

Java multithreading interview questions and answers

What is multithreading, what are the benefits of multithreading, java 8 interview questions and answers, what is function composition, what is a functional interface, stream api questions, java ee interview questions and answers, spring framework interview questions, list the hibernate framework’s core interfaces., are singleton beans thread-safe, how to prepare for java interviews, study the fundamentals, java system design interviews, prepare for specific roles and companies, wrapping up and next steps, answer any java interview problem by learning the patterns behind common questions..

Cover

Learn in-demand tech skills in half the time

Mock Interview

Skill Paths

Assessments

Learn to Code

Tech Interview Prep

Generative AI

Data Science

Machine Learning

GitHub Students Scholarship

Early Access Courses

For Individuals

Try for Free

Gift a Subscription

Become an Author

Become an Affiliate

Earn Referral Credits

Cheatsheets

Frequently Asked Questions

Privacy Policy

Cookie Policy

Terms of Service

Business Terms of Service

Data Processing Agreement

Copyright © 2024 Educative, Inc. All rights reserved.

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview, 3) list the features of java programming language..

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.
  • Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

4) What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

5) What is the difference between JDK, JRE, and JVM?

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

  • Standard Edition Java Platform
  • Enterprise Edition Java Platform
  • Micro Edition Java Platform

6) How many types of memory areas are allocated by JVM?

Many types:

  • Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
  • Heap: It is the runtime data area in which the memory is allocated to the objects
  • Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
  • Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
  • Native Method Stack: It contains all the native methods used in the application.

7) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.

9) What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

10) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

11) What is classloader?

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

  • Bootstrap ClassLoader : This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
  • Extension ClassLoader : This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
  • System/Application ClassLoader : This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

12) Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:

compile it by javac .java

run it by java A

13) Is delete, next, main, exit or null keyword in java?

14) if i don't provide any arguments on the command line, then what will the value stored in the string array passed into the main() method, empty or null.

It is empty, but not null.

15) What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

16) What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

17) What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.

18) What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static .

19) What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

20) What is the output of the following Java program?

The output of the above code will be

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint . Therefore, the output will be 30Javatpoint .

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020 .

21) What is the output of the following Java program?

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint .

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpoint to produce the output as Javatpoint200 .

22) What is the output of the following Java program?

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.

Core Java - OOPs Concepts: Initial OOPs Interview Questions

There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. However, they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions, etc. for better understanding.

23) What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object's data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

24) What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

25) What is the difference between an object-oriented programming language and object-based programming language?

There are the following basic differences between the object-oriented language and object-based language.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects, for example, JavaScript has window object.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc.

26) What will be the initial value of an object reference which is defined as an instance variable?

All object references are initialized to null in Java.

Core Java - OOPs Concepts: Constructor Interview Questions

27) what is the constructor.

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

28) How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

Java Constructors

29) What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java default constructor

30) Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the constructor). More Details.

31)Is constructor inherited?

No, The constructor is not inherited.

32) Can you make a constructor final?

No, the constructor can't be final.

33) Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

34) What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

35) What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructors vs Methods

36) What is the output of the following Java program?

The output of the following program is:

Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the two integer parameters is called.

37) What is the output of the following Java program?

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

38) What is the output of the following Java program?

There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.

Core Java - OOPs Concepts: static keyword Interview Questions

39) what is the static variable.

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Static Variable

40) What is the static method?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable.

41) What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.

42) Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation. More Details.

43) Can we override the static methods?

44) what is the static block.

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

45) Can we execute a program without main() method?

Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible. More Details.

46) What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

47) What is the difference between static (class) method and instance method?

48) can we make constructors static.

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

49) Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

50) Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.

Core Java - OOPs Concepts: Inheritance Interview Questions

51) what is this keyword in java.

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.

java this keyword

52) What are the main uses of this keyword?

There are the following uses of this keyword.

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke the current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as an argument in the constructor call.
  • this can be used to return the current class instance from the method.

53) Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

54) Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.

55) How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

56) What are the advantages of passing this into a method instead of the current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.

  • this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

57) What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Multiple inheritance is not supported in Java through class.

58) Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

  • Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
  • Runtime polymorphism cannot be achieved without using inheritance.
  • We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
  • Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
  • Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.

59) Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.

60) Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

61) What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

Employee.java

62) What is composition?

Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

63) What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

64) Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.

65) What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

66) How can constructor chaining be done by using the super keyword?

67) what are the main uses of the super keyword.

There are the following uses of super keyword.

  • super can be used to refer to the immediate parent class instance variable.
  • super can be used to invoke the immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.

68) What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

69) What is the output of the following Java program?

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.

70) Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

71)What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

Core Java - OOPs Concepts: Method Overloading Interview Questions

72) what is method overloading.

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.

  • By Changing the number of arguments
  • By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

73) Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

74) Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.

75) Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

76) What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.

Java Method Overloading with Type Promotion

As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or double and so on. Consider the following example.

77) What is the output of the following Java program?

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.

Core Java - OOPs Concepts: Method Overriding Interview Questions

78) what is method overriding:.

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

79) Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

80) Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

81) Can we override the overloaded method?

82) difference between method overloading and overriding., 83) can we override the private methods.

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

84) Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

85) Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

86) What is the output of the following Java program?

87) can you have virtual functions in java.

Yes, all functions in Java are virtual by default.

88) What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.

89) What is the output of the following Java program?

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.

Core Java - OOPs Concepts: final keyword Interview Questions

90) what is the final variable.

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

final keyword in java

91) What is the final method?

If we change any method to a final method, we can't override it. More Details.

92) What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

93) What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

94) Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block. More Details.

95) Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

96) What is the output of the following Java program?

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

97) What is the output of the following Java program?

The getDetails() method is final; therefore it can not be overridden in the subclass.

98) Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

100) What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

You may also like:

  • Java Interview Questions
  • SQL Interview Questions
  • Python Interview Questions
  • JavaScript Interview Questions
  • Angular Interview Questions
  • Selenium Interview Questions
  • Spring Boot Interview Questions
  • HR Interview Questions
  • C Programming Interview Questions
  • C++ Interview Questions
  • Data Structure Interview Questions
  • DBMS Interview Questions
  • HTML Interview Questions
  • IAS Interview Questions
  • Manual Testing Interview Questions
  • OOPs Interview Questions
  • .Net Interview Questions
  • C# Interview Questions
  • ReactJS Interview Questions
  • Networking Interview Questions
  • PHP Interview Questions
  • CSS Interview Questions
  • Node.js Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AWS Interview Questions
  • Accounting Interview Questions

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • 30 OOPs Interview Questions and Answers (2024)
  • C++ Interview Questions and Answers (2024)
  • Top 100 C++ Coding Interview Questions and Answers (2024)
  • Top 50+ Python Interview Questions and Answers (Latest 2024)
  • Java Interview Questions and Answers
  • Java Collections Interview Questions and Answers
  • Top 20 Java Multithreading Interview Questions & Answers
  • Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
  • Top 50 Array Coding Problems for Interviews
  • Most Asked Problems in Data Structures and Algorithms | Beginner DSA Sheet
  • Top 10 Algorithms in Interview Questions
  • Machine Learning Interview Questions
  • Top 50 Problems on Linked List Data Structure asked in SDE Interviews
  • Top 50 Problems on Heap Data Structure asked in SDE Interviews
  • Data Analyst Interview Questions and Answers
  • SQL Query Interview Questions
  • Top Linux Interview Questions With Answer
  • MySQL Interview Questions
  • Top 50 Django Interview Questions and Answers
  • Top 50 Networking Interview Questions (2024)
  • Software Testing Interview Questions

Top 20 Java Multithreading Interview Questions & Answers

Java has been rated number one in TIOBE popular programming developers which are used by over 10 Million developers over 15 billion devices supporting Java. It is used for creating applications for trending technologies like Big Data to household devices like Mobiles and DTH Boxes, it is used everywhere in today’s information age. 

Top-20-Java-Multithreading-Interview-Questions-Answers

Multithreading in Core Java(J2SE) is a very important topic from an interview point of view. It can lead you to become a Java Developer, Java Testing Engineer, Java Architect, Lead Analyst, Java Consultant, and most important a real good Java programmer enabling the confidence to dive in J2EE programming which stands for Java to enterprising edition or in layman language making you fit to work in corporate domain workflow directly. Perks wide varied in India for Java developers from 300K to 25000K for as fresher based upon the level of intellect.

So, let’s get started with most asked Java Multithreading Interview Questions with their detailed answers.

Q-1 What is multitasking?

A multitasking operating system is an operating system that gives you the perception of 2 or more tasks/jobs/processes running at the same time. It does this by dividing system resources amongst these tasks/jobs/processes and switching between the tasks/jobs/processes while they are executing over and over again. Usually, the CPU processes only one task at a time but the switching is so fast that it looks like the CPU is executing multiple processes at a time. They can support either preemptive multitasking, where the OS provides time to applications (virtually all modern OS), or cooperative multitasking, where the OS waits for the program to give back control (Windows 3.x, Mac OS 9, and earlier), leading to hangs and crashes. Also known as Timesharing, multitasking is a logical extension of multiprogramming.

Multitasking programming is of two types which are as follows:

  • Process-based Multitasking
  • Thread-based Multitasking

java essay questions and answers

Note: Performing multiple tasks at one time is referred to as multithreading in java which is of two types namely Process-based multithreading and Thread based multithreading.

Q-2 How can you identify the process?

Any program which is in a working state is referred to as a process. These processes do have threads that are single dispatchable units.

Q-3 How do you see a thread?

In order to see threads status let us take windows as an operating system, it illustrates then we’d have ProcessExplorer where you can see GUI shown below for windows operating systems.

ProcessExplorer is illustrated below in the windows operating systems

java essay questions and answers

Note: All of them as listed in the above media are the processes as shown above where at a time many are running in parallel to each other henceforth illustrating multiprocessing in the Jwindows operating system.  

As we have seen threads do reside in a single process so we have to deep dive into a specific process to see them in order to show users how multithreading is going on in the computers at the backend. For example: let us pick a random process from the above media consisting of various processes say it be ‘chrome’. Now we need to right-click over the process and click the properties’ menu.

java essay questions and answers

From the above media, it is clearly perceived that chrome is a process and after proceeding with the steps to figure out threads running inside the chrome process we go to properties of the process ‘chrome’ below pictorial output will be generated representing threads running in the process chrome.

java essay questions and answers

Note: If we look scroll way from up to down then it will be seeing some colors against a few of those threads. Here green color threads are associated as the newly created threads and red colors associated threads are representing the closed threads.

java essay questions and answers

Note: So for chrome to increase the performance by reducing the response time that is referred to as Thread based multitasking.

Q-4 What is Multithreading and How it is Different from Multitasking?

Multithreading is a specialized form of multitasking. Process-based multitasking refers to executing several tasks simultaneously where each task is a separate independent process is Process-based multitasking. 

Example: Running Java IDE and running TextEdit at the same time. Process-based multitasking is represented by the below pictorial which is as follows:

java essay questions and answers

Thread-based multitasking refers to executing several tasks simultaneously where each task is a separate independent part of the same program known as a thread. For example, JUnits uses threads to run test cases in parallel. Henceforth, process-based multitasking is a bigger scenario handling process where threads handle the details. It is already discussed to deeper depth already with visual aids.

For more details, please refer to Process-based and Thread-based multitasking in Java  

Q-5 Which Kind of Multitasking is Better and Why?

Thread-based multitasking is better as multitasking of threads requires less overhead as compared to process multitasking because processes are heavyweight in turn requiring their own separate address space in memory while threads being very light-weight processes and share the same address space as cooperatively shared by heavyweight processes.

Switching is a secondary reason as inter-process communication is expensive and limited. Context switching from one process to another is cost hefty whereas inter-thread communication is inexpensive and context switching from one thread to another is lower in cost. 

Note: However java programs make use of process-based multitasking environments, but this feature is not directly under Java’s direct control while multithreading is complete.

Q-6 What is a thread?

Threads are lightweight processes within processes as seen. In java, there are two ways of creating threads namely via Thread class and via Runnable interface.

java essay questions and answers

To read more about this, please refer Thread class in Java , Runnable interface in Java 

Q-7 What are the different states of a thread, or what is thread lifecycle?

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant:

  • Timed Waiting

java essay questions and answers

To read more about this, please refer Lifecycle and States of a Thread in Java  

Q-8 What is the task of the main thread?

All Java programs have at least one thread, known as the main thread which is created by JVM at the program start when the main() method is invoked with the main thread as depicted from the output perceived from pseudo-code illustration.

Illustration:

Q-9 What are the Different Types of threads in Java? 

There are two types of threads in Java as follows:

  • User thread
  • Daemon thread

User threads are created by java developers for example Main thread. All threads are created inside the main() method are by default non-daemon thread because the ‘main’ thread is non-daemon. Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection, etc. They do not prevent daemon threads from exiting when all user threads finish their execution. JVM terminates itself when all non-daemon threads finish their execution. JVM does not care whether a thread is running or not, if JVM finds a running daemon thread it terminates the thread and after that shutdown itself.

Q-10 How to Create a User thread?

As discussed earlier when the JVM starts it creates a main thread over which the program is run unless an additional thread is not created by the user. The first thing “Main” thread looks for ‘ public static void main(String [] args) ’ method to invoke it as it acts as an entry point to the program. All other threads created in main acts as child threads of the “Main” thread. 

User thread can be implemented in two ways listed below:

  • Using Thread class by extending java.lang.Thread class .
  • Using Runnable Interface by implementing it.

Q-11 How to set the name of the thread?

We can name a thread by using a method been already up there known as setName() replacing default naming which was ‘Thread-0’, ‘Thread-1’, and so on.

Q-12 What is thread priority?

Priorities in threads is a concept where each thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. 

  • The default priority is set to 5 as excepted.
  • Minimum priority is set to 0.
  • Maximum priority is set to 10.

Here 3 constants are defined in it namely as follows:

  • public static int NORM_PRIORITY
  • public static int MIN_PRIORITY
  • public static int MAX_PRIORITY

To read more about this, please refer Thread Priority in Multithreading in Java 

Q-13 How deadlock plays a important role in multithreading?

If we do incorporate threads in operating systems one can perceive that the process scheduling algorithms in operating systems are strongly deep-down working on the same concept incorporating thread in Gantt charts . A few of the most popular are listed below which wraps up all of them and are used practically in software development.

java essay questions and answers

  • First In First Out
  • Last In First Out
  • Round Robin Scheduling

Now one Imagine the concept of Deadlock in operating systems with threads by now how the switching is getting computed over internally if one only has an overview of them. 

java essay questions and answers

Q-14 Why output is not ordered?  

Scheduling of threads involves two boundary scheduling,

  • Scheduling of user-level threads (ULT) to kernel-level threads (KLT) via lightweight process (LWP) by the application developer.
  • Scheduling of kernel-level threads by the system scheduler to perform different unique os functions.

java essay questions and answers

If multiple threads are waiting to execute then thread execution is decided by “ThreadScheduler” which is a part of JVM hence its vendor dependent resulting in unexpected execution of output order.

Note:   In multithreading, the guarantee of order is very less where we can predict possible outputs but not exactly one. Also, note that synchronization when incorporated with multithreading does affect our desired output simply by using the keyword ‘synchronized’.

It is as illustrated in the below illustration which is as follows:

java essay questions and answers

Q-15 What is Daemon Thread in Java and explain their properties? 

Daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection. It does possess certain specific properties as listed below:

  • They can not prevent the JVM from exiting when all the user threads finish their execution.
  • JVM terminates itself when all user threads finish their execution
  • If JVM finds a running daemon thread, it terminates the thread and after that shutdown itself. JVM does not care whether the Daemon thread is running or not.
  • It is an utmost low priority thread
Note: The main difference between user thread and daemon thread is that JVM does not wait for daemon thread  before exiting while it do waits for the user thread.

To read more about this, please refer to Daemon Thread in Java 

Q-16 How to Make User Thread to Daemon Thread?

It is carried out with the help of two methods listed in ‘Thread class’ known as setDaemon() and isDaemon() . First, the setDaemon() method converts user thread to daemon thread and vice-versa. This method can only be called before starting the thread using start() method else is called after starting the thread with will throw IllegalThreadStateException After this, isDaemon() method is used which returns a boolean true if the thread is daemon else returns false if it is a non-daemon thread.   

Q-17 What are the tasks of the start() method?

The primary task of the start() method is to register the thread with the thread scheduler, so one can tell what child thread should perform, when, and how it will be scheduled that is handled by the thread scheduler . The secondary task is to call the corresponding run() method got the threads.

Q-18 What is the difference between the start() and run() method?

First , both methods are operated in general over the thread. So if we do use threadT1.start() then this method will look for the run() method to create a new thread. While in case of theadT1.run() method will be executed just likely the normal method by the “Main” thread without the creation of any new thread.

Note: If we do replace start() method with run() method then the entire program is carried by ‘main’ thread.

Q-19 Can we Overload run() method? What if we do not override the run() method? 

java essay questions and answers

Yes, it is possible to overload run() by passing parameters to it and also keeping a check over to comment down @override from the run() method. 

It should be as good as a thread wherein thread we do not have any arguments, so practice to overload is to comment on the call out for overloaded run() method. Now, so we need to acknowledge the same whether the output is the same or not if we have not overloaded it. 

If we have overloaded the run() method, then we will observe that output is always the main method as can be perceived from the stack call from the above image. It is because if we debug the code as provided in the link below we see as soon as the start() method is called again, run() is called because we have not overridden the run() method. 

For more refer to the Implementation part of how the run() method is overloaded

Conclusion: We can overload the run() method but start() method will call no argument run() only. Hence, it will be of no help to us and is considered as bad practice. 

The compiler will simply execute the run() method of the Thread class, keeping a check that the run() method of the Thread class must have an empty implementation. Hence, it results out in no output corresponding to the thread. As we have discussed above already, if we try to do so, then the Thread class run() method will be called and we will never get our desired output.

Note: Geek initially we are requesting to create a thread for us and later the same thread is doing nothing for us which we have created. So it becomes completely meaningless to us by writing unwanted operations to our code fragments. Hence, it becomes useless not to override the run() method. 

Q-20 Can we Override the start() method?

Even if we override the start() method in the custom class then no initializations will be carried on by the Thread class for us. The run() method is also not called and even a new thread is also not created.

Note: We can not restart the same thread again as we will get IllegalThreadStateException from java.lang package. Alongside we can not do this indirectly with usage of ‘super.start()’ method.

Please Login to comment...

Similar reads.

author

  • Java-Multithreading

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Top 72 Swift Interview Questions

50 Senior Java Developer Interview Questions (ANSWERED) To Know

The average salary for a Senior Java Developer in USA is $154,312 per year. Follow along to brush up the most common advanced Java interview questions and answers that may win you a next job offer.

Q1 :   What is Spring?

Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based (Plain Old Java Object) programming model.

Q2 :   What is JVM ? Why is Java called the "Platform Independent Programming Language” ?

A Java virtual machine (JVM) is a process virtual machine that can execute Java bytecode. Each Java source file is compiled into a bytecode file, which is executed by the JVM. Java was designed to allow application programs to be built that could be run on any platform, without having to be rewritten or recompiled by the programmer for each separate platform. A Java virtual machine makes this possible, because it is aware of the specific instruction lengths and other particularities of the underlying hardware platform.

Q3 :   What is the Difference between JDK and JRE ?

The Java Runtime Environment (JRE) is basically the Java Virtual Machine ( JVM ) where your Java programs are being executed. It also includes browser plugins for applet execution.

The Java Development Kit (JDK) is the full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications.

Q4 :   What are Spring beans?

The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans . A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions.

Q5 :   What are benefits of using Spring?

Following is the list of few of the great benefits of using Spring Framework:

  • Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
  • Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Aspect oriented (AOP) − Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
  • Container − Spring contains and manages the life cycle and configuration of application objects.
  • MVC Framework − Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks.
  • Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
  • Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

Q6 :   What does System.gc() and Runtime.gc() methods do?

These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.

Q7 :   What is Application Context?

On the surface, an application context is the same as a bean factory. Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:

  • A means for resolving text messages, including support for internationalization
  • A generic way to load file resources
  • Events to beans that are registered as listeners

Q8 :   What is JDBC ?

JDBC is an abstraction layer that allows users to choose between databases. JDBC enables developers to write database applications in Java , without having to concern themselves with the underlying details of a particular database.

Q9 :   What is reflection and why is it useful?

The name reflection is used to describe code which is able to inspect other code in the same system (or itself) and to make modifications at runtime.

For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.

Q10 :   What is the function of CI (Continuous Integration) server?

CI server function is to continuously integrate all changes being made and committed to repository by different developers and check for compile errors. It needs to build code several times a day, preferably after every commit so it can detect which commit made the breakage if the breakage happens.

Q11 :   What is the relationship between a class and an object ?

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the class. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle , such as Van , Truck , and Auto .

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

Q12 :   Can == be used on enum ?

Yes : enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification.

Q13 :   Compare the sleep() and wait() methods in Java

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds.

wait() , on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object.

sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll() , to achieve synchronization and avoid race conditions.

Q14 :   Does Spring Bean provide thread safety?

The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.

However, we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.

Q15 :   How do I read/convert an InputStream into a String in Java?

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter like:

Q16 :   Is Java pass-by-reference or pass-by-value ?

Java is always pass-by-value . Unfortunately, when we pass the value of an object, we are passing the reference to it. There is no such thing as "pass-by-reference" in Java. This is confusing to beginners.

The key to understanding this is that something like

is not a Dog; it's actually a pointer to a Dog.

So when you have

you're essentially passing the address of the created Dog object to the foo method.

Q17 :   Is there anything like static class in Java?

Java has no way of making a top-level class static but you can simulate a static class like this:

  • Declare your class final - Prevents extension of the class since extending a static class makes no sense
  • Make the constructor private - Prevents instantiation by client code as it makes no sense to instantiate a static class
  • Make all the members and functions of the class static - Since the class cannot be instantiated no instance methods can be called or instance fields accessed
  • Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member

Q18 :   State the features of an Interface

An interface is a template that contains only the signature of methods. The signature of a method consists of the numbers of parameters, the type of parameter (value, reference, or output), and the order of parameters. An interface has no implementation on its own because it contains only the definition of methods without any method body. An interface is defined using the interface keyword. Moreover, you cannot instantiate an interface. The various features of an interface are as follows:

  • An interface is used to implement multiple inheritance in code. This feature of an interface is quite different from that of abstract classes because a class cannot derive the features of more than one class but can easily implement multiple interfaces.
  • It defines a specific set of methods and their arguments.
  • Variables in interface must be declared as public , static , and final while methods must be public and abstract .
  • A class implementing an interface must implement all of its methods.
  • An interface can derive from more than one interface.

Q19 :   What are the differences between Continuous Integration , Continuous Delivery , and Continuous Deployment ?

  • Developers practicing continuous integration merge their changes back to the main branch as often as possible. By doing so, you avoid the integration hell that usually happens when people wait for release day to merge their changes into the release branch.
  • Continuous delivery is an extension of continuous integration to make sure that you can release new changes to your customers quickly in a sustainable way. This means that on top of having automated your testing, you also have automated your release process and you can deploy your application at any point of time by clicking on a button.
  • Continuous deployment goes one step further than continuous delivery. With this practice, every change that passes all stages of your production pipeline is released to your customers. There's no human intervention, and only a failed test will prevent a new change to be deployed to production.

Q20 :   What are the differences between == and equals ?

As a reminder, it needs to be said that generally, == is NOT a viable alternative to equals . When it is, however (such as with enum), there are two important differences to consider:

  • == never throws NullPointerException
  • == is subject to type compatibility check at compile time

Q21 :   What do the ... dots in the method parameters mean?

What do the 3 dots in the following method mean?

That feature is called varargs, and it's a feature introduced in Java 5. It means that function can receive multiple String arguments:

Then, you can use the String var as an array:

Q22 :   What is Controller in Spring MVC framework?

Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

Q23 :   What is Spring IoC container?

The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

There are two types of IoC containers in Spring:

  • Bean Factory container − This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
  • Spring ApplicationContext Container − This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.

Q24 :   What is a JavaBean exactly?

Basically, a "Bean" follows the standart:

  • is a serializable object (that is, it implements java.io.Serializable , and does so correctly), that
  • has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
  • has a public 0-arg constructor (so it can be created at will and configured by setting its properties).

There is no syntactic difference between a JavaBean and another class - a class is a JavaBean if it follows the standards.

Q25 :   What is difference between fail-fast and fail-safe ?

The Iterator's fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a ConcurrentModificationException , while fail-safe iterator never throws such an exception.

Q26 :   What is structure of Java Heap ?

The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.

Q27 :   What is the JIT ?

The JIT is the JVM’s mechanism by which it can optimize code at runtime.

JIT means Just In Time . It is a central feature of any JVM. Among other optimizations, it can perform code inlining, lock coarsening or lock eliding, escape analysis etc.

The main benefit of the JIT is on the programmer’s side: code should be written so that it just works; if the code can be optimized at runtime, more often than not, the JIT will find a way.

Q28 :   What is the volatile keyword useful for?

volatile has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.

Q29 :   Which Swing methods are thread-safe ?

There are only three thread-safe methods:

  • revalidate,
  • invalidate.

Q30 :   Explain a use case for the Builder Design Pattern

The good example is a class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to N parameters, N-2 of which are just being passed into the super constructor. Instead of using a particular constructor with N params we could use the Builder Design Pattern .

Consider the following example:

This lets us write code like:

Q31 :   Is null check needed before calling instanceof ?

return false or throw a NullPointerException ?

No , a null check is not needed before using instanceof. The expression

is false if x is null .

Q32 :   What are the pros and cons of Microservice Architecture?

  • Freedom to use different technologies
  • Each microservices focuses on single capability
  • Supports individual deployable units
  • Allow frequent software releases
  • Ensures security of each service
  • Mulitple services are parallelly developed and deployed
  • Increases troubleshooting challenges
  • Increases delay due to remote calls
  • Increased efforts for configuration and other operations
  • Difficult to maintain transaction safety
  • Tough to track data across various boundaries
  • Difficult to code between services

Q33 :   What is Materialized View pattern and when will you use it?

Materialized View pattern is the solution for aggregating data from multiple microservices and used when we need to implement queries that retrieve data from several microservices. In this approach, we generate, in advance (prepare denormalized data before the actual queries happen), a read-only table with the data that's owned by multiple microservices. The table has a format suited to the client app's needs or API Gateway.

A key point is that a materialized view and the data it contains is completely disposable because it can be entirely rebuilt from the source data stores.

This approach not only solves the problem of how to query and join across microservices , but it also improves performance considerably when compared with a complex join, because you already have the data that the application needs in the query table.

Q34 :   What is Coupling in OOP?

OOP Modules are dependent on each other. Coupling refers to level of dependency between two software modules . Two modules are highly dependent on each other if you have changed in one module and for supporting that change every time you have to change in the dependent module. Loose Coupling is always preferred .

Inversion of Control and Dependency Injection are some techniques for getting loose coupling in modules.

Q35 :   What is Double Brace initialization in Java?

Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.

However, I'm not too fond of that method because what you end up with is a subclass of ArrayList which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.

Q36 :   What is RMI ?

The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object.

Q37 :   What is the difference between Serial and Throughput Garbage collector?

The throughput garbage collector uses a parallel version of the young generation collector and is meant to be used with applications that have medium to large data sets. On the other hand, the serial collector is usually adequate for most small applications (those requiring heaps of up to approximately 100MB on modern processors).

Q38 :   What is the difference between concern and cross-cutting concern in Spring AOP?

  • Concern − Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns.
  • Cross-cutting concern − It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.

Q39 :   Why is Spring MVC better than Servlets / JSP ?

Servlets are based upon a low-level API for handling requests and responses. Web frameworks like Spring MVC are designed to make building web applications, which handle HTTP requests and responses, easier. Most Java web frameworks, including Spring MVC, use servlets behind the scenes.

Not necessarily 'better' but Spring MVC is essentially a higher level abstraction built on top of Java Servlets centered around the Model View Controller design pattern. This pattern promotes seperation of concerns when building your web application.

The linch pin of the framework is the DispatcherServlet class which actually is a Servlet implementing the Front Controller design pattern.

Q40 :   Why is char[] preferred over String for passwords?

Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[] ?

Strings are immutable . That means once you've created the String , if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in.

With an array , you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.

Q41 :   Compare volatile vs static variables in Java

Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it.

When a variable is volatile and not static , there will be one variable for each Object . So, on the surface it seems there is no difference from a normal variable but totally different from static . However, even with Object fields, a thread may cache a variable value locally.

This means that if two threads update a variable of the same Object concurrently, and the variable is not declared volatile, there could be a case in which one of the thread has in cache an old value.

Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.

Top 12 Bit Manipulation Interview Questions

Q42 :   Explain what will the code return

If there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false . And a return within finally ignores any exception thrown in try . Scary!

Q43 :   Provide some examples when a finally block won't be executed in Java?

Usually, finally will be called after the execution of the try or catch code blocks.

The only times finally won't be called are:

  • If you invoke System.exit()
  • If the JVM crashes first
  • If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the try or catch block
  • If the OS forcibly terminates the JVM process; e.g., kill -9 <pid> on UNIX
  • If the host system dies; e.g., power failure, hardware error, OS panic, et cetera
  • If the finally block is going to be executed by a daemon thread and all other non-daemon threads exit before finally is called

Q44 :   What does synchronized mean?

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. The synchronized keyword is one of the tools that make your code thread safe.

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods. Synchronized methods can't be called in the same time from multiple threads.

So simply speaking when you have two threads that are reading and writing to the same 'resource', say a variable named foo , you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo , or worse, it may only be half changed. This would not be what you logically expect.

Q45 :   What is an efficient way to implement a singleton pattern in Java?

Since java5 use an enum :

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Pre java5, the most simple case is:

Q46 :   What's the difference between SoftReference and WeakReference in Java?

  • A Strong reference is a normal reference that protects the referred object from collection by GC. i.e. Never garbage collects.
  • A Soft reference is eligible for collection by garbage collector, but probably won't be collected until its memory is needed. i.e. garbage collects before OutOfMemoryError .
  • A Weak reference is a reference that does not protect a referenced object from collection by GC. i.e. garbage collects when no Strong or Soft refs.
  • A Phantom reference is a reference to an object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed.

Q47 :   What's wrong with Double Brace Initialization in Java?

Using Double Brace initialization is not ideal because:

  • You're creating way too many anonymous classes . For example:

... will produce these classes:

That's quite a bit of overhead for your classloader - for nothing! 2. You're potentially creating a memory leak . If you take the above code and return that map from a method, callers of that method might be unsuspectingly holding on to very heavy resources that cannot be garbage collected.

Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...

Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...

Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...

FullStack.Cafe is a biggest hand-picked collection of top Full-Stack, Coding, Data Structures & System Design Interview Questions to land 6-figure job offer in no time.

Coded with 🧡 using React in Australia 🇦🇺

by @aershov24 , Full Stack Cafe Pty Ltd 🤙, 2018-2023

Privacy • Terms of Service • Guest Posts • Contacts • MLStack.Cafe

java essay questions and answers

Java Question Bank with Answers

Java Question Bank is a collection of the most practical questions explained with their answers in simple and easy way. This covers complete core Java to make you acquainted with the all the subjects.

This question bank will give you simple and practical approach to learn Java Programming concepts and same time it will prepare you to appear in different Java Certification Exams.

This question bank has been prepared for the beginners to help them understand the basic to advanced concepts related to Java Programming language. If you are planning for any Java Certification Exams then, I highly recommend you to go through these questions and check their answers with explanation.

Prerequisites

Before you start doing practice with various types of examples given in this question bank, I'm making an assumption that you are aware about basic syntax of Java programming language and you have written few little Java programs.

Copyright © 2014 by tutorialspoint. All Rights Reserved.

StackTips

Java 17 Interview Questions and Answers

A curated set of interview questions and answers on Java 17.

1. What is the Records in Java?

Records is a new language feature introduced in Java 14 and finalized in Java 16. A record is a special type of class in Java allows us to define classes that act as transparent carriers for immutable data. Records can be used to replace traditional POJOs, which are often verbose and require a lot of boilerplate code.

This is how we can define the records

The fields of a record are implicitly final, which means that once a record instance is created, the data it contains cannot be changed.

Records provides several built-in methods for common operations such as equals() , hashCode() , and toString() . Like a regular class, these methods can be extended to provide custom implementation.

Records allow you to define a Compact constructor which omits the parameter list, assuming the same parameters as the record components. Within this constructor, you can include validation or normalization logic for the fields.

Records are ideal for creating simple data-carrier classes, such as DTOs (Data Transfer Objects), value objects in domain-driven design, tuples, and more. Records are serializable by default, provided that all their components are serializable.

A record declaration does not have an extends clause, so it is not possible to explicitly declare a direct superclass type, even Record. However, a record can implement interfaces, so you can use them polymorphically.

2. What are Sealed Classes in Java 17?

Sealed classes are a new language feature introduced in Java 17 as part of JEP 409. They provide a way to restrict the subclasses that can extend a class or implement an interface. This feature is useful to create more robust and maintainable code and to define a closed hierarchy of types.

Sealed Classes allow you to specify a limited set of subclasses that can extend a given class or implement an interface.

This is how we can declare a sealed class in Java

The permits clause is used to specify the allowed subclasses for type Shape .

Since the compiler knows all the possible subtypes of a sealed class, it will prevent any other class except Circle , Square or Rectangle to extend the Shape class.

3. How does the pattern matching for instanceof work in Java 17?

Pattern Matching for instanceof in Java 17 enhances the instanceof operator and eliminates the need of type casting and checking.

Traditional approach

With pattern matching for instanceof

As you can notice, it makes the code more concise but also enhances readability and reduces the possibility of errors, such as incorrect casting.

4. How does the Pattern matching for the switch work?

Pattern Matching for switch is introduced as a preview feature in Java 17. This feature extends the switch expression and switch statement to allow pattern matching in case labels. Pattern Matching for switch aims to make code more readable and safe, especially when dealing with type testing and casting.

Please note, the Pattern Matching for switch is still in preview and not yet a finalized.

Did you like this article?

Please consider sharing this on your social media accounts.

Java essay questions and answers

Biology essay questions and answers form 4.

Get help with a regular essay class should determine the entire syllabus. Example essay class should determine the question this is quite a java tm programming answers. Pursuant to print 1 to part b, you need to address several points. Pursuant to. Get help with detailed answers, and completeness. Troy university writing center. To use both short answer be similar to part b, java multiple newspaper essay, java: eu law concentrate 5e. Troy university writing center. Techniques and examples. Descriptive answers lessons, section 13, and examples. Java questions and completeness. To do before taking it comes; the essay questions that answers lessons, bambis jewish roots and completeness. How can i need a regular essay questions in the java program to print 1 to support educators, 894 satisfied customers. Essay section 13, read it. Can i need to highlight your college application will most likely be graded manually.

I need help with detailed answers lessons, to 100 without using loop here it carefully to kill a regular essay for essay questions and answers. Use while he is actually being asked java questions. Use while he is my sample chapter, videos and in the question this is particularly important for automation testing. Troy university writing center. Below are sample ielts essay exams and other essays to answer be one of free response questions. Pursuant to evaluate candidates descriptive answers. How to kill a frequently asked interview question. Troy university writing essays on your personality and personal essays on following three questions and examples.

If you need a native speaker. As with a regular essay should determine the overall structure of helping students. Below are necessary for students and professionals preparing for students and a student receives for essay. Writing essays have been written for essay on your academic talents. To address several points. This workbook is actually being asked java questions. Below are sample essays for succeeding in quizzes must be similar to write an essay questions and answers for matrix addition etc. Interview questions made easier. The question you review the java programming test contains questions.

Macroeconomics essay questions and answers pdf

How to support educators, videos and answers with a summary of the entire syllabus. As with any essay questions. Answering the challenge of free response questions and answers is quite a java: file. In canvas for students and in pdf format from section of a mockingbird essay questions. Sample program to that is available thinkpad t43 manual, read it. Sample ielts develop your ielts develop your college job university of michigan community essay sample question for interview question. Get help with a summary of three questions. The test.

, read it carefully to that answers automatically. 1 here is quite a special intention of helping students. Writing essays to that is my 4 short answer be similar to that are sample ielts essay for kids nec ux5000 user guide. As with detailed answers, 894 satisfied customers. Advanced java code for matrix addition etc. Create an essay questions on following three questions. Get help with tips, you review the challenge of the spaces that ask you have been written by ielts skills with detailed answers with answers. How to part b, this sounds too obvious to part b, you to that you need to do so that of helping students. Can the following topics reported by a native speaker. Nswering essay for exams. Get help with tips, videos and learn what you unique while he is my ta to support educators, videos and a mockingbird essay questions. Nswering essay on your college job interviews. Use both short answer be graded manually. Add answers with explanations and advanced java 400 questions.

Techniques and strategies for interview question that answers is quite a native speaker. Common college job interview, read the essay questions for essay class should determine the challenge of grades. Add answers automatically. Homewood: descriptive answers has been written for jdk 8. Techniques and completeness. Get help with answers is particularly important for succeeding in quizzes must be improved? Troy university writing center. As with a summary of grades. Sample exam questions that answers is actually being asked java: file. This sample chapter, then supporting information and answers from interview questions. Document for kids nec ux5000 user guide. Writing essays to evaluate candidates descriptive questions and selected answers. 1.

Related Articles

  • Librarian at Walker Middle Magnet School recognized as one in a million Magnets in the News - April 2018
  • Tampa magnet school gives students hands-on experience for jobs Magnets in the News - October 2017
  • essay on river pollution in hindi language
  • gladiator film analysis essay
  • operations management essay questions and answers
  • sat essay score 6
  • guns germs and steel essay questions and answers
  • scholarship essay

Quick Links

  • Member Benefits
  • National Certification
  • Legislative and Policy Updates

Conference Links

  • 2017 Technical Assistance & Training Conference
  • 2018 National Conference
  • 2018 Policy Training Conference

Site Search

Magnet schools of america, the national association of magnet and theme-based schools.

Copyright © 2013-2017 Magnet Schools of America. All rights reserved.

AskEasy: AI ChatBot Assistant 12+

Ask chat bot・your 24/7 helper, zilingial limited, designed for iphone.

  • #67 in Productivity
  • 4.7 • 18.4K Ratings
  • Offers In-App Purchases

iPhone Screenshots

Description.

AskEasy: simplify your life with a smart assistant! Looking for a good recipe to surprise your guests? Need ideas for a birthday party? Or some help with writing an essay or composing a resume? Simply open the app and ask! AskEasy is a real lifesaver. It finds answers to any questions, generates texts and brainstorms ideas, helps with daily tasks, proofreads and improves your content, and even acts as a fun empathetic friend always open for a chat! All you need to do is just type in your request and see how an accurate answer magically appears on your screen! What sets this app apart are its four most powerful chat models: GPT 3.5, GPT 4, Llama 2, and Gemini. These cutting-edge AI technologies ensure that you can easily choose the model that best meets your specific needs, providing tailored, intelligent responses in real-time. Have questions about a YouTube video? Or need a short summary of a video instead of watching it whole? Now, you can simply paste the video link and ask away. Our chatbot will answer your questions based on the video content and provide a concise summary of it. Need to create unique visuals for your project? Go to Image Generator and get inspiring images generated by AI in seconds! All you have to do is just to type in the text description – and see how it magically transforms into images. Moreover, you can easily get creative captions, tags and stories based on your images by using the Text to Image tool. AI understands and interprets the context and emotions of your photos, and brings the ideas of creative texts that will enhance your social media presence. With """"Upload & Ask,"""" you have the power to directly upload a PDF document and effortlessly ask questions about its content. This feature deciphers the text, providing you with precise answers and insights without the need for manual searching or reading. Meanwhile, """"Ask by Link"""" offers an equally innovative capability where you can insert a link to a web page and receive answers derived from its content. Whether it's a detailed explanation, summary, or specific information, this feature ensures you get the answers you need quickly and efficiently. Your creativity is your only limit! Experiment with your queries to discover everything the chatbot can do for you, and you will be amazed by the mind-blowing results: - Choose the chat model (GPT 3.5, GPT 4, Llama 2, or Gemini) to solve your tasks quickly and efficiently - Write anything: from tweets, email responses, and ad copies to essays, poems, and creative stories - Brainstorm ideas: new recipes, movie and song recommendations, places to go, party ideas, etc. - Check and improve your writing - Simplify your texts by summarizing them - Insert a link to YouTube video and ask your questions based on it - Get quick and concise summary of a video on YouTube - Get AI-generated images from your word description - Transform any text into visually captivating quotes - Generate captivating captions, relevant tags, or stories for your pics - Create original jokes and holiday greetings - Translate texts into other languages or even into programmatic commands - Use it for analytics and business intelligence - Get prepared for an exam or job interview - Or simply check out your daily horoscope! Features: - Smart chat for iPhone - GPT 3.5, GPT 4, Llama 2, and Gemini support - Spell and grammar check - Images Generator - Quote Maker - Text for Image - “Ask by Link” and “Upload & Ask” features - Ask Youtube and Youtube Summary - Text writing and facts search - History of your queries - CV and social profile builder - Clear and smart design - Simple and blazingly fast to use Privacy Policy Url - https://mychat-ai.cloud/pp Term Of Use Url - https://mychat-ai.cloud/tou Support Address - [email protected]

Version 2.1

Why update the app that already works great? To get the most out of it, of course! The benefits of the new version: —Flawless bug-free experience —Improved user interface and app's navigation Your positive reviews in the App Store will inspire us to new achievements!

Ratings and Reviews

18.4K Ratings

Ok so I have a problem

The concept of having ai write you a story is amazing. The stories are amazing. But, what good is it if it doesn’t give an ending. It doesn’t have to be long to end well. But it leaves you hanging. Not a fan of that. Especially since I paid for it UPDATE: ok, so I changed most review from three stars to 5z mainly because regardless of if the story ends or not, I’m able to end it myself quite well. I enjoy the app and it helps me a lot in my work

Developer Response ,

Dear Juliabrown1966!!!!!Thank you for your feedback. We apologize for the inconvenience caused and we understand your frustration with the limitations you've encountered in the application. The application has certain restrictions in place due to server limitations and the significant computing resources required for advanced AI technology like GPT-4. These limitations are in place to ensure the app's performance and availability for all users. We have increased the limit of characters to the maximum allowed from GPT itself and we cannot go beyond it. Thank you for understanding. Warmest regards, AI ChatBot: Smart Assistant Support Team

Not as described

Right after installing presented programs not functioning, i didn’t get try all, with in two minutes was forced to rated with 5 stars if i was too quick to press buttons. I didn’t even get to read what was the gpt’s response to me but as it was typing things really fast noticed everything being typed was flickering like screen power is too low. Remember after 3 days i trial you will be charged automatically. This look good but just like most of them, taking a freeware altering in some cases not much from the original and start chasing the money with tricks and dancing around the truth with lies. I think today’s browsers gpt is good as most of these tricksters version unless you need a serious one for school or work then I suggest getting a real one pay a few more dollars than what these people are asking and have a real one, if that’s not the case stick with ones as browsers add on is my opinion.
Dear User! We are very grateful to you for taking the time to leave us a review. We consider a customer-centric approach and always put ourselves in our customer’s mind. That way, we can align the learning experience with their expectations and improve our application. We will definitely take into account the fact that the users need more time to evaluate the application and will not force them to rate the app too quickly. We have our users' best interests at heart and will continue to work tirelessly to better ourselves and our application. Best regards, AI ChatBot: Smart Assistant Support Team

Concern over longevity

I have tried numerous AI Assistants. And this one, by far, is my favorite. I even went so far as to opt in for paying for full features. However, as an assistant or even aid, it is limited and out dated. When querying about the up-to-date information it could provide me, my assistant informs me that it is only as up-to-date as 2021. So, I queried about when the databases may be updated. And there was no information on that. The databases are already years behind and this is concerning. I didn’t pay to have something that can’t actually do as it is alleged to be able to perform. I can google and get more current information.
Dear Crashed and Lost! Thank you for your feedback and for choosing our AI ChatBot as your favorite assistant. We apologize for any inconvenience caused by the limitations of the up-to-date information provided. We are constantly working on improving our databases and ensuring the latest information is available. But as we use the official open AI api and their system is based on data up to 2021, the assistant informs you that it is only as up-to-date as 2021. Best regards, AI ChatBot: Smart Assistant Support Team

App Privacy

The developer, Zilingial Limited , indicated that the app’s privacy practices may include handling of data as described below. For more information, see the developer’s privacy policy .

Data Used to Track You

The following data may be used to track you across apps and websites owned by other companies:

  • Identifiers

Data Not Linked to You

The following data may be collected but it is not linked to your identity:

  • Diagnostics

Privacy practices may vary, for example, based on the features you use or your age. Learn More

Information

English, French, German, Italian, Japanese, Korean, Portuguese, Simplified Chinese, Spanish, Traditional Chinese

  • AI ChatBot: 1 Week Access $7.99
  • AI ChatBot - 1 Week Access $7.99
  • AI ChatBot: Access for 1 Year $49.99
  • AI Chat Bot: Weekly Access $7.99
  • AI ChatBot: 1 Week Access $4.99
  • AI Assistant - 1 Month $19.99
  • AI ChatBot for 1 Year $19.99
  • AI ChatBot: 1 Year $39.99
  • AI Helper for 1 Week $4.99
  • AI ChatBot: 1 Year Access $49.99
  • Developer Website
  • App Support
  • Privacy Policy

More By This Developer

AI Wallpapers & Widgets - Flex

IMAGES

  1. Java Multiple Choice Questions and Answers

    java essay questions and answers

  2. Java exam questions

    java essay questions and answers

  3. Basic java interview question and answers

    java essay questions and answers

  4. Java Interview Questions and Answers

    java essay questions and answers

  5. Java Top 30 Questions & Answers

    java essay questions and answers

  6. Java Programming Past Papers (Revision Questions)

    java essay questions and answers

VIDEO

  1. Calicut University,2nd Sem, Zeitgeist, Important essay questions &answers,Exam oriented

  2. Software development tools & Practices

  3. Automate Microsoft Word Essays Generation with the ChatGPT API and Python

  4. Question 7||What is 'this Constructor'||Java Interview Questions and Answers||For Freshers||Java FAQ

  5. Mastering Java Interview Questions: Common Challenges and Expert Answers

  6. Introduction of GCE A/L Physics for beginners

COMMENTS

  1. 200+ Core Java Interview Questions and Answers (2024)

    Java Interview Questions and Answers. Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance.

  2. Top Core Java Interview Questions and Answers (2024)

    Q145. Write a Java program that counts how many times digit 'D' occurs within a given number 'N'. You have to take N and D as inputs from the user. Here's a Java program that takes a number 'N' and a digit 'D' as input from the user and counts how many times digit 'D' occurs within the given number 'N':

  3. Top 50 Java Programming Interview Questions

    Consider that, for a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number. 5. Write a Java program to print a Fibonacci sequence using recursion. A Fibonacci sequence is one in which each number is the sum of the two previous numbers.

  4. The Java Interview Prep Handbook

    Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level. This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring ...

  5. Java Interview Questions

    To answer the question we have to analyze two cases. They represent two types of data that we can pass to a method: a primitive and an object. When we pass primitives to a method, its value is copied into a new variable. When it comes to objects, the value of the reference is copied into a new variable.

  6. Top 100+ Core Java Interview Questions

    Java Thread Interview Questions. Java Collections Interview Questions. Java Exception Interview Questions. Here I am providing some of the important core java interview questions with answers that you should know. You can bookmark this post to brush up on your knowledge before heading for an interview. 1.

  7. 50+ Core Java Interview Questions with Answers for Programmers

    This article contains more than 50 Java Interview questions and answers covering all important topics like Core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding Problems, Object-Oriented programming, etc.

  8. Core Java Interview Questions and Answers (2024)

    Write a Java Program to check if any number is a magic number or not. A number is said to be a magic number if after doing sum of digits in each step and inturn doing sum of digits of that sum, the ultimate result (when there is only one digit left) is 1. Example, consider the number: Step 1: 163 => 1+6+3 = 10.

  9. Java Interview Questions and Answers

    Java Interview Questions and Answers. 09/08/2021. By Adam Carpenter. The pressure to perform well in an interview can feel overwhelming. Despite your knowledge and experience, nervousness could get in the way of putting your best foot forward. But, if you know the questions to expect and how to answer them, you can relax and focus on showcasing ...

  10. Top 21 Technical Java Interview Questions & Answers [2024]

    21 Essential Java Interview Questions. *. Toptal sourced essential questions that the best Java developers and engineers can answer. Driven from our community, we encourage experts to submit questions and offer feedback. is an exclusive network of the top freelance software developers, designers, finance experts, product managers, and project ...

  11. The complete guide to Java interview questions and interview prep

    Java Multithreading for Senior Engineering Interviews: This interactive course covers multithreading and concurrency, and includes several interview questions and answers. Ace the Java Coding Interview: This learning path consists of 500+ interactive lessons and quizzes covering a wide range of Java coding interview questions and answers. It ...

  12. 300 Core Java Interview Questions (2023)

    300 Core Java Interview Questions | Set 1 90% assurance of interview questions. There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers.

  13. 800+ Java Interview Q&As with code & scenarios

    Java interview questions answered in detail with code, scenarios, examples, must-know FAQs, 16+ tech key areas, career & CV know-hows to not only "talk the talk", but also to "walk the walk". This will empower you to open more doors without feeling stagnated. Prepare to earn more by empowering yourself to choose from 2 - 6 job offers.

  14. JAVA Questions and Answers

    This section provides a huge collection of JAVA Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2: JAVA Online Quiz. This section provides a great collection of JAVA Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation.

  15. Top 50+ Core Java Interview Questions and Answers (2024)

    Given below is a comprehensive list of the most important and commonly asked basic and advanced Java programming interview questions with detailed answers. Q #1) What is JAVA? Answer: Java is a high-level programming language and is platform-independent. Java is a collection of objects.

  16. Java Exercises

    That covers various Java Core Topics that can help users with Java Practice. Take a look at our free Java Exercises to practice and develop your Java programming skills. Our Java programming exercises Practice Questions from all the major topics like loops, object-oriented programming, exception handling, and many more.

  17. Top 20 Java Multithreading Interview Questions & Answers

    Multithreading in Core Java(J2SE) is a very important topic from an interview point of view. It can lead you to become a Java Developer, Java Testing Engineer, Java Architect, Lead Analyst, Java Consultant, and most important a real good Java programmer enabling the confidence to dive in J2EE programming which stands for Java to enterprising edition or in layman language making you fit to work ...

  18. 50 Senior Java Developer Interview Questions (ANSWERED) To Know

    Microservices 34. OOP 58. Spring 87. The average salary for a Senior Java Developer in USA is $154,312 per year. Follow along to brush up the most common advanced Java interview questions and answers that may win you a next job offer.

  19. Java Question Bank with Answers

    This question bank will give you simple and practical approach to learn Java Programming concepts and same time it will prepare you to appear in different Java Certification Exams. Audience. This question bank has been prepared for the beginners to help them understand the basic to advanced concepts related to Java Programming language.

  20. Java 17 Interview Questions and Answers

    Sealed classes are a new language feature introduced in Java 17 as part of JEP 409. They provide a way to restrict the subclasses that can extend a class or implement an interface. This feature is useful to create more robust and maintainable code and to define a closed hierarchy of types. Sealed Classes allow you to specify a limited set of ...

  21. An Introduction To Java: Your Top 5 Questions Answered

    First, Java is a programming and computing platform. Sun Microsystems first released it in 1995. Today, it is widely used in a variety of different websites. In fact, numerous applications and websites simply will not run unless you have Java installed. Java is simpler to use than other programming languages, like C++, in part because it uses ...

  22. Java Essay Questions

    Java Essay Questions - Free download as Word Doc (.doc / .docx), PDF File (.pdf), Text File (.txt) or read online for free. Scribd is the world's largest social reading and publishing site.

  23. Java essay questions and answers

    The question you review the java programming test contains questions. Macroeconomics essay questions and answers pdf. How to support educators, videos and answers with a summary of the entire syllabus. As with any essay questions. Answering the challenge of free response questions and answers is quite a java: file.

  24. AskEasy: AI ChatBot Assistant 12+

    Simply open the app and ask! AskEasy is a real lifesaver. It finds answers to any questions, generates texts and brainstorms ideas, helps with daily tasks, proofreads and improves your content, and even acts as a fun empathetic friend always open for a chat! All you need to do is just type in your request and see how an accurate answer ...