Bytes
Computer Science

Top 100 Java Interview Questions and Answers for 2024

Last Updated: 8th January, 2024
icon

Ritu Verma

Web Development Consultant at almaBetter

Discover essential core Java Interview Questions and Answers (2024). From core concepts to advanced topics, prepare for your interviews with Java fundamentals.

Whether you're a fresh graduate looking for your first job or an experienced professional aiming to advance your career, these interview questions on Java will test your knowledge, problem-solving abilities, and understanding of Java’s best practices. We have carefully selected questions covering various aspects of Java, from fundamental concepts to advanced topics.

Throughout this article, you'll explore Java basics interview questions, core Java interview questions, java programming interview questions, and more. Each question challenges you and encourages you to think critically about Java programming.

Java interview questions for freshers and Java interview questions for experienced are included, ensuring a comprehensive coverage of topics such as syntax, object-oriented programming principles, exception handling, multithreading, memory management, and more. Dive into this resource to enhance your preparation for Java interviews and gain a deeper understanding of the language.

Q1. What is Java?

Answer. Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle Corporation) in 1995. It is designed to be platform-independent, allowing Java programs to run on any system with a Java Virtual Machine (JVM).

Q2. List the features of Java Programming language.

Answer. There are many features Java provide, as given below:

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes it 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 types 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 secure.
  • 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.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • 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 multimedia, Web applications, etc.

Q3. What do you understand by Java Virtual Machine?

Answer. Java Virtual Machine (JVM) is an abstract machine that enables the execution of Java programs. It interprets and executes Java bytecode, converting the Java code into bytecode for platform-independent execution.

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

Answer. The main difference between the three of them is given below:

  • VM (Java Virtual Machine): Abstract machine providing the runtime environment.
  • JRE (Java Runtime Environment): Implementation of JVM. It includes libraries and files required for runtime.
  • JDK (Java Development Kit): Software development environment containing JRE and development tools.

Q5. How many types of memory areas are allocated by JVM?

Answer. JVM allocates memory in several areas:

  • 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 is complete.
  • Program Counter Register: The 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.

Q6. What is abstraction?

Answer. Abstraction is the process of hiding implementation details and showing only the functionality to the user. It allows focusing on what an object does rather than how it achieves its functionality.

Q7. What is a JIT compiler?

Answer. JIT (Just-In-Time) compiler is used to improve performance by compiling parts of bytecode with similar functionality at runtime. It translates Java bytecode into machine code for efficient execution.

Q8. What is the platform?

Answer. A platform is the hardware or software environment in which software is executed. Java provides a software-based platform that is independent of the underlying hardware.

Q9. What are the main differences between the Java platform and other platforms?

Answer. Java is a software-based platform executed on top of other hardware platforms, while other platforms can be either hardware or software-based.

Q10. What gives Java its 'write once and run anywhere' nature?

Answer. The 'write once and run anywhere' nature of Java is attributed to bytecode. Java compiler converts programs into bytecode, which is platform-independent and can be executed on any computer with a Java Virtual Machine (JVM).

Q11. What is a classloader?

Answer. Classloader is a subsystem of JVM used to load class files. There are three built-in classloaders in Java: Bootstrap ClassLoader, Extension ClassLoader, and System/Application ClassLoader.

Q12. Is an Empty .java file name a valid source file name?

Answer. Yes, Java allows saving a Java file with the name .java. It can be compiled using `javac .java` and run using `java classname`.

Q13. Is delete, next, main, exit, or null a keyword in Java?

Answer. No.

Q14. If I don't provide any arguments on the command line, what will the value stored in the String array passed into the main() method, empty or NULL?

Answer. It is empty, but not null.

Q15. What if I write static public void instead of public static void?

Answer. The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

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

Answer. Local variables are not initialized to any default value, neither primitives nor object references.

Q17. What are the various access specifiers in Java?

Answer In Java, there are four access specifiers: Public, Protected, Default, and Private.

Q18. What is the purpose of static methods and variables?

