Java Interview Questions

Programming languages or concepts
0

 In This post will cover all the popular Core Java interview questions for freshers and experienced candidates in depth. Go through all the questions to enhance your chances of performing well in the interviews. The questions will revolve around the basic and core fundamentals of Java.

Java was developed as an open-source and platform-independent programming language by Sun Microsystems in the year of 1995.


For Downloading this OOP'S interview questions as a PDF please Click


1. What are the key differences between C++ and Java?

        

C++

Java

1) C++ is platform dependent.      

1) Java is platform-independent.

2) C++  writes structural programs without using classes and objects.

2) Java is a pure object-oriented language except for the primitive variables.

3) C++ doesn’t support documentation comments.

3) Java supports documentation comment  to create documentation for java code.

4) C++ fully supports pointers.

4) In Java, there is no concept of pointers.

5) C++ supports multiple inheritance.

5) Java doesn’t support multiple inheritance.

2. List the features of the Java Programming language?

A few of the significant features of Java Programming Language are:

  • Easy: Java is a language that is considered easy to learn. One fundamental concept of OOP Java has a catch to understand.
  • Secured Feature: Java has a secured feature that helps develop a virus-free and tamper-free system for the users.
  • OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in Java, everything is considered an object.
  • Independent Platform: Java is not compiled into a platform-specific machine; instead, it is compiled into platform-independent bytecode. This code is interpreted by the Virtual Machine on which the platform runs.

3. Why is Java a platform independent language?

Java language was developed in such a way that it does not depend on any hardware or software due to the fact that 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.


4. 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.

5. Difference Between  JDK And JRE ?


JDK

JRE

Abbreviation for Java Development Kit

Abbreviation for Java Runtime Environment

JDK is a dedicated kit for solely software development

JRE is a set of software and library designed for executing Java Programs

Unlike JVM, JDK is Platform Dependent

Unlike JVM, JRE is also Platform Dependent

JDK package is a set of tools for debugging and Developing

JRE Package is one that only supports files and libraries for a runtime environment 

JDK package will be provided with an installer file

JRE Package does not get an installer but has only a runtime environment

 

6. Which class is a superclass of all classes?

     Java.lang.The object is the root class for all the java classes and we don’t need to extend it. Every other java classes fall back under the object. All the different non-primitive types including arrays are inherited directly or indirectly from this class.

7. What are finally and finalize in Java?

    Finally block is used with a try-catch block to put the code that you always want to get executed even the execution is thrown by the try-catch block.  Finally is just used for releasing the resources which were created by the try block.
Finalize() is a special method in Object class that we can override in our classes. Finalize() is called by the Garbage collector to collect the garbage value when the object is getting it. This method is generally overridden to release the system resources when garbage value is collected from the object.

8. 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.
Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
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.
Example:
public void athlete() {
String athleteName;
double athleteSpeed;
int athleteAge;
}


9. Can you tell the difference between equals() method and equality operator (==) in Java?

equals() 

==

This is a method defined in the Object class. 

It is a binary operator in Java.

This method is used for checking the equality of contents between two objects as per the specified business logic.

This operator is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.

 


10.  What is the static keyword?
     The static keyword is used with a class level variable to make it global so all the objects will be able to share the same variable. It can also be used with methods. A static method can access only static variables of the class and invoke only a static method of the class.
The interview generally asks this question in the Java interview questions for freshers. Even if you are a fresher, you should have a good knowledge of the keywords in Java.


11. 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.

12. 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.

13. 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.


14. 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

15. What are the Memory Allocations available in Java ?

Java has five significant types of memory allocations.
  • Class Memory
  • Heap Memory
  • Stack Memory
  • Program Counter-Memory
  • Native Method Stack Memory

16. What is break and continue statement?

     In a while or do-while loop, we use break for a statement to terminate the loop. We use a break statement in a switch statement to exit the switch case. We can also use break statement for terminating the nested loop.

17. What is Type casting in Java?

     Casting in Java is one of the top topics from where you can get questions in your interview. When we assign a value of one data type to a different data type then these two data types might not be compatible with each other and needs conversion. If data types are compatible with each other like, in case of the conversion of int value to long then automatic conversion is done by Java and doesn’t require typecasting. But if data types are not compatible with each other then they need to be cast for conversion.
