Repeated Java Questions (2021-2024) with Answers
1. Difference between Method Overloading and Overriding
Overloading: Same method name, different parameters, within the same class.
Overriding: Same method name and signature, in subclass, to provide specific implementation.
Example:
class A { void show(int a) {} }
class B extends A { void show(int a) {} }
2. Abstract Class vs Interface
Abstract Class: Can have method definitions and variables. Use 'abstract' keyword.
Interface: Only method signatures (Java 7), supports default/static methods (Java 8+).
Example:
interface A { void show(); }
abstract class B { abstract void show(); }
3. Exception Handling in Java
Use try-catch to handle exceptions.
throw: to manually throw an exception.
throws: declares exception.
finally: runs regardless of exception.
Example:
try { int x = 5/0; } catch(Exception e) { System.out.println(e); } finally { System.out.println("Done"); }
4. final, finally, finalize
final: used to declare constants or prevent overriding.
finally: block always executed after try-catch.
finalize(): method called before object is garbage collected.
5. File I/O (FileInputStream / FileOutputStream)
Used for byte stream reading/writing files.
Example:
FileOutputStream fout = new FileOutputStream("file.txt");
fout.write(65); fout.close();
6. JavaFX vs AWT
JavaFX: Rich UI, modern, uses SceneGraph.
AWT: Old UI toolkit, platform dependent.
JavaFX is preferred for new GUI apps.
7. OOP Concepts
Encapsulation: Hiding data using private variables and public methods.
Inheritance: Acquiring properties of parent class.
Polymorphism: Many forms (method overloading/overriding).
Abstraction: Hiding implementation details.
8. Access Modifiers
public: accessible everywhere
private: within class
protected: within package + subclass
(default): within package
9. String vs StringBuffer
String: Immutable, slower for modifications.
StringBuffer: Mutable, thread-safe.
Example:
StringBuffer sb = new StringBuffer("Hello"); sb.append(" World");
10. Constructors in Java
Used to initialize objects.
Types: Default, Parameterized, Copy constructor.
Overloading possible with different parameter lists.
11. Multithreading
Achieved using Thread class or Runnable interface.
Methods: start(), run(), sleep(), join().
Example:
class A extends Thread { public void run() {} }
12. Packages
Used to group related classes.
Use 'package' keyword.
Example:
package mypack; import java.util.*;
13. Arrays and Enhanced For Loop
Array: Collection of fixed-size elements.
Enhanced loop:
for(int i : arr) { System.out.println(i); }
14. Scanner Class
Used for input from user.
Example:
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();