Answer. Static methods and variables are shared among all objects of the class. They are part of the class, not the object, and are used when defining elements common to all objects.

Q19. What are the advantages of Packages in Java?

Answer. The advantages of Java are listed below:

  • Packages avoid name clashes.
  • Packages provide easier access control.
  • Hidden classes can be defined within packages.
  • It is easier to locate related classes.

Q20. What is the output of the following Java program?

Loading...

Answer.

30Javatpoint
Javatpoint1020

Explanation: In the first case, numerical addition is performed before string concatenation. In the second case, string concatenation starts with the first string encountered.

Q21. What is the output of the following Java program?

Loading...

Answer.

200Javatpoint
Javatpoint200

Explanation: In the first case, numerical multiplication is performed before string concatenation. In the second case, string concatenation starts with the first string encountered.

Q22. What is the output of the following Java program?

Loading...

Answer. The above code will give a compile-time error because the for loop expects a boolean value in the second part, and an integer value (i.e., 0) is provided.

Q23. What is object-oriented paradigm?

Answer. Object-oriented paradigm is a programming paradigm based on objects having data and methods defined in the class to which it belongs. It aims to incorporate modularity and reusability, focusing on data with methods to operate upon the object's data.

Q24. What is an object?

Answer. An object is a real-time entity with some state and behavior. In Java, an object is an instance of a class with instance variables representing its state and methods representing its behavior. Objects are created using the new keyword.

Q25. What is the difference between an object-oriented programming language and an object-based programming language?

Answer. Object-oriented languages follow all OOPs concepts, while object-based languages don't necessarily implement all OOPs concepts like inheritance and polymorphism. Examples of object-oriented languages include Java and C#, while object-based languages include JavaScript and VBScript.

Q26. What will be the initial value of an object reference which is defined as an instance variable?

Answer. All object references are initialized to null in Java.

Q27. What is the constructor?

Answer. The constructor is a special type of method used to initialize the state of an object. It is invoked when the class is instantiated, and memory is allocated for the object. The constructor must have the same name as the class and does not have an explicit return type.

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

Answer. There are two types of constructors in Java:

  1. Default Constructor
  2. Parameterized Constructor

Q29. What is the purpose of a default constructor?

Answer. The purpose of the default constructor is to assign default values to the objects. If no constructor is defined in the class, the Java compiler creates a default constructor.

Q30. Does a constructor return any value?

Answer. Yes, a constructor implicitly returns the current instance of the class. It cannot have an explicit return type.

Q31. Is constructor inherited?

Answer. No, The constructor is not inherited.

Q32. Can you make a constructor final?

Answer. No, the constructor can't be final.

Q33. Can we overload the constructors?

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

Loading...

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.

Q34. What do you understand by copy constructor in Java?

**Answer.**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.

Loading...

Output:

111 Karan
111 Karan

Q35. What are the differences between the constructors and methods?

Answer. There are many differences between constructors and methods. They are given below.

Screenshot 2024-01-08 at 11.28.01 AM.png

Q.36 What is the output of the following Java program?

Answer.

Loading...

The output of the following program is:

a = 10 b = 15

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.

Q37. What is the output of the following Java program?

Answer.

Loading...

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.

Q38. What is the output of the following Java program?

Answer.

Loading...

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.

Q39. What is the static variable?

Answer. 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. The static variable gets memory only once in the class area during 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.

Loading...

Output:

111 Karan ITS

222 Aryan ITS

Q40. What is the static method?

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

Q41. What are the restrictions that are applied to the Java static methods?

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

Q42. Why is the main method static?

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

Q43. Can we override the static methods?

Answer. No, we can't override static methods.

Q44. What is the static block?

Answer. Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

Loading...

Output:

static block is invoked

Hello main

Q45. Can we execute a program without main() method?

Answer. No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible.

Q46. What if the static modifier is removed from the signature of the main method?

Answer. Program compiles. However, at runtime, It throws an error "NoSuchMethodError.”

Q47. What is the difference between static (class) method and instance method?

Answer.

Screenshot 2024-01-08 at 11.29.59 AM.png

Q48. Can we make constructors static?

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

Q49. Can we make the abstract methods static in Java?

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

Q50. Can we declare the static variables and methods in an abstract class?

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

Loading...

Output

hi !! I am good !!

i = 102

Q51. What is this keyword in Java?

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

Q52. What are the main uses of this keyword?

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

Q53. Can we assign the reference to this variable?

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

Loading...

Output

Test.java:5: error: cannot assign a value to final variable this

        this = null; 

        ^

1 error

Q.54 Can this keyword be used to refer static members?

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

Loading...

Output

10

Q55. How can constructor chaining be done using this keyword?

Answer. Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use the this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how we can use this keyword to achieve constructor chaining.

Loading...

Output:

ID105 Name:Vikas age:22 address: Delhi

Q56. What are the advantages of passing this into a method instead of the current class object itself?

Answer.

  1. this is a final variable, and it cannot be assigned to any new value, whereas the current class object might not be final and can be changed.
  2. this can be used in the synchronized block.

Q57. What is Inheritance?

Answer. Inheritance is a mechanism by which one object acquires all the properties and behaviour of another object of another class. It is used for Code Reusability and Method Overriding. There are five types of inheritance in Java: Single-level, Multi-level, Multiple, Hierarchical, and Hybrid (multiple and hierarchical combined).

Q58. Why is Inheritance used in Java?

Answer. Inheritance in Java is used for the following advantages:

  1. Code reusability: The derived class can reuse the methods and fields of the parent class.
  2. Runtime polymorphism: Achieved through method overriding.
  3. Realistic representation: Inheritance allows the simulating of real-world relationships between objects.
  4. Data hiding: The base class can hide some data from the derived class by making it private.
  5. Method overriding: Specific implementations of methods in the base class can be provided in the derived class.

Q59. Which class is the superclass for all the classes?

Answer. The Object class is the superclass for all other classes in Java.

Q60. Why is multiple inheritance not supported in Java?

Answer. Multiple inheritance is not supported in Java to reduce complexity and simplify the language. The absence of multiple inheritances prevents ambiguity and potential conflicts in cases where two or more superclasses have methods or attributes with the same name. The compile-time error is preferred over runtime errors in Java.

Q61. What is aggregation?

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

Loading...

Q62. What is composition?

Answer. 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 the 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.

Q63. What is the difference between aggregation and composition?

Answer. 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).

Q64. Why does Java not support pointers?

Answer. Java does not support pointers because they are considered unsafe (unsecured) and complex to understand. Pointers in other languages can lead to memory-related issues like memory leaks, segmentation faults, and other vulnerabilities. Java was designed with a focus on security and simplicity, and the absence of pointers contributes to achieving these goals.

Q65. What is super in java?

Answer. 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 the super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no superor this.

Q66. How can constructor chaining be done by using the super keyword?

Answer.

Loading...

Q67. What are the main uses of the super keyword?

Answer. There are the following uses of the 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 the immediate parent class constructor.

Q68. What are the differences between this and super keyword?

Answer. 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 is 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 the constructor; otherwise, the compiler will throw an error.

Q69. What is the output of the following Java program?

Answer.

Loading...

Output:

Person class constructor called

Employee class constructor



 called

Explanation: 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.

Q70. Can you use this() and super() both in a constructor?

Answer. No, because this() and super() must be the first statement in the class constructor.

Example:

Loading...

Output:

Test.java:5: error: call to this must be the first statement in the constructor

Q71. What is object cloning?

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

Q72. What is method overloading?

Answer. 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 and is performed to figure out the program quickly.

Q73. Why is method overloading not possible by changing the return type in java?

Answer. In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

Loading...

Output:

Compile Time Error: method add(int, int) is already defined in class Adder

Q74. Can we overload the methods by making them static?

