Top 100 Java Interview Questions & Answers

Primavera P6 is the newest addition to the suite of project management solutions that is project, program and portfolio management tool which is one of the dominant project management software tools that is used for planning, managing and executing projects in a number of diverse industries, such as construction, manufacturing, energy, and IT.

Our Primavera Interview Questions is the one-stop resource which helps you to boost your interview preparation. The main aim of our blog is to boost your confident level and make you crack the interview successfully. We have 100+ questions on Primavera Programming basics prepared by our expert team that help you with different expertise levels to reap the maximum benefit from our blog. These most frequently asked questions are revised every three months to cope up with the industry standard.

Frequently asked Java Interview Questions

Q1. Define Java?

Answer:Java is the high level, object oriented, platform independent programming language. It is one of the most popular, general purpose, class based programminglanguage. It was developed by James gosling in 1991.

Q2. List the features of Java programming language?

Answer:

  • Simple, secured: Java is easy to learn, write and use without explicit pointers.
  • Object-Oriented: Java follows the object-oriented paradigm which allows maintaining the code.
  • Portable, Robust : Java supports read-once-write-anywhere approach with strong memory management.
  • Platform Independent, interpreted: Java is a platform independent programming language which comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed that uses the Just-in-time (JIT) interpreter.
  • High Performance: Java is faster than other traditional interpreted programming languages.

Q3. What is thread?

Answer:Threads are used to perform complicated tasks in the background without interrupting the main program and to operate more efficiently by doing multiple things at the same time.It can be created by extending the Thread class and overriding its run() method.

Q4. What do you understand by Java Virtual Machine?

Answer:Java Virtual Machine is an abstract machine which enables the computer to run the Java program that provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine.

Q5.What is JIT compiler?

Answer:Just-In-Time (JIT) compileris used to improve the performance that compiles parts of the bytecode 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.

Q6. What are the various access specifiers in Java?

Answer: Access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. The four access specifiers are,

  • Public
  • Public
  • Protected
  • Default
  • Private

Attend a Free Online Mock Interview

Q7. What is enumeration?

Answer: The Enumeration is a data type which contains a fixed set of constants that are public, static and final implicitly which is available since JDK 1.5. Enumeration can have constructors, methods and instance variables. Enumeration variables are used and declared in much a same way as you do a primitive variable.

Q8. Why is Java a platform independent language?

Answer: Java language was developed in such a way that it does not depend on any hardware or software due to the fact that the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

Q9.What do you mean by data encapsulation?

Answer: Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviour 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.

Q10. What is inheritance?

Answer:The process by which one class acquires the properties (data members) and functionalities (methods) of another class is called inheritance. It helps to provide the reusability of code so that a class has to write only the unique features and rest can be extended from another class.

Q11. What is static?

Answer: A static member is a member of a class in which the member belongs to the class itself. As a result, we can access the static member without first creating a class instance.

Q12. What is the main objective of garbage collection?

Answer:The main objective is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects. It ensures that the memory resource is used efficiently.

Q13. What is array?

Answer: An array is a container object that holds a fixed number of values of a single type. When the array is created, the length is established. After creation, its length is fixed. Each item in an array is called an element, each element is accessed by its numerical index.

Q14. How hashmap works internally in java?

Answer:HashMap works on hashing principles. It is a data structure which allows to store object and retrieve it in constant time O(1) provided we know the key. In hashing, hash functions are used to link key and value in HashMap.

Q15.What is byte code?

Answer: Byte code is the intermediate representation of a Java program, allowing a JVM to translate a program into machine-level assembly instructions. When a Java program is compiled, byte code is generated in the form of a . class file.

Q16. How does an exception propagate in the Java code?

Answer:When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

Q17. Why is synchronization necessary?

Answer: Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource. Synchronization assists in resolving the issue and the resource is shared by a single thread at a time.

Q18. How many types of memory areas are allocated by JVM?

Answer:

  • Class(Method) Area: 
  • Heap Stack: 
  • Counter Register: 
  • Native Method Stack: 

Q19. What gives Java its 'write once and run anywhere' nature?

