×

Search anything:

Interview Questions in Java (MCQ)

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have presented several Interview Questions in Java (MCQ) covering all important topics in Java. These questions are frequently asked in Coding Interviews and you must attempt these questions.

If you need to revise Java quickly before attempting the questions, go through this article: Learn Java in one post (30 minutes) with code examples.

1. What is the size of boolean data type in Java?

1 byte
2 byte
4 byte
1 bit
Boolean data type is a primitive data type in Java and requires only 1 bit of memory. As 1 byte is the minimum assignable memory, the size of boolean data type is 1 byte (= 8 bits).

2. What is the default value of char data type in Java?

\u0000
""
u1111
null
The default value of char data type in Java is \u0000 which is known as the null character.

3. What are instance variable in Java?

defined in main()
local to a method
common to entire code
with only one instance
Instance variables are variables that have been defined in main() function. There are two other types of variables in Java which are "static variable" and "local variable".

4. What is the keyword used for Inheritance in Java?

extends
inherit
implements
clone
"extends" is the keyword used for Inheritance in Java. "implements" keyword is used for using an Interface.

Following are the member variables in a standard HashMap implementation in Java:

static final int DEFAULT_INITIAL_CAPACITY = 16;
	static final int MAXIMUM_CAPACITY = 1 << 30;
	static final float DEFAULT_LOAD_FACTOR = 0.75f;

	transient Entry[] table;
	transient int size;
	int threshold;
	final float loadFactor;

5. In the above code, what is meant by "transient"?

Prevent Serialization
Efficient transfer
Local variable
Enable Multi-threading
transient keyword is used to avoid converting an object to a stream of bytes during serialization.

In Queue collection in Java, we can remove element using two standard member functions:

Queue<String> queue=new PriorityQueue<String>();  
// add
queue.add("opengenus"); 
// remove
queue.remove();
queue.poll();

6. What is the extra feature provided by queue.poll()?

Return null if empty
Does not return value
Return type is boolean
Thread safe removal
queue.poll() is used to remove an element for Queue collection in Java. The difference from remove() is that poll() will return null if the Queue is empty while remove() will throw an error.

7. Among String, StringBuffer and StringBuilder, which is the fastest?

StringBuilder
StringBuffer
String
Same time for all
StringBuilder is not threadsafe or synchronized and does not create a new object when modified, hence it is the fastest among the three options. The second fastest is StringBuffer which is threadsafe while String is the slowest as a new object is created everytime it is modified.

Following is a sample Java implementation of Singleton class:

// Singleton class in Java
// Part of iq.opengenus.org
public final class ClassSingleton {
    private static ClassSingleton INSTANCE;
    private String info = "Initial info class";
    
    private ClassSingleton() {
    }
    
    public static ClassSingleton getInstance() {
        if(INSTANCE == null) {
            INSTANCE = new ClassSingleton();
        }
        return INSTANCE;
    }
}

8. What is the issue with the above Java code for Singleton class?

Not threadsafe
Static instance not created
constructor should be public
Serializable not supported
It is not threadsafe so synchronized keyword must be used with method definition getInstance().

9. How we can explicitly call Garbage Collector in Java?

System.gc()
System.exit(2)
Not possible
Allocate large amount of memory
System.gc() can be used to explicitly call Garbage Collector in Java. Note that this call only suggests the Garbage Collector to run so there may be a case where Garbage Collector will not run if it does not find it necessary.

10. There are 3 phases in Garbage Collector in Java. Which one of these is not one of the 3 phases?

Mark-copy
Major
Minor
Full
Mark-copy is a Garbage Collection algorithm which is used in specific cases. There are three main phases in Garbage Collector in Java: Major, Minor and Full.

There are 4 types of References in Java. Weak Reference in Java is defined as follows:

// Creates a strong reference
Object obj = new Object();
// New Weak Reference to obj object
WeakReference<Object> softRef = new WeakReference<Object>(obj);

11. When is an object having a weak reference removed by the Garbage Collector?

