[LATEST] JAVA Interview Question & Answer | Beginner & Advanced
Last updated on 02nd Aug 2020, Blog, General
1. Describe Java.
Popular object-oriented programming languages include Java. It is described as an entire group of objects. Java enables us to create a wide range of applications, including games, mobile apps, and websites.
2. Can you briefly outline Java’s history?
A small team of engineers known as the “Green Team,” headed by James Gosling, put a lot of effort into developing the new programming language “Java” in the year 1991. This language was developed in a way that it will completely transform society. In the modern world, Java is a hidden force that powers several activities, gadgets, and programs in addition to invading the internet.
3. What was the impetus behind the creation of Java?
JVM (Java Virtual Machine) is the acronym for Java, which was the first programming language to be used to create programs for virtual machines. This JVM is a brand-new idea that Java introduced. Additionally, it offers code reuse, a new feature that is not achievable in C.
4. What in Java is a Class?
A class is described as a blueprint or template that is used to define objects and methods as well as generate new ones.
5. What does Object in Java mean?
An object is the name for a class instance. In Java, each object has a state and a behavior. Fields are used to hold an object’s state, while methods are used to specify its behavior
6. What is JVM?
The acronym JVM stands for Java Virtual Machine. It is a virtual machine that offers a programming environment in which to run programs. JRE (Java Runtime Environment) contains a component called JVM that is used to translate bytecode into machine-level language. This system is in charge of allocating memory.
7. Describe the class loader in JVM and name the memory regions that JVM allots?
The JVM allocates memory to a total of five locations, including:
- Class Area
- Native Method Stack
- PC Register
ClassLoader: class loader is a subschema of JVM which is used to load class files. Whenever we run Java programs, the data will be first loaded from the classloader. There are mainly three in-built classloaders in JVM, they are:
- Application Classloader
- Bootstrap Classloader
- Extension Classloader
8. Describe JDK.
One of the three main technology packages used in Java development is the Java Development Kit. JVM and JRE employ JDK as a stand-alone component to execute Java programs. This kit is used to implement the class libraries and compiler requirements of the Java platform.
9. How do you define JRE?
A group of software tools known as the Java Runtime Environment (JRE) are created specifically for the creation of Java applications. Although it is a component of JDK, this can be downloaded alone. The coordination of the component activities is primarily the responsibility of JRE.
10. What are the key distinctions between the JVM, JRE, and JDK?
The following diagram can help us grasp the distinctions between JVM, JDK, and JRE:
Platform independence is provided via Java programming’s primary component, the Java Virtual Machine (JVM). To run our Java programs, JVM is a component of both JRE and JDK.
JDK: This development kit is mostly utilized for software development.
Java programs are typically run using the JRE: Java Runtime Environment.
11. What does the Java JIT compiler mean?
The JRE component known as Just In Time Compiler is utilized to translate the method’s bytecodes into native machine code. JVM calls this method’s compiled code straight without ever interpreting it.
12. Give a definition of a variable in Java and an illustration?
Java variables can be thought of as the fundamental programming building block. It is a storage device that keeps the value during the running of the application. A datatype is always assigned to the variable.
int a = 10;
13. What are the key characteristics of Java?
Platform independence, object-oriented programming, automatic memory management (garbage collection), and robust type checking are all characteristics of the Java programming language.
14. What are the differences between Java’s == and.equals()?
Checks if two object references lead to the same location in memory by comparing them. The equals() method is used to compare an object’s content or values.
15. What function does Java’s static keyword serve?
In order to access class-level variables and methods without first creating an instance of the class, the static keyword is utilized.
16. What is the Java language’s final keyword used for?
Making a variable, function, or class final makes them unchangeable. For instance, a final method cannot be substituted, and a final variable cannot be transferred.
17. What are the Difference between Array and Array List?
The Difference between Array and Array List can be understood from the below table:
| Array ||Array List|
|Size should be given at the time of array declaration.|
String name = new String
|Size may not be required. It changes the size dynamically.|
ArrayList name = new ArrayList
|To put an object into array we need to specify the index.|
name = “book”
|No index required.|
|Array is not type parameterized||ArrayList in java 5.0 are parameterized.|
Eg: This angle bracket is a type parameter which means a list of String.
18. What distinguishes an abstract class from an interface?
While an interface can only have abstract methods, an abstract class can have both abstract (unimplemented) and concrete (implemented) methods. Java only allows for single-class inheritance, however many interface implementations are supported.
19. What does a Java constructor do?
A class’s unique constructor method is used to initialize instances. It receives a call when an object is generated and shares the same name as the class.
20. What role does the try-catch block have in handling exceptions?
Java uses the try-catch block to manage exceptions. The try block’s code is checked for exceptions, and if one is found, the associated catch block is run to gracefully manage the exception.
21. How is a Java thread distinct from a process, and what is it?
The smallest unit of a program’s execution is a thread. While processes have independent memory, threads inside the same process share memory.
22. What does Java method overloading entail?
By using method overloading, you can define many methods in the same class that have the same name but distinct argument lists.
23. Describe Java’s toString() function.
A method called toString() provides a string representation of an object. The need to offer insightful information is frequently overridden
24. What does Java’s garbage collection do?
The automatic process of reclaiming memory used by items no longer in use is known as garbage collection.
25. What is the Java collection framework?
Classes and interfaces are available for storing and managing collections of objects through the Java collection framework. Sets, maps, and lists are examples of common types.
26. Why are the equals() and hashCode() methods used?
HashCode() provides an object’s unique identification, whereas equals() determines whether two objects are equal.
27. What is the role of the finally block in exception handling?
The finally block in exception handling ensures that certain code always runs, whether an exception occurs or not. It’s used for cleanup and guaranteeing the execution of critical tasks.
28. Describe Java’s multithreading idea.
By leveraging several CPU cores, multithreading enables numerous threads to execute simultaneously, improving program performance.
29. Why is Java not purely object-oriented?
Java does not strictly fall under the category of an object-oriented language because it supports primitive data types including byte, boolean, char, short, int, float, long, and double.
30. What distinguishes Java from C++?
- Java is both a compiled and an interpreted language, whereas C++ is simply a compiled language.
- A C++ program can only execute on the system in which it was compiled, but Java programs are machine-agnostic.
- Users of C++ can use pointers in their programs. Java, however, forbids it. Pointers are used internally by Java.
- Java does not support the idea of multiple inheritances, whereas C++ does. And the diamond problem is brought on by avoiding the complication of name ambiguity.
Get Hands-On Learning on Java Training and Master Your Skills
- Instructor-led Sessions
- Real-life Case Studies
31. In C/C++, pointers are used. Why don’t pointers exist in Java?
Beginner programmers should avoid using pointers because they are fairly difficult. Java relies on writing simple code, therefore using pointers might be difficult. Potential faults can also be caused through pointer usage. Furthermore, the use of pointers compromises security since they allow users to directly access memory.
Thus, the absence of pointers in Java provides a certain level of abstraction. Furthermore, the use of pointers may result in a delayed and inaccurate garbage collection process. Java uses references because, unlike pointers, they cannot be changed.
32. What are the variables’ and instances’ default values in Java?
Java doesn’t provide its variables any default values. Before using the value, it must first be initialized. Otherwise, a compilation error with the message “Variable might not be initialized” will be raised.
However, depending on the data type, the default value will be initialized by the default constructor if we build the object.
- It will be assigned to null if it is a reference.
- If it is a number, it will assign a value of 0.
- If the value is a Boolean, false will be assigned. Etc.
33. How would you define data encapsulation?
Data encapsulation is an Object-Oriented Programming paradigm that involves condensing the actions of each data attribute into a single unit.
By guaranteeing that each object is independent of other objects by having its own methods, properties, and functions, it aids developers in adhering to the modularity principle when creating software.
It serves the objective of data concealing by being used to secure an object’s private properties.
34. What distinguishes a Java static method from a non-static method?
A static method is one that can be used on a class itself, as opposed to an instance of the class. Instance methods, commonly referred to as non-static methods, can only be called on a class instance.
35. Describe how final keywords are used in variables, methods, and classes.
finalvariables cannot be changed after the assignment.
finalmethods cannot be overridden.
finalclasses cannot be extended (inherited from).
36. Is it possible to overload static methods?
Yes! A class may contain one or more static methods with the same name but various input parameters.
37. In Java, why is the main method static?
Because static members are those methods that belong to the classes rather than a specific object, the main method is always static. Therefore, if the main method is not static, it is accessible to all objects. And JVM does not accept that. JVM uses the class name itself to call the main function. not by making the thing.
Since the main method is where a Java program’s execution begins, there can only be one main method. The main method is static as a result.
38. Are static methods capable of being modified?
No! Subclasses may declare static methods with identical signatures, but run-time polymorphism is not permitted in these circumstances. While overriding or dynamic polymorphism happens at runtime, static methods are loaded and looked up statically at build time. As a result, these techniques cannot be modified.
39. The distinction between static classes, static variables, and static methods in Java.
|Aspect||Static Class||Static Variable||Static Method|
|Definition||Nested, static||Class-level field||Class-level method|
|Instantiation||Cannot be created||Shared among all||Accessed via class|
|Access||Via enclosing class||Via class name||Via class name|
|Memory Usage||No instances||Shared memory||No instance data|
40. What is the primary goal of Garbage collection?
The primary goal of this operation is to remove those unreachable objects from memory, which were being used by unwanted and unneeded objects while the Java application was being executed.
While this makes sure that the memory resource is used effectively, there is no assurance that there will be enough memory for the program to run.
41. What is a ClassLoader, exactly?
The program that is a part of the JRE (Java Runtime Environment) is called Java Classloader. When necessary, ClassLoader loads the necessary classes and interfaces into the JVM.
We need the scanner class in order to get input from the console. Additionally, the ClassLoader loads the Scanner class.
42. Describe Java’s public static void main(String args).
Java’s main function
In Java, we stated the main method as a public static void main (String args), unlike in other programming languages like C, C++, etc. The following definitions of the terminologies are provided:
- Public: The access modifier public specifies who may access an element or a function and what the access limit is. It is in charge of making the primary function accessible to everyone. Since it is not a part of the current class, it is made public so that JVM can call it from outside the class.
- Static: The static keyword allows us to access an element without first launching the class, preventing needless memory allocation.
- void: The term void is used to indicate that a method returns nothing. We use void because the main function doesn’t return anything.
- main: The word “main” indicates that the declared function is the primary function. Knowing that the stated function is the main function aids JVM.
- String args is an array of type java.lang that contains Java command-line parameters.String type.
43. How does Java String Pool work?
The heap memory location where all the strings defined in the program are kept is called a Java String Pool. The variable holding the string is kept in a different location on a stack. Every time we create a new string object, the JVM checks to see if it already exists in the String pool. If it does, the object reference is shared with the variable; otherwise, a new object is produced.
- String str1=”Hello”;
- // “Hello” will be stored in String Pool
- // str1 will be stored in stack memory
44. What will happen if the main is not declared as static?
Without utilizing static and without encountering any issues, the main method can be declared. However, the main approach won’t be regarded as the program’s or application’s entrance.
45. What do Java packages do?
In Java, a package is a collection of linked classes, interfaces, etc. that provide access to namespace management and protection.
46. Why are packages used?
In Java, packages are used to avoid naming conflicts, restrict access, and facilitate finding and using classes, interfaces, etc.
47. What are the benefits of Java packages?
Organization: Packages help you neatly organize your code.
Prevent Conflicts: They prevent naming clashes in code.
Access Control: You control who can use what in your code.
Code Reusability: You can reuse code from other packages.
Readability: It makes code easier to understand and maintain.
48. In Java, how many different package types are there?
In Java, there are two kinds of packages.
- Individual packages
- Installed packages
49. What is a Java Virtual Machine?
JVM is a software application that decodes intermediate Java byte code and produces the appropriate results. Java programs are extremely portable due of bytecode and JVM.
50. How is great performance made possible by Java?
When using just-in-time compilation, the necessary code is run only when it is needed. Usually, it entails converting bytecode into machine code and then running it immediately. It enables excellent performance. When a method is called, the JIT compiler, which is enabled by default in Java, is active.
Enroll in Java Certification Course with In-Depth Modules By Certified ExpertsWeekday / Weekend BatchesSee Batch Details
51. How can we use primitive data types as objects?
Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.
The Java method’s bytecode is subsequently converted into native machine code.
The compiled code is then called directly by the JVM rather than being translated.
52. Describe typecasting.
the idea of transferring data from one data type to another through assignment. The Boolean data type prohibits this from being feasible. Both implicit and explicit kinds exist.
53. What are the local variables’ default values?
Primitives or object references are not initialized with any default values for the local variables.
54. What is Object-Oriented Programming?
A programming paradigm known as OOPs is focused on objects rather than functions. It is not a programming language or tool, but rather a paradigm that was created to address the shortcomings of procedural programming.
Numerous programming languages use OOPs principles; among of the more well-known ones include Java, Python, and Ruby. Some frameworks, like Angular, also adhere to OOPs principles.
55. What Exactly Is an Object?
An object in Java is a particular instance of a class. The behaviors and states of a Java object are two crucial characteristics. The moment the JVM encounters the new keyword, an object is formed.
56. How can you guarantee that N threads can access N resources without experiencing a deadlock?
Here are the important details in the scenario where N threads can access N resources without causing a deadlock. We can avoid a deadlock situation if we acquire resources in a specific sequence and release resources in the opposite order.
57. What are static variables and methods?
One component of a class declares variables, and the other section declares methods. These are referred to as instance methods and instance variables, respectively. They are given this name because a new instance of each of them is created each time a class is instantiated.
By designating them as static, you can establish variables and methods that can be used without a specific object and are shared by all objects. Other classes and methods can also make use of static members.
58. How would you define a constructor?
A method with the same name as the class to which it belongs is called a constructor. A class-specific constructor is called as soon as a new object is created. Although a constructor can be expressly constructed by the user, it is automatically created as soon as a class is established. The default constructor is this one. Overloaded constructors are possible.
It is required to create another constructor without a parameter if an expressly constructed constructor has one.
59. What do instance variables and local variables mean?
Local variables are those that can only be accessed by the method or code block in which they are declared. On the other hand, all methods in a class can access instance variables. Instance variables are declared inside a class, not a method, as opposed to local variables, which are declared inside a function or a code block. Instance variables always have a value, which may be null, 0, 0.0, or false. Contrary to this, failing to assign a value to a local variable that requires one will result in an error. When a method is called, local variables are automatically created and removed when the method ends. It is necessary to use the new keyword when defining instance variables.
60. What is overloading, exactly?
When two or more distinct methods (method overloading) or operators (operator overloading) have the same representation, overloading occurs. For instance, the + operator concatenates two texts but adds two numeric values. Similar to that, there are two uses for the overloaded function Add.
- To combine two integers
- combining two threads together
Method overloading, in contrast to method overriding, necessitates that two overloaded methods share the same name but take distinct arguments. Different return types might or might not be included in the overloaded functions.
61. Compare and contrast an array and an array list.
An array must declare its size at the time of declaration, whereas an array list need not because its size can change dynamically. You must give the index in order to insert an object into an array. However, there is no such necessity for an array list. An array is not parameterized, although an array list is.
62. What distinguishes String, Stringbuilder, and Stringbuffer from one another?
- Immutable: Once a String object is created, its content cannot be changed. If you want to modify a String, a new String object is created, which can be inefficient when dealing with large strings or many modifications.
- Thread-safe: String objects are inherently thread-safe because they cannot be modified. Multiple threads can safely access and share String objects.
- Mutable: StringBuilder is a mutable sequence of characters. You can add, remove, or modify characters within a StringBuilder without creating new objects. This makes it more efficient when you need to perform multiple string manipulations.
- Not thread-safe: StringBuilder is not thread-safe, so if you need to work with it in a multi-threaded environment, you should synchronize access to it explicitly or consider using StringBuffer.
- Mutable: StringBuffer is similar to StringBuilder in that it is a mutable sequence of characters. You can modify its content efficiently.
- Thread-safe: StringBuffer is designed to be thread-safe, which means it includes synchronization mechanisms to ensure that multiple threads can safely access and modify their content. This makes it a suitable choice in multi-threaded applications when you need mutable strings.
63. What does String Pool mean?
A group of strings kept in the heap memory is referred to as the string pool. Every time an object is generated, the string pool is examined to see if it already exists. The reference is returned to the variable if it already exists; otherwise, a new object is generated in the string pool and the reference is returned.
64. Describe Abstract class and Abstract method in detail.
In Java, an abstract class is one that cannot be instantiated. Such a class is often used to implement the abstract methods, override the implemented methods defined in the abstract class, and provide a base for subclasses to extend.
It must be followed with the abstract keyword to produce an abstract class. Both abstract and non-abstract methods can be found in any abstract class. An abstract method in Java is one that merely has the declaration and no implementation. Additionally, the abstract keyword is followed by the name of an abstract method. An implementation for abstract methods must be provided by any concrete subclass that extends the abstract class.
65. Why do we utilize the yield() method?
The thread class contains the yield() method. It also permits the other threads to run while putting the presently active thread into a runnable state. In other words, it allows threads with equal priority to execute. Since yield() is a static function, no lock is released by its use.
66. When should you use the Thread class instead of the Runnable interface, and vice versa?
Java only allows for the extension of one class. The thread class is therefore only extended if no other classes need to be. The Runnable interface must be used if a class has to extend a class other than the thread class.
67. Compare the notify() and notifyAll() methods
Sending a signal to wake up a single thread in the waiting pool is done using the notify() function. In contrast, a signal to wake up every thread in a waiting pool is sent using the notifyAll() method.
68. What transpires when the main procedure throws an exception?
When the main() function throws an exception, Java Runtime ends the program and prints the stack trace and exception message in the system console.
69. How can you stop a thread in Java?
In Java, there are three ways to halt a thread from running:
70. What is ThreadLocal?
For creating thread-local variables in Java, use ThreadLocal. We are aware that an object’s variables are shared by all threads. So, we can use synchronization if the variable is not thread-safe. But we can utilize ThreadLocal variables if we wish to avoid synchronization.
Each thread has a unique ThreadLocal variable, which they can access using the get() and set() methods to retrieve the default value or modify. Classes that want to link the state with a thread often use private static fields called ThreadLocal instances.
71.Describe the different Java exception handling terms.
The final keyword, which may or may not be used after handling exceptions, is the third and final is the most important exception handling keyword in Java.
A try block is used to include code segments that are inserted there if and when they are likely to contain an error or anomaly. The catch block takes care of handling and catching the exception when it is raised.
The catch block responds to an exception that is raised in the try block.
Regardless of the exception, this block gets executed. It may come either after the try block or the catch block.
72. What are the different sorts of maps?
A Java Map is an object that associates values with keys. No duplicate keys are allowed, and each key can only map to one value. Map uses the equals() method to determine whether two keys are the same or different. There are 4 different types of Map in Java, as follows:
73. What is a Priority Queue?
Similar to a conventional queue, a priority queue is an abstract data type, but each of the elements it contains has a priority. In a priority queue, the item with the highest priority gets served before the item with the lowest priority. A priority queue’s elements are arranged either organically or in accordance with the comparator. A priority queue’s element order corresponds to their relative priority.
74. What Exactly Is a Set? Types in Java Collections should be explained.
A set in Java is a grouping of distinct objects. To determine whether two objects are identical or not, it employs the equals() method. The various set types in Java Collections are as follows:
Hash Set: An unsorted, unordered set that adds values using the object’s hash code. used when the collection’s arrangement isn’t crucial
The “Linked Hash Set” is an ordered hash set that keeps a doubly-linked list of every element. used when the iteration order must be followed. The order of insertion is the same as the order in which the elements are added to the Set.
One of Java’s two sorted collections, the Tree Set makes use of a Read-Black tree structure to make sure the elements are present and in ascending order.
75. What are ordered and sorted in terms of collections?
- Ordered: A collection of values is kept in a particular order, although the order is unrelated to the values themselves. as in a list
- Sorted: The collection has an order that is based on an element’s value. The SortedSet example.
76. Could you provide a code example to show how to delete a cookie in JSP?
A cookie can be deleted in JSP by using the code shown below:
- MyCook cookie equals new Cookie(“name1″,”value1”);
- Cookie killmycook = new Cookie(“value1″,”mycook1”);
- setMaxAge (0) for killmycook;
- setPath (“/”) for killmycook;
- addCookie (killmycook 1), killmycook
77. Why is the Volatile variable used?
A volatile variable’s value is read from the main memory rather than the thread’s cache memory. The main time when volatile variables are used is during synchronization.
78. Compare serialization and deserialization.
- Java objects are transformed into the byte stream through a process known as serialization.
- The process of deserialization, in which Java objects are retrieved from the byte stream, is the exact reverse of serialization.
- An ObjectOutputStream is used to serialize Java objects, and an ObjectInputStream is used to deserialize them.
79. What does OutOfMemoryError mean?
The OutOfMemoryError exception is typically thrown when the JVM is unable to allocate an object because memory is running low. No memory could be recovered by the garbage collector in such a circumstance.
- The OutOfMemoryError exception can occur for a number of causes, the following being the most significant ones:
- holding things too long
- attempting to comprehend too much data simultaneously
- using a string caching third-party library
- the use of an application server that doesn’t clear its memory after deployment
- when it is impossible to satisfy a native allocation
80. Will the application still operate if static public void is used in place of the public static void?
Yes, the program would successfully compile and run because the sequence of the specifiers is irrelevant.
81. Why are pointers not used in Java? ?
Pointers are thought to be dangerous, they make the program more difficult, and the addition of the concept of pointers might be confusing. Additionally, the JVM is in charge of implicit memory allocation; as a result, Java discourages the use of pointers to prevent user-direct memory access.
82. What does the phrase “break and continue” mean?
- Use of a break for a statement signals the end of a while or do-while loop. To end the switch case in a switch statement, use the break statement. Break statements can also be used to end nested loops.
- You can skip the current iteration of a for, while, or do-while loop by using the continue statement. To skip the current iteration of the outermost loop, use the break statement with a label.
- The most fundamental programming query, not just in relation to Java. This is one of the often asked Java interview questions for freshers, therefore if you have any experience with programming languages, you should be able to respond.
83. What is an interface, exactly?
The fundamental building block of the Java programming language, interfaces are extensively utilized in JDK, Java design patterns, and the majority of frameworks and tools. Java’s interfaces offer a means of achieving abstraction and serve to specify the terms of the subclasses’ implementation contracts. In order to describe the type and build a top-level hierarchy in your code, the interface is a smart place to start. Since a class in Java can implement many interfaces, it is usually preferable to use interfaces as a superclass.
84. What does Java aggregation mean?
The easiest way to define aggregate is as an entity reference that depicts the connection between two classes and includes a reference to the class that it owns. Aggregation symbolizes a whole/part and has-a relationship. Think of an aggregate class, for instance. Address class data includes city, state, and pin code, whereas Employee class data includes name, age, and income. Now, it will be said that the Employee object has an Address object if the Employee class is defined to hold one. Since every employee needs a place to reside, the Address object is also a component of the Employee object. As a result, the Address object is owned by the Employee object.
85. What function does Java’s System class serve?
The System class in Java provides access to system resources and functions, including input/output streams, environment variables, system properties, and more. It’s a part of the Java standard library for interacting with the underlying operating system and Java runtime environment.
86. What Exactly Is an Iterator?
Any collection can be iterated through using the iterator interface’s methods. The iterator() method allows us to retrieve an iterator instance from a collection. In the Java Collection Framework, Iterator replaces Enumeration. During the iteration, the iterator lets the caller remove elements from the underlying collection. The Java Collection Iterator implements the Iterator Design Pattern and offers a general method for a collection’s cross-sectional members.
87. What is the Java Collections Framework?
The Java Collections Framework is a set of pre-defined classes and interfaces in Java that provide a unified way to work with collections of objects, such as lists, sets, and maps. It offers data structures and algorithms for storing, manipulating, and accessing data efficiently.
88. How well-versed are you in Thread Priority?
Every thread that is created is given a priority value, and in general, the threads with higher priorities are executed first. However, this relies on how the OS’s implementation of the Thread Scheduler is implemented. Although we can set a thread’s priority, there is no assurance that higher priority threads will be processed before lower priority threads. The integer value of thread priority ranges from 1 to 10, with 1 denoting the lowest priority thread and 10 the highest.
89. What Are Time Slicing and Thread Scheduler?
- The operating system service known as Thread Scheduler allots CPU time to the available runnable threads. A thread’s execution is dependent on how the Thread Scheduler is implemented once it has been generated and has entered the runnable phase.
- The process of time slicing allocates CPU time to the numerous runnable threads. The priority of the thread or the length of time it has been in the waiting state will determine how much CPU time is allocated to it. Java cannot control thread scheduling, hence it is always preferable for the application to do so.
90. Which is preferred: the synchronized block or the synchronized method?
The synchronized block is favored since it doesn’t lock the object; synchronized methods lock the object. If a class has several synchronization blocks, even if they are unrelated, the execution of all of them will be halted and placed in a wait state until the lock on the object has been obtained.
91.In Java, how can I construct a daemon thread?
Set thread classIn Java, daemon threads are created using the daemon(true) function. Before invoking start(), we used to invoke this method to avoid receiving an IllegalThreadStateException.
92. What is polymorphism and how does Java use it?
WORA or Write Once Read Anywhere, is the property of a language to run on any platform. Java is allowed this property due to its bytecode nature. This is midway between machine code and source code and is thus not platform specific.