Answer. No, we cannot overload the methods by just applying the static keyword to them (number of parameters and types are the same).

Loading...

Output:

Animal.java:7: error: method consume(int) is already defined in class Animal

    static void consume(int a)

                ^

Animal.java:15: error: non-static method consume(int) cannot be referenced from a static context

        Animal.consume(20);

              ^

2 errors

Q75. Can we overload the main() method?

Answer. Yes, we can have any number of main methods in a Java program by using method overloading.

Q76. What is method overloading with type promotion?

Answer.

Loading...

Output:

40

60

Q77. What is the output of the following Java program?

Answer.

Loading...

Output:

OverloadingCalculation3.java:7: error: reference to sum is ambiguous

obj.sum(20,20);//now ambiguity

     ^

      both method sum(int,long) in OverloadingCalculation3

      and method sum(long,int) in OverloadingCalculation3 matcherror

Q78. What is method overriding?

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

Q79. Can we override the static method?

Answer. No, you can't override the static method because they are part of the class, not the object.

Q80. Why can we not override static method?

Answer. It is because the static method is part of the class, and it is bound with the class, whereas an instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

Q81. Can we override the overloaded method?

Answer. Yes.

Q82. Difference between method Overloading and Overriding.

Answer.

Screenshot 2024-01-08 at 11.31.36 AM.png

Q83. Can we override the private methods?

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

Q84. Can we change the scope of the overridden method in the subclass?

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

Q85. Can we modify the throws clause of the superclass method while overriding it in the subclass?

Answer. 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 the same, subclass exception, or no exception but cannot declare parent exception.

Q86. What is the output of the following Java program?

Answer.

Base class method called with integer a = 10

Explanation: The method() is overloaded in class Base, whereas it is overridden in class Derived with the double type as the parameter. In the method call, the integer is passed.

Q87. Can you have virtual functions in Java?

Answer. Yes, all functions in Java are virtual by default.

Q88. What is the covariant return type?

Answer.

Loading...

Output:

welcome to covariant return type

Q89. What is the output of the following Java program?

Answer.

Derived method called ...

Explanation: The method of Base class, i.e., baseMethod() is overridden in Derived class. In the 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.

Q90. What is the final variable?

Answer. 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. It 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.

Loading...

Output:

Compile Time Error

Q91. What is the final method?

Answer. A final method cannot be overridden. If we change any method to a final method, we can't override it.

Loading...

Q92. What is the final class?

Answer. A final class cannot be inherited. If we make any class final, we can't inherit it into any of the subclasses.

Loading...

Q93. What is the final blank variable?

Answer. A final variable, not initialized at the time of declaration, is known as the final blank variable.

Loading...

Q94. Can we initialize the final blank variable?

Answer. Yes, if it is not static, we can initialize it in the constructor. If it is a static blank final variable, it can be initialized only in the static block.

Q95. Can you declare the main method as final?

Answer. Yes, We can declare the main method as public static final void main(String[] args){}.

Q96. What is the output of the following Java program?

Answer.

20

Loading...

Q97. What is the output of the following Java program?

Answer.

Loading...

Output:

Compile Time Error

Q98. Can we declare a constructor as final?

Answer. No, the constructor can never be declared as final because it is never inherited.

Q99. Can we declare an interface as final?

Answer. No, we cannot declare an interface as final because some class must implement the interface to provide its definition.

Q100. What is the difference between the final method and the abstract method?

Answer. The main difference between the final method and the abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

Conclusion

In conclusion, this ultimate guide on the Top 100 interview questions on Java has equipped you with the knowledge and confidence to tackle basic and coding interview questions head-on. By mastering these concepts, you are well-prepared to face your upcoming Java interviews and showcase your expertise to potential employers.

Remember that practice is key, and reviewing these Java coding interview questions regularly will help you solidify your understanding of the language. As the world of web development continues to evolve, these core Java interview questions help you stay up-to-date with the latest trends and technologies and will give you an edge in this competitive field.

Related Articles

Top Tutorials

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter