0% found this document useful (0 votes)
7 views14 pages

Java T-6

The document covers key concepts in Java programming, including variable-length arguments (varargs), static variables and methods, and garbage collection. It explains the rules and benefits of using varargs, the differences between static and instance variables, and the garbage collection process in Java. Additionally, it provides code examples to illustrate these concepts, demonstrating their practical applications in Java programming.

Uploaded by

dheeraj72006
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)
7 views14 pages

Java T-6

The document covers key concepts in Java programming, including variable-length arguments (varargs), static variables and methods, and garbage collection. It explains the rules and benefits of using varargs, the differences between static and instance variables, and the garbage collection process in Java. Additionally, it provides code examples to illustrate these concepts, demonstrating their practical applications in Java programming.

Uploaded by

dheeraj72006
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

Tutorial 6: varargs, Static, and Garbage Collection

Batch-1

1. Variable-Length Arguments (varargs)

i) Why does Java allow only one varargs parameter in a method? Support your
answer with an example. [R - 3 Marks]

Java allows only one varargs parameter in a method, and this parameter must be the
last parameter in the method's signature.

This rule is enforced to prevent ambiguity during method invocation. If a method could
accept multiple varargs parameters (e.g., method(int... a, int... b)), the compiler
wouldn't know where the elements for a stop and the elements for b begin when the
method is called with a sequence of integers.

Example of Ambiguity:

Java

// ILLEGAL: Compiler cannot determine where array 'a' ends and 'b' begins

// void illegalMethod(int... a, int... b) {}

// LEGAL: varargs must be the last parameter

void legalMethod(String name, int... marks) {

// String "Alice" goes to 'name'

// All remaining integers (90, 85, 95) go to 'marks'

ii) Develop a Java program to sum up integers using (i) fixed parameters and (ii)
varargs. (Hint: show how variable length arguments can simplify method
overloading). [Ap - 7 Marks]

Java

