0% found this document useful (0 votes)
21 views

Java Oops

Uploaded by

rahulbadhe2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Oops

Uploaded by

rahulbadhe2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Java Interview: Class, Constructor, Inheritance

December 15, 2023


act as a java interviewer and give answers of this question according springboot classconnect project with
project examples Q)What is a class?Explain steps for writing a class?
Q)What is a constructor,its use & types
Q)what is constructor chaining?How do you implement it?
Q)Does constructor return any value?
Q)Can constructor be inherited
Q)can we make constructor static/abstract/final
Q)can we make constructor private
Q)what is singleton class?how do we implement it
Q)what is difference between local variable,static variable,instance variable
Q)what is static block?when is it invoked?
Q)can we write multiple static blocks ?
Q)what is static method & its use
Q)why main method is static
Q)In a java file,how many java classes can we write
Q)can we call main explicitly
Q)Can we declare main() method as private or protected or with no access modifier?
Q)Can we run java class without main() method?
Q)what are command line arguments?How do we pass them in java?
Q)How do we create object in java?what is an object reference?
Q)Can you create an object without using new operator in Java?
Q)what is ’this’ reference?Explain its use?
Q)what is inheritance ?How do we implement it in Java?
Q)List types of Inheritance
Q)what is difference between this & super
Q)Is it mandatory for every super class to have default constructor
Q)Does class to super() must be first line ?if yes why
what will happen if we dont call super() from subclass?
Q)what is polymorphism .Explain its types
Q)what is difference between static binding & dynamic binding
ChatGPT
Sure, let’s go through these questions one by one:

Q) What is a class? Explain steps for writing a class?


A class in Java is a blueprint for creating objects. It defines a data structure along with methods to work o
n that data. Here are the steps for writing a class:

Define the Class: Use the class keyword followed by the class name.

java
Copy code
public class MyClass {
Declare Variables: Define the data members of the class.

java
Copy code
private int myVariable;
Write Constructors: Constructors initialize the object. You can have multiple constructors.

java
Copy code
public MyClass() {
// Constructor code here
}
Define Methods: Methods perform actions or provide functionality.

java
Copy code
public void myMethod() {
// Method code here
}
Create Objects: Instantiate the class to create objects.

java
Copy code
MyClass myObject = new MyClass();
Q) What is a constructor, its use & types?
A constructor is a special method used to initialize objects. It has the same name as the class and is calle
d when an object is created. Types of constructors:

Default Constructor: No parameters.


Parameterized Constructor: Takes parameters.
Copy Constructor: Takes an object of the same class as a parameter.
Q) What is constructor chaining? How do you implement it?
Constructor chaining is calling one constructor from another within the same class. It is achieved using thi
s() keyword. Example:

java
Copy code
public class MyClass {
public MyClass() {
// Default constructor code
}

public MyClass(int value) {


this(); // Calling default constructor
// Parameterized constructor code
}
}
Q) Does a constructor return any value?
No, a constructor doesn’t have a return type, not even void.

Q) Can a constructor be inherited?


No, constructors are not inherited. However, the subclass implicitly calls the constructor of the superclass
using super().

Q) Can we make a constructor static/abstract/final?


No, constructors cannot be static, abstract, or final.

Q) Can we make a constructor private?


Yes, you can make a constructor private. It is useful for creating singleton classes.

Q) What is a singleton class? How do we implement it?


A singleton class is a class that allows only one instance to be created. To implement it, make the constru
ctor private and provide a static method that returns the instance of the class.

java
Copy code
public class Singleton {
private static Singleton instance;

private Singleton() {
// Private constructor
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Q) What is the difference between local variable, static variable, and instance variable?
Local Variable: Declared inside a method or block. Exists only within that scope.
Static Variable: Belongs to the class rather than an instance. Shared by all instances.
Instance Variable: Belongs to an instance of the class. Each instance has its own copy.
Q) What is a static block? When is it invoked?
A static block is a block of code inside a class that is executed when the class is loaded into memory. It is
used for static initialization. Example:

java
Copy code
public class MyClass {
static {
// Static block code
}
}
Q) Can we write multiple static blocks?
Yes, you can write multiple static blocks in a class. They are executed in the order they appear.

Q) What is a static method & its use?


A static method belongs to the class rather than an instance. It can be called using the class name. It is c
ommonly used for utility functions that do not depend on object state.

java
Copy code
public class MyClass {
public static void myStaticMethod() {
// Static method code
}
}
Q) Why is the main method static?
The main method is static because it is called by the JVM before any objects are created, and thus there i
s no instance of the class to call the method on.

Q) In a Java file, how many Java classes can we write?


In a Java file, you can have at most one public class, and the file name must match the name of that publi
c class. However, you can have multiple non-public classes in the same file.

Q) Can we call main explicitly?


Yes, you can call the main method explicitly like any other static method. However, it won’t be the entry p
oint for the application.
Q) Can we declare main() method as private or protected or with no access modifier?
Yes, you can declare the main method as private, protected, or with no access modifier, but then the JVM
won’t be able to access it, and the program won’t run.

Q) Can we run a Java class without the main() method?


No, the main method is the entry point for the Java program. Without it, the JVM won’t know where to star
t execution.

Q) What are command line arguments? How do we pass them in Java?


Command line arguments are values passed to a program when it is run from the command line. In Java,
they are passed to the main method as an array of strings.

java
Copy code
public class MyClass {
public static void main(String[] args) {
// args is the array of command line arguments
}
}
Q) How do we create an object in Java? What is an object reference?
You create an object in Java using the new keyword. An object reference is a variable that holds the mem
ory address of the object.

java
Copy code
MyClass obj = new MyClass();
Q) Can you create an object without using the new operator in Java?
No, you cannot create an object without using the new operator.

Q) What is ’this’ reference? Explain its use?


The this keyword in Java refers to the current instance of the class. It is used to differentiate instance vari
ables from local variables when they have the same name.

java
Copy code
public class MyClass {
private int value;

public void setValue(int value) {


this.value = value; // ’this’ refers to the instance variable
}
}
Q) What is inheritance? How do we implement it in Java?
Inheritance is a mechanism in Java by which one class can acquire the properties and behaviors of anoth
er class. It is implemented using the extends keyword.

java
Copy code
public class ChildClass extends ParentClass {
// ChildClass inherits from ParentClass
}
Q) List types of Inheritance?
Single Inheritance: A class extends only one class.
Multiple Inheritance: A class can extend more than one class (not supported in Java for classes).
Multilevel Inheritance: A class is derived from another derived class.
Hierarchical Inheritance: Multiple classes extend a single base class.
Q) What is the difference between ’this’ and ’super’?
this refers to the current instance of the class.
super refers to the immediate parent class instance.
Q) Is it mandatory for every superclass to have a default constructor?
No, it’s not mandatory. If a superclass doesn’t have a default constructor, and the subclass constructor do
esn’t explicitly call a parameterized constructor of the superclass using super(...), the compiler will automa
tically insert a call to the default constructor of the superclass.

Q) Does the class to super() must be the first line? If yes, why? What will happen if we don’t call super() fr
om the subclass?
Yes, if you use super(), it must be the first line in the constructor of the subclass. The reason is that the su
perclass must be initialized before the subclass. If you don’t call super(), the compiler will insert a call to th
e default constructor of the superclass automatically.

Q) What is polymorphism? Explain its types.


Polymorphism is the ability of a class to take on multiple forms. In Java, polymorphism is mainly of two typ
es:

Compile-time Polymorphism (Method Overloading): Methods with the same name but different parameter
s.
Runtime Polymorphism (Method Overriding): Methods with the same signature in the superclass and sub
class.
Q) What is the difference between static binding and dynamic binding?
Static Binding (Compile-time Binding): The type of object is determined at compile time. Method overloadi
ng is an example.
Dynamic Binding (Runtime Binding): The type of object is determined at runtime. Method overriding is an
example.
list 50 questions leading to this question in interview for each questions with project like examples practic
al with detailed answers write a code in java only
continue
ChatGPT
Certainly, let’s continue with more detailed questions, examples, and answers, focusing on practical scen
arios with Java code.

