LAB Assignment 9 Memory Allocation Java
LAB Assignment 9 Memory Allocation Java
Instructions: The instructor is required to discuss the concept of memory management with the
students.
Write a program using C/C++/Java to simulate the First Fit, Best Fit, and Worst Fit memory
allocation strategies.
Assume memory chunks and initial requirements for memory blocks from your side.
2. Display the menu for the user to choose an allocation strategy (First Fit, Best Fit, Worst Fit) or to
exit.
3. Prompt the user to request a memory block allocation, specifying the size.
import java.util.Scanner;
class Block {
int size;
boolean allocated;
Block(int size) {
this.size = size;
this.allocated = false;
}
}
switch (choice) {
case 1:
for (int i = 0; i < memory.length; i++) {
if (!memory[i].allocated && memory[i].size >= reqSize) {
index = i;
break;
}
}
break;
case 2:
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i < memory.length; i++) {
if (!memory[i].allocated && memory[i].size >= reqSize &&
memory[i].size - reqSize < minDiff) {
minDiff = memory[i].size - reqSize;
index = i;
}
}
break;
case 3:
int maxDiff = -1;
for (int i = 0; i < memory.length; i++) {
if (!memory[i].allocated && memory[i].size >= reqSize &&
memory[i].size - reqSize > maxDiff) {
maxDiff = memory[i].size - reqSize;
index = i;
}
}
break;
}
if (index != -1) {
memory[index].allocated = true;
System.out.println("Memory allocated at block " + (index + 1));
} else {
System.out.println("No suitable block found. Allocation failed.");
}
System.out.println("Memory Blocks:");
for (int i = 0; i < memory.length; i++) {
System.out.println("Block " + (i + 1) + ": Size = " + memory[i].size +
", " + (memory[i].allocated ? "Allocated" : "Free"));
}
}
sc.close();
}
}
Sample Output: