Corejava Interview Questions and Answers

1) What are the principle concepts of OOPS in Java?

There are four principle concepts upon which object oriented design and programming rest. They are:<br/> 1. Abstraction<br/> 2. Polymorphism<br/> 3. Inheritance<br/> 4. Encapsulation

2) What is Abstraction in Java?

Abstraction refers to the act of representing essential features without including the background details or explanations.

3) What is Encapsulation in Java?

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.

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

<strong>Abstraction </strong> 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.<br/> <strong>Abstraction</strong> solves the problem in the design side while Encapsulation is the Implementation. <strong>Encapsulation</strong> is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.

5) What is Inheritance in Java?

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:<br/> To promote code reuse<br/> To use polymorphism

6) What is Polymorphism in Java?

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.

7) What is runtime polymorphism or dynamic method dispatch?

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.

8) What is Dynamic Binding in Java?

Binding refers to the linking of a procedure call to the code to be executed in response to the call. <strong>Dynamic binding</strong> (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.

9) What is method overloading in Java?

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.<br/> 1. Overloaded methods MUST change the argument list<br/> 2. Overloaded methods CAN change the return type<br/> 3. Overloaded methods CAN change the access modifier<br/> 4. Overloaded methods CAN declare new or broader checked exceptions<br/> 5. A method can be overloaded in the same class or in a subclass

10) Can we overload main method in Java?

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 <strong> public static void main(String args[]).</strong>

11) What is method overriding?

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.<br/> 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).<br/> 2. You cannot override a method marked final<br/> 3. You cannot override a method marked static

12) Can you override private or static method in Java ?

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.

13) Can overloaded methods be overriden too in Java?

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.

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

No, because main is a static method. A static method can't be overridden in Java.

15) What is super in Java?

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. <strong>Note:</strong> <br/> 1. You can only go back one level.<br/> 2. In the constructor, if you use super(), it must be the very first code, and you cannot access any variables or methods to compute its parameters.

16) What is static keyword in Java?

static keyword can be used with class level variables to make it global i.e all the objects will share the same variable.<br/> 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.

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

<strong>PATH</strong> 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. <br/> <strong>Classpath</strong> 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.

18) What is final keyword in Java?

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.<br/> We can use final keyword with methods to make sure child classes can’t override it.<br/> 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.<br/> Java interface variables are by default final and static.

19) What is JIT compiler?

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.

20) What is classloader in JVM in Java?

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.<br/> 1. Bootstrap classloader (loads class file from rt.jar) <br/> 2.Extension classloader (loads class file from ext folder under JDK installlation directory) <br/> 3.System classloader (loads class file from classpath )

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

It is empty. But not null.

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

Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.

23) What is difference between aggregation and composition?

Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).

24) What is difference between final, finally and finalize?

<strong>final:</strong> 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.<br/> <strong>finally:</strong> finally block is used in exception handling. finally block is always executed.<br/> <strong>finalize():</strong> 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.

25) What is break and continue statement?

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.<br/> 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.

26) What is an Interface?

An interface is a description of a set of methods that conforming implementing classes must have.<strong> Note:</strong><br/> You can’t mark an interface as final.<br/> Interface variables must be static.<br/> An Interface cannot extend anything but another interfaces.

27) Can we create an object for an interface?

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.

28) What modifiers are allowed for methods in an Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

29) What is a marker interface?

Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The 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.

30) What is anonymous inner class?

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.<br/> 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.

31) What is an abstract class?

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

32) Can we instantiate an abstract class?

An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

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

<strong>Use Interfaces when…</strong><br/> You see that something in your design will change frequently.<br> If various implementations only share method signatures then it is better to use Interfaces.<br> 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.<br/> <strong>Use Abstract Class when…</strong><br/> If various implementations are of the same kind and use common behavior or status then abstract class is better to use.<br/> When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.<br/> Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for non-leaf classes in class hierarchies.

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

Yes, other nonabstract methods can access a method that you declare as abstract.

35) What is Constructor?

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

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

Constructors use this to refer to another constructor in the same class with a different parameter list.<br/> 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.

37) What are Access Specifiers available in Java?

Java offers four access specifiers, listed below in decreasing accessibility:<br/> Public- public classes, methods, and fields can be accessed from everywhere.<br/> 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.<br/> 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.<br/> Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. <br/>Private methods and fields are not visible within subclasses and are not inherited by subclasses.<br/>

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

Classes can have only public or default access.<br/> A class with default access can be seen only by classes within the same package.<br/> A class with public access can be seen by all classes from all packages.

39) What are the properties of legal nonabstract implementing class?

It provides concrete implementations for the interface's methods.<br/> It must follow all legal override rules for the methods it implements.<br/> It must not declare any new checked exceptions for an implementation method.<br/> It must not declare any checked exceptions that are broader than the exceptions declared in the interface method.<br/> It may declare runtime exceptions on any interface method implementation regardless of the interface declaration.<br/> 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).

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

Instance variables can't be abstract, synchronized, native, or strictfp.

41) What is checked exception?

Checked exceptions include all subtypes of Exception, excluding classes that extend RuntimeException.<br/> 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.

42) What is unchecked exception?

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.

43) How to create custom Exception class?

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.

44) What is try-with-resources in java?

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.<br/> 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.

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

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.

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

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.

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

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.<br/> <strong>String s = new String("Test");</strong><br/> 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. <strong>String s = "Test" </strong>Java automatically put that into String pool.

48) What is Externalizable?

Externalizable interface is used to write the state of an object into a byte stream in compressed format.It is not a marker interface.

49) What is the difference between Serializalble and Externalizable interface?

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.

50) How can you implement custom serialization and deserialization process?

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.

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

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.

52) Difference between sleep and wait?

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.

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

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.

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

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.

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

We can ensure it by acquiring resources in a particular order and releasing resources in reverse order we can prevent deadlock.

56) Can synchronized modifier be applied to class?

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.

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

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

58) Why Java doesn’t support multiple inheritance?

Java doesn’t support multiple inheritance in classes because of <strong>Diamond Problem.</strong> 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.

59) What are the different required criterias for overriding?

With respect to the method it overrides, the overriding method must have the same argument list.<br/> 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.<br/> Must not have a more restrictive access modifier.<br/> May have a less restrictive access modifier.<br/> Must not throw new or broader checked exceptions.<br/> May throw fewer or narrower checked exceptions, or any unchecked exception.<br/> final methods cannot be overridden.<br/> Only inherited methods may be overridden, and remember that private methods are not inherited.<br/> A subclass uses super.overriddenMethodName() to call the superclass version of an overridden method.<br/>

60) What are the different required criterias for overloading?

Overloaded methods:<br/> Must have different argument lists<br/> May have different return types, if argument lists are also different<br/> May have different access modifiers<br/> May throw different exceptions<br/> Methods from a superclass can be overloaded in a subclass.<br/> Polymorphism applies to overriding, not to overloading.

61) Can an abstract class can have the constructor?

Every class, even an abstract class, has at least one constructor.

62) How constructor execution occurs?

Typical constructor execution occurs as follows:<br/> The constructor calls its superclass constructor, which calls its superclass constructor, and so on all the way up to the object constructor.<br/> 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.<br/> The compiler will create a default constructor if you don't create any constructors in your class.<br/>

63) What are the different meanings of collection?

Three meanings for "collection":<br/> collection Represents the data structure in which objects are stored<br/> Collection java.util interface from which Set and List extend<br/> Collections A class that holds static collection utility methods

64) What are the common collection classes and its properties?

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

65) What is an Iterator ?

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

66) How is ListIterator?

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.

67) What are the main implementations of the List interface?

The main implementations of the List interface are as follows :<br/> <strong>ArrayList :</strong> Resizable-array implementation of the List interface. The best all-around implementation of the List interface.<br/> <strong>Vector : </strong>Synchronized resizable-array implementation of the List interface with additional "legacy methods."<br/> <strong>LinkedList :</strong> 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).

68) What are the advantages of ArrayList over arrays?

Some of the advantages ArrayList has over arrays are:<br/> It can grow dynamically<br/> It provides more powerful insertion and search mechanisms than arrays.

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

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.<br/> 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.<br/> 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. <br/> 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.

70) Why are Iterators returned by ArrayList called Fail Fast?

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.

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

If you need to support random access, without inserting or removing elements from any place other than the end, then <strong>ArrayList </strong>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 <strong>LinkedList</strong> offers the better implementation.

72) What is the Set interface ?

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

73) What are the main Implementations of the Set interface ?

The main implementations of the List interface are as follows:<br/> HashSet<br/> TreeSet<br/> LinkedHashSet<br/> EnumSet

74) 61.What is a HashSet ?

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

75) What is a TreeSet?

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.

76) What is an EnumSet?

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.

77) What is a Map?

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

78) What are the main Implementations of the Map interface?

The main implementations of the List interface are as follows:<br/> HashMap<br/> HashTable<br/> TreeMap<br/> EnumMap

79) What is a TreeMap?

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.

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

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.

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

TreeMap actually implements the SortedMap interface which extends the Map interface. <br/>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. <br/>TreeMap is based on the Red-Black tree data structure.

82) What Are the different Collection Views That Maps Provide?

Maps Provide Three Collection Views.<br/> Key Set - allow a map's contents to be viewed as a set of keys.<br/> Values Collection - allow a map's contents to be viewed as a set of values.<br/> Entry Set - allow a map's contents to be viewed as a set of key-value mappings.

83) What is the Comparable interface ?

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.<br/> The Comparable interface in the generic form is written as follows:<br/> interface Comparable<T><br/> where T is the name of the type parameter.<br/> 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:<br/> int i = object1.compareTo(object2)<br/> If object1 < object2: The value of i returned will be negative.<br/> If object1 > object2: The value of i returned will be positive.<br/> If object1 = object2: The value of i returned will be zero.

84) Difference between Comparable and Comparator?

When your class implements <strong>Comparable</strong>, 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.<br/> A <strong>Comparator</strong> 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.<br/> 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.<br/> 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.

85) What is difference between Heap and Stack Memory?

Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.<br/> 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.<br/> Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.

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

1. Class(Method) Area <br/> 2. Heap <br/> 3. Stack <br/> 4. Program Counter Register<br/> 5. Native Method Stack

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

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.

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

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.

89) What is a shutdown hook?

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() { } });

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.