Answer: Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This byte code is not platform specific and can be executed on any computer.

Q20.What is object-oriented paradigm?

Answer: Object oriented paradigm is a programming paradigm based on objects having data and methods defined in the class to which it belongs. It aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interact with one another to design applications and programs.

Q21. What is the constructor?

Answer:The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated and the memory is allocated for the object. Every time an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

Q22. What is an object?

Answer: Object is the real-time entity having some state and behaviour. It is an instance of the class having the instance variables as the state of the object and the methods as the behaviour of the object. The object of a class can be created by using the new keyword.

Q23.What is the static variable?

Answer: The static variable is used to refer to the common property of all objects (e.g., the company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Q24.What are the main uses of this keyword?

Answer: This keyword can be used to refer to the current class instance variable, to invoke current class methods, constructor. It can be passed as an argument in the method call, constructor call. It can be used to return the current class instance from the method.

Q25.How to get current date in java?

Answer: "DateFormat df = new SimpleDateFormat(""dd/MM/yy HH:mm:ss""); Date dateobj = new Date(); System.out.println(df.format(dateobj));"

Q26. Why we use interface in java?

Answer:It is used to achieve total abstraction. Java does not support multiple inheritances in case of class, but by using interface it can achieve multiple inheritances. It is also used to achieve loose coupling and to implement abstraction.

Q27. What is difference between throw and throws?

Answer: Throw is a keyword which is used to throw an exception explicitly in the program inside a function or inside a block of code. Throws is a keyword used in the method signature used to declare an exception which might get thrown by the function while executing the code.

Q28. What is Method overloading? Why is it used in Java?

Answer: If multiple functions in a class have the same name but different function definitions is called method overloading. It is used to make a java function serve multiple purposes making the code cleaner and API less complex.

Q29. What is the difference between JDK, JRE, and JVM?

Answer: JDK is a software environment used for the development of Java programs. It’s a collection of libraries that can be used to develop various applications. JRE (Java Runtime Environment) is a software environment that allows Java programs to run. All java applications run inside the JRE. JVM (java virtual machine) is an environment that is responsible for the conversion of java programs into bytecode executables. JDK and JRE are platform-dependent whereas JVM is platform-independent.

Q30. Does Java Support Pointers?

Answer: Pointers are not supported in java to make it more secure.

Q31. What are wrapper classes?

Answer:Wrapper classes are a functionality supported by java to accept primitive data types as inputs and then later convert those into string objects so that they can be compared to other objects.

Q32. How can we sort a list of elements in Java?

Answer: The built-in sorting utility sort() can be used to sort the elements. It can also write our custom functions but it’s advisable to use the built-in function as its highly optimized.

Q33.What is the use of the final keyword?

Answer: The final keyword is used to declare the final state of an entity in java which cannot be modified at a later stage in the application. The entity can be a variable, class, object, etc. It is used to prevent unnecessary modifications in a java application.

Q34. What is object cloning?

Answer: Object cloning is the process of creating an exact copy of an object of a class. The state of the newly created object is the same as the object used for cloning. The clone() method is used to clone objects. The cloning done using the clone method is an example of a deep copy.

Q35. What’s the difference between String and String Builder class in java?

Answer: Strings are immutable while string Builder class is mutable. The string builder class is also synchronized.

Q36. What’s the difference between == and .equals()?

Answer: “==” is an operator, whereas .equals() is a function.
“==” checks if the references share the same location, whereas .equals() checks if both object values are the same on evaluation.

Q37. What is servlet?

Answer: A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. They are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

Q38.What are object serialization and deserialization?

Answer:The use of java.io.Serializable to convert an object into a sequence of bytes is known as object serialization. Deserialization is the process of recovering back the state of the object from the byte stream.

Q39. What is polymorphism?

Answer: Polymorphism means many forms. It is one of the OOPs features that allow to perform a single action in different ways. A single object can refer to the super-class or sub-class depending on the reference type which is called polymorphism.

Q40. How to convert string to int in java?

Answer: "class Scratch{ public static void main(String[] args){ String str = ""50""; System.out.println( Integer.parseInt( str )); // Integer.parseInt() } }"

Q41.What is wrapper class?

Answer: Wrapper classes are used for converting primitive data types into objects, like int to Integer etc.

Q42. How to split string in java?

Answer:String string = ""004-034556""; String[] parts = string.split(""-""); String part1 = parts[0]; // 004 String part2 = parts[1]; // 034556

Q43. What is maven in java?

Answer: Maven is a powerful project management tool that is based on POM (project object model). It is used for project build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT.

Q44.What is applet in java?

Answer: An applet is a special kind of Java program that runs in a Java-enabled browser. This is the first Java program that can run over the network using the browser. It is embedded inside a web page and runs in the browser.

Q45. What is stream in java?

Answer: A Stream can be defined as a sequence of elements from a source. It supports aggregate operations on the elements. The source of elements refers to a collection or array that provides data to the Stream. It keeps the ordering of the elements the same as the ordering in the source. The aggregate operations are operations that allow to express common manipulations on stream elements quickly and clearly.

Q46. How to replace a character in a string in java?

Answer: String replace(char oldChar, char newChar): It replaces all the occurrences of a oldChar character with newChar character. For e.g. “pog pance”.replace(‘p’, ‘d’) would return dog dance.

Q47. How many ways to create object in java?

Answer: There are five different ways to create an object in Java:

  • Java new Operator
  • Java Class. newInstance() method
  • Java newInstance() method of constructor
  • Java Object. clone() method
  • Java Object Serialization and Deserialization

Q48. What is type casting in java?

Answer:The process of converting the value of one data type (int, float, double, etc.) to another data type is known as typecasting.

Q49. What is exception handling in java?

Answer: Exception Handling is a way to keep the program running even if some fault has occurred. An exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object-oriented way to handle exception scenarios, known as Java Exception Handling.

Q50. What is the difference between next () and nextline () in java?

Answer: next() can read the input only till space. It can’t read two words separated by space. Also, next() places the cursor in the same line after reading the input. nextLine() reads input including space between the words (that is, it reads till the end of line \n).

Q51. How to call a method in java?

Answer: To call a method in Java, write the method’s name followed by two parentheses () and a semicolon; the process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method.

Q52. What is MVC in java?

Answer: MVC Pattern represents the Model-View-Controller Pattern. This example is utilized to isolate the application’s interests. Model – Model speaks to an item or JAVA POJO conveying information. It can likewise have a rationale to refresh regulator if its information changes.

Q53.How to create a package in java?

Answer:To make a bundle, you pick a name for the bundle (naming shows are talked about in the following area) and put a bundle articulation with that name at the head of each source record that contains the sorts (classes, interfaces, lists, and explanation types) that you need to remember for the bundle.

Q54. What do you understand by an instance variable and a local variable?

Answer: Instance variables are variables that are accessible by all the methods in the class which are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.
Local variables are variables present within a block, function, or constructor and can be accessed only inside them.
The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

Q55. Explain the use of final keyword in variable, method and class?

Answer:The final keyword is used as defining something as constant /final and represents the non-access modifier.
Final variable:
When a variable is declared as final in Java, the value can’t be modified once it has been assigned. If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
Final method:
A method declared as final cannot be overridden by its children's classes. A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here.
Final class:
No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage

Q56. Explain the Java thread lifecycle?

Answer: Java thread life cycle is as follows:

  • New – When the instance of the thread is created, the thread is considered to be alive.
  • Runnable – Once the start () method is invoked, before the run () method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state which has entered from the Waiting or Sleeping state of the thread.
  • Running – When the run () method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state.
  • Non-Runnable (Blocked/Waiting) – When the thread is not able to run despite the fact of its aliveness, the thread is said to be in a NON-RUNNABLE state.
  • Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.
  • Waiting state it waits for work until the signal is received.
  • Terminated – Once the run () method execution is completed; the thread is said to enter the TERMINATED step and is considered to not be alive.

Q57. What is an iterator?

Answer: Assigned in overall/master schedule, look-ahead targets, and accomplishment reports and monitoring

Q58. Write a program to do bubble sort on an array in java.

Answer:A stack is a data structure that supports LAST IN FIRST OUT methodology. The element pushed last is at the top of the stack. A stack supports the following functionality:

  • Push-operation to push an element into the stack
  • Pop-operation to push an element out of the stack
  • Peek-An option to check the top element

Q59.Write a program to do bubble sort on an array in java.

Answer:import java.util.Scanner; class star { public static void main(String args[]) { int arr[] =new int [10]; Scanner sc = new Scanner( System.in ); System.out.println("Enter size of array"); int n=sc.nextInt(); System.out.print("Enter an arry : "); for (int i=0;iarr[j+1]) { int t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } } } for (int i=0;i

Q60. What is object in java?

Answer:An object is a software bundle of variables and related methods. Real-world objects can be represented using software objects. software objects are also used to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.

Q61. How many types of constructor does Java support?

Answer: Non-Parameterized or Default Constructors
Parameterized Constructors
Copy constructor

Q62. What is a singleton class in Java?

Answer: A singleton class is a class that can have one instance of it in an application. If new instances are created for the same class they point to the first instance created and thus have the same values for all attributes and properties. It is created to create global points of access to objects.

Q63. Explain abstraction in Java?

Answer: Abstraction is the process of revealing the essential information and hiding the trivial details across units in java. Java has abstract classes and methods through which it does data abstraction.

Q64. What is the use of super?

Answer: Super () is used to invoke the super class constructor by the subclass constructor. In this way, we do not have to create different objects for super and subclasses.

Q65. What is constructor chaining?

Answer: Constructor chaining is the process of invoking constructors of the same class or different classes inside a constructor. In this way, multiple objects are not required for constructor invocation with constructors having different parameters.

Q66. What is multithreading in java?

Answer: Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such a program is called a thread. So, threads are light-weight processes within a process.

Q67. What is volatile in java?

Answer: Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread-safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.

Q68. Why is string immutable in Java?

Answer:String is immutable in Java to ensure that the value of the string does not change. Java uses string literals, if there are multiple variables that refer to one object and the value of the object is changed, it would affect all reference variables. So, strings are immutable in Java.

Q69. What is API?

Answer: API stands for Application Programming Interface which is software that allows two applications to talk to each other. It is a list of classes that is part of a JDK or Java Development Kit and includes interfaces, packages, classes, fields, methods and constructors.

Q70. Name the Java IDE’s?

Answer:Eclipse, NetBeans

Q71.What are the OOPs concepts?

Answer: OOPs concepts include:

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • Interface

Q72. Difference between String and String Buffer.

Answer: String variables are stored in a “constant string pool”. Once the string reference changes the old value that exists in the “constant string pool”, it cannot be erased.
String Buffer:

  • Here string values are stored in a stack. If the values are changed then the new value replaces the older value.
  • The string buffer is synchronized which is thread-safe.
  • Performance is slower than the String Builder.

Q73.What is collection?

Answer:Collection is a framework that is designed to store the objects and manipulate the design to store the objects. A group of objects is known as collections. All the classes and interfaces for collecting are available in Java util package.
Collections are used to perform the following operations:

  • Searching
  • Sorting
  • Manipulation
  • Insertion
  • Deletion

Q74. What is meant by Ordered and Sorted in collections?

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

Q75. What are the different ways to handle exceptions?

Answer:Two different ways to handle exceptions are explained below:
a) Using try/catch:
The risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block.
b) By declaring throws keyword:
At the end of the method, we can declare the exception using throws keyword.

