100+ Core Java Interview Questions and Answers for 2022

Java Interview questions

Introduction

In this post we will look into the most commonly asked Interview questions related to Java. We will take a look at the most common topics in Java for interviews and provide the answer to the questions in detail with examples to help you ace your next interview.

We recommend following this post step by step to match the topics according to their difficulty level.

Java Interview Questions

Given below are about 100 Java Interview Questions, that questions you will see are among the common and top questions asked in interviews. These will also help you in your Computer Science degree subjects as well as other entrance exams.

So, without further ado let’s dive into it.

1. What is the key difference between C++ and Java programming languages?

Ans. C++ is both Procedural and Object Oriented Programming Language, primarily used for system programming, as opposed to other applications. Java is a pure Object Oriented Programming Language, primarily used for application development, as opposed to server programming. It is widely used in the development of a variety of applications, including desktop, web-based, enterprise, and mobile applications.

2. Is Java completely object-oriented or 100% Object Oriented?

Ans. Java uses the concepts of object-oriented language but we cannot say that it is completely or 100% object-oriented. It is because it still makes use of the primitive data types like int, float, double etc. An object-oriented programming language functions using objects only. Primitive data types are not objects. Hence, Java is not 100% object- oriented.

3. Is there a way to convert primitive data types to objects in Java?

Ans. Yes, there is a way to convert primitive data types to objects in Java. We can do so by using the Wrapper class. The Wrapper class in Java is used for interconversion between objects and primitive data types. For example, int is converted to Integer, char to Character, byte to Byte, and so on. These are 8 wrapper classes in total.

4. What are Autoboxing and Unboxing?

Ans. The automatic conversion of a primitive data type to an object is known as Autoboxing, it can be seen as a promotion of data type. Similarly, the automatic conversion of an object to its corresponding primitive data type is known as Unboxing.

In simple words, if we assign a literal value to a Wrapper Class Object it is called Autoboxing, whereas if we assign a Wrapper Class to its equivalent primitive type it is known as Unboxing.

Important Note: After Autoboxing, if we assign a Wrapper Class Object to a Primitive type it is known as Auto-Unboxing, a special case of Autoboxing. We will look at this in example:

Example Program:

Output:

5. Does Java support pointers?

Ans. Java does not support pointers. Pointers are used to directly point a location in memory. This will pose a threat to security of Java and compromise its purpose. As we know that Java uses the concepts of OOP, it is already complex. Hence to make it less complex and remove ambiguity, pointers are not allowed in Java.

6. What is a string literal?

Ans. In Java, a string literal is basically a string enclosed in double quotes “”. A string literal can contain alphabets, numbers, and special characters. Java uses string literal because in this way if a string literal already exists in the string pool, then Java does not create a new object for it. This property makes it memory efficient. Although we concatenate two String literals using + operator.

Example:

Output:

The sample code does not include the main method and class declaration. Please write the sample code inside the main method and a class to get the above desired output.

7. What do you know about StringBuffer?

Ans. The string is immutable in Java. We can use its mutable version with the StringBuffer class. Any changes done to a StringBuffer type String using methods will reflect in the original string. We can also set the size of the buffer for the string. By default, its size is 16 characters. We can also perform other string functions on StringBuffer like append, insert, etc.

Example of StringBuffer in Java:

Output:

8. What do you know about Java String Pool?

Ans. The Java String Pool is a pool that contains all the strings created. It is possible to have many strings in the string pool in Java, each of which has its own heap memory allocation.

Whenever a new string object is generated, the String pool checks to see if the object has already been created and stored somewhere else. The relevant reference will be returned if it is there. Otherwise, a new object will be generated in the String pool and the new reference will be returned to the variable.

9. Are Java strings mutable?

Ans. No, java strings are not mutable. String objects in Java are immutable by nature, which basically implies that once a string object has been created, its state cannot be changed in any way. Java creates a new string object whenever you attempt to edit the value of that object rather than modifying the values of that particular object.

Java String objects are immutable because string objects are typically cached in the String pool, which makes them immutable. Due to the fact that strings are typically shared between numerous clients, an action taken by one client may have an impact on the rest.

10. What do you know about garbage collection?

Ans. Garbage collection is an interesting feature of Java. In simple words, unreferenced objects are garbage in Java. Unused runtime memory is automatically recollected by Garbage Collection. Also, it is a method of destroying useless objects. Java garbage collection automates memory management in Java applications.

A program’s heap is formed when it runs on the JVM. After the execution, some objects eventually become obsolete. These obsolete objects are found and deleted by the garbage collector. This feature makes it convenient for programmers to build large scale applications as they need not worry about every object. If it is unused it will be garbage collected.

11. Explain the gc() method?