Syntax:
dataType variablename = (dataType) variableToConvert;


18. Define Copy Constructor in Java ?

A Copy Constructor in Java is a constructor that initializes an object through another object of the same class.

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

Stack is generally used to store the order of method execution and local variables. In contrast, Heap memory is used to store the objects. After storing, they use dynamic memory allocation and deallocation.


20. Why is Java not completely object-oriented?

Java is not considered as a 100% object-oriented programming language because it still makes use of eight or more primitive data types like int, float double, etc.

21. What is Object Cloning?

An ability to recreate an object entirely similar to an existing object is known as Object Cloning in Java. Java provides a clone() method to clone a current object offering the same functionality as the original object.


22. Define Wrapper Classes in Java?

In Java, when you declare primitive datatypes, then Wrapper classes are responsible for converting them into objects(Reference types). 

23. What is an object-oriented paradigm?

A Paradigm that is based on the concepts of “Objects.” It contains data and code. Data that is in the form of fields, and regulation, that is in the form of procedures. The exciting feature of this paradigm is that the object’s procedures can access and often modify the data fields themselves.

24. 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.
final variable:
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.
final method:
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
final class:
No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

25. Define Singleton Classes in Java?

In Java, when you make the constructor of a class private, that particular class can generate only one object. This type of class is popularly known as a Singleton Class.


26. What happens when an exception is thrown by the main method?

     When an exception is thrown by the main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

27.  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.
Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions.
  Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented.

28. 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.


29. 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.

30. 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.


31. What part of memory - Stack or Heap - is cleaned in garbage collection process?

Heap

32. 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.

33. 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;

34. Define package in Java ?

The package is a collective bundle of classes and interfaces and the necessary libraries and JAR files. The use of packages helps in code reusability.

35. Differentiate between instance and local variables ?

For instance, variables are declared inside a class, and the scope is limited to only a specific object.
A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the code segment where the variable is declared. 

36. Can you implement pointers in a Java Program ?

Java Virtual Machine takes care of memory management implicitly. Java's primary motto was to keep programming simple. So, accessing memory directly through pointers is not a recommended action. Hence, pointers are eliminated in Java. 

37. What is an Exception ?

An Exception in Java is considered an unexpected event that can disrupt the program's normal flow. These events can be fixed through the process of Exception Handling

38. Explain Java String Pool ?

A collection of strings in Java's Heap memory is referred to as Java String Pool. In case you try to create a new string object, JVM first checks for the presence of the object in the pool. If available, the same object reference is shared with the variable, else a new object is created.

39. What is the final keyword in Java ?

The term final is a predefined word in Java that is used while declaring values to variables. When a value is declared using the final keyword, then the variable's value remains constant throughout the program's execution.


40. What makes a HashSet different 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.

41. What are the differences between JVM, JRE and JDK in Java?

    

Criteria

JDK 

JRE

JVM

Abbreviation

Java Development Kit

Java Runtime Environment

Java Virtual Machine

Definition

JDK is a complete software development kit for developing Java applications. It comprises JRE, JavaDoc, compiler, debuggers, etc.

JRE is a software package providing Java class libraries, JVM and all the required components to run the Java applications.

JVM is a platform-dependent, abstract machine comprising of 3 specifications - document describing the JVM implementation requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution

Tools provided

JDK provides tools like compiler, debuggers, etc for code development

JRE provides libraries and classes required by JVM to run the program.

JVM does not include any tools, but instead, it provides the specification for implementation.

Main Purpose

JDK is mainly used for code development and execution.

JRE is mainly used for environment creation to execute the code.

JVM provides specifications for all the implementations to JRE.

 

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

HashMap

HashTable

HashMap is not synchronized thereby making it better for non-threaded applications.

HashTable is synchronized and hence it is suitable for threaded applications.

Supports order of insertion by making use of its subclass LinkedHashMap.

Order of insertion is not guaranteed in HashTable.

Allows only one null key but any number of null in the values.

