0% found this document useful (0 votes)
6 views12 pages

Day 13 Practices Java

The document contains multiple Java programming tasks focused on garbage collection and memory management. Each task includes a description, input/output format, and example test cases. The tasks range from creating objects and handling a shopping cart to working with arrays and finding maximum values, all while demonstrating garbage collection behavior.

Uploaded by

jeevaprasathc33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views12 pages

Day 13 Practices Java

The document contains multiple Java programming tasks focused on garbage collection and memory management. Each task includes a description, input/output format, and example test cases. The tasks range from creating objects and handling a shopping cart to working with arrays and finding maximum values, all while demonstrating garbage collection behavior.

Uploaded by

jeevaprasathc33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Question 1:

In the given Java code, a simple program creates a specified number of objects of the MyClass
class and then explicitly requests garbage collection using System.gc(). The MyClass has a
constructor and a finalize method to indicate when an object is created and destroyed.

Input Format:

The program expects a single integer as input, representing the number of objects to be created.
The input should be provided through the standard input (console).

Output Format:

The program produces output messages based on the actions taken. The expected output format
is as follows:

For each object created, the program prints "Object created" on a new line.

After invoking garbage collection, the program prints "Object destroyed" for each object that is
being garbage collected on a new line.

Title for Question 1: Analyzing Garbage Collection Behavior

Solution:

import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// System.out.print("Enter the number of objects to create: ");


int numObjects = scanner.nextInt();

// Creating objects
for (int i = 0; i < numObjects; i++) {
new MyClass();
}

// Requesting garbage collection explicitly


System.gc();

scanner.close();
}
}

class MyClass {
// Constructor
public MyClass() {
System.out.println("Object created");
}

// Destructor (finalize method)


protected void finalize() throws Throwable {
System.out.println("Object destroyed");
}
}

TestCases:

S.No Inputs Outputs

1 2 Object created Object created Object destroyed Object destroyed

Object created Object created Object created Object destroyed Object


2 3
destroyed Object destroyed

3 1 Object created Object destroyed

Object created Object created Object created Object created Object created
4 5 Object destroyed Object destroyed Object destroyed Object destroyed
Object destroyed

Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
5 10 Object destroyed Object destroyed Object destroyed Object destroyed
Object destroyed Object destroyed Object destroyed Object destroyed
Object destroyed Object destroyed

Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
6 99 Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object created
Object created Object created Object created Object created Object
destroyed Object destroyed Object destroyed Object destroyed Object
destroyed Object destroyed Object destroyed Object destroyed Object
destroyed Object destroyed Object destroyed
Question 2:

Write a Java program that allows a user to create a shopping cart for a customer. The program
should use the Main class, which contains an inner class Item. The Item class represents items
that can be added to the shopping cart. Each item has a name and a price.

The program should prompt the user to enter the customer's name and the number of items they
want to add to the shopping cart. For each item, the user should be asked to enter the item's name
and price.

After collecting all the information, the program should display the shopping cart for the customer,
listing the names and prices of all the items.

Ensure that the program handles input validation, such as ensuring that the number of items
entered is not negative and that the item price is a valid numeric value.

Additionally, implement a mechanism to remove unnecessary references and free up memory once
the shopping cart is displayed.

Input format:

Enter customer name: [Customer Name]

Enter the number of items: [Number of Items]

[Item Name 1]

[Item Price 1]

[Item Name 2]

[Item Price 2]

...

[Item Name N]

[Item Price N]

Output format:

Shopping Cart for [Customer Name]

Item: [Item Name 1]

Price: $[Item Price 1]

Item: [Item Name 2]

Price: $[Item Price 2]

...

Item: [Item Name N]


Price: $[Item Price N]

Title for Question 2: Shopping cart using garbage collection