Q76. Explain about wait () method?

Answer: Wait () method is used to make the thread to wait in the waiting pool. When the wait () method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool. It tells the thread to wait for a given amount of time. Then the thread will wake up after notify () (or) notify all () method is called.

Q77. What is meant by Method Overriding?

Answer: Method overriding happens if the sub-class method satisfies the below conditions with the Super-class method: The key benefit of overriding is that the Sub-class can provide some specific information about that sub-class type than the super-class.

  • Method name should be the same
  • The argument should be the same
  • Return type should also be the same

Q78. Difference between HashSet and TreeSet?

Answer: In HashSet, the elements are inserted in random order that can able to store null object whereas it is maintained in sorted order in Treeset which cannot store null object. The performance of HashSet is fast when compared to TreeSet.

Q79.Define Copy Constructor in Java?

Answer:A Copy Constructor in Java is a constructor that initializes an object through another object of the same class.

Q80. Explain Java String Pool?

Answer: A collection of strings in Java's Heap memory is referred to as Java String Pool. When we create a new string object, Java Virtual Machine 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.

Q81. Define Late Binding.

Answer: 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. 

Q82. Explain the difference between >> and >>> operators?

Answer:

  • >> operator does the job of right shifting the sign bits
  • >>> operator is used in shifting out the zero-filled bits