This does not allow null in both keys or values.

 

43. What are the differences between constructor and method of a class in Java?

 

Constructor

Method

Constructor is used for initializing the object state.

Method is used for exposing the object's behavior.

Constructor gets invoked implicitly.

Method has to be invoked on the object explicitly.

Constructor has no return type.

Method should have a return type. Even if it does not return anything, return type is void.

If the constructor is not defined, then a default constructor is provided by the java compiler.

If a method is not defined, then the compiler does not provide it.

The constructor name should be equal to the class name.

The name of the method can have any name or have a class name too.

 

44. 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().

45. 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.
  • Non-Runnable (Blocked/Waiting) :- When the thread is not able to run despite the fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally, after some time of its aliveness, the thread should go to a runnable 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.

46.What is the difference between JDK, JRE, and JVM?

JVM has a Just in Time (JIT) compiler tool that converts all the Java source code into the low-level compatible machine language. Therefore, it runs faster than the regular application.
JRE has class libraries and other JVM supporting files. But it doesn’t have any tool for java development such as compiler or debugger.
JDK has tools that are required to write Java Programs and uses JRE to execute them. It has a compiler, Java application launcher, and an applet viewer.

47. Explain Access Specifiers and Types of Access Specifiers?

Access Specifiers are predefined keywords used to help JVM understand the scope of a variable, method, and class. We have four access specifiers.
  • Public Access Specifier 
  • Private Access Specifier 
  • Protected Access Specifier 
  • Default Access Specifier

48. How many types of constructors are used in Java?

There are two types of constructors that are used in Java.
  • Parameterized Constructors: 
  • Default constructors:

  1. Parameterized Constructors: 
        Parameterized constructor accepts the parameters with which users can initialize the instance variables. Users can initialize the class variables dynamically at the time of instantiating the class.

      2.Default constructors:-

        This type doesn’t accept any parameters; rather, it instantiates the class variables with their default values. It is used mainly for object creation.


49. Explain ‘super’ keyword in Java?

The term "super" is a particular keyword designated as a reference keyword. The "super" keyword refers to the immediate parent class object.


50. Can a constructor return a value?

Yes, A constructor can return a value. It replaces the class's current instance implicitly; you cannot make a constructor return a value explicitly.

51. Explain Method Overloading in Java.

The process of creating multiple method signatures using one method name is called Method Overloading in Java. Two ways to achieve method overloading are:
  • Varying the number of arguments.
  • Changing the return type of the Method .

52. Define Late Binding ?

Binding is a process of unifying the method call with the method's code segment. Late binding happens when the method's code segment is unknown until it is called during the runtime. 

53. Explain ‘this’ keyword in Java ?

The term "this" is a particular keyword designated as a reference keyword. The "this" keyword is used to refer to the current class properties like method, instance, variable, and constructors.

54. Can we overload a static method?

No, Java does not support the Overloading of a static method. The process would throw an error reading "static method cannot be referenced."

55. Give a briefing on the life cycle of a thread ?

The life cycle of a thread includes five stages, as mentioned below.
  • New Born State
  • Runnable State
  • Running State
  • Blocked State
  • Dead State

56. Define Dynamic Method Dispatch ?

The Dynamic method dispatch is a process where the method call is executed during the runtime. A reference variable is used to call the super-class. This process is also known as Run-Time Polymorphism

57. Explain the difference between >> and >>> operators ?

Although they look similar, there is a massive difference between both.
  • >> operator does the job of right shifting the sign bits
  • >>> operator is used in shifting out the zero-filled bits

58. Can you run a code before executing the main method?

Yes, we can execute any code, even before the main method. We will be using a static block of code when creating the objects at the class's load time. Any statements within this static block of code will get executed at once while loading the class, even before creating objects in the main method.

59. How many times is the finalize method called?

The finalize method is called the Garbage collector. For every object, the Garbage Collector calls the finalize() method just for one time.

60. What is JDBC?

JDBC is an abbreviation for Java Database Connector.
JDBC is an abstraction layer used to establish connectivity between an existing database and a Java application


Post a Comment

0Comments

Post a Comment (0)
close