Solution:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {


private String customerName;
private List<Item> items;

public Main(String customerName) {


this.customerName = customerName;
items = new ArrayList<>();
}

public void addItem(String itemName, double price) {


Item item = new Item(itemName, price);
items.add(item);
}

public void displayItems() {


System.out.println("Shopping Cart for " + customerName);

for (Item item : items) {


System.out.println("Item: " + item.getName());
System.out.println("Price: $" + item.getPrice());
}
}

// Inner class definition


static class Item {
private String name;
private double price;

public Item(String name, double price) {


this.name = name;
this.price = price;
}

public String getName() {


return name;
}

public double getPrice() {


return price;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

//System.out.print("Enter customer name: ");


String customerName = scanner.nextLine();

Main cart = new Main(customerName);

//System.out.print("Enter the number of items: ");


int numItems = Integer.parseInt(scanner.nextLine());

for (int i = 0; i < numItems; i++) {


//System.out.print("Enter item name: ");
String itemName = scanner.nextLine();

//System.out.print("Enter item price: ");


double itemPrice = Double.parseDouble(scanner.nextLine());

cart.addItem(itemName, itemPrice);
}

cart.displayItems();
System.gc();

scanner.close();
}
}

TestCases:

S.No Inputs Outputs

1 John Doe 0 Shopping Cart for John Doe

Shopping Cart for Alice Smith Item: Shirt Price:


2 Alice Smith 1 Shirt 29.99
$29.99

Shopping Cart for Bob Johnson Item: Hat Price:


Bob Johnson 3 Hat 12.50
3 $12.5 Item: Sunglasses Price: $35.75 Item: Shorts
Sunglasses 35.75 Shorts 24.99
Price: $24.99

Emma Brown 4 Notebook 5.99 Shopping Cart for Emma Brown Item: Notebook
4 Pen 2.49 Notebook 6.49 Pencil Price: $5.99 Item: Pen Price: $2.49 Item:
1.29 Notebook Price: $6.49 Item: Pencil Price: $1.29

Michael Lee 3 Laptop & Mouse Shopping Cart for Michael Lee Item: Laptop &
5 89.99 Smartphone / Case 69.50 Mouse Price: $89.99 Item: Smartphone / Case
Monitor (24") 179.00 Price: $69.5 Item: Monitor (24") Price: $179.0

Sophia Williams 5 Green T-shirt Shopping Cart for Sophia Williams Item: Green T-
15.99 Blue Jeans 29.50 Black shirt Price: $15.99 Item: Blue Jeans Price: $29.5
6
Shoes 49.75 White Socks 5.49 Item: Black Shoes Price: $49.75 Item: White
Red Hat 12.25 Socks Price: $5.49 Item: Red Hat Price: $12.25
Question 3:

Write a Java program to demonstrate the use of arrays and automatic garbage collection.

Input Format:

An integer representing the size of the numbers array.

Integers for each element of the numbers array.

An integer representing the size of the strings array.

Strings for each element of the strings array (one per line).

An integer representing the size of the doubles array.

Doubles for each element of the doubles array.

Output Format:

The first number from the numbers array.

The first string from the strings array.

The first double from the doubles array.

A message suggesting the JVM to run garbage collector.

A message indicating that garbage collection might have taken place.

Title for Question 3: Arrays and automatic garbage collection

Solution:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

//System.out.print("Enter the size for numbers array: ");


int[] numbers = new int[scanner.nextInt()];
//System.out.println("Enter the numbers:");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = scanner.nextInt();
}
//System.out.print("\nEnter the size for strings array: ");
String[] strings = new String[scanner.nextInt()];
scanner.nextLine(); // Consume newline
//System.out.println("Enter the strings:");
for (int i = 0; i < strings.length; i++) {
strings[i] = scanner.next();
}

//System.out.print("\nEnter the size for doubles array: ");


double[] doubles = new double[scanner.nextInt()];
//System.out.println("Enter the doubles:");
for (int i = 0; i < doubles.length; i++) {
doubles[i] = scanner.nextDouble();
}

// Print some values for demonstration purposes


System.out.println("\nFirst number: " + numbers[0]);
System.out.println("First string: " + strings[0]);
System.out.println("First double: " + doubles[0]);

// Set the arrays to null to make them eligible for garbage collecti
numbers = null;
strings = null;
doubles = null;

// Suggest the JVM to run the garbage collector


System.out.println("\nSuggesting JVM to run garbage collector...");
System.gc();

// Just to pause the application for a while


try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Garbage collection might have taken place.");

// Close the scanner to release resources


scanner.close();
}
}

TestCases:

S.No Inputs Outputs

First number: 10 First string: Hello First double: 0.5


3 10 20 30 2 Hello
1 Suggesting JVM to run garbage collector... Garbage
World 2 0.5 1.5
collection might have taken place.
S.No Inputs Outputs

First number: 0 First string: a First double: 0.0 Suggesting


2 1 0 1 a 1 0.0 JVM to run garbage collector... Garbage collection might have
taken place.

First number: 10 First string: apple First double: 1.5