Ans. In Java, the gc() method is used to start the process of garbage collection. Calling it implies that
the Java Virtual Machine recycles or deallocates memory of unwanted objects to free up memory for reuse. It is
a method of System class. The gc() method is also present in the Runtime Class but is not used commonly.

In order to view the object before it goes for garbage collection we can use the finalize() method.

Note: An object is eligible for garbage collection if it is unreachable or contains null value.

Example:

Output:

12. What is inner class?

Ans. Classes in Java can have members of other classes, exactly like methods. Java permits the creation of classes that extend other classes. Inner classes are classes that include other classes, and classes that hold other classes are referred to as outer classes. In other words, the non-static nested classes are also known as inner classes.

13. What do you know about the types of inner class?

Ans. There are four types of inner classes. These are:

  • Anonymous inner class
  • Local inner class
  • Member inner class
  • Static member inner class

14. What do you mean when you say Java virtual machine?

Ans. The Java Virtual Machine allows a computer to run a Java program without the need for any additional software. The Java Virtual Machine (JVM) functions as a run-time engine, invoking the main method defined in the Java code.

The Java Virtual Machine (JVM) specification must be implemented in the computer system. The Java code is compiled into bytecode by the JVM, which is machine-independent and very near to the native code in terms of performance.

The Java Virtual Machine (JVM) executes the following tasks:

  •  It loads the code into memory.
  •  It checks for errors in the code.
  •  It generates an output by executing the program.
  •  It sets up a runtime environment.

15. What makes the Classloader important?

Ans. A class file is a file that contains the bytecode generated by Java Virtual Machine (JVM). It is an important file as it makes the code transferable and executable on any platform containing JVM. Class loader loads class files. Its ability to load class files first when a java program is run makes it important for Java virtual machines.

16. What do you know about the Just-In-Time compiler?

Ans. It is commonly known as the JIT compiler. Its purpose is to increase the overall performance. JIT compiler translates portions of bytecode that have similar functionality as the original, reducing the amount of time required for compilation. It enhances the performance by converting the instruction set of a Java virtual machine (JVM) into the instruction set of a particular CPU where the program is run.

17. Is an empty java file name considered to be an acceptable source file name?

Ans. Yes, only Java permits us to save our java files as .java extensions; nevertheless, we must compile them as javac .java. What Java does by default is that it uses the name of the class as the file name.

18. What is an interface?

Ans. To put it another way, an interface is in Java what you might refer to as the blueprint of a class, or as a collection of abstract methods and constants. Each method in an interface is public and abstract, but it lacks a constructor.

This means that in its most basic form, an interface is nothing more than a collection of undefined methods. Only method signatures and constant declarations are allowed in interfaces. Interfaces are specified with the interface keyword.

19. Is there any marker interface in Java?
Ans. A Marker interface is one that lacks data members and member functions. To put it another way, an empty interface is referred to as the Marker interface. Serializable, Cloneable, and others are the most frequently used Marker interfaces in Java.

20. What do you know about packages in Java?
Ans. A package is a collection of classes, interfaces, and other packages. Java classes and interfaces are packaged. Java has two types of packages: built-in and user-created. In order to use a package, we need to import it. For example, if we want to use Arrays Class in Java, we import a package like this:

import java.util.Arrays
Here, java is the top-level package, util is a sub-package, and Arrays is a class in util.

21. How to create a package in Java?

Ans. It is quite easy to create a package in Java. One should follow the given steps to create a package in Java. These are:

  • Select the name of the package.
  • Write package command in Java source file on the first line.
  • Compile

22. Are empty and null two different things in Java?

Ans. In Java, empty and null are totally two different concepts. Even if it is an empty string or null string; or empty collection or null collection there exists a difference between the two terms.

If we talk about empty string and null string, then an empty string is a string that contains no value but is allocated memory i.e. it exists. On the other hand, a null string does not exist at all. It has no value nor any memory identity.

If we print the length of an empty string literal we get 0. Whereas, if we print the length of a null string we will get a NullPointerException. This explains the difference regarding memory allocation. We will look at this in example program.

Output:

23. What are the main types of access specifiers available in Java?

Ans. Access specifiers are keywords in Java that we use to describe the access scope of a method, a class, or a variable. They are also known as access modifiers. There are four main access specifiers in Java, which are listed below.

  • Public: The public classes, methods, and variables are those that can be accessed by any class or method that has been designated as public. These members are accessible from everywhere in the program as well as outside the package.
  • Protected: The protected class, method, or variable can only be accessible by classes belonging to the same package, or by subclasses of this class, or by classes belonging to the same package.
  • Default: All of the default terms are only accessible within the package. By default, all classes, methods, and variables are included in the default scope of the application.
  • Private: It is only possible to access the class, methods, and variables designated as private from within the same class.

24. What are the key points that one should keep in mind while changing access specifiers of a method?

Ans. Following are the key points that one should keep in mind while changing access specifiers of a method:

  • We can change the private method to public, default, and protected.
  • We can change the protected method to public and default only.
  • We can change the default method to the public only.
  • The public method cannot be changed.

25. Can we access one class in another class?

Ans. Yes, we can access another class from another class. There are two methods for it.

  • By using the package name along with the class name. By doing so, one doesn’t need to import the package.
  • By using its path with the entire package structure.

26. Can a private method be accessed outside the class?

Ans. The fields that are private cannot be accessed outside the class. But a private method can be accessed outside the class using Java Class and Method classes.

27. Give an example explaining the function of static keyword.

Ans. The static variable is a property of the class rather than of the object. We use the static keyword when we need to declare variables or methods that are shared by all instances of a class and are not specific to any one object.

It is not necessary to create an object in order to access static variables or methods because they are stored in the class area. Static members are allocated memory only once. Whereas other instance variables are allocated memory every time we create an object.

Example: Suppose, we are storing the details of a class then we can declare the name of the class teacher as static as all students of a class have the same class teacher. Let us understand this with help of a program.

Output:

28. Do the order of specifiers, modifiers, and keywords matter in Java?

Ans. No, the order doesn’t matter as the program gets compiled perfectly. As we have generated the class file, we can run it without any problem. There will be no errors.

All the three variable naming conventions are same to Java.

29. What do you know about the term method?

Ans. A method is basically a procedure for carrying out a specific task. Similar in nature, a Java method is a collection of instructions that are used to do a certain task. It allows code to be reused in multiple places. A method can be built-in as well as user-defined. A method can be parameterized or non-parameterized.

30. What are the types of a method?

Ans. A method in Java has two main types; predefined method and user-defined method. The predefined methods are built-in methods. In Java these methods usually belong to a class. Whereas user-defined methods are the methods that a user writes according to his/her need. User-defined methods increase the scope of a programming language as one is able to perform his/her specific task.

Example:

An example of pre-defined method in Java is the length() method of String Class.

31. Can we make a method static?

Ans. Yes, we can use the static keyword to make a method static. Variables, methods, blocks, and nested classes can be static. A static method is a method that uses the static keyword. A static method belongs to the class, not the object. A static method can be called without creating a class instance or object. We can use a static method to access and modify the value of a static data member.

32. Can we run a Java program without a main method?

Ans. It was possible in the older versions of JDK. But after the release of JDK 1.7, it is impossible to run and execute a Java program without a main method. In older versions prior to Java 7, we could use a Java static block to run the program without the main method.

33. When we create the main method, we define it as static. Why is that so?

Ans. In Java, we use objects to call methods. But we can invoke static methods without creating a class object. This property of static methods is useful while invoking the main method.

This helps the JVM to automatically invoke the main method without any instance of the class having the main method. We define the main method as static so that we do not have to create a class object to invoke the main method.

34. Will our program compile, if we remove static keyword from the main method?

Ans. Yes, our program will get compiled. The program will not show any error on compiling but during execution it will show a run time error. The run time error will be Main Method is not Static.

35. Can a Java program have more than one main method?

Ans. Yes, a Java program can have more than one main method. Having more than one method with the same name is known as method overloading. We can use method overloading to create more than one main method in a Java program.

We know that the name is the same and parameters are different in overloaded methods. But it is necessary for us to write the original main method one with String array parameter. During compilation, the JVM will search for that method.

We will have a look at this in example program.

Output:

36. What do you know about the instance method?

Ans. A method that is not static is known as an instance method. As obvious from its name, an object is needed to invoke an instance method.

37. What do you know about method overloading?

Ans. If there are two methods with the same name and different parameters in the same class, then these methods are called overloaded methods, and the process is known as overloading. If two methods have the same name and number of parameters but their parameter types are different, then such methods are also overloaded. This helps us achieve Compile Time Polymorphism in java.

Overloading is useful when we need scalability in our program. Scalability in sense of parameters, sometimes we need two parameters and sometimes we need three or more. In such cases, overloaded methods become handy and increase the readability of the code.

Example Program for Method Overloading:

Output:

38. Can we overload methods by changing their return types only?

Ans. No, we cannot overload methods by changing their return type. The only golden rule of method overloading is that the number of parameters must be different.

39. What is method overriding?

Ans. The concept of overriding rises when we talk about inheritance. When there is a parent and child class or super or subclass. Method overriding is the act of adding a method to a subclass that already exists in the superclass. Overriding allows a child class to provide its own implementation of a method given by the parent class.

Method Overriding helps us achieve Run Time Polymorphism in Java. In this situation, the parent class method is overridden method and the child class method is an overriding method.

Output:

40. Is Java an object-oriented programming language?

Ans. Yes, Java is an object-oriented programming language. When we say object-oriented, the first thing that pops up in our minds is objects. An object-oriented programming language deals with the objects having methods. These objects belong to a specific class. We can safely say that we can create as many objects of a class as we want.

41. What is the purpose of a constructor?

Ans. We need a constructor while creating an object of a class. It is called when an object of a class is created and memory is allocated for the object to be created. If you create a new object with the new keyword, the default constructor of the class will be invoked every time you do so.

The constructor must have a name that is similar to the name of the class. The constructor must not return a type that is specified explicitly.

42. What are the two types of constructors?

Ans. The two types of a constructor are:

  • Default Constructor
  • Parameterized constructor

Default Constructor: The default constructor accepts no values. If no constructor is defined in the class, the compiler uses a default constructor. We use the default constructor to set default values for instance variables. We can also use it to create
objects.
Parameterized Constructor: The parameterized constructor, as obvious from its name, accepts parameters. This is the main difference between the two constructors.

43. Why is there a need for a parameterized constructor?

Ans. We need a parameterized constructor to create different objects. A default constructor initializes objects created with the same values defined in the constructor. However, if we want to allot different values to different objects then we can use a parameterized constructor. A parameterized constructor can have as many parameters as one wants.

44. What are the three important points that one should keep in mind while defining constructors?

Ans. Constructors are essential to objects. A constructor tells about the object. A constructor can be default or user-defined. A user can define a constructor while keeping the following three restrictions in mind:

  • The name of the constructor must be the same as the name of the class.
  •  The return type of the constructor must not be specified explicitly.
  • A constructor cannot be defined using keywords abstract, static, and final.

45. What makes a C++ constructor and a Java constructor different?

Ans. In C++, we have a copy constructor. However, in Java, there is no copy constructor. We use a copy constructor to create the copy of an object. It’s easy in C++ as we can use the copy constructor. In Java, there are other methods to create a copy of an object.

46. What happens when we call the default constructor and define parameterized constructor?

Ans. If we have defined a parameterized constructor and we have called a default constructor, then according to our thinking the compiler should implicitly call the default constructor. But this is not the case.

The compiler only calls the default constructor if no constructor is defined or given. Now that we have defined a parameterized constructor, the compiler will give an error. It will treat it similar to a method. Let’s see the example program as well.

On executing this we get the below error.

47. Can a constructor be static?

Ans. The Java constructors cannot be static. The fact that a Java constructor cannot be static is an important Java design feature. Static is a keyword that refers to a class, not a specific object of a class. Constructors are used for objects so they cannot be static.

48. What are the different methods to create a copy of an object in Java?

Ans. As there is no copy constructor in Java, we will use other methods to create a copy of an object. We can create a copy of an object by defining a constructor that accepts an object as a parameter. In this way, we can copy the data of an already created object and assign it to the newly created object.
Another way is to directly assign the value of an object to the other. We can also use the clone method to create a copy of an object.

49. Can we create a copy of an object without a Cloneable interface?

Ans. The class whose object copy we wish to create must implement the Cloneable interface. If the Cloneable interface is not implemented, the clone() function throws a CloneNotSupportedException.

50. What is the difference between an object and a class?

Ans. A class can be thought of as a template from which new objects can be built. An object is something that exists in the real world, like a pen, laptop, mobile phone, bed, keyboard, mouse, or chair. A class can be thought of as a collection of comparable objects. An object is a real-world thing.

Programmers can access variables and methods inside a class by creating objects, which are instances of the class. When data and methods are combined into a single unit, they are called a class.

51. What do you know about Java blocks?

Ans. In Java, a block is a collection of one or more statements that are enclosed in braces. Beginning with an opening brace { and ending with a closing brace }, a block is formed. We can add one or more code lines in the space between the opening and closing braces. We can make a block static by using the static keyword.

52. What was the benefit of a Java block in the older versions of JDK?

Ans. There are multiple benefits of using blocks in Java. But the main benefit was that we could use a static block to execute the program without the main method. Static block is executed before the main method. It could be executed without the main method in older versions of JDK. But after the release of JDK 1.7 main method is a must to run a java program.

53. What do you know about the reference variable of Java?

Ans. The this and super keywords are means by which we can implement the concept of Reference variables in Java. The keyword this relates to the current object. This keyword has a variety of applications in Java.

It can refer to current class properties such instance methods, variables, constructors, and so forth. It can also be used as an argument in methods and constructors. It can alternatively be returned as the current class instance from the method. The super keyword is used when there is inheritance involved.

54. Can we assign value to this variable?

Ans. We cannot assign value to this variable as we use it for reference purposes. It points to the current class object. If we try to give it a value, then we will get a compile-time error.

55. Can we pass this as a parameter to a method?

Ans. Yes, we can pass this as a parameter to a method. We can also pass it as a parameter to the constructor.

56. Tell about the super keyword.

Ans. We use the super keyword whenever we talk about inheritance in Java. It is a reference variable. We use it to refer to immediate parent class methods, variables, and constructors. The super reference variable refers to an implicit parent class instance created when a subclass instance is formed.

57. What is the main difference between this and super?

Ans. The main and only difference between this and the super keyword is inheritance. Both work in the same way but the difference lies in the class to which these variables are referencing.

This keyword references the variable, method, or constructor of the current class. There is no inheritance involved in using this keyword. But the super variable is only used when there is an inheritance relationship between classes. Super keyword refers to the parent class’s variables, methods, and constructors.

58. Can a referenced object be unreferenced?

Ans. Yes, we can dereference a referenced object. There are different ways of doing that. The most common way to do that is to assign a null value to the object. Another way is to assign the reference of one object to another making the former unreferenced.

59. Is there any keyword as final in Java?

Ans. Yes, there is a keyword with name final in Java. It restricts modification to variables, methods and classes in a certain way. If we talk about final variables i.e., the variables that are using the final keyword, then we must know that we cannot modify final variables.

In the same manner, we cannot override final methods. However, we can overload final methods. Hence, we have to be very careful while using the final keyword as it restricts the normal function of a variable and a method.

60. Can we make a method, class, and variable final?

Ans. Yes, we can make a method, class, and variable final. But each has its restrictions. A final class cannot be inherited or extended. A final method can not be overridden. If we initialize a final variable with a value we cannot change its value again.

61. Can we make an interface final?

Ans. No, we cannot make an interface final. Multiple classes use or implements one interface. If we make
the interface final, then different classes will not be able to use it.

62. What is constructor chaining?

Ans. Constructor chaining is the practice of calling a constructor from another constructor in the same class. Constructor Chaining serves the function of allowing you to provide parameters across several constructors while only performing initialization once.

While offering various constructors to the user, you can preserve your initializations in a single area. You’ll have to initialize a parameter twice if we don’t chain, and if the value is modified in one constructor, you’ll have to modify it in each one instead of just the first.

63. Can constructor chaining be done using this and super?

Ans. Yes, constructor chaining can be done using this and super keywords. If we are calling the constructors of the same class, we will use this keyword. If we are using the constructor of the parent class within the child class, then we will use the super keyword.

Let us look at sample program to explain their use.

Output:

64. Which main concepts of OOP are implemented in Java?

Ans. There are 4 main concepts of OOP that Java uses. These are inheritance, abstraction, polymorphism, and encapsulation.

65. Why do we use inheritance?

Ans. Inheritance in Java refers to the concept of creating new classes from existing ones. Just like a child inherits some of its characteristics from its parent, we can reuse methods and properties of the parent class when we inherit from it. In addition, we can extend our current class by adding additional methods and properties.

66. What are the types of inheritance?

Ans. Inheritance allows one object to inherit the characteristics and behavior of another object of a different class.
There are typically five types of inheritance:

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Out of the the above mentioned types, Java does not support multiple inheritance.

67. What do you know about multiple inheritance?

Ans. Multiple inheritance is a type of inheritance in which there is more than one parent class. Java does not support multiple inheritance. Because in multiple inheritance, a subclass is unable to choose between two classes that define various ways of doing the same thing. So, to decrease ambiguity, Java does not support multiple inheritance.

However we can achieve Multiple Inheritance in Java using Interfaces. Using Interface, a class can implement multiple interfaces hence can implement its own functionalities for each interface.

68. Is there any one parent class in Java?

Ans. Yes, there is a parent class to whom all other classes are subclasses. That class is Object class present in java.lang package. All other classes in java are the subclasses of the Object class.

69. What do you know about type promotion?

Ans. In Java, type promotion occurs when we use method overloading. When the data types are different than defined in the method, we promote one data type to the next higher data type in the hierarchy. We are unable to downgrade from one data type to
another.

  • It is possible to convert byte to byte, short, int, long, float, and double.
  •  Short can be made to work like short, int, long, float, and double.
  •  Int can be made to work like int, long, float, and double.
  •  Long can be made to work like long, float, and double.
  •  Float can be elevated to the status of a float and double by using type
    promotion.

70. What is Abstraction in Java?

Ans. We use data abstraction when we want to hide details from the user. Data Abstraction is the property that allows the user to see only the essential details. We use interfaces and abstract classes to implement abstraction in Java.

For example, when we eat food, we know that our food will digest but we don’t know that how our food will digest. This depicts the real-life example of abstraction. The unnecessary detail is hidden.

71. What is polymorphism?

Ans. Polymorphism refers to the fact that something exists in numerous forms. Polymorphism, put simply, is the ability of an object to appear in multiple forms.

