Java Interview Questions
100 Interview Questions for Freshers 1 -2 Experienced Candidates

Java Interview Questions
1.What is Java?
Java is the high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications.
2. Why is Java not a pure object oriented language?
Java supports primitive data types – byte, boolean, char, short, int, float, long, and double and hence it is not a pure object-oriented language.
3. Difference between Heap and Stack Memory in java. And how java utilizes this.
Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program.
Java Utilizes this memory as –
- When we write a java program then all the variables, methods, etc are stored in the stack memory.
- And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.
Example- Consider the below java program:
class Main {
public void printArray(int[] array){
for(int i : array)
System.out.println(i);
}
public static void main(String args[]) {
int[] array = new int[10];
printArray(array);
}
}
4. Why is Java a platform independent language?
Java language was developed in such a way that it does not depend on any hardware or software because the compiler compiles the code and then converts it to platform-independent bytecode which can be run on multiple systems.
- The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it
5. List the features of Java Programming language.
There are the following features in Java Programming Language.
- Simple: Java is easy to learn. The syntax of Java is based on C++ which makes it easier to write the program in it.
- Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different types of objects that incorporates both data and behavior.
- Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
- Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which need a platform to be executed. Java comes with its platform on which its code is executed. Java doesn’t depend upon the operating system to be executed.
- Secured: Java is secured because it doesn’t use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secure.
- Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
- Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn’t exist in Java.
- Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
- High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is “close” to native code. It is still a little bit slower than a compiled language (e.g., C++).
- Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn’t occupy memory for each thread. It shares a common memory area. Threads are important for multimedia, Web applications, etc.
- Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
- Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Learn Java From Our Expert Trainer
6. What do you understand about Java virtual machines?
Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine that calls the main method present in the Java code.
JVM is the specification that must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.
7. What is a ClassLoader?
A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading class files when a program is executed; ClassLoader is the first to load the executable file.
Java has Bootstrap, Extension, and Application classloaders.
8. What are the Memory Allocations available in JavaJava?
Java has five significant types of memory allocations.
- Class Memory
- Heap Memory
- Stack Memory
- Program Counter-Memory
- Native Method Stack Memory
9. What are the differences between Heap and Stack Memory in Java?
Stack memory in data structures is the amount of memory allocated to each program. It is a fixed memory space.
Heap memory, in contrast, is the portion that was not assigned to the Java code but will be available for use by the Java code when it is required, which is generally during the program’s runtime.
10. How is Java different from C++?
- C++ is only a compiled language, whereas Java is compiled as well as an interpreted language.
- Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled.
- C++ allows users to use pointers in the program. Whereas java doesn’t allow it. Java internally uses pointers.
- C++ supports the concept of Multiple inheritances whereas Java doesn’t support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
11. How do you connect your Django project to the database?
Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging.
Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous.
Java makes use of references as these cannot be manipulated, unlike pointers.
12. What is the default value stored in Local Variables?
Neither the Local Variables nor any primitives and Object references have any default value stored in them.
13. Explain the expected output of the following code segment?
public class Simplilearn
{
public static void main (String args[])
{
System.out.println(100 + 100 +“Simplilearn”);
System.out.println(“E-Learning Company” + 100 + 100);
}
}
14. What are the default values assigned to variables and instances in java?
- There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of (Variable might not be initialized).
- But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type.
- If it is a reference, then it will be assigned to null.
- If it is numeric, then it will assign to 0.
- If it is a boolean, then it will be assigned to false. Etc.
15. What do you mean by data encapsulation?
- Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviors in a single unit.
- It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities.
- It is used for the security of the private properties of an object and hence serves the purpose of data hiding.
Learn Java From Our Expert Trainer
16. What gives Java its 'write once and run anywhere' nature?
The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code.
This bytecode is not platform specific and can be executed on any computer.
17. Is delete, next, main, exit or null keyword in java?
No.
18. If I don't provide any arguments on the command line, then what will the value stored in the String array passed into the main() method, empty or NULL?
It is empty, but not null.
19. What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.
20. What are the various access specifiers in Java?
In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.
- Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
- Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
- Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
- Private The private class, methods, or variables defined as private can be accessed within the class only.
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
21. What is the purpose of static methods and variables?
The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object.
The static variables are stored in the class area, and we do not need to create an object to access such variables. Therefore, static is used in the case where we need to define variables or methods which are common to all the objects of the class.
For example, In the class simulating the collection of students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static.
22. What is an Association?
An Association can be defined as a relationship that has no ownership over another. For example, a person can be associated with multiple banks, and a bank can be related to various people, but no one can own the other.
23. What do you mean by aggregation?
The term aggregation refers to the relationship between two classes best described as a “whole/part” and “has-a” relationship.
This kind is the most specialized version of an association relationship. It contains the reference to another class and is said to have ownership of that class.
24. Define Copy Constructor in Java
A Copy Constructor in Java is a constructor that initializes an object through another object of the same class.
25. What is a Marker Interface?
An empty interface in Java is referred to as a Marker interface. Serializable and Cloneable are some famous examples of Marker Interfaces.
Learn Java From Our Expert Trainer
26. What is Object Cloning?
An ability to recreate an object entirely similar to an existing object is known as Object Cloning in Java. Java provides a clone() method to clone a current object offering the same functionality as the original object.
27. Can Java be said to be the complete object-oriented programming language
No, Java cannot be treated as a complete object-oriented programming language.
28. What is an object-oriented paradigm?
A Paradigm that is based on the concepts of “Objects.” It contains data and code. Data is in the form of fields, and regulation is in the form of procedures.
The exciting feature of this paradigm is that the object’s procedures can access and often modify the data fields themselves.
29. Define Wrapper Classes in Java.
In Java, when you declare primitive data types, then Wrapper classes are responsible for converting them into objects(Reference types).
30. What is the output of the following Java program?
class Test
{
public static void main (String args[])
{
for(int i=0; 0; i++)
{
System.out.println(“Hello Javatpoint”);
}
}
}
The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
31. How many types of constructors are used in Java?
Based on the parameters passed in the constructors, there are two types of constructors in Java.
- Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
- Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.
32. Can you implement pointers in a Java Program?
Java Virtual Machine takes care of memory management implicitly. Java’s primary motto was to keep programming simple. So, accessing memory directly through pointers is not a recommended action. Hence, pointers are eliminated in Java.
33. Differentiate between instance and local variables.
For instance, variables are declared inside a class, and the scope of variables in javascript is limited to only a specific object.
A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the code segment where the variable is declared.
34. Explain Java String Pool.
A collection of strings in Java’s Heap memory is referred to as Java String Pool. In case you try to create a new string object, JVM first checks for the presence of the object in the pool.
If available, the same object reference is shared with the variable, else a new object is created.
35. What is an Exception?
Exception handling in Java is considered an unexpected event that can disrupt the program’s normal flow. These events can be fixed through the process of Exception Handling.
Learn Java From Our Expert Trainer
36. What is the final keyword in Java?
The term final is a predefined word in Java that is used while declaring values to variables. When a value is declared using the final keyword, then the variable’s value remains constant throughout the program’s execution.
37. What happens when the main() isn't declared as static?
When the main method is not declared as static, then the program may be compiled correctly but ends up with a severe ambiguity and throws a run time error that reads “NoSuchMethodError.”
38. What is JDK? Mention the variants of JDK?
JDK is an abbreviation for Java Development Kit. It is a combined Package of JRE and Developer tools used for designing Java Applications and Applets. Oracle has the following variants.
- JDK Standard Edition
- JDK Enterprise Edition
- JDK Micro Edition
39.Is constructor inherited?
No, The constructor is not inherited.
40.Can you make a constructor final?
No, the constructor can’t be final.
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
41. Can we overload the constructors?
Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.
- class Test
- {
- int i;
- public Test(int k)
- {
- i=k;
- }
- public Test(int k, int m)
- {
- System.out.println(“Hi I am assigning the value max(k, m) to i”);
- if(k>m)
- {
- i=k;
- }
- else
- {
- i=m;
- }
- }
- }
- public class Main
- {
- public static void main (String args[])
- {
- Test test1 = new Test(10);
- Test test2 = new Test(12, 15);
- System.out.println(test1.i);
- System.out.println(test2.i);
- }
- }
In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.
42. What do you understand about copy constructor in Java?
There is no copy constructor in java. However, we can copy the values from one object to another like a copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
- By constructor
- By assigning the values of one object into another
- By clone() method of Object class
43. What is a JIT compiler?
JIT compiler refers to the Just in Time compiler. It is the simplest way of executing the computer code that takes in compilation during the execution of a program rather than before performance.
It commonly uses bytecode translation to machine code. It is then executed directly.
44. What are Brief Access Specifiers and Types of Access Specifiers?
Access Specifiers are predefined keywords used to help JVM understand the scope of a variable, method, and class. We have four access specifiers.
- Public Access Specifier
- Private Access Specifier
- Protected Access Specifier
- Default Access Specifier
45. How many types of constructors are used in Java?
There are two types of constructors in Java.
Parameterized Constructors: Parameterized constructor accepts the parameters with which users can initialize the instance variables. Users can initialize the class variables dynamically at the time of instantiating the class.
Default constructors: This type doesn’t accept any parameters; rather, it instantiates the class variables with their default values. It is used mainly for object creation.
Learn Java From Our Expert Trainer
46. Can a constructor return a value?
Yes, A constructor can return a value. It replaces the class’s current instance implicitly; you cannot make a constructor return a value explicitly.
47. Explain ‘this’ keyword in Java.
The term “this” is a particular keyword designated as a reference keyword. The “this” keyword is used to refer to the current class properties like method, instance, variable, and constructors.
48. Explain the ‘super’ keyword in Java.
The term “super” is a particular keyword designated as a reference keyword. The “super” keyword refers to the immediate parent class object.
49. Explain Method Overloading in Java.
The process of creating multiple method signatures using one method name is called Method Overloading in Java. Two ways to achieve method overloading are:
- Varying the number of arguments
- Changing the return type of the Method
50. Can we overload a static method?
No, Java does not support the Overloading of a static method. The process would throw an error reading “static method cannot be referenced.”
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer

51. Define Late Binding.
Binding is a process of unifying the method call with the method’s code segment. Late binding happens when the method’s code segment is unknown until it is called during the runtime.
52. What is a Comparator in java?
Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees.
Then that is not possible to sort using the Collections. sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.
The comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values.
53. In Java, static as well as private method overriding is possible. Comment on the statement.
The statement in the context is completely False. The static methods have no relevance to the objects, and these methods are of the class level.
In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error.
The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible.
Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.
54. What makes a HashSet different from a TreeSet?
Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.
- Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
- Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
- Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons.
- Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exceptions occur while inserting heterogeneous objects or null objects.
55. Why is the character array preferred over string for storing confidential information?
In Java, a string is immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage.
In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.
As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them.
Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant.
Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.
Learn Java From Our Expert Trainer
56. What do we get in the JDK file?
- JDK- For making java programs, we need some tools that are provided by JDK (Java Development Kit). JDK is the package that contains various tools, Compiler, Java Runtime Environment, etc.
- JRE – To execute the java program we need an environment. (Java Runtime Environment) JRE contains a library of Java classes + JVM. What are JAVA Classes? It contains some predefined methods that help Java programs to use that feature, build and execute. For example – there is a system class in java that contains the print-stream method, and with the help of this, we can print something on the console.
- JVM – (Java Virtual Machine) JVM is a part of JRE that executes the Java program at the end. Actually, it is part of JRE, but it is software that converts bytecode into machine-executable code to execute on hardware.
57. What are the restrictions that are applied to the Java static methods?
Two main restrictions are applied to the static methods.
- The static method can not use non-static data members or call the non-static method directly.
- this and super cannot be used in a static context as they are non-static.
58. Why is the main method static?
59.Can we override the static methods?
No, we can’t override static methods.
60. Why is the delete function faster in the linked list than an array?
Delete Function is faster in linked lists in Java as the user needs to make a minor update to the pointer value so that the node can point to the next successor in the list
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
61. Give a briefing on the life cycle of a thread.
The life cycle of a thread includes five stages, as mentioned below.
- New Born State
- Runnable State
- Running State
- Blocked State
- Dead State
62. Explain the difference between >> and >>> operators.
Although they look similar, there is a massive difference between both.
- >> operator does the job of right shifting the sign bits
- >>> operator is used in shifting out the zero-filled bits
63. Brief the life cycle of an applet.
The life cycle of an applet involves the following.
- Initialization
- Start
- Stop
- Destroy
- Paint
64. Why are generics used in Java Programming?
Compile-time type safety is provided by using generics. Compile-time type safety allows users to catch unnecessary invalid types at compile time.
Generic methods and classes help programmers specify a single method declaration, a set of related methods, or related types with an available class declaration.
65. Explain the Externalizable interface.
The Externalizable interface helps with control over the process of serialization. An “externalizable” interface incorporates readExternal and writeExternal methods.
Learn Java From Our Expert Trainer
66. What is the Daemon Thread?
The Daemon thread can be defined as a thread with the least priority. This Daemon thread is designed to run in the background during the Garbage Collection in Java.
The setDaemon() method creates a Daemon thread in Java.
67. Explain the term enumeration in Java.
Enumeration or enum is an interface in Java. Enum allows the sequential access of the elements stored in a collection in Java.
68. Why is Java Dynamic?
Java is designed to adapt to an evolving environment. Java programs include a large amount of runtime information that is used to resolve access to objects in real-time.
69. Can you run a code before executing the main method?
Yes, we can execute any code, even before the main method. We will be using a static block of code when creating the objects at the class’s load time.
Any statements within this static block of code will get executed at once while loading the class, even before creating objects in the main method.
70. How many times is the finalize method called?
The finalize method is called the Garbage collector. For every object, the Garbage Collector calls the finalize() method just for one time.
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
71. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?
There are a total of 3 different types of priority available in Java.
MIN_PRIORITY: It has an integer value assigned with 1.
MAX_PRIORITY: It has an integer value assigned with 10.
NORM_PRIORITY: It has an integer value assigned with 5.
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM.
72. What is the difference between the program and the process?
- A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution.
- A program doesn’t execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.
73. What is JDBC?
JDBC is an abbreviation for Java Database Connector.
JDBC is an abstraction layer used to establish connectivity between an existing database and a Java application
74. Explain the various directives in JSP.
Directives are instructions processed by JSP Engine. After the JSP page is compiled into a Servlet, Directives set page-level instructions, insert external files, and define customized tag libraries. Directives are defined using the symbols below:
start with “< %@” and then end with “% >”
The various types of directives are shown below:
- Include directive
It includes a file and combines the content of the whole file with the currently active pages.
- Page directive
Page Directive defines specific attributes in the JSP page, like the buffer and error page.
- Taglib
Taglib declares a custom tag library, which is used on the page.
75. What are the observer and observable classes?
Objects that inherit the “Observable class” take care of a list of “observers.”
When an Observable object gets upgraded, it calls the update() method of each of its observers.
After that, it notifies all the observers that there is a change of state.
The Observer interface gets implemented by objects that observe Observable objects
Learn Java From Our Expert Trainer
76. What are the advantages of passing this into a method instead of the current class object itself?
As we know, this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.
- This is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
- this can be used in the synchronized block.
77. Explain FailFast iterator and FailSafe iterator along with examples for each.
FailFast iterators and FailSafe iterators are used in Java Collections.
FailFast iterators do not allow changes or modifications to the Java Collections, which means they fail when the latest element is added to the collection or an existing element gets removed from the collection.
The FailFast iterators tend to fail and throw an exception called ConcurrentModificationException.
Ex: ArrayList, HashMap
Whereas, on the other hand, FailSafe iterators allow changes or modifications to be done on the Java Collections. It is possible, as the FailSafe iterators usually operate on the cloned copy of the collection. Hence, they do not throw any specific exception.
Ex: CopyOnWriteArrayList
78. How do we reverse a string?
The string can be reversed by using the following program.
package simplilearnJava;
public class StringReverse {
public static void main(String args[]) {
String str = “Simplilearn”;
String reverse = new StringBuffer(str).reverse().toString();
System.out.printf(“Actual Word: %s, Word after reversing %s”, str, reverse);
}
public static String reverse(String source) {
if (source == null || source.isEmpty()) {
return source;
}
String reverse = “”;
for (int i = source.length() – 1; i >= 0; i–) {
reverse = reverse + source.charAt(i);
}
return reverse;
}
}
Expected Output:
Actual Word: Simplilearn, Word after reversing nraelilpmiS
79. Write a program to find the square root of a number.
The Square root of a number can be found by using the following program.
package simplilearnJava;
import java.util.Scanner;
public class SRoot {
public static void main(String args[]) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println(“Input a number to find square root: “);
double square = sc.nextDouble();
double squareRoot = Math.sqrt(square);
System.out.printf(“The square root is: %f “, squareRoot);
}
}
}
Expected Output:
Input a number to find square root:
25
The square root is: 5
80. Which among String or String Buffer should be preferred when there are a lot of updates required to be done in the data?
StringBuffer is mutable and dynamic whereas String is immutable. Every update/modification of String creates a new String thereby overloading the string pool with unnecessary objects.
Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
81. How to not allow serialization of attributes of a class in Java?
- In order to achieve this, the attribute can be declared along with the usage of transient keyword as shown below:
public class InterviewBitExample {
private transient String someInfo;
private String name;
private int id;
// :
// Getters setters
// :
}
- In the above example, all the fields except someInfo can be serialized.
82. What happens if the static modifier is not included in the main method signature in Java?
There wouldn’t be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws “NoSuchMethodError ” error at the runtime.
83. Consider the below program, identify the output, and also state the reason for that.
public class Main{
public static void main(String[] args) {
System.out.println(” Hello. Main Method. “);
}
public static void main(int[] args) {
System.out.println(” Hello. Main Method2. “);
}
}
The output of the above program will be Hello. Main Method. This is because JVM will always call the main method based on the definition it already has. Doesn’t matter how many main methods we overload it will only execute one main method based on its declaration in JVM.
84. What do you understand about an instance variable and a local variable?
Generally, instance variables are declared in a class but outside methods whereas a local variable is declared within the blocks of code.
//Local Variable
import Java.io.*;
class Main {
public static void main(String[] args)
{
int var = 145;
System.out.println(“Local Variable: ” + var);
}
}
//Instance variable
import Java.io.*;
class Main {
public int value = 12;
public static void main(String[] args)
{
Main va = new Main();
System.out.println(“My value is: ” + va.value);
}
}
85. Can the main method be overloaded?
Yes, the main method can be overloaded as many times as we want. Nevertheless, JVM prefers to call the main method with the help of its predefined calling method.
Example:
class Main {
public static void main(String args[]) {
System.out.println(” Main Method”);
}
public static void main(int[] args){
System.out.println(“Overloaded Integer array Main Method”);
}
public static void main(char[] args){
System.out.println(“Overloaded Character array Main Method”);
}
public static int main(double[] args){
System.out.println(“Overloaded Double array Main Method”);
}
public static void main(float args){
System.out.println(“Overloaded float Main Method”);
}
}
Learn Java From Our Expert Trainer
86. Comment on method overloading and overriding by citing relevant examples.
Method overloading occurs during the compile time, whereas method overriding occurs during the run time. Static binding is used during overloading, whereas dynamic binding is used during methods overriding.
//Function overloading
#function1
void addPodium(int a, int b)
{
System.out.println(a + b);
}
#function2
float addPodium(float a, float b, float c)
{
System.out.println(a + b + c);
}
//Function overriding
class Parent {
void show()
{
System.out.println(“I am Parent”);
}
}
class Child extends Parent {
void show()
{
System.out.println(“I am Child”);
}
}
class Main {
public static void main(String[] args)
{
Parent obj = new Parent();
obja.show();
Parent obj = new Child();
objb.show();
}
}
87. How do exemptions affect the program if it doesn't handle them?
Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn’t exist (This is the case of exception in java).
And if this case is not handled properly then the application will crash. This will be a bad experience for users. This is the type of error that cannot be controlled by the programmer.
But programmers can take some steps to avoid this so that the application won’t crash. The proper action can be taken at this step.
88. Is it mandatory for a catch block to be followed after a try block?
No, it is not necessary for a catch block to be present after a try block. – A try block should be followed either by a catch block or by a finally block. If the exception’s likelihood is more, then they should be declared using the throws clause of the method.
89. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below?
public int someMethod(int i){
try{
//some statement
return 1;
}catch(Exception e){
//some statement
return 999;
}finally{
//finally block statements
}
}
finally block will be executed irrespective of the exception or not. The only case where the finally block is not executed is when it encounters the ‘System.exit()’ method anywhere in the try/catch block.
90. Can you call a constructor of a class inside another constructor?
Yes, the concept can be termed as constructor chaining and can be achieved using this().
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version
Learn Java From Our Expert Trainer
91. A single try block and multiple catch blocks can co-exist in a Java Program. Explain.
One or more catch blocks can follow a try block. Each catch block must have a unique exception handler. So, if you want to perform multiple tasks in response to various exceptions, use the Java multi-catch block.
92. Do final, finally and finalize keywords have the same function?
No, final, finally and finalize keywords have different functionalities.
Final is used to restrict classes, variables, or methods, the final keyword.
Finally is used to execute the code written inside the block without handling any exceptions.
Finalize is used to call the function of the implementation of cleaning the garbage collection of an object.
93. When can you use the "super" keyword?
Basically, the super keyword is used to refer to the parent class. When there are the same fields in both parent and child classes, then one can use a super keyword to access data members of the parent class.
94. What are shallow copies and deep copies in Java?
In the case of a shallow copy, primitive data types are copied, whereas in the case of a deep copy along with primitive data types the object references are also copied.
95. Using relevant properties highlight the differences between interfaces and abstract classes.
An abstract class can have a combination of both abstract and non-abstract methods, whereas an interface has only abstract methods in it.
Learn Java From Our Expert Trainer
96. What are the different ways of thread usage?
There are two ways to define and implement a thread in Java. They are by implementing the runnable interface and extending the thread class.
Extending the Thread class
class InterviewBitThreadExample extends Thread{
public void run(){
System.out.println(“Thread runs…”);
}
public static void main(String args[]){
InterviewBitThreadExample in = new InterviewBitThreadExample();
ib.start();
}
}
Implementing the Runnable interface
class InterviewBitThreadExample implements Runnable{
public void run(){
System.out.println(“Thread runs…”);
}
public static void main(String args[]){
Thread ib = new Thread(new InterviewBitThreadExample());
ib.start();
}
}
Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes.
start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.
97. What is the difference between the ‘throw' and ‘throws' keyword in Java?
The throw keyword is often used to explicitly throw an exception. It can only throw one exception at a time whereas throws can be used to declare multiple exceptions.
98. Why does the java array index start with 0?
It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address.
99. Why is the remove method faster in the linked list than in an array?
In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used.
So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.
100. Is it possible that the ‘finally' block will not be executed? If yes then list the case.
Yes, there is a possibility that the ‘finally’ block cannot get executed. Here are some of the cases where the above situation occurs.
During the time of fatal errors such as memory exhaustion, memory access error, etc.
During the time of using System.exit()
Want to download these Java Interview Questions and Answers in the form of a readable and printable PDF for your interview preparation?
Click the download button below for the PDF version