What is the purpose of garbage collection in Java?

Garbage collection is an important part of Java that helps to manage memory. It is the process of reclaiming memory from objects that are no longer in use. Garbage collection is an automatic process in Java that runs in the background and frees up memory by deleting objects that are no longer being used.

An example of garbage collection in Java would be when a program creates an instance of an object. After the object is no longer needed, the memory allocated to it is freed up by the garbage collector. This allows the memory to be used for other objects.

What is the purpose of the Java Reflection API?

The Java Reflection API is a set of classes and interfaces that provide a way to examine the runtime behavior of applications written in the Java programming language. It allows developers to inspect, modify, and interact with the classes, interfaces, constructors, methods, and fields at runtime.

For example, the Java Reflection API can be used to instantiate objects, invoke methods, and get and set field values even if the names of the classes, methods, and fields are not known at compile time. It can also be used to determine the superclass of a class, and the interfaces that a class implements.

What is the difference between a constructor and a method in Java?

A constructor is a special method used to initialize a newly created object and is called automatically when an object is created. A constructor has the same name as the class and does not have a return type.

Example:

public class Car {
private String model;
private int year;

public Car(String model, int year) {
this.model = model;
this.year = year;
}
}

A method is a block of code that performs a specific task and returns the result of the task. A method has a return type and can be called explicitly by the code.

Example:

public class Car {
private String model;
private int year;

public Car(String model, int year) {
this.model = model;
this.year = year;
}

public String getModel() {
return model;
}

public int getYear() {
return year;
}
}