public class VarargsSum {

// (i) Fixed parameters (Requires method overloading for di erent counts)

public static int sumFixed(int a, int b) {


return a + b;

public static int sumFixed(int a, int b, int c) {

return a + b + c;

// ... many more overloaded methods needed for N parameters

// (ii) Varargs parameter (Single method handles any count >= 0)

public static int sumVarargs(int... numbers) {

int sum = 0;

// The varargs parameter is treated as an array inside the method

for (int num : numbers) {

sum += num;

return sum;

public static void main(String[] args) {

// Using Fixed Parameters (Requires two separate method calls)

[Link]("--- Sum using Fixed Parameters ---");

[Link]("Sum (2 args): " + sumFixed(5, 10)); // Calls sumFixed(int, int)

[Link]("Sum (3 args): " + sumFixed(5, 10, 15)); // Calls sumFixed(int,


int, int)

[Link]("\n--- Sum using Varargs ---");

// Using Varargs (One method handles all calls, simplifying overloading)

[Link]("Sum (2 args): " + sumVarargs(5, 10));

[Link]("Sum (3 args): " + sumVarargs(5, 10, 15));


[Link]("Sum (5 args): " + sumVarargs(1, 2, 3, 4, 5));

[Link]("Sum (0 args): " + sumVarargs()); // Handles zero arguments


gracefully

2. Static Keyword

i) What is the syntax of accessing a static method and a non-static method. [R-1
Marks]

Method Type Access Syntax

Accessed using the Class Name:


Static Method
[Link](arguments)

Non-static Accessed using an Object Instance:


Method [Link](arguments)

ii) Explain how static variables di er from instance variables in terms of memory
allocation and lifetime. [U-3 Marks]

Feature Static Variables (Class Variables) Instance Variables (Non-Static)

Allocated in a separate area of


Memory
memory (usually the Method Area Allocated in the Heap memory.
Allocation
or Static Pool).

One single copy of the variable A separate copy of the variable is


Copies exists, shared by all objects of the created for every new object
class. instance.

Created when the class is loaded by Created when the object is


the JVM and persists until the instantiated (new operator) and
Lifetime
program execution ends or the class destroyed when the object is
is unloaded. garbage collected.

iii) Develop a Java program that demonstrates the use of static variables to count
the number of objects created for a class. [Ap-6 Marks]

Java

class Counter {
// Static variable: one copy shared by all objects

private static int objectCount = 0;

// Instance variable: unique for each object

private int objectID;

// Constructor: increments the static counter every time a new object is created

public Counter() {

objectCount++;

[Link] = objectCount; // Assign unique ID based on count

[Link]("Object created. ID: " + [Link]);

// Static method: accesses the static variable without needing an object instance

public static int getObjectCount() {

return objectCount;

public class StaticCounterDemo {

public static void main(String[] args) {

// Accessing the static method before any object is created

[Link]("Initial Count: " + [Link]());

// Create the first object

Counter c1 = new Counter();

// Create the second object


Counter c2 = new Counter();

// Create the third object

Counter c3 = new Counter();

// Accessing the static variable via the Class Name (Standard Practice)

[Link]("\nTotal Objects Created (via Class Name): " +


[Link]());

// Note: You can also access it via an object reference (e.g., [Link]()),

// but the compiler internally translates it to [Link]().

3. Garbage Collection

i) What is garbage collection in Java. [R-2 Marks]

Garbage Collection (GC) is an automatic memory management process in Java. It


automatically identifies and frees memory occupied by objects that are no longer
referenced (reachable) by the executing program. This mechanism prevents memory
leaks and relieves the programmer from manual memory deallocation.

ii) Compare garbage collection in Java with free function-DMA used in C. [U-3
Marks]

C Dynamic Memory Allocation


Feature Java Garbage Collection (GC)
(free)

Automatic. JVM automatically Manual. Programmer must


Mechanism identifies and reclaims unreferenced explicitly call free() to deallocate
objects. memory.

Memory High. Prevents memory leaks Low. Prone to memory leaks


Safety (forgotten free() calls) and dangling (forgetting free) and security
C Dynamic Memory Allocation
Feature Java Garbage Collection (GC)
(free)

pointers (using memory after free() vulnerabilities if free is used


has been called). incorrectly.

Non-deterministic. Programmers Deterministic. Memory is freed


Determinism cannot guarantee when GC will run immediately upon the explicit
or which memory will be freed. call to free().

iii) Apply the concept of garbage collection and find the output for the given code.
[Ap - 5 Marks]

The code uses the finalize() method, which the Garbage Collector calls just before
destroying an object.

Java

class GarbageCollectorDemo {

public void finalize() {

[Link]("Garbage Collector called and object destroyed");

public class Main {

public static void main(String[] args) {

GarbageCollectorDemo obj1 = new GarbageCollectorDemo(); // Object 1 created

GarbageCollectorDemo obj2 = new GarbageCollectorDemo(); // Object 2 created

obj1 = null; // Object 1 is now eligible for GC

obj2 = null; // Object 2 is now eligible for GC

// Request JVM to run garbage collector ([Link]() is only a suggestion)

[Link]();
[Link]("End of main method");

Output and Explanation:

The output order is non-deterministic but the content will be:

End of main method

Garbage Collector called and object destroyed

Garbage Collector called and object destroyed

 obj1 = null and obj2 = null make both objects eligible for GC.

 [Link]() is a hint to the JVM to run GC. If the GC runs, it will call finalize() for
both objects.

 The println("End of main method") is usually executed before the GC thread


completes its work, as GC runs asynchronously.

 Therefore, the two finalize() messages will appear, but their relative order and
timing with respect to "End of main method" are not guaranteed, although "End
of main method" usually prints first.

Batch-2

4. varargs Flexibility and Applications

i) Explain with examples how varargs improve code reusability and flexibility
compared to method overloading. [U-3 Marks]

varargs improve code reusability and flexibility because they allow a single method
definition to accept a variable number of arguments (zero or more) of a specific type.

 Reusability: Instead of writing and maintaining multiple overloaded methods


(e.g., print(int a), print(int a, int b), print(int a, int b, int c), etc.), you write one
generic method: print(int... numbers). This single method is reused across all
call sites, regardless of argument count.

 Flexibility: The caller gains flexibility since they can pass any number of
arguments to the method without the method needing to be explicitly defined for
that exact argument count. The method signature remains clean and simple.
ii) Apply the concept of varargs to design a printDetails() method that can print
student information (like name, roll number, subjects, marks) even if the number of
subjects varies. [Ap-7 Marks]

Java

public class StudentVarargsDetails {

// printDetails method uses varargs to handle a variable number of subject/mark pairs

// Note: The structure requires the method to be flexible, but the first two arguments

// (name, rollno) are fixed, which is a key strength of varargs: it must be last.

public static void printDetails(String name, int rollNo, String... subjectMarkPairs) {

[Link]("\n--- Student Information ---");

[Link]("Name: " + name);

[Link]("Roll No: " + rollNo);

[Link]("Subjects & Marks:");

if ([Link] == 0) {

[Link](" No subjects recorded.");

return;

// Loop through the subjectMarkPairs array, assuming they come in pairs

for (int i = 0; i < [Link]; i += 2) {

String subject = subjectMarkPairs[i];

// Assuming the next element is the mark (as a string, cast to int or print as string)

String mark = (i + 1 < [Link]) ? subjectMarkPairs[i + 1] : "N/A";

[Link](" " + subject + ": " + mark);

}
}

public static void main(String[] args) {

// Case 1: Student with two subjects

printDetails("Ravi", 101, "OOPJ", "90", "DSA", "85");

// Case 2: Student with three subjects

printDetails("Priya", 102, "Chemistry", "78", "Physics", "88", "Math", "95");

// Case 3: Student with zero subjects

printDetails("Kishore", 103);

5. Static Variables and Methods in a Class

i) Why can't static methods directly access non-static variables? [R-1 Marks]

Static methods cannot directly access non-static (instance) variables because static
methods belong to the class rather than any specific object. Non-static variables are
created only after an object is instantiated (new keyword). Since a static method can be
called without any object existing, it cannot reliably refer to memory that might not be
allocated yet.

ii) Compare the use of static initialization blocks and constructors for initializing
class members. Provide suitable examples and highlight the di erences. [U-3
Marks]

Feature Static Initialization Block Constructor

ClassName(...) { ... } (special


Syntax static { ... } (block of code)
method)

Target Used to initialize instance


Used to initialize static variables.
Member variables.
Feature Static Initialization Block Constructor

Executed once when the class is first Executed every time a new
Invocation
loaded by the JVM. object of the class is created.

Used to set up a static database Used to assign unique IDs or


Example connection pool or read a static parameter values to individual
configuration file. objects.

iii) Develop a class Product with instance members... and static member
totalprice... (Ap - 6 Marks)

The static member totalprice will track the cumulative price of all products created.

Java

import [Link];

class Product {

// Instance members

int itemno;

String itemname;

double price;

int quantity;

double totprice; // Instance total price

// Static member: shared by all objects

public static double totalprice = 0.0;

// Instance method to read product details

public void read(Scanner scanner) {

[Link]("Enter itemno: ");

itemno = [Link]();

[Link]();

[Link]("Enter itemname: ");


itemname = [Link]();

[Link]("Enter price: ");

price = [Link]();

[Link]("Enter quantity: ");

quantity = [Link]();

// Calculate instance total price and update static totalprice

totprice = price * quantity;

totalprice += totprice; // Update the shared static variable

// Instance method to display details of one product

public void display() {

[Link]("%-8d %-10s %-8.2f %-10d %-8.2f\n", itemno, itemname, price,


quantity, totprice);

// Static method: accesses the static member

public static void displaytotprice() {

// Only static members can be accessed here

[Link]("\nTotal price: %.2f\n", totalprice);

public class ProductApp {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter number of products: ");


int numProducts = [Link]();

Product[] products = new Product[numProducts];

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

[Link]("\n--- Product " + (i + 1) + " ---");

products[i] = new Product();

products[i].read(scanner);

[Link]("\n--- Output ---");

[Link]("%-8s %-10s %-8s %-10s %-8s\n", "itemno", "itemname", "price",


"quantity", "totprice");

for (Product p : products) {

[Link]();

// Call the static method to display the grand total

[Link]();

[Link]();

6. Garbage Collection (Cont.)

i) Which method is called prior to garbage collection. [R-2 Marks]

The finalize() method (inherited from [Link]) is called by the Garbage


Collector (GC) just before an object is destroyed and its memory is reclaimed.

ii) Outline about implicit and explicit garbage collection? [U-3 Marks]
 Implicit Garbage Collection: This is the automatic process where the JVM runs
the GC thread whenever it determines that memory is running low or resources
need to be cleaned up. This process is non-deterministic, meaning the
programmer has no direct control over when it occurs. This is the standard way
GC works.

 Explicit Garbage Collection: This refers to the programmer making a


suggestion to the JVM to run the Garbage Collector, usually by calling
[Link]() or [Link]().gc(). However, these are merely hints; the
JVM is not guaranteed to run GC immediately, if at all.

iii) Identify the number of objects and the object pointed by which reference is
eligible for garbage collection in the given below code at line 8. [Ap- 5 Marks]

Java

public class Test {

public static void main(String[] args) { // line 3

Test t1 = new Test(); // line 4 (Object O1 created, referenced by t1)

Test t2 = fun1(t1); // line 5 (t2 points to O3)

Test t3 = new Test(); // line 6 (Object O4 created, referenced by t3)

t2 = t3; // line 8 (t2 now points to O4)

} // line 9

static Test fun1(Test temp) { // line 11

temp = new Test(); // line 13 (Object O3 created, referenced by local 'temp')

return temp; // line 14

} // line 15

Tracing Memory and References up to Line 8:

Objects References
Line Action GC Eligibility
Created (Stack)

t1 = new t1 $\rightarrow$
L4 O1 None
Test() O1
Objects References
Line Action GC Eligibility
Created (Stack)

O2 temp
t2 =
L5 (inside $\rightarrow$ O2 None
fun1(t1)
fun1 L13) (Local to fun1)

O1 (Original object passed as


argument to fun1. The local temp
fun1
t2 $\rightarrow$ inside fun1 was immediately
L5 End returns O2
O2 reassigned to O2, making O1
O2
unreachable inside fun1's scope).
Wait, t1 still points to O1.

t1 $\rightarrow$
L5 t2 =
O2 O1, t2 None
Corrected fun1(t1)
$\rightarrow$ O2

t1 $\rightarrow$
O1, t2
t3 = new
L6 O3 $\rightarrow$ O2, None
Test()
t3 $\rightarrow$
O3

O2 (The object previously


t2 now
L8 t2 = t3 referenced only by t2 is now
$\rightarrow$ O3
unreachable).

Answer at Line 8:

1. Number of Objects Eligible for GC: 1

2. Object Pointed by Which Reference is Eligible for GC: The object that was
originally pointed to by t2 (Object O2, created inside fun1) is now eligible for
garbage collection because t2 is reassigned to point to t3 (Object O3), and no
other live reference points to O2.

You might also like