1. Question: What is the purpose of a constructor in Java? Can you provide an example from a real-world
project?
Answer:
Constructors initialize the state of an object. In a real-world project, consider a Person class:

java
Copy code
public class Person {
private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
2. Question: Explain the difference between method overloading and method overriding. Can you provide
an example from a project?
Answer:
Method Overloading example:

java
Copy code
public class MathOperations {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}
Method Overriding example:

java
Copy code
public class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
3. Question: What is the purpose of the this keyword in Java? Can you provide a practical example?
Answer:
The this keyword refers to the current instance of the class. Example:

java
Copy code
public class Student {
private String name;

public void setName(String name) {


this.name = name; // ’this’ avoids ambiguity
}
}
4. Question: How do you implement method overriding in Java? Provide an example with a real-world con
text.
Answer:
Example from a project:

java
Copy code
public class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
public class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
5. Question: Can you explain the concept of encapsulation? Provide an example with a practical applicati
on.
Answer:
Encapsulation is the bundling of data and methods that operate on the data into a single unit. Example:

java
Copy code
public class BankAccount {
private double balance;

public void deposit(double amount) {


// Validation and logic here
balance += amount;
}

public double getBalance() {


return balance;
}
}
6. Question: What is the Singleton design pattern? How would you implement it in a project?
Answer:
Singleton ensures a class has only one instance and provides a global point to access it. Example:

java
Copy code
public class AppConfig {
private static AppConfig instance;

private AppConfig() {
// Private constructor to prevent instantiation
}

public static AppConfig getInstance() {


if (instance == null) {
instance = new AppConfig();
}
return instance;
}
}
7. Question: Explain the difference between method overloading and method overriding with a detailed ex
ample.
Answer:
Overloading example:

java
Copy code
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}
Overriding example (previously mentioned in question 2).

8. Question: What is the purpose of the super keyword in Java? Provide a code example from a project.
Answer:
The super keyword is used to refer to the immediate parent class instance. Example:

java
Copy code
public class Animal {
public void eat() {
System.out.println("Animal eats");
}
}

public class Dog extends Animal {


@Override
public void eat() {
super.eat(); // Call the eat() method of the parent class
System.out.println("Dog eats bones");
}
}
9. Question: Explain the importance of access modifiers in Java. Provide an example from a project.
Answer:
Access modifiers control the visibility of classes, methods, and fields. Example:

java
Copy code
public class Customer {
private String name; // Private - accessible only within the class

public void setName(String name) {


// Public method to set the name
this.name = name;
}
}
10. Question: Can you provide an example of method hiding in Java with a real-world analogy?
csharp
Copy code
**Answer:**
Method hiding occurs when a subclass provides a static method with the same signature as a static meth
od in its superclass. Real-world analogy:

‘‘‘java
public class Vehicle {
public static void repair() {
System.out.println("Vehicle is being repaired");
}
}
public class Car extends Vehicle {
public static void repair() {
System.out.println("Car is being repaired"); // Method hiding
}
}
‘‘‘
11. Question: How would you implement an abstract class and its methods in Java? Provide a project exa
mple.
csharp
Copy code
**Answer:**
Example:

‘‘‘java
abstract class Shape {
abstract void draw(); // Abstract method

void resize() {
System.out.println("Resizing the shape");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle");
}
}
‘‘‘
12. Question: What are the advantages and disadvantages of using the final keyword in Java? Provide a
code example.
markdown
Copy code
**Answer:**
Advantages:
- **Security:** Prevents modification.
- **Performance:** Can be used by the compiler for optimization.

Disadvantages:
- **Flexibility:** Limits extension and modification.

Example:

‘‘‘java
public final class Constants {
public static final int MAX_VALUE = 100;
}
‘‘‘
13. Question: Explain the concept of polymorphism and provide an example with method overloading and
overriding.
csharp
Copy code
**Answer:**
Polymorphism is the ability of a method to take multiple forms. Example:
‘‘‘java
public class Calculator {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}