2 10 20 2 apple
3 Suggesting JVM to run garbage collector... Garbage
banana 2 1.5 2.5
collection might have taken place.

First number: -1 First string: negative First double: -0.5


3 -1 -2 -3 1 negative
4 Suggesting JVM to run garbage collector... Garbage
3 -0.5 -1.0 -1.5
collection might have taken place.

First number: 1000000000 First string: longword First double:


1 1000000000 1
5 1000.5 Suggesting JVM to run garbage collector... Garbage
longword 1 1000.500
collection might have taken place.

First number: 1 First string: this is a sentence First double: 1.1


1 1 1 this is a
6 Suggesting JVM to run garbage collector... Garbage
sentence 1 1.1
collection might have taken place.

Question 4:

Implement a Java program that creates a large array and then clears it to release memory before
garbage collection.

Input Format:

<size_of_array>

Where:

<size_of_array> is an integer (0 ? size_of_array ? maximum array size your JVM can handle).

Output Format:

<first_value>

<second_value>

...

<value_n>

Suggesting JVM to run garbage collector...

Memory for large array might have been released.

Where:

<first_value>, <second_value>, ..., <value_n> are the first n values of the array, where n is the
minimum of the array's size and 5.
Title for Question 4: Large array and Release Garbage collection

Solution:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


//System.out.print("Enter the size of the array you'd like to create

// Step 1: Get the size from the user and create the array
int size = scanner.nextInt();
int[] largeArray = new int[size];

// Populate the array with some values (e.g., value equal to its ind
for (int i = 0; i < size; i++) {
largeArray[i] = i;
}

// Display the first few values of the array for verification


//System.out.println("First 5 values of the array:");
for (int i = 0; i < Math.min(size, 5); i++) {
System.out.println(largeArray[i]);
}

// Clear the array by setting its values to the default


for (int i = 0; i < size; i++) {
largeArray[i] = 0;
}

// Set the array reference to null


largeArray = null;

// Suggest the JVM to run the garbage collector


System.out.println("\nSuggesting JVM to run garbage collector...");
System.gc();
// Just to pause the application for a while
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Memory for large array might have been released.
// Close the scanner to release resources
scanner.close();
}
}

TestCases:
S.No Inputs Outputs

Suggesting JVM to run garbage collector... Memory for large array might
1 0
have been released.

0 Suggesting JVM to run garbage collector... Memory for large array might
2 1
have been released.

0 1 2 3 Suggesting JVM to run garbage collector... Memory for large array


3 4
might have been released.

0 1 2 3 4 Suggesting JVM to run garbage collector... Memory for large array


4 5
might have been released.

0 1 2 3 4 Suggesting JVM to run garbage collector... Memory for large array


5 10
might have been released.

0 1 2 3 4 Suggesting JVM to run garbage collector... Memory for large array


6 6
might have been released.

Question 5:

Java Array Maximum Element Finder

Write a Java program that:

Reads an integer n from the standard input, which represents the number of elements in an array.

Reads n integers from the standard input and stores them in an array.

Finds the maximum value from the given array of integers.

Prints the maximum value to the standard output.

After printing the result, the program should release any resources it used and suggest garbage
collection.

Input format:

<number of elements>

<element 1> <element 2> ... <element n>

Output format:

Maximum value is: <maximum value>

Note: This question assumes that the user already knows that they should first input the number of
elements and then the elements themselves without requiring further prompts. If you're using this
question in an educational setting or for beginners, it might be helpful to use the commented-out
print statements in the provided code for clarity.
Title for Question 5: Maximum Element Finder and garbage collection

Solution:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Get the size of the array from the user


//System.out.println("Enter the number of elements you want to input
int n = scanner.nextInt();

int[] arr = new int[n];

// Get the array elements from the user


//System.out.println("Enter the " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Maximum value is: " + findMax(arr));
// Close the scanner as we're done with it
scanner.close();

System.gc();
}
static int findMax(int[] arr) {
int max = Integer.MIN_VALUE;
for (int num : arr) {
if (num > max) max = num;
}
return max;
}
}

TestCases:

S.No Inputs Outputs

1 512345 Maximum value is: 5

2 3 -1 -2 -3 Maximum value is: -1

3 4 0 -1 -2 3 Maximum value is: 3

4 17 Maximum value is: 7


S.No Inputs Outputs

5 6 10 10 10 10 10 10 Maximum value is: 10

6 554321 Maximum value is: 5

You might also like