Java Unit II Answers
Java Unit II Answers
Objects contain data in the form of fields and methods. OOP principles include Encapsulation,
Inheritance, Polymorphism, and Abstraction. These principles enhance modularity, code reuse, and
maintainability.
Garbage Collection in Java is the process of reclaiming memory by removing unused objects. The
JVM automatically performs this. To test it, you can use `System.gc()` to request garbage collection,
2 a) Define a Class, Method, and Object? Write the syntax to define these in Java.
A class is a blueprint for creating objects. A method defines the behavior of a class. An object is an
class MyClass {
void myMethod() {
System.out.println("Hello");
Example:
class Example {
class ConstructorDemo {
int x;
ConstructorDemo() {
x = 0;
ConstructorDemo(int value) {
x = value;
4 a) What are the varargs in Java? Write the syntax and develop any program.
Varargs allow a method to accept variable arguments. Syntax: `void methodName(int... args)`
Example:
System.out.println(num);
}
4 b) What is Inheritance? Explain types of inheritance.
Inheritance is a mechanism where one class acquires properties and behavior of another.
Types:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
Example:
class Parent {
void display() {
System.out.println("Parent");
void display() {
super.display();
System.out.println("Child");
Overloading: Defining methods with the same name but different parameters within the same class.
6) Explain about the Dynamic Method Dispatch in Java with example program.
Dynamic Method Dispatch is the process by which a call to an overridden method is resolved at
runtime.
Example:
class Parent {
void display() {
System.out.println("Parent");
void display() {
System.out.println("Child");
7) What is an abstract class? Explain all the cases to implement abstract class.
An abstract class cannot be instantiated and can have abstract and non-abstract methods. It
Cases:
class Parent {
void display() {
System.out.println("Parent Method");
}
}
void displayChild() {
System.out.println("Child Method");
Creating a package:
An interface is a reference type in Java that contains abstract methods. All methods are public and
abstract by default.
Rules:
Example:
interface MyInterface {
void display();
void display() {
System.out.println("Implementation");
}
}
10) Write a Java program to find the factorial value of the given number using user-defined
package concept.
package mypackage;
if (n == 0) return 1;
// In another file:
import mypackage.Factorial;
class Test {
System.out.println(fact.calculate(5));