For example, a person can have multiple traits at the same time. As a female, you are a mother, a daughter, sister, and an employee all at the same time. As a result, the same person exhibits several behaviors depending on the situation.

Polymorphism is the scientific term for this. As a result of polymorphism, we can accomplish the same action in multiple ways.

72. What are the types of polymorphism?
Ans. In Java, there are two types of polymorphism:

  • Compile-time polymorphism
  • Run-time polymorphism

Method Overloading is the best example of Compile-time polymorphism. We know that overloaded methods have the same name but different parameters. So, during compilation, the compiler decides which method will be implemented. It is also known as static polymorphism.

Method Overriding is an example of Run-time polymorphism. It is also known as Dynamic Method Dispatch where a call to a overridden method is resolved at runtime rather than compile time.

73. What are the benefits of using multithreading in Java?

Ans. The benefits of Multithreading are as follows:

  • Threads are used to speed up Java applications by allowing them to perform numerous tasks at the same time.
  • Thread is a Java feature that allows you to implement parallelism in your programs.
  • Because the CPU is extremely fast, and nowadays it even has multiple cores, a single thread cannot use all of the cores, resulting in your expensive hardware being idle most of the time. By implementing multiple threads, you may make full use of multiple cores by handling more customers and providing them more quickly than you could otherwise.

Given the importance of response time in today’s fast-paced world, multi-core CPUs are becoming increasingly popular; however, if your application does not make full use of all available resources, there is no point in adding them. Multi-threading is one method of utilizing the enormous computing power of the CPU in a Java application.

74. What is the purpose of the sleep() method in Java?

Ans. We use the sleep() method to temporarily halt the execution of a thread for a specified time, after which the thread that was executing before begins to execute again and so on. It has no return type.

75. What is the purpose of the wait() method in Java?

Ans. We use the wait() method to pause a thread and to release lock during synchronization. We cannot override it as it is a final method.

76. What is the difference between the start() and run() methods?

Ans. We use both start() and run() methods to start the execution of a thread. The difference lies in the thread itself. The run() method executes the code using the current thread. But the start() method executes the code by creating a new thread.

77. What is a daemon thread in Java?

Ans. It is a thread with the lowest possible priority that runs in the background and performs duties such as garbage collection and reloading the page. They will not be able to prevent the JVM from terminating when all of the user threads have completed their execution.

When all user threads have completed their execution, the JVM stops itself. If the JVM detects a functioning daemon thread, it stops the thread and then shuts down the entire system. The JVM is unconcerned about whether or not the Daemon thread is executing.

78. How can we check if a thread is a daemon thread or not?

Ans. We use the isDaemon() method to check if a thread is a daemon or not. It is a Boolean method. If it returns true, then the current thread is daemon. Otherwise, the current thread is not a daemon thread.

79. What do you know about shutdown hook?

Ans. In JVM, the shutdown hook is a thread that is automatically invoked just before the JVM shuts down completely. In this case, we can utilize it to do resource cleanup or state saving when the JVM goes down, whether it is properly or unexpectedly.

Shutdown hooks have been initialized, however, they can only be used if the JVM has been shut down. As a result, shutdown hooks are more dependable than the finalizer() function since there are significantly fewer chances that shutdown hooks will not be executed. By invoking the halt(int) method of the Runtime class, it is possible to terminate the shutdown hook.

80. Can we interrupt a thread?

Ans. Yes, we can interrupt a thread using the interrupt() method. We can stop its execution by throwing an InterruptedException. The interrupt() function of the Thread class can be used to wake up a thread that is asleep or waiting.

81. Why do we use the volatile keyword for threads?

Ans. We use the volatile keyword to allow several threads to alter the value of a variable at the same time. It is also employed to ensure thread safety. It means that several threads can utilize a method and an instance of a class at the same time without encountering any complications.

82. What is the purpose of execute() method?

Ans. The execute() method act as a scheduler for executing a specific task. A new thread may be created to execute the scheduled task if no thread is available.

83. What do you mean by synchronous and asynchronous programming?

Ans. There are two ways to program. In the Synchronous programming model, assigning tasks to individual threads and making them available for other activities as soon as the allocated task is completed occurs. Asynchronous programming allows numerous threads to work on the same task at the same time, making the individual threads as useful as possible.

84. What do you know about Java exceptions?

Ans. A problem that occurs during the execution of a program is known as an exception (or unusual situation). It is not advised for processes to terminate unexpectedly when an Exception occurs. As a result, these exceptions must be handled carefully. Exceptions can occur for a variety of reasons, including user mistakes, programmer errors, and failure of physical resources.

85. What are the types of exceptions?

Ans. There are mainly two types of exceptions in Java. These are:

  • Built In Exceptions
    • Checked Exceptions
    • Un-Checked Exceptions.
  • User Defined Exceptions

