SECTION ONE:
1. What is a functional interface?
An interface with a single abstract method. Enables lambda expressions.
2. Difference between map() and flatMap() in Streams?
map() transforms each element. flatMap() flattens nested structures.
3. What are method references?
A shorthand for calling methods using :: syntax. E.g., [Link]::println.
4. What is Optional and how should it be used?
To avoid null. Use isPresent(), orElse(), map(). Don’t misuse as container.
5. What is the purpose of default methods in interfaces?
Allows adding methods without breaking implementations.
6. What is garbage collection in Java?
Automatic process of reclaiming memory from unreachable objects.
7. Explain the Java memory model.
Heap (Young, Old), Stack, Metaspace. Thread-safe reads/writes governed by JMM.
8. What is PermGen vs Metaspace?
PermGen (pre-Java 8) was fixed-size. Metaspace grows dynamically.
9. How does G1GC differ from CMS?
G1GC is region-based, parallel, and has predictable pause times.
10. How can you detect and fix memory leaks?
Using tools like VisualVM, JProfiler. Common causes: static collections, listeners not removed.
SECTION TWO: MCQ
1. Who invented Java Programming?
a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
Answer: b
Explanation: Java programming was developed by James Gosling at Sun Microsystems in 1995.
James Gosling is well known as the father of Java.
2. Which statement is true about Java?
a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language
Answer: d
Explanation: Java is called ‘Platform Independent Language’ as it primarily works on the
principle of ‘compile once, run everywhere’.
3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM
Answer: c
Explanation: JDK is a core component of Java Environment and provides all the tools,
executables and binaries required to compile, debug and execute a Java Program.
4. Which one of the following is not a Java feature?
a) Object-oriented
b) Use of pointers
c) Portable
d) Dynamic and Extensible
Answer: b
Explanation: Pointers is not a Java feature. Java provides an efficient abstraction layer for
developing without using a pointer in Java. Features of Java Programming are Portable,
Architectural Neutral, Object-Oriented, Robust, Secure, Dynamic and Extensible, etc.
5. Which of these cannot be used for a variable name in Java?
a) identifier & keyword
b) identifier
c) keyword
d) none of the mentioned
Answer: c
Explanation: Keywords are specially reserved words that can not be used for naming a user-
defined variable, for example: class, int, for, etc.
6. What is the extension of java code files?
a) .js
b) .txt
c) .class
d) .java
Answer: d
Explanation: Java files have .java extension.
7. What will be the output of the following Java code?
1. class increment {
2. public static void main(String args[])
3. {
4. int g = 3;
5. [Link](++g * 8);
6. }
7. }
a) 32
b) 33
c) 24
d) 25
Answer: a
Explanation: Operator ++ has more preference than *, thus g becomes 4 and when multiplied by
8 gives 32.
output:
$ javac [Link]
$ java increment
32
8. Which environment variable is used to set the java path?
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME
Answer: d
Explanation: JAVA_HOME is used to store a path to the java installation.
9. What will be the output of the following Java program?
1. class output {
2. public static void main(String args[])
3. {
4. double a, b,c;
5. a = 3.0/0;
6. b = 0/4.0;
7. c=0/0.0;
8.
9. [Link](a);
10. [Link](b);
11. [Link](c);
12. }
13. }
a) NaN
b) Infinity
c) 0.0
d) all of the mentioned
Answer: d
Explanation: For floating point literals, we have constant value to represent (10/0.0) infinity either
positive or negative and also have NaN (not a number for undefined like 0/0.0), but for the integral type,
we don’t have any constant that’s why we get an arithmetic exception.
10. Which of the following is not an OOPS concept in Java?
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
View Answer
Answer: c
Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation, Polymorphism and
Abstraction.
11. What is not the use of “this” keyword in Java?
a) Referring to the instance variable when a local variable has the same name
b) Passing itself to the method of the same class
c) Passing itself to another method
d) Calling another constructor in constructor chaining
Answer: b
Explanation: “this” is an important keyword in java. It helps to distinguish between local
variable and variables passed in the method as parameters.
12. What will be the output of the following Java program?
1. class variable_scope
2. {
3. public static void main(String args[])
4. {
5. int x;
6. x = 5;
7. {
8. int y = 6;
9. [Link](x + " " + y);
10. }
11. [Link](x + " " + y);
12. }
13. }
a) Compilation error
b) Runtime error
c) 5 6 5 6
d) 5 6 5
Answer: a
Explanation: Second print statement doesn’t have access to y , scope y was limited to the block
defined after initialization of x.
output:
$ javac variable_scope.java
Exception in thread "main" [Link]: Unresolved compilation problem: y
cannot be resolved to a variable
1. Describe Java in a single sentence
Java is a platform-independent (write once, run anywhere) object-oriented language with
automatic memory management (garbage collection), strong typing, and a rich standard library.
2. What are the differences between primitive data types and objects in Java?
Primitives and objects highlight the core methods in how Java handles basic data vs. complex
structures.
In terms of storage, primitives store actual values while objects store references. Primitives take
up less memory, objects more. Primitives have limited built-in operations while you can
implement as many methods as you want for objects.
Also, primitives can’t be null, limiting their flexibility (depends on the context) while objects
can. For their simplicity, primitives are generally faster to access and manipulate.
In Java, there are 9 primitive types (int, boolean, etc.) while you can create unlimited object
types.
3. What is the difference between String, StringBuilder, and StringBuffer?
If your string is not going to change, use a String class as a String object is immutable. If your
string should be modified and will be accessed only by a single thread, StringBuilder is good
enough. In other scenarios (string can be changed, using multiple threads), use StringBuffer
because it is synchronous and thread-safe.
/ String (immutable)
String s = "Hello";
s += " World"; // Creates a new String object
// StringBuilder (mutable, not thread-safe)
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // Modifies the same object
// StringBuffer (mutable, thread-safe)
StringBuffer sbf = new StringBuffer("Hello");
[Link](" World"); // Thread-safe modification
4. How do you handle exceptions in Java?
Exceptions in Java can be gracefully handled using try-catch blocks. In the try block, we
write the code that might throw an exception, and the catch block specifies what the code must
do if the exception occurs.
A finally block can be used for cleanup operations if try-catch blocks deal with external
resources like file managers, database connections, etc.
Here is a code example demonstrating exception handling in Java:
import [Link];
import [Link];
public class ExceptionHandlingExample {
public static void main(String[] args) {
FileReader reader = null;
try {
reader = new FileReader("[Link]");
// Code that might throw an exception
int character = [Link]();
[Link]((char) character);
} catch (IOException e) {
// Handling the specific exception
[Link]("An error occurred while reading the file: " +
[Link]());
} finally {
// Cleanup code that always executes
if (reader != null) {
try {
[Link]();
} catch (IOException e) {
[Link]("Error closing file: " +
[Link]());
}
}
}
}
5. What is the purpose of the static keyword in Java?
The static keyword in Java is used to declare members (variables, methods, nested classes) that
belong to the class itself rather than instances of the class. Declaring static members allows
sharing data across all instances of a class, creating utility methods that don't require object
instantiation or defining constraints.
For example, in the following BankAccount class, the totalAccounts and INTEREST_RATE
variables are static, so they will be available only within the class itself.
example
public class BankAccount {
private String accountHolder;
private double balance;
private static int totalAccounts = 0;
private static final double INTEREST_RATE = 0.05;
// The rest of the code here ...
}
6. Explain the concept of inheritance in Java through examples
Inheritance is one of the core pillars of object-oriented programming in Java. It allows one class
to inherit properties and methods from another class, promoting code reuse and establishing a
parent-child relationship between classes.
For example, Car class may inherit from a general Vehicle class. When doing so, Car can
behave just like Vehicle in terms of attributes and methods like:
Vehicle class has members like year and make while Car has an additional member
transmission.
Vehicle class has a move method while Car overrides move with additional behavior
suited to cars.
7. What is the difference between == and .equals() when comparing strings?
== compares object references (memory addresses), while .equals() compares the content of
strings. For string comparison, always use .equals().
Here’s an example to illustrate the difference:
String str1 = "Hello";
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
[Link](str1 == str2); // true (same object reference)
[Link](str1 == str3); // false (different object references)
[Link]([Link](str2)); // true (same content)
[Link]([Link](str3)); // true (same content)
8. How do you create and use an array in Java? How do arrays in Java differ
from arrays in other languages?
Arrays are critical objects that store multiple values of the same type in Java. They are created
using square brackets and can be initialized in several ways. Here is a couple of common
patterns:
1. Declaration and allocation:
int[] numbers = new int[5]; // Creates an array of 5 integers
. Declaration, allocation, and initialization:
int[] numbers = {1, 2, 3, 4, 5}; // Creates and initializes an array
Powered By
If we compare Java arrays to Python lists, there are many differences. Here is a couple:
Fixed size: Java arrays, once created, cannot change size
Type safety: Java arrays are type-safe; you can’t put an integer into a String array
9. What is the purpose of class constructors in Java?
Constructors are special and very important methods used to initialize instances of a class. They
have the same name as the class and are called when a new object is created using the new
keyword.
10. Explain the difference between break and continue statements.
break and continue are important loop flow control keywords in Java. break statement is used
to stop the entire loop immediately and ignore the rest of the loop. It is useful to terminate the
loop early based on a condition.
For example, I use break for debugging purposes like running only a single iteration of a long
loop.
continue is used to skip the rest of the current iteration and immediately jumps to the next
iteration. It is useful when looping over sequences and want to skip certain elements based on a
condition.
Here is a code example:
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue; // Skip iteration when i is 2
}
if (i == 4) {
break; // Exit loop when i is 4
}
[Link](i);
}
11. What is method overloading in Java?
Method overloading is a powerful technique that allows a class to have multiple methods with
the same name but different parameters. This gives the objects of the class to handle closely
related (almost the same) tasks but with different inputs.
Here’s a super short example demonstrating method overloading:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Powered By
In this example, the Calculator class has two add methods: One that takes two integers and
returns an integer sum, and another that takes two doubles and returns a double sum. The method
name is the same, but the parameters differ, allowing the appropriate method to be called based
on the argument types.
12. How do you read user input from the console in Java?
To accept user input from the user, one can use the Scanner class:
Scanner scanner = new Scanner([Link]);
String input = [Link]();
Powered By
Here’s what each line does:
1. Scanner scanner = new Scanner([Link]); This line creates a new Scanner
object that reads input from the console ([Link]).
2. String input = [Link](); This line reads a full line of text entered by the
user and stores it in the input variable.
The Scanner class is used to parse primitive types and strings from various input sources. In this
case, it’s reading from the standard input (keyboard).
The nextLine() method reads the entire line of text, including spaces, and returns it as a String.
13. What is the difference between ArrayList and array?
One limitation of Java’s built-in array objects is that their size can’t be changed after
initialization. ArrayList solves this problem and offers more methods for manipulation.
However, this comes at the cost of not being able to store primitives directly. ArrayList only
stores objects.
14. How do you iterate through a collection in Java?
A collection in Java is an object that groups multiple elements into a single unit and part of the
Java Collections Framework. It is often used to store, retrieve, manipulate and communicate
aggregate data.
To iterate through a collection, you can use a for-each loop, iterator, or a traditional for loop.
The code example below shows the use of a for-each and a regular for loop:
// Example using for-each loop:
List<String> fruits = [Link]("Apple", "Banana", "Orange");
for (String fruit : fruits) {
[Link](fruit);
}
// Example using regular for loop:
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
Powered By
15. What is the purpose of the final keyword when used with a variable?
The final keyword in Java is a modifier that can be applied to variables, methods and classes.
When used with a variable, the keyword makes it immutable or in other words, constant. For
example, PI is declared as a final variable in the class below:
public class CircleCalculator {
private final double PI = 3.14159;
public double calculateArea(double radius) {
return PI * radius * radius;
}
}
Powered By
If any code attempts to modify PI, it will result in a compile-time error.