1. How do Java and C++ vary from one another?
Ans:
Java is platform-independent, uses automatic garbage collection, and does not directly support pointers. In contrast, C++ is platform-dependent, requires manual memory management, and supports pointers. Java programs run on the JVM, while C++ code compiles directly into machine code.
2. Describe the Java encapsulation principle.
Ans:
Encapsulation means wrapping data (variables) and code (methods) into a single unit (class) and restricting direct access to them. It is done using private variables and public getter/setter methods.
3. What is inheritance in Java? Give an example.
Ans:
Inheritance allows a class (child) to inherit fields and methods from another class (parent).
Example:
- class Animal {
- void sound() { System.out.println("Animal sound"); }
- }
- class Dog extends Animal {
- void bark() { System.out.println("Dog barks"); }
- }
4. How does Java handle memory management?
Ans:
Java handles memory using automatic garbage collection. It allocates memory for objects and reclaims it when objects are no longer in use, without needing manual deletion.
5. Can you explain the concept of polymorphism in Java?
Ans:
- Polymorphism means one method can behave differently based on the object.
- Compile-time polymorphism: Method overloading
- Runtime polymorphism: Method overriding using inheritance
6. What is the use of "this" keyword in Java?
Ans:
The this keyword refers to the current class instance. It’s used to:
- Differentiate between local and instance variables
- Call current class constructors or methods
7. How does Java handle exceptions?
Ans:
Java uses try-catch-finally blocks to handle exceptions.
- try block has risky code
- catch block handles the exception
- finally block runs always (for cleanup)
8. In Java, what distinguishes throw from throws?
Ans:
To manually throw an exception Use toss inside a method. throws is used to declare exceptions that a method might throw.
Example:
- throw new ArithmeticException("error");
- void myMethod() throws IOException { }
9. Can you explain the concept of synchronization in Java?
Ans:
Synchronization is a mechanism that controls concurrent access to shared resources in multithreaded environments, ensuring that only one thread can execute a synchronized block or method at a time to prevent data inconsistency.
10. What is the use of HashSet in Java?
Ans:
HashSet is part of the Java Collection Framework. It stores unique elements and does not maintain order. It's ideal when you want to avoid duplicates and don't care about element order.