public class Animal {


public void makeSound() {
System.out.println("Animal makes a sound");
}
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
‘‘‘
14. Question: How do you handle exceptions in Java? Provide an example from a project.
csharp
Copy code
**Answer:**
Example:

‘‘‘java
public class FileReader {
public void readFile(String filePath) {
try {
// Code to read file
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
} finally {
// Code to close resources
}
}
}
‘‘‘
15. Question: What is the role of the static keyword in Java? Provide an example from a practical scenari
o.
arduino
Copy code
**Answer:**
The ‘static‘ keyword is used to create a class-level variable or method. Example:

‘‘‘java
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static final double PI = 3.14;
}
‘‘‘
16. Question: How does the hashCode() and equals() methods work in Java? Provide an example with a
project scenario.
java
Copy code
**Answer:**
Example:

‘‘‘java
public class Person {
private String name;
private int age;

// Constructors, getters, and setters

@Override
public int hashCode() {
return Objects.hash(name, age);
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && Objects.equals(name, person.name);
}
}
‘‘‘
17. Question: What is the purpose of the final keyword in Java? Provide an example with a real-world app
lication.
arduino
Copy code
**Answer:**
The ‘final‘ keyword is used to restrict the user. Example:

‘‘‘java
public final class Constants {
public static final double PI = 3.14;
// Other constant values
}
‘‘‘
18. Question: How would you implement an interface in Java? Provide an example from a project.
java
Copy code
**Answer:**
Example:

‘‘‘java
public interface Logger {
void log(String message);
}
public class ConsoleLogger implements Logger {
@Override
public void log(String message) {
System.out.println(message);
}
}
‘‘‘
19. Question: Explain the concept of method references in Java 8. Provide an example from a project.
vbnet
Copy code
**Answer:**
Method references allow you to refer to a method without invoking it. Example:

‘‘‘java
public class StringUtils {
public static int compare(String s1, String s2) {
return s1.compareTo(s2);
}
}

// Method reference
List<String> names = Arrays.asList("John", "Alice", "Bob");
names.sort(StringUtils::compare);
‘‘‘
20. Question: What are lambdas in Java, and how do you use them? Provide an example with a practical
scenario.
mathematica
Copy code
**Answer:**
Lambdas are a concise way to express instances of single-method interfaces (functional interfaces). Exa
mple:

‘‘‘java
List<String> names = Arrays.asList("John", "Alice", "Bob");
names.forEach(name -> System.out.println(name));
‘‘‘
These questions cover a range of Java concepts with practical examples from real-world scenarios. For e
ach question, it’s essential to provide detailed explanations and demonstrate your understanding through
code examples.

continue
ChatGPT
Certainly! Let’s continue with more Java interview questions, examples, and detailed answers.

21. Question: What is the purpose of the try-with-resources statement in Java? Provide a code example.
Answer:
The try-with-resources statement automatically closes resources like files, sockets, etc., when the try bloc
k finishes execution. Example:

java
Copy code
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line = reader.readLine();
// Process the file content
} catch (IOException e) {
e.printStackTrace();
}
22. Question: Explain the concept of the Comparator interface in Java. Provide an example with a real-wo
rld application.
Answer:
The Comparator interface is used to define custom sorting orders. Example:

java
Copy code
public class Student {
private String name;
private int age;

// Constructors, getters, and setters

public static Comparator<Student> ageComparator = Comparator.comparingInt(Student::getAge);


}

// Usage
List<Student> studentList = // Populate the list
studentList.sort(Student.ageComparator);
23. Question: What is the difference between ArrayList and LinkedList? Provide an example to illustrate th
eir use cases.
Answer:
ArrayList is backed by an array, providing fast random access. LinkedList is a doubly-linked list, offering f
ast insertion and deletion. Example:

java
Copy code
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
// Use cases: arrayList for random access, linkedList for frequent insertions/deletions
24. Question: How do you handle concurrent access to shared resources in Java? Provide an example us
ing synchronization.
Answer:
Example:

java
Copy code
public class SharedResource {
private int counter;

public synchronized void increment() {


counter++;
}
}
25. Question: What is the Observer design pattern? Provide an example from a project.
Answer:
The Observer pattern defines a one-to-many dependency between objects. Example:

java
Copy code
// Observer interface
public interface Observer {
void update(String message);
}