Built In Exceptions: These exceptions are already present in Java libraries and comes in handy when we have to throw any known exception which eases such cases. These are again subdivided into two types:

  1. Checked Exceptions: These exceptions are Compile-Time Exceptions as they are checked or evaluated by the compile during compile time. Hence, it is necessary for the programmer to handle these exceptions.
  2. Un-Checked Exceptions: These exceptions are not checked during compile time. These exceptions occur during execution of the program by the user. Hence, even if we didn’t handle such exceptions, during compilation we will not get any error.

User Defined Exception: In java, we can create our own exception as well. With the help of a try-catch block and creating a custom exception class, we can create our own custom exception as well.

Below image illustrates different types of exception.

86. What is the main difference between an exception and an error?

Ans. Both create a problem but the difference is that we can handle an exception but we cannot handle a code. Try and catch blocks are used to handle an exception.

87. What action does throw and throws perform? How do they differ?

Ans. To explicitly throw an exception, use the throw keyword. To declare multiple exceptions or if we want to show that a method will predominantly throw an exception then, use the throws keyword followed by commas to mention different exceptions. When using throw, only one exception will be thrown.

88. Can we throw an integer?

Ans. No, we cannot throw an integer. We cannot throw any primitive data type using the throw keyword as they are not objects.

89. What do you know about try and catch block?

Ans. We use the try statement with a block to test for errors while a block of code is being executed. If an error happens in the try block, you may use the catch statement to specify a code block that should be performed instead.

90. Is it necessary that every try should have a catch?

Ans. No, it is not always necessary to use a catch block after try block. But we cannot leave try on its own. If we are not using catch block, then we must use the finally block.

91. What is finally block?

Ans. Using the finally block in Java, you may execute critical pieces of code. Whether or not an exception is handled, the finally block in Java is always run. Consequently, regardless of whether an exception occurs, it provides all of the relevant statements. Contrary to catch block that depends on try block, a finally block always executes.

92. What do you know about serialization and deserialization?

Ans. When we convert an object into a byte stream, the process is referred to as serialization. When deserialization occurs, the byte stream is used to reconstruct the actual Java object in memory, which is the inverse of serialization.

The fact that the entire process is JVM independent is the most striking feature. This means that an object can be serialized on one platform and deserialized on another completely different platform.

93. Can we establish a connection between the server and a client in Java?

Ans. We can easily establish a connection between the server and a client in Java. We need to establish a connection session. Java socket programming is used to cover Java networking problems.

94. What do you know about an applet?

Ans. In computing, an applet is a Java program that runs in a web browser. Because it has access to the complete Java API, an applet can perform the functions of a fully functional Java application. An applet extends java.applet.Applet class. It is used to display information. Applets are a type of program. An applet does not have a main() method, and it does not have a main() method defined in its class. Applets are little programs that are intended to be embedded within an HTML page.

95. How can we create an applet in Java?

Ans. To create an applet in Java, first, write a program extending the Java Applet class. Then embed this program into your HTML code. Run your HTML code. The output available on the Web page will be the output of the applet.

96. What do you know about JDBC?
Ans. Connection and execution of the query to the database are accomplished through the use of the JDBC Java API. When connecting to a database, the JDBC API makes use of JDBC drivers. The JDBC API can be used to retrieve tabular data from any relational database that supports the JDBC standard. It is a piece of software that lets Java applications communicate with databases through the use of JDBC.

97. Tell about the BLOB and CLOB data types?

Ans. BLOB is an abbreviation for the Binary Large Object. This type of data is a collection of binary data that is saved as a single entity in a database management system (DBMS). CLOB is an acronym that stands for Character Large Object. In several database management systems, character files are stored in this data type. CLOB is identical to Blob with the exception that BLOB represents binary data such as photos, audio and video files, and so on, whereas CLOB represents character stream data such as character files and so on.

98. Are Collection and Collections the same in Java?

Ans. No, these are two different terms. The Collection is an interface while Collections is a class.

99. What is the difference between array and Arraylist?

Ans. An array is a data structure with a fixed length, whereas Array List is a Collection class with a variable length. Once an array has been constructed in Java, its length cannot be modified; however, we can alter the length of an Arraylist. Arraylist does not support the storage of primitive data types; it can only store objects. In Java, however, an array can include both primitive data types and objects.

100. What are HashSet and Linked HashSet?

Ans. The HashSet class of the Java collection framework is for creating a collection that stores objects using a hash table as the primary storage mechanism.  It does not maintain the order of insertion.

The LinkedHashSet class, on the other hand, is very similar to the HashSet class. Furthermore, it preserves the order of insertions. The HashSet class inherits the features of the Java class known as AbstractSet and it uses the Set interface. The L1inkedHashSet class is derived from the HashSet class and implements the Set interface, among other things.

