2nd Module Java Solution
2nd Module Java Solution
2nd Module Java Solution
1. Young Generation:
o Newly created objects are allocated in this region.
o Divided into Eden Space and Survivor Spaces (S0 and S1).
o Most objects are short-lived and quickly become eligible for garbage
collection.
o Minor GC occurs when the Young Generation fills up, and live objects are
moved to the Old Generation.
2. Old (Tenured) Generation:
o Objects that survive multiple GC cycles in the Young Generation are moved to
the Old Generation.
o Major GC or Full GC happens here less frequently but takes more time.
3. Permanent Generation (Metaspace):
o Contains metadata required by the JVM (such as class definitions, method
objects).
o In Java 8 and later, Metaspace replaces PermGen, which dynamically adjusts
in size, improving performance.
// Area of rectangle
public static double area(double length, double width) {
return length * width;
}
// Area of circle
public static double area(double radius) {
return Math.PI * radius * radius;
}
// Area of triangle
public static double area(double base, double height, String triangle)
{
return 0.5 * base * height;
}
Modifiers (optional)
Class Keyword followed by the class name
Fields (variables) to store object states
Methods to perform actions
Example:
java
Copy code
public class MyClass {
// Fields (or instance variables)
int num;
String name;
// Constructor
public MyClass(int num, String name) {
this.num = num;
this.name = name;
}
a. this Keyword:
Example:
java
Copy code
public class Demo {
int num;
Demo(int num) {
this.num = num; // `this` refers to the current object instance
}
void display() {
System.out.println("Number: " + this.num);
}
}
b. static Keyword:
Example:
java
Copy code
public class DemoStatic {
static int count = 0; // Static variable
DemoStatic() {
count++; // Increment count whenever a new object is created
}
System.out.println("\nEmployee Information:");
for (Employee emp : employees) {
emp.write();
System.out.println();
}
sc.close();
}
}
Example:
java
Copy code
public class Person {
String name;
// Default constructor
public Person() {
name = "Unknown";
}
// Parameterized constructor
public Person(String name) {
this.name = name;
}
Method Overloading occurs when multiple methods have the same name but different
parameter lists.
Example:
java
Copy code
public class Calculator {
8. Stack Class with Push, Pop, and Display Methods (12 marks)
java
Copy code
class Stack {
private int maxSize;
private int[] stackArray;
private int top;