Java Interview Questions & Answers for Freshers and Experienced

Prepare for Java interviews with a comprehensive set of Core Java interview questions and answers. This guide covers OOP concepts, JVM internals, collections, multithreading, exception handling, and memory management commonly asked in technical interviews.

Top Java Interview Questions for Freshers and Experienced

89 Questions Easy · Medium · Hard

1 What are the principle concepts of OOPS in Java?

Answer
There are four principle concepts upon which object oriented design and programming rest. They are:
1. Abstraction
2. Polymorphism
3. Inheritance
4. Encapsulation
Did you know it?

2 What is Abstraction in Java?

Answer
Abstraction refers to the act of representing essential features without including the background details or explanations.
Did you know it?

3 What is Encapsulation in Java?

Answer
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It helps to modify your code without breaking the client code.
Did you know it?

4 What is the difference between abstraction and encapsulation in Java?

Answer
Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
Abstraction solves the problem in the design side while Encapsulation is the Implementation. Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
Did you know it?

5 What is Inheritance in Java?

Answer
Inheritance is the process by which objects of one class acquire the properties of objects of another class. The two most common reasons to use inheritance are:
To promote code reuse
To use polymorphism
Did you know it?

6 What is Polymorphism in Java?

Answer
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
Did you know it?

7 What is runtime polymorphism or dynamic method dispatch?

Answer
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
Did you know it?

8 What is Dynamic Binding in Java?

Answer
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
Did you know it?

9 What is method overloading in Java?

Answer
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
1. Overloaded methods MUST change the argument list
2. Overloaded methods CAN change the return type
3. Overloaded methods CAN change the access modifier
4. Overloaded methods CAN declare new or broader checked exceptions
5. A method can be overloaded in the same class or in a subclass
Did you know it?

10 Can we overload main method in Java?

Answer
Yes, we can have multiple methods with name “main” in a single class. However if we run the class, java runtime environment will look for main method with syntax as public static void main(String args[]).
Did you know it?

11 What is method overriding?

Answer
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
1. The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
2. You cannot override a method marked final
3. You cannot override a method marked static
Did you know it?

12 Can you override private or static method in Java ?

Answer
You can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding.
Did you know it?

13 Can overloaded methods be overriden too in Java?

Answer
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not be binding the method calls since it is overloaded, because it might be overridden now or in the future.
Did you know it?

14 Is it possible to override the main method in Java?

Answer
No, because main is a static method. A static method can't be overridden in Java.
Did you know it?

15 What is super in Java?

Answer
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note:
1. You can only go back one level.
2. In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.
Did you know it?

16 What is static keyword in Java?

Answer
static keyword can be used with class level variables to make it global i.e all the objects will share the same variable.
static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.
Did you know it?

17 What is difference between path and classpath variables in Java?

Answer
PATH is an environment variable used by operating system to locate the executables. That’s why when we install Java or want any executable to be found by OS, we need to add the directory location in the PATH variable.
Classpath is specific to java and used by java executables to locate class files. We can provide the classpath location while running java application and it can be a directory, ZIP files, JAR files etc.
Did you know it?

18 What is final keyword in Java?

Answer
final keyword is used with Class to make sure no other class can extend it, for example String class is final and we can’t extend it.
We can use final keyword with methods to make sure child classes can’t override it.
final keyword can be used with variables to make sure that it can be assigned only once. However the state of the variable can be changed, for example we can assign a final variable to an object only once but the object variables can change later on.
Java interface variables are by default final and static.
Did you know it?

19 What is JIT compiler?

Answer
It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
Did you know it?

20 What is classloader in JVM in Java?

Answer
The classloader is a subsystem of JVM that is used to load classes and interfaces. Following are the class loaders which executes in below mentioned order.
1. Bootstrap classloader (loads class file from rt.jar)
2.Extension classloader (loads class file from ext folder under JDK installlation directory)
3.System classloader (loads class file from classpath )
Did you know it?

21 If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?

Answer
It is empty. But not null.
Did you know it?

22 What is difference between object oriented programming language and object based programming language?

Answer
Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.
Did you know it?

23 What is difference between aggregation and composition?

Answer
Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).
Did you know it?

24 What is difference between final, finally and finalize?

Answer
final: final is a keyword, final can be variable, method or class.You, can't change the value of final variable, can't override final method, can't inherit final class.
finally: finally block is used in exception handling. finally block is always executed.
finalize(): finalize() method is used in garbage collection.finalize() method is invoked just before the object is garbage collected.The finalize() method can be used to perform any cleanup processing.
Did you know it?

25 What is break and continue statement?

Answer
We can use break statement to terminate for, while, or do-while loop. We can use break statement in switch statement to exit the switch case.
The continue statement skips the current iteration of a for, while or do-while loop. We can use continue statement with label to skip the current iteration of outermost loop.
Did you know it?

26 What is an Interface?

Answer
An interface is a description of a set of methods that conforming implementing classes must have. Note:
You can’t mark an interface as final.
Interface variables must be static.
An Interface cannot extend anything but another interfaces.
Did you know it?

27 Can we create an object for an interface?

Answer
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.
Did you know it?

28 What modifiers are allowed for methods in an Interface?

Answer
Only public and abstract modifiers are allowed for methods in interfaces.
Did you know it?

29 What is a marker interface?

Answer
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
Did you know it?

30 What is anonymous inner class?

Answer
A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement. Anonymous inner class always extend a class or implement an interface.
Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class. Anonymous inner classes are accessible only at the point where it is defined.
Did you know it?

31 What is an abstract class?

Answer
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Note:
If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
You can’t mark a class as both abstract and final.
Did you know it?

32 Can we instantiate an abstract class?

Answer
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
Did you know it?

33 When should I use abstract classes and when should I use interfaces?

Answer
Use Interfaces when…
You see that something in your design will change frequently.
If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for non-leaf classes in class hierarchies.
Did you know it?

34 When you declare a method as abstract, can other nonabstract methods access it?

Answer
Yes, other nonabstract methods can access a method that you declare as abstract.
Did you know it?

35 What is Constructor?

Answer
A constructor is a special method whose task is to initialize the object of its class.
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.
Did you know it?

36 How are this() and super() used with constructors?

Answer
Constructors use this to refer to another constructor in the same class with a different parameter list.
Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
Did you know it?

37 What are Access Specifiers available in Java?

Answer
Java offers four access specifiers, listed below in decreasing accessibility:
Public- public classes, methods, and fields can be accessed from everywhere.
Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the methods and fields belong.
Private methods and fields are not visible within subclasses and are not inherited by subclasses.
Did you know it?

38 What are the different access level we can use for class?

Answer
Classes can have only public or default access.
A class with default access can be seen only by classes within the same package.
A class with public access can be seen by all classes from all packages.
Did you know it?

39 What are the properties of legal nonabstract implementing class?

Answer
It provides concrete implementations for the interface's methods.
It must follow all legal override rules for the methods it implements.
It must not declare any new checked exceptions for an implementation method.
It must not declare any checked exceptions that are broader than the exceptions declared in the interface method.
It may declare runtime exceptions on any interface method implementation regardless of the interface declaration.
It must maintain the exact signature (allowing for covariant returns) and return type of the methods it implements (but does not have to declare the exceptions of the interface).
Did you know it?

40 What are the different modifiers that can be used with instance variables?

Answer
Instance variables can't be abstract, synchronized, native, or strictfp.
Did you know it?

41 What is checked exception?

Answer
Checked exceptions include all subtypes of Exception, excluding classes that extend RuntimeException.
Checked exceptions are subject to the handle or declare rule; any method that might throw a checked exception (including methods that invoke methods that can throw a checked exception) must either declare the exception using throws, or handle the exception with an appropriate try/catch.
Did you know it?

42 What is unchecked exception?

Answer
Subtypes of Error or RuntimeException are unchecked, so the compiler doesn't enforce the handle or declare rule. You're free to handle them, or to declare them, but the compiler doesn't care one way or the other.
Did you know it?

43 How to create custom Exception class?

Answer
You can create your own exceptions, normally by extending Exception or one of its subtypes. Your exception will then be considered a checked exception, and the compiler will enforce the handle or declare rule for that exception.
Did you know it?

44 What is try-with-resources in java?

Answer
One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished.
Did you know it?

45 What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?

Answer
Finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.
Did you know it?

46 What is immutable object? Can you write immutable object?

Answer
Immutable classes are Java classes whose objects can not be modified or changed once created. Any modification in Immutable object result in new object or exception. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also it is required not have any setter methods in the class.
Did you know it?

47 What is the difference between creating String as new() and literal?

Answer
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String("Test");
does not put the object in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
Did you know it?

48 What is Externalizable?

Answer
Externalizable interface is used to write the state of an object into a byte stream in compressed format.It is not a marker interface.
Did you know it?

49 What is the difference between Serializalble and Externalizable interface?

Answer
Serializable is a marker interface but Externalizable is not a marker interface.When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.
Did you know it?

50 How can you implement custom serialization and deserialization process?

Answer
You can supplement a class's automatic serialization process by implementing the writeObject() and readObject() methods. If you do this, embedding calls to defaultWriteObject() and defaultReadObject(), respectively, will handle the part of serialization that happens normally.
Did you know it?

51 What is the difference between preemptive scheduling and time slicing?

Answer
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
Did you know it?

52 Difference between sleep and wait?

Answer
The fundamental difference is wait() is from Object and sleep() is static method of Thread . The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.
Did you know it?

53 What is difference between Executor.submit() and Executer.execute() method ?

Answer
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.
Did you know it?

54 What do you understand by thread-safety ? Why is it required ?

Answer
Java Memory Model defines the legal interaction of threads with the memory in a real computer system. In a way, it describes what behaviors are legal in multi-threaded code. It determines when a Thread can reliably see writes to variables made by other threads. It defines semantics for volatile, final & synchronized, that makes guarantee of visibility of memory operations across the Threads.
Did you know it?

55 How do you ensure that N thread can access N resources without deadlock?

Answer
We can ensure it by acquiring resources in a particular order and releasing resources in reverse order we can prevent deadlock.
Did you know it?

56 Can synchronized modifier be applied to class?

Answer
No.The synchronized modifier applies only to methods and code blocks and synchronized methods can have any access control and can also be marked final.
Did you know it?

57 Can we call start() method twice on an object?

Answer
You can call start() on a Thread object only once. If start() is called more than once on a Thread object, it will throw a RuntimeException
Did you know it?

58 Why Java doesn’t support multiple inheritance?

Answer
Java doesn’t support multiple inheritance in classes because of Diamond Problem. However multiple inheritance is supported in interfaces. An interface can extend multiple interfaces because they just declare the methods and implementation will be present in the implementing class. So there is no issue of diamond problem with interfaces.
Did you know it?

59 What are the different required criterias for overriding?

Answer
With respect to the method it overrides, the overriding method must have the same argument list.
Must have the same return type, except that as of Java 5, the return type can be a subclass—this is known as a covariant return.
Must not have a more restrictive access modifier.
May have a less restrictive access modifier.
Must not throw new or broader checked exceptions.
May throw fewer or narrower checked exceptions, or any unchecked exception.
final methods cannot be overridden.
Only inherited methods may be overridden, and remember that private methods are not inherited.
A subclass uses super.overriddenMethodName() to call the superclass version of an overridden method.
Did you know it?

60 What are the different required criterias for overloading?

Answer
Overloaded methods:
Must have different argument lists
May have different return types, if argument lists are also different
May have different access modifiers
May throw different exceptions
Methods from a superclass can be overloaded in a subclass.
Polymorphism applies to overriding, not to overloading.
Did you know it?

61 Can an abstract class can have the constructor?

Answer
Every class, even an abstract class, has at least one constructor.
Did you know it?

62 How constructor execution occurs?

Answer
Typical constructor execution occurs as follows:
The constructor calls its superclass constructor, which calls its superclass constructor, and so on all the way up to the object constructor.
The Object constructor executes and then returns to the calling constructor, which runs to completion and then returns to its calling constructor, and so on back down to the completion of the constructor of the actual instance being created.
The compiler will create a default constructor if you don't create any constructors in your class.
Did you know it?

63 What are the different meanings of collection?

Answer
Three meanings for "collection":
collection Represents the data structure in which objects are stored
Collection java.util interface from which Set and List extend
Collections A class that holds static collection utility methods
Did you know it?

64 What are the common collection classes and its properties?

Answer
ArrayList: Fast iteration and fast random access.
Vector: It's like a slower ArrayList, but it has synchronized methods.
LinkedList: Good for adding elements to the ends, i.e., stacks and queues.
HashSet: Fast access, assures no duplicates, provides no ordering.
LinkedHashSet: No duplicates; iterates by insertion order.
TreeSet: No duplicates; iterates in sorted order.
HashMap: Fastest updates (key/values); allows one null key, many null values.
Hashtable: Like a slower HashMap (as with Vector, due to its synchronized methods). No null values or null keys allowed.
LinkedHashMap: Faster iterations; iterates by insertion order or last accessed; allows one null key, many null values.
TreeMap: A sorted map.
PriorityQueue: A to-do list ordered by the elements' priority.
Did you know it?

65 What is an Iterator ?

Answer
The Iterator interface is used to step through the elements of a Collection.
Iterators let you process each element of a Collection.
Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
Iterator is an Interface implemented a different way for every Collection.
Did you know it?

66 How is ListIterator?

Answer
ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element.
Did you know it?

67 What are the main implementations of the List interface?

Answer
The main implementations of the List interface are as follows :
ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).
Did you know it?

68 What are the advantages of ArrayList over arrays?

Answer
Some of the advantages ArrayList has over arrays are:
It can grow dynamically
It provides more powerful insertion and search mechanisms than arrays.
Did you know it?

69 Why insertion and deletion in ArrayList is slow compared to LinkedList?

Answer
ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion.
In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node.
Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
Did you know it?

70 Why are Iterators returned by ArrayList called Fail Fast?

Answer
Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Did you know it?

71 How do you decide when to use ArrayList and When to use LinkedList?

Answer
If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.
Did you know it?

72 What is the Set interface ?

Answer
The Set interface provides methods for accessing the elements of a finite mathematical set.
Sets do not allow duplicate elements.
Contains no methods other than those inherited from Collection.
It adds the restriction that duplicate elements are prohibited.
Two Set objects are equal if they contain the same elements.
Did you know it?

73 What are the main Implementations of the Set interface ?

Answer
The main implementations of the List interface are as follows:
HashSet
TreeSet
LinkedHashSet
EnumSet
Did you know it?

74 61.What is a HashSet ?

Answer
A HashSet is an unsorted, unordered Set.
It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
Did you know it?

75 What is a TreeSet?

Answer
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
Did you know it?

76 What is an EnumSet?

Answer
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.
Did you know it?

77 What is a Map?

Answer
A map is an object that stores associations between keys and values (key/value pairs).
Given a key, you can find its value. Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.
Did you know it?

78 What are the main Implementations of the Map interface?

Answer
The main implementations of the List interface are as follows:
HashMap
HashTable
TreeMap
EnumMap
Did you know it?

79 What is a TreeMap?

Answer
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
Did you know it?

80 How do you decide when to use HashMap and when to use TreeMap ?

Answer
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
Did you know it?

81 How does a Hashtable internally maintain the key-value pairs?

Answer
TreeMap actually implements the SortedMap interface which extends the Map interface.
In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time.
TreeMap is based on the Red-Black tree data structure.
Did you know it?

82 What Are the different Collection Views That Maps Provide?

Answer
Maps Provide Three Collection Views.
Key Set - allow a map's contents to be viewed as a set of keys.
Values Collection - allow a map's contents to be viewed as a set of values.
Entry Set - allow a map's contents to be viewed as a set of key-value mappings.
Did you know it?

83 What is the Comparable interface ?

Answer
The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable
where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative.
If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
Did you know it?

84 Difference between Comparable and Comparator?

Answer
When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Did you know it?

85 What is difference between Heap and Stack Memory?

Answer
Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.
Did you know it?

86 How many types of memory areas are allocated by JVM?

Answer
1. Class(Method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack
Did you know it?

87 Why should a thread not be stopped by calling its method stop()?

Answer
A thread should not be stopped by using the deprecated methods stop() of java.lang.Thread, as a call of this method causes the thread to unlock all monitors it has acquired. If any object protected by one of the released locks was in an inconsistent state, this state gets visible to all other threads. This can cause arbitrary behavior when other threads work this this inconsistent object.
Did you know it?

88 Is it possible to convert a normal user thread into a daemon thread after it has been started?

Answer
A user thread cannot be converted into a daemon thread once it has been started. Invoking the method thread.setDaemon(true) on an already running thread instance causes a IllegalThreadStateException.
Did you know it?

89 What is a shutdown hook?

Answer
A shutdown hook is a thread that gets executed when the JVM shuts down. It can be registered by invoking addShutdownHook(Runnable) on the Runtime instance: Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { } });
Did you know it?
0 / 0 answered