// Concrete Observer
public class ConcreteObserver implements Observer {
@Override
public void update(String message) {
System.out.println("Received update: " + message);
}
}

// Subject
public class Subject {
private List<Observer> observers = new ArrayList<>();

public void addObserver(Observer observer) {


observers.add(observer);
}

public void notifyObservers(String message) {


for (Observer observer : observers) {
observer.update(message);
}
}
}
26. Question: What is the volatile keyword used for in Java? Provide an example.
Answer:
The volatile keyword ensures that a variable is always read from and written to the main memory. Exampl
e:

java
Copy code
public class SharedResource {
private volatile boolean flag = false;

public void setFlag() {


flag = true;
}

public boolean getFlag() {


return flag;
}
}
27. Question: Explain the concept of Dependency Injection in Java. Provide a code example.
Answer:
Dependency Injection is a design pattern where dependencies are injected into a class from the outside.
Example using Spring:

java
Copy code
public class OrderService {
private PaymentService paymentService;

// Constructor injection
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}

public void processOrder(Order order) {


// Process order and use paymentService
}
}
28. Question: What is the purpose of the @Override annotation in Java? Provide a code example.
Answer:
The @Override annotation is used to indicate that a method in a subclass is intended to override a metho
d in its superclass. Example:

java
Copy code
public class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
29. Question: How does garbage collection work in Java? Provide an example with best practices for man
aging memory.
Answer:
Garbage collection automatically reclaims memory by collecting and removing objects that are no longer r
eachable. Best practices include letting the JVM manage memory and avoiding unnecessary object creati
on.

30. Question: Explain the concept of the transient keyword in Java. Provide an example.
Answer:
The transient keyword is used to indicate that a field should not be serialized. Example:

java
Copy code
public class User implements Serializable {
private transient String password;

// Other fields, getters, and setters


}
31. Question: How do you implement the Builder design pattern in Java? Provide an example from a proje
ct.
Answer:
Example:

java
Copy code
public class User {
private final String username;
private final String password;
private User(Builder builder) {
this.username = builder.username;
this.password = builder.password;
}

public static class Builder {


private final String username;
private final String password;

public Builder(String username, String password) {


this.username = username;
this.password = password;
}

public User build() {


return new User(this);
}
}
}

// Usage
User user = new User.Builder("john.doe", "password123").build();
32. Question: Explain the concept of the Streams API in Java. Provide an example with a project scenario
.
Answer:
The Streams API provides a fluent way to process sequences of elements. Example:

java
Copy code
List<String> names = Arrays.asList("John", "Alice", "Bob");
long count = names.stream().filter(name -> name.startsWith("A")).count();
33. Question: How do you implement a custom exception in Java? Provide an example.
Answer:
Example:

java
Copy code
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
34. Question: What is the purpose of the enum keyword in Java? Provide a code example from a project.
Answer:
Enums define a set of named constant values. Example:

java
Copy code
public enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
35. Question: Explain the concept of the this() constructor call in Java. Provide an example.
Answer:
The this() constructor call is used to invoke another constructor in the same class. Example:
java
Copy code
public class Person {
private String name;
private int age;

public Person() {
this("John Doe", 25); // Calls the parameterized constructor
}

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}
36. Question: How do you perform file I/O in Java? Provide an example with the java.nio package.
Answer:
Example:

java
Copy code
Path filePath = Paths.get("example.txt");
try (BufferedWriter writer = Files.newBufferedWriter(filePath)) {
writer.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
37. Question: What is the Optional class in Java, and how do you use it? Provide a code example.
Answer:
Optional is a container object that may or may not contain a non-null value. Example:

java
Copy code
Optional<String> optionalName = Optional.ofNullable(getName());
String name = optionalName.orElse("Default");
38. Question: Explain the concept of the super() constructor call in Java. Provide an example.
Answer:
The super() constructor call is used to invoke the constructor of the superclass. Example:

java
Copy code
public class Animal {
private String type;

public Animal(String type) {


this.type = type;
}
}

public class Dog extends Animal {


private String breed;

public Dog(String type, String breed) {


super(type); // Calls the constructor of the superclass
this.breed = breed;
}
}
39. Question: How do you implement caching in Java? Provide an example using the java.util.Cache inter
face.
Answer:
Example:

java
Copy code
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();

// Usage
cache.put("key", "value");
40. Question: What is the purpose of the break and continue statements in Java? Provide examples.
Answer:
break is used to exit a loop prematurely, and continue is used to skip the remaining code in a loop and mo
ve to the next iteration. Examples:

java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i);
}

for (int i = 0; i < 10; i++) {


if (i % 2 == 0) {
continue; // Skips even numbers
}
System.out.println(i);
}
These additional questions cover a variety of Java concepts and provide practical examples to showcase
your understanding. Remember to articulate your thought process and discuss any design considerations
in your answers during an interview.

continue
ChatGPT
Certainly! Let’s continue with more Java interview questions along with examples and detailed answers.

41. Question: What is the ConcurrentHashMap class in Java, and how does it differ from HashMap? Provi
de an example.
Answer:
ConcurrentHashMap is a thread-safe version of HashMap that allows concurrent read and write operation
s. Example:

java
Copy code
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("one", 1);
concurrentMap.put("two", 2);
42. Question: How do you implement a thread-safe singleton pattern in Java? Provide an example.
Answer:
Example using double-checked locking:

java
Copy code
public class Singleton {
private static volatile Singleton instance;

private Singleton() {
// Private constructor
}

public static Singleton getInstance() {


if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
43. Question: What is the purpose of the ThreadLocal class in Java? Provide an example.
Answer:
ThreadLocal provides thread-local variables. Example:

java
Copy code
public class ThreadSafeFormatter {
private static final ThreadLocal<SimpleDateFormat> dateFormat =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

public static String format(Date date) {


return dateFormat.get().format(date);
}
}
44. Question: Explain the concept of the ExecutorService framework in Java. Provide an example.
Answer:
ExecutorService provides a higher-level replacement for managing threads. Example:

java
Copy code
ExecutorService executorService = Executors.newFixedThreadPool(5);

executorService.submit(() -> {
// Task to be executed
});

executorService.shutdown();
45. Question: What is the purpose of the autocloseable interface in Java? Provide an example.
Answer:
The AutoCloseable interface is used to close resources automatically. Example:
java
Copy code
public class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
// Code to close the resource
}
}

// Usage
try (MyResource resource = new MyResource()) {
// Code that uses the resource
} catch (Exception e) {
e.printStackTrace();
}
46. Question: How do you implement a custom annotation in Java? Provide an example.
Answer:
Example:

java
Copy code
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyCustomAnnotation {
String value() default "Default";
}

// Usage
public class MyClass {
@MyCustomAnnotation(value = "Custom Value")
public void myMethod() {
// Method implementation
}
}
47. Question: Explain the concept of the Deque interface in Java. Provide an example.
Answer:
Deque (Double Ended Queue) is a linear collection that supports element insertion and removal at both e
nds. Example:

java
Copy code
Deque<String> deque = new LinkedList<>();
deque.addFirst("First");
deque.addLast("Last");
48. Question: How do you handle concurrent modification in Java collections? Provide an example.
Answer:
Example using an Iterator:

java
Copy code
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("removeMe")) {
iterator.remove();
}
}
49. Question: What is the purpose of the StringJoiner class in Java? Provide an example.
Answer:
StringJoiner is used to construct a sequence of characters separated by a delimiter. Example:

java
Copy code
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("John").add("Alice").add("Bob");
String result = joiner.toString(); // "[John, Alice, Bob]"
50. Question: Explain the concept of the CompletableFuture class in Java. Provide an example.
Answer:
CompletableFuture is used for asynchronous programming. Example:

java
Copy code
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Asynchronous task
return "Hello, World!";
});

future.thenAccept(result -> {
// Process the result
System.out.println(result);
});
These additional questions cover various aspects of Java programming and provide examples to illustrate
practical usage. As always, be prepared to discuss your thought process and design considerations durin
g an interview.

Upgrade to Plus to create your own GPT


Report content
|
Terms of use
|
Privacy policy
|
Manage cookies

You might also like