That’s it, folks! These were the basic 100 Java interview questions. If you perfectly prepare these questions for your interview or even any entrance exam, then we can guarantee that you will ace it. These are the most important interview questions related to Java that everyone
must know.


Java Interview Tips

The interview tips here are for both fresher and experienced candidates appearing for their next Java Interview.

  • As Java has its primary use in application programming so if you’re a fresher or an experienced candidate; expect the focus of the interview aligned with questions on Java API’s, Java Design Pattern in OOP and Concepts.
  • However if you are a fresher candidate with 0-2 years of experience will see more questions on topics like Java fundamentals, Java API’s like Collections, their implementation with respective data structure, and algorithms.
  • If you are an experienced Java developer applying for senior developer profiles, you might find more questions on concurrent programming, Java concurrency API, JVM internals, GC tuning, and Java Performance.
  • If you are preparing for a interview related to Java Backend developer profile, it is recommended to be well versed with Frameworks like Spring & Spring Boot and one Database server(of your choice).
  • When it comes to your interview, make sure you answer the questions to the point any misleading argument that might lead to another question which will waste the interviewer’s time and pose a negative feedback.
  • Instead try to pay attention and listen to the hints carefully given by the interviewer before answering the questions related to coding problems.
  • After this, make note of key topics that you find hard to understand. Then make sure you go through them in depth to avoid any problems.

If you follow these tips it will be much easier for you to ace your next java interview.

More Java Interview Q&A

Core java interview questions

This list includes top 50 core java interview questions. Whether you are fresher or experienced programmer, this interview questions will definitely help you to crack core java interview.


Collections interview questions

Collection is one of the major important parts of core java. These interview questions include questions on HashMap, Hashet, Arraylist etc. These are logical interview questions which will help you built reasoning for these questions.


Multithreading interview questions

Multithreading concepts are the tricky one. This java interview questions list covers threads, synchronization, inter thread communication and executor frameworks.


Java 8 interview questions

Java 8 has a lot of new features. If you are going to core java interview, you might be asked about lambda expressions, function interface, streams, new Date and time APIs etc.


OOPs interview questions

Object-oriented principles are build blocks of java. This list includes questions on Abstraction, encapsulation, inheritance, and polymorphism.


Exception Handling interview questions

This java interview questions list covers questions on Exception hierarchy, check, unchecked exceptions, try catch block etc.


String interview questions

String is one of the most used datatype in Java. These interview questions will check your knowledge on String concepts.


Serialization interview questions

Serialization is one of the most important topic in core java. These interview question covers some of the tricky questions on Serialization.


method overloading and method overriding interview questions

This java interview question list includes tricky method overloading and overriding interview questions. It will help you to understand method overloading and overriding in the better way.


Immutable class interview questions

Immutable class is one of the most important concepts as immutable classes are by default thread safe. This interview question list will check your knowledge on immutable classes.


Java tricky interview questions

This interview question list includes some tricky interview questions. These java interview questions will help you to build logic.


Basic interview questions for fresher

This java interview questions list includes basic interview questions on beginner java programmers.


Interview questions for 5 to 7 years experienced

This java interview questions list includes some good questions for an experienced programmer. It includes concepts from multithreading and collections .


How HashMap works in java?

This is most asked java interview question and it is favorite interview questions for most of the interviewer. This interview question checks your knowledge on HashMap, hashcode and equals method.


Difference between Interface and abstract class? What are changes made to interface in Java 8?

You can have default and static method in java from Java 8 onwards.


Spring

Spring interview questions

Spring framework is most widely used Java EE framework. Spring interview questions check your knowledge on spring framework. It covers topics like dependency injection, scopes, Spring AOP concepts and some important Spring annotations.


Spring boot interview questions

Spring boot is getting popular day by day because it helps you to bootstrap spring application faster. These spring boot interview questions check your knowledge on Spring boot.


Web services

Web services interview questions

Web services interview questions check your knowledge on soap and restful web services.


Rest web services interview questions

These interview questions include restful web services,HTTP methods, and various web service annotations.


Data structure and algorithms

Introduction

This post provides an introduction to important data structures in java. It will help you to understand basic data structures such as queue, stack and linked list.


Data structures and algorithms interview questions

These 40+ interview questions check your knowledge on Stack, queue, linked list, binary tree, binary search tree etc.

Java interview programs

For beginners

If you are freshers or novice programmer, here is the list of interview programs which you can practice.

For experienced programmer

If you are experienced programmer and looking for the list of some good java interview programs, here is the list of java interview programs which you can practice.

If you are looking for java developer remote job, I will recommend jooble job portal.
I hope this Java interview questions list will help you to crack java interview. If you want to add more interview questions, please do comment.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *