Core Java Interview Questions and Answers | Top 150 Java Questions

Cora Java Interview Questions
Share this:

Top 150 Frequently Asked Core Java Interview Question

1. What is Java?
Answer: Java is the high-level programming language and it is also platform-independent. It is the collection of the various objects. It is an Object-Oriented Programming Language. It was developed by James Gosling and first released by the Microsystems in 1995. There are a lot of applications, websites and games that are developed using it. It is supported by the huge community. There are many devices available for us which make use of the Java like Desktop applications such as acrobat reader, media player, antivirus and Enterprise applications.

2. Why Java is so popular?
Answer: There are two main reasons for popularity of Java and they are:
● Platform Independence
● Object Oriented Language

3. What is the role of main function in Java?
Answer: The role of the main function in Java is mandatory for the code execution to start. If your program does not contain "main" method then you will get a run-time error. So, it can be concluded that in the absence of "main" method the whole program will compile but it will throw an error at runtime.

4. What are different Data types in Java?
Answer: ● Byte – 8 bit
● Short – 16 bit
● Char – 16 bit Unicode
● Int – 32 bit (whole number)
● Float – 32 bit (real number)
● Long – 64 bit (Single precision)
● Double – 64 bit (double precision)

5. What are the supported platforms by Java?
Answer: We can see that Java runs on different kinds of platforms and they are Windows, Mac OS and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

6. What are the features of Java?
Answer:OOPs Concepts
It includes the Object-oriented, Inheritance, Encapsulation, Polymorphism and Abstraction.
Platform Independent
It means that a single program works on different platforms without any modification.
High Performance
Java uses Just-in-Time compiler in enabling the high performance. Just-in-Time compiler is a program that turns JAVA byte code into instructions and must be interpreted into instructions that can be sent directly to the processor.
Multi-threaded
The flow of the execution is known as Thread. JVM creates a thread which is called the main Thread. The user in this can generate various threads by extending the thread class or by implementing the runnable interface.

7. List some important features of Java 10 release?
Answer:

● Local-Variable Type Inference
● Consolidate the JDK Forest into a Single Repository
● Garbage-Collector Interface
● Parallel Full GC for G1
● Application Class-Data Sharing
● Thread-Local Handshakes
● Heap Allocation on Alternative Memory Devices
● Experimental Java-Based JIT Compiler
● Root Certificates
● Time-Based Release Versioning

8. How does JAVA enable high performance?
Answer: Java uses Just-in-Time compiler to enable the high performance. Just-in-Time compiler is a program that turns JAVA byte code into instructions and must be interpreted into instructions that can be sent directly to the processor.

9. Why JAVA is considered dynamic?
Answer: Java is designed in a way that it can adapt to an evolving environment. JAVA programs usually carries extensive amount of run-time information which can be later used to verify and resolve accesses to objects on run-time.

10. Java is platform independent language. Why?
Answer:  Java is a programming language which is not dependent on any particular hardware or software because it is compiled by the compiler and then converted into byte code. Byte code is platform-independent and can run on multiple systems. The only requirement for Java is that it needs a runtime environment and that is JRE. It is a set of tools used for the development of Java applications.

11. What is Object-Oriented Programming?
Answer:  Object-Oriented Programming is used as an approach which helps in providing a way of modularizing programs by creating a partitioned memory area for both data and functions that can also be used as templates for creating copies of the modules on the demand.

12. Why we can't say that Java is a pure Object Oriented language?
Answer:  Java is not a pure OOPs language as it uses primitive data types such as int float char double. A pure OOPs language should not use anything but objects and everything to be used should be a class as we can see that in Java, not everything is a class, such as byte, int, float, char, etc. That is the reason for not considering Java as a pure OOPs language.

13. Could you explain the OOPs concepts?
Answer:  Following are the various OOPs concepts:
● Abstraction- Representing essential features without the need to give out background details. This technique is used for creating a new suitable data type for some specific application.
● Aggregation- All objects have their separate lifecycle but the ownership is present. And the no child object can belong to some other object except in case of the parent object.
● Association- The relationship between two objects where each object has its separate lifecycle. There is no ownership.
● Class- A group of similar entities.
● Composition- It is also termed as the death relationship as it is a specialized form of aggregation. Child objects don’t have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted.
● Encapsulation- Refers to the wrapping up of data and the code into a single entity. Allows the variables of a class to be only accessible by the parent class and no other classes.
● Inheritance- When an object acquires the properties of some other objects it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. Offers a robust and natural mechanism of organizing and structuring software.
● Object- Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data.
● Polymorphism- Refers to the ability of a method, object or variable to assume several forms.

14. What do you mean by Java Annotations?
Answer:  Annotation is a tag which represents metadata in Java and attached with a class, method, interface, or field. It provides additional information to be used by compiler and JVM. Annotations do not change a compiled program action and they are also not pure comments.

15. What is synchronization?
Answer: Synchronization refers to multi-threading. A synchronized block of code can be executed by only one thread at a time. As the programming language Java supports execution of multiple threads, two or more threads may access the same fields or objects. It is a process which helps in keeping all of the concurrent threads in execution to be in sync. Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory.

When a method is confirmed as synchronized then the thread holds the monitor for that method’s object. If another thread is executing the synchronized method then the thread is blocked until that thread releases the monitor.

16. Mention the uses of the synchronized block.
Answer: We use the synchronized block because:
● It helps lock an object for every shared resource.
● The scope of the synchronized block is smaller than the method.

17. What is Starvation?
Answer: Starvation describes a situation where a thread is not able to make any process and also not able to gain regular access to the shared resources. This takes place when the shared resources are made unavailable for long periods by “greedy” threads.

18. What is deadlock?
Answer: Deadlock describes a situation where two or more threads are blocked forever and they have to wait for each other.

19. What is Serialization and deserialization?
Answer: Serialization is the process which involves writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

20. Do we need to implement any method to make an object serializable?
Answer: No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.

21. What is a transient variable?
Answer:

● Transient variables are those variables which are not included in the process of serialization.
● Transient variables are not a part of the object’s serialized state.

22. What is javac?
Answer: The javac compiles the source code of your program and generates the bytecode. Javac is able to produce the java byte code from the source code. JVM executes the bytecode to run the program.

23. What is Unicode?
Answer: Java programming language makes use of the Unicode to represent the characters. Unicode are the fully international character set which can represent all of the characters found in human languages.

24. What are Literals?
Answer: Any constant value which is assigned to a variable in Java is termed as literal.

25. What is dynamic initialization?
Answer: Dynamic initialization is a process in which initialization value of a variable isn’t known at compile-time. It’s computed at runtime to initialize the variable.

26. What is BREAK statement in java?
Answer:

● The break statement is used to break the flow sequence in Java. Break statement is generally used with switch case data structure to come out of the statement once a case is executed.
● It can be used to come out of the loop in Java.

27. What is List?
Answer: Elements that can be inserted or accessed by their position or their order in the list using a zero-based index. A list may also contain duplicate elements.

28. What is Map?
Answer: Map interface maps unique keys to values. A key is an object which is used to retrieve a value later. A map is unable to contain duplicate key. Each key can map to at most one value.

29. What is Set?
Answer: A Set is a collection of various elements that cannot contain duplicate elements.

30. Differentiate between List, Set, Map and Queue in Java?
Answer:

● List, Set and Map are three important interfaces of Java collection framework.
● Set provides an unordered collection of unique objects i.e. set does not allow duplicates while Map provides a data structure based on key-value pair and hashing.
● The difference between List and Set interface in Java is that List allows duplicates while Set does not allow duplicates. All implementation of Set honour this agreement. Map holds two objects per entry.
● One more difference between List and Set is that List is an ordered collection. List’s contract maintains insertion order or element. Set is an unordered collection, therefore you get no assurance on which order elements will be stored.
● Nevertheless, some of the set implementation (e.g. LinkedHashSet) retains order.
● All elements in the queue get inserted at the ‘end’ and are removed from the beginning’ (or head).
● You are able to find out how many elements are in the queue but you are not able to find out what the ‘third’ element is.

31. Differentiate between Comparator and Comparable in Java?
Answer: The comparable interface is used to define the natural order of the objects while Comparator is used to describe custom order. Comparable can always be one but it is possible to have multiple comparators to define a custom order for objects.

32. Why ArrayList is better than Arrays?
Answer: Both are different from each other. Array can hold fixed number of elements. ArrayList can grow dynamically.

33. What is the difference between ArrayList and LinkedList?
Answer: LinkedList is used to store the elements within a doubly-linked list data structure. ArrayList is used to store elements within a dynamically resizing array. LinkedList is generally used for addition and updating the operations while ArrayList is a good choice for search operations.

34. For addition and deletion. Which one is most preferred: ArrayList or LinkedList?
Answer: We will prefer LinkedList because deleting or adding a node in LinkedList is faster than ArrayList.

35. For searches. Which one is most preferred: ArrayList or LinkedList?
Answer: We will prefer ArrayList. We can search an element faster in the ArrayList compared to LinkedList.

36. What is the difference between ArrayList and Vector?
Answer:

● The difference between ArrayList and Vector is that vector is synchronized and ArrayList is not synchronized.
● As in the Vector when it is re-sized internally it doubles the size of its array. When ArrayList is re-sized it increases by half of its size.

37. What is the difference between Iterator and ListIterator?
Answer: Following are the major differences between them:
1. Iterator can be used for traversing Set, List and Map.
2. For the traversing of the list the ListIterator can only be used.
3. We can traverse only in forward direction using Iterator. ListIterator can be used for traversing in both the directions.

38. Difference between TreeSet and SortedSet?
Answer: TreeSet implements SortedSet interface.

39. Explain yield and sleep?
Answer: yield() – It allow other threads to execute and also causes currently executing thread object to temporarily pause.
sleep() – It causes to suspend execution for the current thread for a specified period and it doesn’t release the lock when a thread goes into sleep state.

40. What is the difference between sleep() and wait()?
Answer: sleep() – It causes to suspend execution for the current thread for a specified period and it doesn’t release the lock when a thread goes into sleep state.
wait() – It causes the present thread to wait for the another thread until any other thread invokes the notify() method or the notifyAll() method for this object or a specified amount of time has elapsed.

41. What is a container?
Answer: A component which is capable of holding another component is called container.
● Container
● Panel
● Applet
● Window
● Frame
● Dialog

42. Define classes in Java?
Answer: A class is the collection of similar data types. Classes are defined as the user-defined data types and behave like built-in types of a programming language Java. It has variables and the methods. Variables are the attributes which define the state of a class. Methods are the place where the exact business logic is to be done. It contains a set of statements or instructions to satisfy the particular requirement.

43. What is the base class of all classes?
Answer: java.lang.Object is the base class (super class) of all classes in java programming language.

44. What is a wrapper class in Java?
Answer: A wrapper class is a class which converts the primitive data type such as int, byte, char, boolean etc. to the objects of their respective classes such as Integer, Byte, Character, Boolean etc.

45. What is Adapter class?
Answer: Adapter class is an abstract class in a Java programming language. It is the class which is straight opposite to Interface.

46. What is final class?
Answer: Final classes are the classes which can’t be inherited and created so that the methods implemented by that class cannot be overridden.

47. What is a path and classpath in Java?
Answer: Path specifies the location of .exe files. Classpath specifies the location of bytecode(.class files).

48. What do you mean by an object?
Answer: An object contains the methods and classes that depict its state and performs operations. A Java program is a program that involves various objects instructing each other their jobs. This concept is important and also part of core Java.

49. What is object cloning in Java?
Answer: Object cloning in Java is the process of creating or making an exact copy of an object. It basically means the ability to create an object as similar as the original object. To make use of this funtionality, Java provides a method clone(). This method helps in creating a new instance of the class of current object and then it initializes all its fields with the exact same contents of the corresponding fields. To object clone(), as to avoid any runtime exceptions the marker interface java.lang.Cloneable must be implemented. We need to override it because it is a protected method.

50. How can we make use of a copy in a programming language?
Answer: We can use the clone to make copy of an object in a programming language. We can create various copies using the clone. Clone is needed for making or creating the copy of objects.

51. What is Object class?
Answer: This is a special class defined by java programming language and all other classes are subclasses of object class. Object class is superclass of all other classes. Object class has the following methods:
ObjectClone() – It is used to create a new object that is same as the object being cloned.
Booleanequals(Object obj) – It determines whether one object is equal to another.
Finalize() – It is called by the garbage collector when garbage collection determines that there are no more references to the object.
ToString() – It returns a string representation of the object.

52. What is a singleton class? Give a practical example of its usage.
Answer: A singleton class is a class in java where all the methods and variables belong to just one instance because it can have only one instance. Singleton class concept has its importance for the situations when there is a need to limit the number of objects for a class.

53. What’s meant by anonymous class?
Answer: An anonymous class is defined as the class without any name in a single line of code using new keyword.

54. What do you understand from inner class in java? Explain
Answer: It is a class that is a member of another class.
There are 4 types of inner classes:
● Nested Inner class
● Method Local inner classes
● Anonymous inner classes
● Static nested classes

55. Differentiate between an Inner Class and a Sub-Class?
Answer: An Inner class is a class that is nested within another class. An Inner class can access all variables, methods defined in the outer class and have access rights for the class which is nesting it. A sub-class is a class which inherits from another class known as super class. Sub-class has access to all fields, public and protected methods of its super class.

56. Can a class be a super class and a sub-class at the same time? Give example.
Answer: A class can be a super class for another class and a sub-class for another one at the same time if there is a hierarchy of inheritance used.

57. Can a top level class be private or protected in Java programming language?
Answer: Top level classes in java can’t be private or protected but inner classes in java can be private or protected. The reason for not making a top level class as private is very obvious because nobody can see a private class and thus they can’t use it. To declare a class as protected also doesn’t make any sense. We can use the visibility in any package by inheriting. It this is the difference between default visibility and protected visibility.

Hence in java we find that there is no such concept of package inheritance and defining a class as protected class is no different from default.

58. What is an interface in Java? Explain
Answer: It is a reference type that is similar to a class in Java. Interface is a collection of abstract methods that is used for full abstraction. It may have methods and variables but the methods in interface are abstract by default.

59. What do you understand by the Marker interface in Programming language?
Answer: It is an interface that has no field or methods. Marker interface helps in conveying to the JVM that the class that is implementing the interface of a category will have some special behavior. It is also known as tag interface.
There are 4 major marker interfaces:
● Searilizable interface
● Cloneable interface
● Remote interface
● ThreadSafe interface

60. Differentiate between an Abstract Class and Interface in Java?
Answer: The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no solid implementation while an abstract class can have members with any access specifiers and they are public or private with or without solid implementations.

Abstract Class Interfaces
An abstract class can provide complete, default code or just the details that have to be overridden in Java. An interface is not able to provide any code at all, just the signature. In the case of an abstract class, a class may extend one abstract class only.

A Class may implement several interfaces. An abstract class can have non- abstract methods. All methods of an Interface are abstract. An abstract class can have instance variables. An Interface cannot have the instance variables. An abstract class can have any visibility such as public, private, protected.

An Interface visibility must be public or none. In abstract class we have the option of providing default implementation if we add a new method to an abstract class and therefore all the existing code might work properly.

We have to track down all the implementations of the interface if we add a new method to an Interface and define implementation for the new method. An abstract class can contain constructors. An Interface cannot contain constructors. Abstract classes are generally fast and do not require extra indirection. Interfaces are slow as it requires extra indirection to find the corresponding method in the actual class

61. What do you mean by Access Modifier?
Answer: Java provides the access modifiers to set the access levels for the different elements like classes, variables, methods and constructors. In Java we can say that access modifiers are the special keywords that are used to restrict the access of a class, constructor, data member and method in another class. Java supports four types of the access modifiers:
1. Default
2. Private
3. Protected
4. Public

62. What is protected access modifier?
Answer: Variables, methods and constructors which are declared protected in a superclass can be accessed by any class within the package of the protected members, class or only by the subclasses in other package. That’s why access modifiers are protected.

63. What do you understand by the term synchronized Non Access Modifier?
Answer: Java provides the modifiers other than Access Modifiers for the purpose of providing functionality and the synchronized is used to indicate that a method can be accessed by only one thread at a time.

64. Explain the various or multiple access specifiers for Java classes?
Answer: In Java the access specifiers are the keywords which are used before a class name and which defines the access scope. The types of access specifiers for classes are:
Public:
The Class, Method, Field are accessible from anywhere.
Protected:
The Method, Field can be accessed from the same class to which they belong or from the sub-classes and from the class of same package but they are not accessed from outside.
Default:
The Method, Field, class can be accessed only from the same package and not from outside of its native package.
Private:
The Method, Field can be accessed from the same class to which they belong.

65. What is a Local Variable?
Answer: Variables which are defined inside the methods, constructors or blocks are called local variables. The variable will be destroyed when the method has completed and will be declared and initialized within the method.

66. What is an Instance Variable?
Answer: Instance variables are the variables which are within a class but outside any method. When the class is loaded then these variables are instantiated.

67. What is a Class Variable?
Answer: These are variables which are declared with in a class, outside any method, with the static keyword.

68. What is static variable in Java?
Answer: Static variables are those variables which are also known as class level variables. Static variables are also same for all the objects of that particular class in which they are declared.

69. Differentiate between static and non-static variables?
Answer: Static variable are same for all the objects of that particular class in which they are declared. Non-static variables take unique values with each object instance and not same for all.

70. Differentiate between transient and volatile variables in Java?
Answer:

Transient: In Java, it is used to specify whether a variable is not being serialized. Serialization is defined as the process of saving an object’s state in Java. When we want to persist the object’s state by default, all instance variables in the object are stored. In some cases, we want to avoid in persisting a few variables because we don’t have the necessity to transfer across the network. So, we declare those variables as transient.
● The transient keyword is used with the instance variable that will not participate in the serialization process. We cannot use static variable along with a transient variable as they are part of the instance variable.
Volatile: The volatile keyword is used with only one variable in Java and it guarantees that the value of the volatile variable will always be read from the main memory and not from the thread’s local cache; it can be static.

71. What is static block?
Answer: A static block is used for initializing static variables and they gets executed at the time of class loading.

72. What is a static method?
Answer: Static methods can be called directly without creating the instance of the class. A static method can have access to all the static variables of a class directly but it cannot access non-static variables without creating instance of class.

73. What’s the role of Static methods and static variables?
Answer: We make use of static methods and static variables to make a method or variable shared for all of the objects between multiple objects of a class instead of creating separate copies for each object.

74. Explain super keyword in Java?
Answer: Super keyword is references to the parent class. There are several uses of super keyword which are as follows:
● It can be used to call the superclass which is the parent class constructor.
● It can be used to access a method of the superclass that has been hidden by subclass by calling parent class version in case of method overriding.
● It can be used to call the constructor of parent class.

75. What is final keyword in Java?
Answer: Final is a special keyword in Java which is used as a non-access modifier. A final variable can be used in different contexts such as follows:
Final variable: When the final keyword is used with a variable then the value of the variable can’t be changed once it is assigned in programming language. By using the class constructor a value can be assigned to it if in the case no value has been assigned to the final variable.
Final method: When a method is declared as final then it can’t be overridden by the inheriting class.
Final class: When a class is declared as final in Java then it can extend other class but also can’t be extended by any subclass.

76. What is the purpose of the keywords final, finally and finalize?
Answer:

Final: Final is used to for the application of restriction on a class, method and variable. A final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.
Finally: Finally is the keyword which is used to place important code and it will be executed whether the exception is handled or not.
Finalize: Finalize is used to perform the clean up processing task just before the object is collected in the garbage collection.

77. What are the differences between throw and throws?
Answer: Throw is used to explicitly throw an exception. Throws is used to declare an exception. Checked exceptions can’t be propagated with throw only. Checked exception can be propagated with throws. Throw is followed by an instance. Throws is followed by class. Throw is used within the method. Throws is used with the method signature. You cannot throw multiple exception. You can declare multiple exception e.g. public void method()throws IOException,SQLException.

78. Why String class is considered immutable?
Answer: String class is considered immutable in Java since Java designer thought that String will be greatly used, making it immutable. It makes the sharing easy and also the same String object between the multiple clients.
It is worth noting that it isn’t possible to share a mutable project with two parties which are unfamiliar to each other.

79. Why StringBuffer is called mutable?
Answer: StringBuffer is called mutable because the String class is immutable in this when once the string object is created then it can’t be changed and if we need to make alot of modifications to Strings of characters then we must use the StringBuffer.

80. Difference between String, StringBuilder and StringBuffer.
Answer: String is immutable where as the other two are mutable. Thread safety doesn’t exist for StringBuilder. String has fast performance. StringBuilder is efficient but StringBuffer is less efficient.

81. Which one should be preferred when we require a lot of change in data from String or StringBuffer?
Answer: We should prefer StringBuffer as they are mutable if we need to make a lot of modifications to String of characters then we must use the StringBuffer because the String class is immutable. In this when once the string object is created then it can’t be changed.

82. What is a Thread?
Answer: A thread is the smallest piece of programmed instructions which can be executed independently by a scheduler. In Java, all the programs contain at least one thread which is called as the main thread and which is created by the JVM when the program starts its execution. The role of this is to invoke the main() of the program.

83. What is a daemon thread?
Answer: A daemon thread is a thread that is not able to prevent the JVM from exiting when the program finishes but the thread is still running. Example: Garbage collection.

84. What are the ways that can be used to create a thread in programming language?
Answer:There are two ways to create the threads in Java which are as follows:-
● By implementing the Runnable interface.
● By extending the Thread

85. Describe different states of a thread.
Answer: The different states of threads are as follows:
a) Ready: When a thread is just created then it’s in its Ready state.
b) Running: A thread currently being executed then it is in running state.
c) Waiting: When the thread is waiting for another thread to free certain resources then it is in its waiting state.
d) Dead: A thread which has become dead after the execution is in its dead state.

86. What is Multithreading?
Answer: Multithreading is a process which helps in executing two or more parts of a program simultaneously. Each of these parts of a program which are executed simultaneously is known as threads. And we can say that it is the process of executing multiple threads simultaneously.

87. What is the role of having multithread environment in programming language?
Answer: It is used to maximize the CPU usage and also to reduce the CPU idle time.

88. How we can get confirmed that a resource isn’t used by multiple threads simultaneously in the case of multi-threading?
Answer: In multi-threading the access to the various resources can be controlled by the concept of synchronization which are shared among multiple threads. By making use of synchronized keyword we can get confirmed that only one thread can use shared resource at a time and others can get control of the resource only once and it has also become free from the other one using it.

89. Explain five best practices that we can apply while we are making use of the threads in Java.
Answer: These are the five best practices which must be applied while using the threads.
● We should always name our thread.
● We should prioritize our task and threads by keeping them separate and use runnable and Callable with thread pool executor.
● Use thread pool.
● We should use the volatile to indicate the compiler about ordering, visibility and atomicity.
● We must avoid thread local variable because improper use of ThreadLocal class in Java can produce a memory leak.

90. Explain five best practices that we can follow while writing multithreaded code in programming language?
Answer: When writing concurrent code in Java the following are some best practices to be kept in mind:
● Always name our thread as this help in debugging.
● Minimise the scope of your synchronisation. Rather than making the whole method synchronised, be mindful that only the critical section should be synchronised.
● Opt for volatile over synchronisation if you have the option to.
● We must use a higher level of concurrency utilities instead of waiting() and notify for inter-thread communication.
● Opt for concurrent collection over synchronised collection in Java as this will provide better scalability.

91. How garbage collection is done in Java?
Answer: In java, when an object is not referenced any more, garbage collection takes place and the object gets destroyed automatically. And also the java calls either System.gc() method or Runtime.gc() method for the automatic garbage collection.

92. How many types of garbage collectors are there in Java?
Answer: Garbage collection helps in implicit memory management in a Java program. As in the Java by making use of the any new keyword we can create objects dynamically and that is the object which once created will also consume some memory and when once the job is over then there are no more references left to that object. Java makes use of the garbage collection and destroys the object and relieves the space occupied by it in the memory.

There are four types of garbage collectors:
● Serial Garbage Collector
● Parallel Garbage Collector
● CMS Garbage Collector
● G1 Garbage Collector

93. Can we say that java program never goes out of memory due to its features?
Answer: As the automatic garbage collection is provided by Java but due to this we can’t say that the program will not go out of memory as there is a possibility that creation of Java objects takes place at a faster rate as compared to garbage collection which results in filling of all the available memory resources. Therefore, we can’t say that it never goes out of memory due to its feature like garbage collection or any other.

94. What is Inheritance?
Answer: Inheritance means the process in which the one class can extend to another class so that the codes can be reused. The existing class is known as the Super class whereas the derived class is known as a sub class.

Inheritance is applicable for public and protected members only and not for others. Private members can’t be inherited.

95. What are multiple inheritances? Is it supported by Java?
Answer: If a child class inherits the property from multiple classes is known as multiple inheritances. Java does not allow extending multiple classes. The problem which is associated with the multiple inheritances is that if sometimes the multiple parent classes have the same method name then it becomes difficult for the compiler to decide at the runtime which method to execute or to use from the child class. Therefore, Java doesn’t support multiple inheritances. The problem is generally called as the Diamond Problem.

96. How many types of inheritance are there in Java?
Answer: Java supports four types of inheritance which are:
1. Single Inheritance: In this inheritance, one class inherits the properties of another and there will be only one parent and one child class.
2. Multilevel Inheritance: In this inheritance, when a class is derived from another class which is also derived from other class and in this a class will have more than one parent class but at different levels.
3. Hierarchical Inheritance: In this inheritance, when a class has more than one child classes (subclasses) or it has more than one child classes and having the same parent class.
4. Hybrid Inheritance: In this there is a combination of two or more types of inheritance.

97. What is composition in java?
Answer: Composition is the design technique which is used for the implementation of has-a relationship in classes. We can use Object composition for code reuse. Java composition can be achieved by making use of the instance variables that refer to other objects. The advantage of this composition is that we can control the visibility of other objects to client classes and reuse only what we need according to our requirement.

98. What is the benefit of Composition over Inheritance?
Answer: Composition is more beneficial than the inheritance in java. Some of the possible reasons are:
● Any change in the superclass might affect subclass even though we might not be using the superclass methods.
● Inheritance exposes all the superclass methods and variables to the client it can lead to the security holes which are not safe and secure if we have no control in designing superclass whereas it is not the case with the composition. It allows users to provide restricted access to the methods and also it is more secure.
● We used to get binding in composition at its runtime where in the inheritance the binding of the classes takes place at its compile time. So composition is more flexible in the invocation of methods.

99. What is meant by collection in Java?
Answer: Collection is a framework that is designed to store the objects and manipulate the design to store the objects.
Collections are used to perform the following operations:
● Searching
● Sorting
● Manipulation
● Insertion
● Deletion
A group of objects is known as collections. All the classes and interfaces for collecting are available in Java.util package.

100. What do you understand from Ordered and Sorted in collections in programming language?
Answer:

Ordered- It means the values that are stored in a collection are based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.
Sorted- Sorting mechanisms can be applied internally or externally so that the group of objects sorted in a particular collection is based on the properties of the objects.

101. Explain five best practices we should apply while using Collection in Java.
Answer: The following are some of the best practices we should apply while using Collection in Java:
● Ensure you are using the right collection, e.g. if there is a requirement of a non- synchronised list then we should opt for ArrayList and not Vector.
● Opt for concurrent collection over a synchronised collection because they are more scalable.
● Ensure that we are using interface to represent and access a collection e.g. use List to store ArrayList, Map to store HashMap.
● Use iterator to loop over collection.
● Always use generics with collection.

102. What is Classloader in Java?
Answer: Java Classloader is the program which is able to load the byte code program into memory when we want to access any class. We are able to create our own classloader by extending the ClassLoader class and overriding loadClass method.

103. What are different types of classloaders?
Answer: The different types of classloaders are as follows:
● Bootstrap Class Loader – It helps in loading JDK internal classes, typically loads are the rt.jar and also other core classes.
● Extensions Class Loader – It loads classes from the JDK extensions directory, usually from the $JAVA_HOME/lib/ext directory.
● System Class Loader – It helps in loading classes from the current classpath that can be set while invoking a program by using -cp or -classpath command line options.

104. What is method overloading?
Answer: When a class has more than one method with the same name but different number, sequence or types of arguments then it is known as method overloading.

105. Explain the best practices in Java of overloading a method.
Answer: The following are the examples of best practices of overloading a method in Java to
avoid the confusion with auto-boxing:
● We should not overload a method where one accepts int and the other accepts Integer.
● Don’t overload method where a number of arguments are the same and only the order of argument is different.

106. What is function overloading?
Answer: It is defined as the overloading in which if a class has multiple functions by same name but different parameters, it is known as Method Overloading.

107. What is function overriding?
Answer: If a subclass is able to provide a specific implementation of a method which is already provided by its parent class, it is termed as Method Overriding.

108. What is method overloading and method overriding?
Answer: Method Overloading:
● In this the methods of the same class share the same name but each method must have a different number of parameters or parameters having different types and order.
● Method Overloading is to “add” or “extend” more to the method’s behavior.
● It is a compile-time polymorphism.
● The methods must have a different signature.
● It may or may not need inheritance means the inheritance is not compulsory in the method overloading.
Method Overriding:
● In this the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.
● Method Overriding is to “Change” existing behavior of the method.
● It is a run time polymorphism.
● The methods must have the same signature.
● It always requires inheritance in Method Overriding.

109. What are constructors in Java?
Answer: A constructor in Java is referred to a block of code which is used to initialize an object. It is necessary for it to have the same name as that of the class. It is automatically called when an object is created and also it has no return type.
There are two types of constructors:
Default Constructor: A default constructor is defined as the constructor which does not take any inputs. Default constructors are also known as the no argument constructors which will be created by default in case when user doesn’t define any constructor. The main purpose of this is to initialize the instance variables with the default values. Also, it is majorly used for object creation.
Parameterized Constructor: A parameterized constructor is the one which has the capacity of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.

110. Define default constructor in Java.
Answer: These are the constructors which are automatically created when no other constructor is defined by the user in Java. The main purpose of this is to initialize the instance variables with the default values. Also, it is majorly used for object creation.

111. Can a class have multiple constructors?
Answer: We can say that a class can have multiple or various constructors with different parameters. These are the constructors which are used for the object creation also it depends on the arguments passed while creating the objects.

112. What is a copy constructor in Java?
Answer: Copy constructor is a construction in Java which is used for initializing an object by using another object which belongs to the same class. Also there is no need for copy constructor in Java since all objects are passed by the reference. Moreover, Java does not even support automatic pass-by-value.

113. What is a constructor overloading in Java?
Answer: Constructor overloading is a technique or method of adding any number of constructors to a class and each having a different parameter list. The compiler uses the number of parameters and their types in the list to differentiate the overloaded constructors.

114. How are destructors defined in Java?
Answer: There are no destructors defined in the class as there is no need to define any destructors in Java. As the Java has its own garbage collection feature which does the job automatically by destroying the objects when they are no longer referenced or needed.

115. Differentiate between the constructors and methods in Java?

Answer:

Methods Constructors
1. Used to represent the behavior of an object. 1. Used to initialize the state of an object.
2. Must have a return type. 2. Do not have any return type.
3. Needs to be invoked explicitly. 3. Is invoked implicitly.
4. There is no default method provided by the compiler in the methods. 4. In this a default constructor is provided by the compiler if the class has no constructor assigned by the user.
5. For the method, name may or may not be same as class name. 5. But for the constructor name must always be the same as the class name

 

116. What are Loops in Java? What are three types of loops?
Answer: Looping is defined as the technique which is used in programming to execute a statement or a block of statement repeatedly. There are different types of loops in Java:
1) For Loops
For loops are used in java for the purpose of executing statements repeatedly for a given number of times.
2) While Loops
While loops are used when certain statements need to be executed repeatedly until a condition is fulfilled and in this the condition is checked at first before execution of statements.
3) Do While Loops
Do While Loops are same as while loops and the only difference is that condition is checked after execution of block of statements in these loops and in case of the do while loops the statements are executed at least once.

117. What is an infinite Loop?
Answer: An infinite loop is defined as the loop which runs without any condition and runs infinitely. Also an infinite loop can be broken by defining any breaking logic in the body of the statement blocks.

118. What is Casting?
Answer: Casting is used for the objective to convert one data type to another data type.
There are two types of Casting:
● Implicit Casting
● Explicit Casting

119. What is Implicit Casting?
Answer: Implicit Casting is done by the compiler. Examples of implicit casting is all the automatic widening conversion i.e. storing smaller values in larger variable types.

120. What is Explicit Casting?
Answer: Explicit Casting is done through code. Examples of explicit casting is the narrowing conversion – storing larger values into smaller variable types. Explicit casting would cause truncation of value if the value stored is greater than the size of the variable.

121. What is objective behind using break and continue statements in Java?
Answer: When the break statement is inside a loop, the loop gets terminated and the program resumes at the next statement after the loop. The role of the continue statement is to get used in the loop control structure. It causes the loop to jump to the next iteration.

122. What is meant by Exception?
Answer: An Exception is a problem that can occur during the normal flow of execution. A method is able to throw an exception when there is something wails at the runtime. If the user is not able to handle the execution properly then in that case the execution gets terminated before it completes the task assigned to it. If the user is capable of handling the exception then the normal flow gets continued. Exceptions are a subclass of java.lang.Exception.

123. What is the difference between Error and Exception?
Answer: An error is an irrecoverable condition occurring at runtime. SuchasOutOfMemoryerror. These JVM errors are those errors which cannot be repaired by the user or programmer at the runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.

Exceptions are conditions which take place due to the bad input or human error etc. e.g. FileNotFoundException is also an exception and it gets flashed while the file is not found and if we try using null reference then the NullPointerException will take place. In almost every case it is possible for the user to get out of the exception by entering proper values.

124. What is OutOfMemoryError in Java?
Answer: OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

125. What are the types of Exceptions?
Answer: There are two types of Exceptions.
Checked Exception:
These are the exceptions which are checked by the compiler at the time of compilation. Classes which are able to extend the Throwable class except Runtime exception and Error are termed as checked Exception. Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.
Unchecked Exception:
These are the exceptions which are not checked by the compiler at the time of the compilation.  The compiler doesn’t force to handle these exceptions. It includes:
ArithmeticException
ArrayIndexOutOfBoundsException

126. Explain Runtime Exceptions?
Answer: These are the exceptions that occurs and they are probably have been avoided by the programmer or users. They are just opposite to checked exceptions as these runtime exceptions are ignored at the time of compilation.

127. What is NullPointerException?
Answer: A NullPointerException is an exception which takes place if we are trying to use null reference like the null object, accessing or modifying the field of a null object etc.

128. What things should be kept in mind while creating our own exceptions in Java?
Answer: While creating our own exception –
● We should keep in our mind that all exceptions should be a child of Throwable class.
● If we want to write a checked exception which is automatically enforced by the Handle or Declare Rule then we only need to extend the Exception class.
● If we want to write a runtime exception then we need to extend the RuntimeException class.

129. What are the different ways to handle exceptions?
Answer: The different ways to handle exceptions are explained below:
Using try/catch:
A risky code is surrounded by try block. If an exception takes place then it is caught by the catch block and the catch block is followed by the try block.
By declaring throws keyword:
We can declare the exception using throws keyword at the end of exception.

130. What are the Exception handling keywords in Java?
Answer: Enlisted below are the Exception Handling Keywords:
Try:
It is used when a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. It can be followed either by catch (or) finally (or) both the blocks. But any one of the blocks is mandatory.
Catch:
This is followed by try block. Exceptions are caught here.
Finally:
This is the keyword which is followed by either try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.

131. Explain about Exception Propagation.
Answer: In the exception propagation a exception is the one which is first thrown from the method that is lying at the top of the stack. If it doesn’t catch the exception then it pops up the method and get moved towards the previous method and it further goes on until they are got. This is called Exception propagation.

If an exception takes place in the addition() method and it is not caught then it moves towards the method add() then it is moved to the main() method and then it will stop the flow of execution. It is called Exception PPropagation.

132. Explain the important methods which are described for the Java Exception Class?
Answer: Exception and all of its subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.
a) String getMessage() – This is the method which returns the message String of Throwable class and the message can be provided while creating the exception with the help of constructor.
b) String getLocalizedMessage() – This is the method which is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
c) Synchronized Throwable getCause() – This is a method which returns the cause of the exception or null id and the cause is unknown.
d) String toString() – This method returns the information about the throwable in the String format and also the returned String contains the name of throwable class and also it contains the localized message.
e) void printStackTrace() – This method prints the stack trace information to the standard error stream. This method is overloaded and we can pass PrintStream or PrintWriter as an argument which is used to write the stack trace information to the file or stream.

133. What is a Socket?
Answer: A Socket helps in providing the communication mechanism between two computers using Transfer Control Protocol and a client program is able to create a socket at its end of the communication and also attempts to connect that socket to a server.

134. What are Advantages of Java Sockets?
Answer: Sockets are flexible and sufficient and also the efficient socket based programming is easy for the implementation for the general communications. It cause low network traffic.

135. What are Disadvantages of Java Sockets?
Answer: Socket based programming is easy for the implementation of the general communications but it allows only to send packets of raw data among the various applications. The efforts are to be done by both client-side and server-side to provide mechanisms for making the data useful and also efficient in any way.

136. Differences between  HashMap and HashTable in Java .
Answer:

1. As the HashMap is non-synchronized it is not-thread safe and we can’t share it among multiple threads without the proper synchronization code whereas the Hashtable is synchronized and is thread safe and we can share it among multiple threads.
2. HashMap allows one null key and multiple null values whereas the Hashtable doesn’t do so and it doesn’t allow any null key or value.
3. Inspite of all this HashMap is generally preferred over HashTable if we do not need any thread synchronization.

137. How an object is serialized in java?
Answer: In java when we need to convert an object into byte stream by serialization, an interface with the name Serializable is implemented by the class. All objects of a class implementing serializable interface get serialized and their state is saved in byte stream.

138. When we should use serialization?
Answer: Serialization is the technique which is used when the data needs to be transmitted over the network. By using the serialization technique the state of an object is saved and converted into the byte stream .The byte stream is transferred over the network and the object is re-created at destination.

139. Differentiate between JDK, JRE and JVM?
Answer:

JDK

It is an acronym for Java development kit. It is also a software development environment that is used for the development of Java applications and applets. It physically exists. It contains JRE and development tools. JDK is an implementation of any one of the below given Java platforms released by the Oracle Corporations.
● Standard Edition Java Platform
● Enterprise Edition Java Platform
● Micro Edition Java Platform

JRE
It stands for Java Runtime Environment. It is implementation of JVM. The Java run-time environment is a set of software tools which are used for developing Java applications. It is used to provide run-time environment. It is the implementation of JVM. It contains a set of libraries and other files that JVM uses at run-time.

JVM
It is a virtual machine that provides runtime environment to drive Java programs or applications. It assists in converting bytecode into machine language and handles system memory.

140. What is an Array?
Answer: An array is a collection (group) of fixed number of items. Array is a homogeneous data structure which means we can store multiple values of same type in an array but it can’t contain multiple values of different types. For example an array of int type have the capacity to hold the integer values.

141. Differentiate between Array list and vector in Java?
Answer:

Array List Vector
Array List is not synchronized.  Vector is synchronized.
Array List is fast as it is non-synchronized. Vector is slow as it is thread safe.
If an element is get inserted into the Array List then it is capable of increasing its Array size by 50%. Vector defaults to doubling size of its array.
Array List does not define the increment size. Vector defines the increment size.
For the Array List it can only use the Iterator for traversing an Array List. Vector can use both Enumeration and Iterator for traversing.

 

142. What is a package in Java? List down various advantages of packages.
Answer: Packages in Java are termed as the collection of related classes and also interfaces that are bundled together. By using packages, developers can easily modularize the code and optimize its reuse. Also, the code within the packages can be imported by other classes and reused. Below I have listed down a few of its advantages:
● Packages help in avoiding name clashes.
● They provide easier access control on the code.
● Packages sometimes also contains some of the classes which are hidden that are not visible to the outer classes and only to be used within the package.
● Packages helps in creating or making a proper hierarchical structure that makes it easier to locate the related classes for the users.

143. What is JIT compiler in Java?
Answer: JIT means Just-In-Time compiler in Java. It is a program which helps to convert the Java bytecode into instructions and these are sent directly to the processor. JIT compiler is enabled or used in Java and is activated whenever a Java method is invoked.

JIT compiler is then capable of compiling the bytecode of the invoked method into the native machine code, compiling it “just in time” for its execution. Once the method gets compiled by the compiler then the JVM do not interpret it but summons the compiled code of that method directly and it is also responsible for the performance optimization of Java programming language.

144. Explain the Java Virtual Machine and how we can say that it is related to the Java’s platform independent feature?
Answer: When Java is compiled then it is compiled into the platform independent byte code and not compiled into platform specific machine. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

145. Differentiate between equals() and == in Java?
Answer: Equals() method is a method that is defined in the Object class in Java and that is used for checking equality of two objects defined by business logic.
“==” or equality operator in Java is defined as the binary operator provided by Java programming language and that is used for comparing primitives and also the objects. public boolean equals is the method which is provided by the Object class.

The default implementation uses == operator to compare between any two objects. For example: The method can be overridden like String class. equals() method is the method that is used to compare the values of two objects.

146. Differentiate between Heap and Stack Memory in Java?
Answer: The difference between Heap and Stack memory are as follows:

Features Stack Heap
Memory Stack memory is used only by the one thread of execution. Heap memory is used by all the parts of the application not only by the one thread execution.
Access Stack memory can’t be accessed by the other threads. The Objects stored in the heap memory can be globally accessible.
Memory Management Stack memory follows the LIFO manner to free memory. In this the memory management is based on the generation associated with each object.
Lifetime Its lifetime is that it exists until the end of execution of the thread. Its lifetime is that it lives from the start till the end of application execution.
Usage Stack memory is the memory that only contains local primitive and reference variables to the objects in heap space. Whenever we are able to create an object then it’s always stored in the Heap space.

 

147. Differentiate between this() and super() in Java Programming language?
Answer: The difference between this() and super() in Java are as follows:

this() super()
1. this() represents the current instance of a class. 1. super() represents the current instance of a parent/base class.
2. Used to call the default constructor of the same class. 2. Used to call the default constructor of the parent/base class.
3. Used to access methods of the current class. 3. Used to access methods of the base class.
4.  Used for pointing the current class instance. 4. Used for pointing the superclass instance.
5. Must be the first line of a block. 5. Must be the first line of a block.

 

148. What is the byte order of ByteBuffer?
Answer: The byte order is used when we need to read or write the multibyte values and when creating buffers that are views of this byte buffer.

149. Differentiate between direct buffer and non-direct buffer in Java?
Answer: Byte buffer is one of the important classes of Java Programming language. This was initially introduced in java.io package on JDK 1.4. It lets us function on heap byte arrays as well as with direct memory which occurs outside the JVM. The main difference between direct and non-direct byte buffers is their memory location, non-direct byte buffers are just a wrapper around byte array and they reside in Java Heap memory.

Meanwhile, direct byte buffer is outside of JVM and memory is not assigned from the heap. A byte buffer is either direct or non-direct. Given a direct byte buffer, the Java Virtual Machine will make a best effort to complete native I/O operations directly upon it. It will try to evade copying the buffer’s content to (or from) an intermediate buffer before (or after) each invocation of one of the underlying operating system’s native I/O operations.

150. What is the memory mapped buffer in Java?
Answer: Java IO has become considerably fast after the introduction of the IO and memory mapped file and offers fastest IO operation which is possible in the Java. A key advantage of memory mapped file is that operating system is responsible for reading and writing and even if your program malfunctioned just after writing into memory.

OS will also take care of writing content within the file.

 

Java is a programming language that doesn’t need any introduction, this is the leading programming language in the world. Core Java is nothing but the combination of all foundational components of Java. Core Java is widely preferred as back end system considering its robustness, flexibility and architecture.

Considering the current usage and predicated usage of Core Java across the world, there is going to be a consistent demand for Core Java skills in Job market.

The above 150 Top Core Java interview questions were compiled to help freshers and experienced Java professionals to help in their job interviews. Please go through these frequently asked Core Java interview questions to get better prepared for your next interview.

 

Share this:

Leave a Comment

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