Java Interview Questions: Final vs. Finally Keywords
Keywords in Java
- Final and finally are predefined keywords in Java.
- Many predefined keywords in Java.
Final Keyword
- Can be used with variables, methods, and classes.
- Final Variables: Once initialized, cannot be updated (become constants).
- Final Methods: Cannot be overridden by child classes.
- Final Classes: Cannot be inherited by other classes (e.g., no child classes).
- Practical demonstration in Eclipse ID: Used final with variables, methods, and classes.
Finally Keyword
- Used in exception handling.
- Finally block always executes regardless of try/catch block execution.
- Typically used to close objects or clean up resources.
- Example: Closing scanner objects or file streams.
Java Interview Questions: Accessing Private Methods
Private Methods and Variables
- Private variables and methods cannot be accessed directly outside the class.
- Encapsulation can be used to indirectly access private members through public methods.
Encapsulation Example
- Create a public method within the same class as the private member.
- Call the private method or variable within this public method.
- Access the public method from outside the class.
Java Interview Questions: Converting Array to ArrayList & ArrayList to Array
Converting Array to ArrayList
- Convert the array to a list using
Arrays.asList()
.
- Pass the list to the
ArrayList
constructor.
Integer[] array = {1, 2, 3, 4};
List<Integer> list = Arrays.asList(array);
ArrayList<Integer> arrayList = new ArrayList<>(list);
Converting ArrayList to Array
- Create an array with the same size as the ArrayList.
- Use
toArray()
method of ArrayList
.
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(1);
arrayList.add(2);
Integer[] array = new Integer[arrayList.size()];
array = arrayList.toArray(array);
Java Interview Questions: Static Keyword Usage
Purpose of Static Keyword
- Static variables and methods can be accessed without creating an object of the class.
- Accessed using the class name directly.
- Example: With and without static keyword for variables and methods.
class Car {
static String color;
static void startCar() {
System.out.println("Car started");
}
}
// Accessed directly without creating an object
Car.color = "Black";
Car.startCar();
Java Interview Questions: Synchronized Block in Java
Purpose of Synchronized Block
- Used for thread safety in multi-threaded environments.
- Ensures that only one thread can access a particular resource at a time.
- Example: Bank account balance update with synchronized block.
class BankAccount {
private int balance = 0;
public void deposit(int amount) {
synchronized(this) {
balance += amount;
}
}
public int getBalance() {
return balance;
}
}