Q83. What is the Daemon Thread?

Answer: The Daemon thread is defined as a thread with the least priority and it is designed to run in the background during the Garbage Collection in Java. The setDaemon() method creates a Daemon thread in Java.

Q84. What is Session Management in Java?

Answer: A session is defined as the random conversation's dynamic state between the client and the server. The virtual communication channel includes a string of responses and requests from both sides. It is implemented by establishing a session ID in the client's communicative discourse and the server.

Q85. Explain JPA in Java?

Answer:The Java Persistence API enables us to create the persistence layer for desktop and web applications. Java Persistence deals in the following:

  • Java Persistence API
  • Query Language
  • Java Persistence Criteria API
  • Object Mapping Metadata

Q86. What is the difference between System.out, System.err, and System.in?

Answer:System.out and System.err represent the monitor by default and thus can be used to send data or results to the monitor. System.out is used to display normal messages and results. System.eerr is used to display error messages. System.in represents InputStream object which by default represents standard input device, i.e., keyboard.

Q87. What is the difference between an Inner Class and a Sub-Class?

Answer:
An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.
A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

Q88. What are Loops in Java? What are three types of loops?

Answer:
Looping is used to execute a statement or a block of statement repeatedly. There are three types of loops in Java:

  • For Loops- to execute statements repeatedly for a given number of times.
  • While Loops- Condition is checked first before execution of statements and certain statements need to be executed repeatedly until a condition is fulfilled.
  • Do While Loops-It is same as while loop with only difference that condition is checked after execution of block of statements.

Q89.Differentiate between continue and break statement?

Answer:
Break and continue are two important keywords used in Loops. When a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with next iteration.

Q90.How can you generate random numbers?

Answer:

  • Generate random numbers using Math.random() in the range greater than or equal to 0.1 and less than 1.0
  • Using Random class in package java.util

Q91. What are Java Packages? What’s the significance of packages?

Answer:
Java package is a collection of classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers to modularize the code and group the code for proper re-use. Once code has been packaged in Packages, it can be imported in other classes and used.

Q92. Can a class have multiple constructors?

Answer:
Yes, a class can have multiple constructors with different parameters. Which constructor gets used for object creation depends on the arguments passed while creating the objects.

Q93. What’s the benefit of using inheritance?

Answer:
Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism is another great benefit which allows new functionality to be introduced without effecting existing derived classes.

Q94. What’s difference between Stack and Queue?

Answer:
Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.

Q95. What are the two environment variables that must be set in order to run any Java programs?

Answer:
Java programs can be executed in a machine only once following two environment variables have been properly set:

  • PATH variable
  • PATH variable

Q96. What will be the output of Round (3.7) and Ceil (3.7)?

Answer:
Round (3.7) returns 4 and Ceil (3.7) returns 4.

Q97. What is a Local class in Java?

Answer:
In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where it’s defined.

Q98. What’s the base class of all exception classes?

Answer:
Java.lang.Throwable is the super class of all exception classes and all exception classes are derived from this base class.

Q99. What is the difference between an Inner Class and a Sub-Class?

Answer:
Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

Q100.Can we use different return types for methods when overridden?

Answer:
The basic requirement of method overriding in Java is that the overridden method should have same name, and parameters. But a method can be overridden with a different return type as long as the new return type extends the original.