Always
Only if memory is needed
Never
Varies across runtime
Weak References have another interpretation from the Garbage Collector. While the types mentioned before are, for default, preserved in memory, if an object has only a weak reference attached to him when the GC is running, then it will be reclaimed even if the virtual machine doesn't need more space.

If an object has a strong reference, then it is never removed by the Garbage Collector. A strong reference is defined as follows:

Object obj = new Object(); // Creates a strong reference

12. How is a strong reference to an object removed?

obj = null
obj.remove()
System.gc()
System.exit(obj)
Using "obj = null", the strong reference to the object obj is removed and the object obj is available for Garbage Collector to remove it to make memory available.

In Java Collections, there are several variants of HashMap of which following are two variants:

Map<String, Integer> map = new HashMap<String, Integer>();

LinkedHashMap<Integer, String> lhmap = 
                 new LinkedHashMap<Integer, String>();

13. What is the additional property of LinkedHashMap over HashMap?

Maintains order of elements
Synchronized
Thread safe
Serializable
LinkedHashHap is an implementation of HashMap which uses Linked List for chaining. It maintains the order of elements based on insertion order and can be traversed as such. HashMap does not maintain the order.

14. What is the default load factor of HashMap collection in Java?

0.75f
0.25f
0.50f
0.95f
Load factor is the fraction of memory already utilized in HashMap so that at this point, the HashMap is resized and the memory is doubled. The load factor by default is 0.75f in HashMap collection in Java. It is captured by the member variable DEFAULT_LOAD_FACTOR in the implementation of HashMap.

15. Which type of Inheritance is not possible in Java?

Multiple Inheritance
Multi-level
option3
All are possible
Multiple Inheritance is not permitted in Java but it can be implemented using Interface. You can learn about this technique here.

throw and throws are different keywords in Java and are used in different places to raise an exception.

16. Which one is used to raise an exception always?

throw
throws
None
Depends on implementation
throw is used to raise an exception always and is used within a function while "throws" is used in method signature and is used as a signal that the function may raise an error.

17. In Java, the Collections library is present in which package?

java.util
java.lang
java.io
java.system
java.util is the package for the various Collections in Java like HashMap.

18. There are two ways to support Multi-threading in Java: Thread and Runnable. Which one is used by inheritance?

Thread
Runnable
None
Both
To support Multi-threading, we need to inherit Thread class or implement the Runnable interface. It is recommended to use Runnable as on using Thread class, we cannot inherit any other class as Multiple Inheritance is not supported in Java.

19. What is the compiler name of Java?

javac
gcc
aocc
java virtual machine
javac is the compiler for Java. A code file named code.java is compiled using the command "javac code.java".

Following code shows the use of static keyword in two different ways:

public class PrintWord {

  // Static variable
  static float check_variable1 = 1.02;
  
  void function_check() {
    // Local variable
    double check_variable2 = 2.931271;
  }
  
  public static void main(final String[] args) {
    // Instance variable
    int check_variable3 = 2;
  }
}

20. What is static keyword used in Java for?

One common copy
Immutable reference
Mutable reference
option4
static keyword is used when we want to keep one common copy across all instances of a class and different functions. Note main() is used with static as there is only one main().

21. Which of the following cleans the permanent memory space?

None of these
Major GC
Minor GC
Full GC
Minor GC cleans the Eden memory space while Major GC cleans the Old generation memory space. Full GC cleans both Eden and Old Generation Memory space. Hence, none of the three GC phases clean the permanent memory space.

22. Which of the following is the slowest process?

Full GC
Major GC
Minor GC
All takes equal time
Full Garbage collection involves both Major and Minor GC so it takes the longest amount of time.

23. Where is a newly declared variable allocated memory?

Eden space
Survivor 1 space
Survivor 0 space
Old generation space
All new variables are allocated memory from Eden space. If there is no space left in Eden space, then a Minor Garbage Collection is used to make space available.

24. Why is Java not purely Object Oriented Programming (OOP) language?

Primitive datatypes are not objects
Strings are immutable objects
Java is OOP
Due to lambda in Java
Java is not a pure Object Oriented Programming (OOP) language because Primitive datatypes are not objects whereas in OOP, everything should be an object.

Pointers is a concept in C and C++ which is not available in Java. Pointer is used to access memory directly. It is not supported in Java to make the language memory safe.

25. Who manages memory in Java?

JVM
JDK
User code
JRE
JVM has the responsibility to manage memory and allocate as and when required.

Java is known for its code portability / write once run anywhere. JIT compiler known as Just In Time Compiler plays a major role.

26. What is the role of JIT compiler?

Bytecode to Machine Code
Code to Bytecode
Runtime optimizations
Remove non-portable code
JIT compiler is used to convert the bytecode to machine code. The bytecode is machine-independent while the machine code varies across systems. It is the bytecode which makes Java platform independent.

27. What keyword is used to prevent a class from being extended / inherited?

final
const
= 0
void static
final keyword is used to define a class which cannot be extended or inherited by any other class in Java. final keyword has similar use case in defined variables and methods.

In Inheritance in Java, super() is used to access methods of the parent or base class.

28. Which keyword is used to access methods of the current class?

this()
-->
static
Use with super()
this() is used to access methods of the current class which super() is used to access methods of the parent or base class.

29. Why is there a String Pool in Java but not Integer Pool for int?

String is immutable
int is primitive datatype
Design principle
String is array of char
Memory Pool is created for all immutable objects. As string is immutable, String Pool exists. On the other hand, as int is a mutable data type, there is not memory pool for int.

30. What is the process of calling one constructor from another constructor called?

Constructor chaining
Constructor Inheritance
Constructor fallback
Polymorphism
Constructor chaining is the process of calling one constructor from another constructor. This involves the use of this() and super() keywords.

String is immutable and stored in its special area called String Pool. The alternative to string are StringBuffer and StringBuilder.

31. Where are StringBuffer and StringBuilder stored?

Heap area
String Pool
Eden space
Old generation space
StringBuffer and StringBuilder are mutable objects so they are stored in Heap area.

32. What is Polymorphism in Java?

One interface, many implementations
Hide details
Use common interface
Use abstract class
Polymorphism refers to the OOP concept of One interface, many implementations. There are two types of Polymorphism: Runtime and Compile-time.

33. Multiple Inheritance is not supported in Java. Why?

Source of several bugs
To be added in future
Major limitation of Java
Memory layout does not support
Multiple Inheritance is not supported in Java because Multiple Inheritance is not considered a good practice and results in complex code and several bugs in practice. For this, this is restricted in Java. A similar design can be implemented using Interfaces. This problem is known as Diamond Problem.

34. What is Copy Constructor?

Initialize object using another object
Constructor with parameters
Constructor in inherited class
Constructor with no parameters
Copy Constructor is a constructor that is used to initialize the new object by copying parameters of another object.

35. finally block is a block of code statements that always execute and is associated with a try catch statement. When will a finally block not execute?

System.exit()
System.gc()
Multi-threads
Memory corruption
finally block not execute in case of System.exit() or a fatal error.

36. OutOfMemoryError is an object and not just a error statement. It is an object of which class?

java.lang.Error
java.util.Error
java.lang
java.io.Error
OutOfMemoryError is an object of java.lang.Error class. In OOP, everything should be an object ideally.Only exception in Java are primitive data types.

37. If a program goes in an unexpected direction, then Error or Exception can occur. Which one can a Programmer handle in code?

Exception
Error
None
Both
Exception can be handled using try and catch block but an Error cannot be handled in code. Exception occur due to unexpected input or behaviour and this can be detected and an alternative path can be taken or execution can be terminated.

38. Among String, StringBuilder and StringBuffer, which one is not thread safe?

StringBuilder
String
StringBuffer
None
StringBuilder is not thread safe but is more efficient than String as StringBuilder is mutable and new objects are not created during its modification.

39. Why are packages used in Java?

Prevent name conflicts
Code organization
Access Specifier
For creating library
Package in Java is used to prevent name conflicts across methods.

With this article at OpenGenus, you must have a good practice in questions in Java Programming Language. Best of luck for your Examination or Coding Interview.

Interview Questions in Java (MCQ)
Share this