Unit 2 Answers
Unit 2 Answers
1.Explain the fundamentals of a class in Java with an example, and demonstrate how objects are
declared, object reference variables are assigned, and analyse the importance of object reference
variables in program execution.
Ans:
Fundamentals of a class in Java
➢ Perhaps the most important thing to understand about a class is that it defines a new data type.
➢ Once defined, this new type can be used to create objects of that type.
➢ Thus, a class is a template for an object, and an object is an instance of a class.
Declaring Objects
➢ When you create a class, you are creating a new data type. You can
➢ First, you must declare a variable of the class type. This variable
you must acquire an actual, physical copy of the object and assign
it to that variable.
➢ You can do this using the new operator. The new operator
➢ This reference is, more or less, the address in memory of the object
They are not permanently linked — changing one won’t affect the other’s reference.
b1 = null;
Now b1 points to nothing, but b2 still refers to the object.
Importance of obeject reference variable in program execution
2. Differentiate between methods and constructors in Java, and illustrate with a program how
constructors (including overloaded ones) are invoked along with method calls in object creation.
Ans:
Difference between methods and constructors
Methods Constructors
1. A method is a block of code or collection 1. A constructor initializes an object
of statements or a set of immediately upon creation. It
code grouped together to perform a certain has the same name as the class in which it
task or operation. It is resides and is
used to achieve the reusability of code. syntactically similar to a method.
2. Here, type specifies the type of data 2. Constructors look a little strange
returned by the method. This because they have no return type,
can be any valid type, including class types not even void.Name is same as class name
that you create. If the method does not return
a value, its return type must be void.
The name of the method is specified by name.
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "Unknown";
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n;
void display() {
System.out.println(id + " " + name);
class TestStudent {
s1.display();
s2.display();
3.Explain how objects are used in method handling by passing them as parameters and returning
them from methods, and justify how this approach enhances code reusability with a suitable Java
program.
Ans:
• In Java, we can pass objects as arguments to methods. This allows methods to operate directly
on object data.
• Methods can also return objects, enabling one method to give an object as output to another.
• This technique enhances code reusability because the same method logic can be applied to
different objects without rewriting code.
Example Program
class Student {
int id;
String name;
Student(int i, String n) {
id = i;
name = n;
void display(Student s) {
Student getStudent() {
class Test {
Student s3 = s1.getStudent();
• The display() method can print details of any Student object passed to it → no need to write
multiple display methods.
• The getStudent() method can return an object to be reused elsewhere.
• Thus, object passing and returning reduces code duplication and makes the program more
modular and reusable.
4. Explain constructors in Java and discuss their types (default and parameterized). Demonstrate
the concept of constructor overloading with a Ticket Booking System program, including discount
logic. • Design a Java program for Ticket Booking using constructors. The program should: •
Create a default constructor that initializes ticket details with default values. • Use a
parameterized constructor to initialize booking details such as passenger name, source,
destination, and fare. • Implement constructor overloading by allowing tickets to be booked with
and without discounts. • Apply a discount logic (e.g., 10% discount on fare for online booking). •
Display the final ticket details, including passenger name, source, destination, original fare,
discount applied, and final payable fare.
import java.util.Scanner;
class TicketBooking {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Default constructor
Ticket t1 = new Ticket();
t1.displayTicket();
sc.close();
}
}
class Ticket {
String passengerName;
String source;
String destination;
double fare;
double finalFare;
boolean discountApplied;
// Default constructor
Ticket() {
passengerName = "Unknown";
source = "Not Specified";
destination = "Not Specified";
fare = 0.0;
finalFare = fare;
discountApplied = false;
System.out.println("\nDefault Ticket Created.");
}
if (onlineBooking) {
this.finalFare = fare - (fare * 0.10); // 10% discount
this.discountApplied = true;
} else {
this.finalFare = fare;
this.discountApplied = false;
}
System.out.println("\nTicket Created With Discount (Online Booking).");
}
5. Explain the concept of Garbage Collection in Java, compare it with memory management in
C++, and evaluate its role in ensuring efficient memory utilization in large applications.
Ans:
Memory
Automatic by JVM Garbage Collector Manual using delete()
release
• Efficiency: GC automatically frees unused memory, reducing the chance of memory leaks.
• Reliability: Applications become more robust since developers don’t need to manually track
memory usage.
• Scalability: In large, complex applications (like servers, databases, enterprise software), GC
ensures smooth performance by recycling memory.
• Focus on Logic: Developers can concentrate on problem-solving instead of debugging memory
issues.
6. Discuss the use of the static and final keywords in Java, illustrate their role with suitable
programs, and analyze their impact on object-oriented programming design.
Ans:
• The static keyword allows class members (variables and methods) to be accessed without
creating objects.
• Static Variables: Shared by all instances of the class (only one copy exists).
• Static Methods: Can be called without object creation, but they:
o Can only directly access other static members.
o Cannot use this or super.
• Static Block: Runs once when the class is loaded, useful for initialization.
Example:
class UseStatic {
static int a = 3;
static int b;
// Static block
static {
b = a * 4;
meth(42);
Output:
x = 42
a=3
b = 12
Example
class FinalDemo {
void show() {
}
}
class TestFinal {
f.show();
• static
o Promotes memory efficiency by sharing variables across objects.
o Useful for utility methods (e.g., Math.sqrt() in Java).
o Reduces object dependency when behavior is class-level rather than object-level.
• final
o Ensures immutability of values (important in secure applications).
o Enforces design constraints: prevents unwanted inheritance or method modification.
o Helps maintain consistent behavior across the program.
7.Explain the fundamentals of Strings in Java, demonstrate at least five important String methods
with examples, and analyse how immutability and memory management affects string handling
and performance
• Unlike some other languages that implement strings as character arrays, Java implements strings
as objects of type String.
• A string in Java is immutable – once a String object has been created, you cannot change its
characters.
• When a modification is performed, a new String object is created that contains the modified
value, while the original string remains unchanged.
Since String objects are immutable, they cannot be changed once created.
• If you modify a string, a new object is created and the old one is left for garbage collection.
o JVM maintains a String pool (intern pool), so identical string literals are stored only
once, reducing memory usage.
• For frequent modifications (e.g., appending, inserting), using StringBuffer or StringBuilder is
more efficient because they are mutable.
8. Differentiate between String and StringBuffer classes with examples, demonstrate append(), insert(), and
delete() methods of StringBuffer, and evaluate how StringBuffer improves efficiency in string
manipulation. Design a Java program to manage student remarks using StringBuffer. The program
should:
a. Start with a remark "Student performance: ".
b. Append the student's grade (e.g., "Excellent").
c. Insert the student’s name at the beginning of the remark.
d. Delete unnecessary words (e.g., remove "performance" if not required).
e. Display the final remark.
2. insert()
• Inserts a string at a specified index.
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
Output:
I like Java!
3. delete()
• Deletes characters from a start index up to (but not including) an end index.
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(5, 7);
System.out.println(sb);
Output:
This a test.
Efficiency of StringBuffer
• Because String objects are immutable, every change creates a new object, which wastes
memory and reduces performance when handling large or frequently modified strings.
• StringBuffer, being mutable, modifies the same object in place.
• It also has extra pre-allocated capacity to minimize reallocation during modifications.
• This makes it more memory-efficient and faster for operations like appending, inserting, or
deleting strings.
import java.util.Scanner;
class StudentRemarks {
StringBuffer remark;
sc.close();
}
}
9.Explain the concepts of method overloading and method overriding in Java with suitable
programs. Demonstrate how method overloading achieves compile-time polymorphism with an
example.
Method Overloading:
In Java, it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process is referred to as method
overloading.
Overloaded methods must differ in the type and/or number of their parameters.
void test(int a) {
System.out.println("a: " + a);
}
double test(double a) {
System.out.println("double a: " + a);
return a * a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test(); // No parameters
ob.test(10); // One int parameter
ob.test(10, 20); // Two int parameters
result = ob.test(123.25); // One double parameter
Method Overriding
• When a subclass defines a method that has the same name, return type, and parameters as a
method in its superclass, then the subclass method overrides the superclass method.
• The version of the method that is executed is determined at runtime, based on the type of the
object. This is runtime polymorphism.
o .
class B extends A {
// Overriding method
void show() {
System.out.println("This is subclass method");
}
}
class OverrideDemo {
public static void main(String args[]) {
A obj = new B(); // reference of superclass, object of subclass
obj.show(); // calls subclass method
}
}
Output:
• Definition: Method overloading means having multiple methods with the same name in the
same class but with different parameter lists (number or type of arguments).
• The compiler decides at compile-time which version of the method to call → this is called
compile-time polymorphism.
• The return type alone cannot differentiate overloaded methods.
10. Explain the purpose of the StringTokenizer class in Java, discuss its constructors and key methods, and
demonstrate its usage in parsing a sentence into words with a program. A library system needs to parse a
string containing book details (title, author, and year) separated by commas. Write a program using
StringTokenizer that:
a. Reads the string "Java The Complete Reference,Herbert Schildt,2024".
b. Extracts each token (book title, author name, and year).
c. Displays them neatly.
StringTokenizer:
• The processing of text often consists of parsing a formatted input string.
• Parsing = dividing text into a set of discrete parts (tokens) that convey meaning.
• The StringTokenizer class provides the first step in this parsing process (lexer or scanner).
• It implements the Enumeration interface.
• Given an input string, it allows us to enumerate the individual tokens contained in it.
Delimiters:
• Tokens are separated by delimiters (characters like , ; :).
• The default delimiters are whitespace characters: space, tab, form feed, newline, carriage return.
Program:
import java.util.Scanner;
import java.util.StringTokenizer; // only this import is added
class Book {
// Instance variables
private String bookName;
private String authorName;
private String year; // replaced isbnNumber & publisher with year
// Constructor
public Book(String bookName, String authorName, String year) {
this.bookName = bookName;
this.authorName = authorName;
this.year = year;
}
// Setters (Mutators)
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public void setYear(String year) {
this.year = year;
}
// Getters (Accessors)
public String getBookName() {
return this.bookName;
}
public String getAuthorName() {
return this.authorName;
}
public String getYear() {
return this.year;
}
// Display details
System.out.println("\n--- Book Details ---");
System.out.println(book.getBookInfo());
sc.close();
}
}
In Java, it is possible to define a class within another class. Such classes are called nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output:display: outer_x = 100
12.Explain multilevel inheritance in Java with a program, highlighting the sequence of constructor
calls and order of execution. Demonstrate the use of the super keyword for accessing superclass
members and constructors, and differentiate it from the this keyword Design a University
Administration System in Java to manage staff records. The system should model both Teaching
Staff and Non-Teaching Staff, sharing common details (name, ID, salary) while maintaining
category-specific information. Implement single, multilevel, and hierarchical inheritance, and
demonstrate the use of the super keyword for invoking superclass methods and constructors. The
program must accept user input to create and display records for different staff types.
Multilevel Inheritance means a class is derived from a subclass, making a chain of inheritance.
Example: A → B → C.
• When objects of the most derived class (C) are created, constructors are called in order of
inheritance:
1. Superclass constructor (A)
2. Intermediate class constructor (B)
3. Subclass constructor (C)
super keyword:
• When a subclass constructor is invoked, it can call its immediate superclass constructor using
super()
• Used to access superclass methods/variables that are hidden by subclass.
this keyword:
• Refers to the current object.
• Used to distinguish instance variables and parameters with the same name.
• Can be passed to methods/constructors or returned from a method.
• Difference between super and this
// Super class
class Staff
{
String name;
int staffId;
double baseSalary;
void displayDetails()
{
System.out.println("Name : " + name);
System.out.println("Staff ID : " + staffId);
System.out.println("Base Salary: " + baseSalary);
}
}
TeachingStaff(String name, int staffId, double baseSalary, String subject, int experience)
{
super(name, staffId, baseSalary);
this.subject = subject;
this.experience = experience;
}
void displayDetails()
{
super.displayDetails(); // Calling super class method
System.out.println("Subject : " + subject);
System.out.println("Experience: " + experience + " years");
}
}
HOD(String name, int staffId, double baseSalary, String subject, int experience, String
department)
{
super(name, staffId, baseSalary, subject, experience);
this.department = department;
}
void displayDetails()
{
super.displayDetails(); // Calling superclass method
System.out.println("Department: " + department);
}
}
void displayDetails()
{
super.displayDetails(); // Accessing superclass method
System.out.println("Work Type : " + workType);
}
}
public class UniversityStaffDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
switch (choice)
{
case 1:
System.out.print("Enter Name: ");
String tName = sc.nextLine();
System.out.print("Enter Staff ID: ");
int tId = sc.nextInt();
System.out.print("Enter Base Salary: ");
double tSalary = sc.nextDouble();
sc.nextLine();
System.out.print("Enter Subject: ");
String tSubject = sc.nextLine();
System.out.print("Enter Experience (in years): ");
int tExp = sc.nextInt();
case 2:
System.out.print("Enter Name: ");
String hName = sc.nextLine();
System.out.print("Enter Staff ID: ");
int hId = sc.nextInt();
System.out.print("Enter Base Salary: ");
double hSalary = sc.nextDouble();
sc.nextLine();
System.out.print("Enter Subject: ");
String hSubject = sc.nextLine();
System.out.print("Enter Experience (in years): ");
int hExp = sc.nextInt();
sc.nextLine();
System.out.print("Enter Department: ");
String hDept = sc.nextLine();
case 3:
System.out.print("Enter Name: ");
String nName = sc.nextLine();
System.out.print("Enter Staff ID: ");
int nId = sc.nextInt();
System.out.print("Enter Base Salary: ");
double nSalary = sc.nextDouble();
sc.nextLine();
System.out.print("Enter Work Type: ");
String nWork = sc.nextLine();
default:
System.out.println("Invalid choice.");
}
sc.close();
}
}