0% found this document useful (0 votes)
2 views19 pages

Java

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)
2 views19 pages

Java

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/ 19

UNIT1

Q1. Explain the concept of Bytecode in Java and why it is called Java’s "Magic".

• Java programs are compiled into an intermediate form called Bytecode (a .class file).

• Bytecode is platform-independent; it runs on the Java Virtual Machine (JVM) of any OS.

• JVM translates bytecode into native machine code at runtime.

• This makes Java’s “write once, run anywhere” (WORA) possible.

• Magic of Bytecode → portability, security, and efficiency.

Q2. Compare Object-Oriented Programming (OOP) and Procedure-Oriented Programming (POP).

Feature POP OOP

Approach Function-centric Object-centric

Data Shared, less secure Encapsulated, more secure

Reusability Limited High via inheritance, polymorphism

Example C Java, C++

Q3. List and explain any Six important features of Java with examples.

1. Platform Independent – Bytecode runs on JVM of any OS.

2. Simple – Syntax is clean and close to C/C++.

3. Object-Oriented – Supports encapsulation, inheritance, polymorphism.

4. Robust – Exception handling, garbage collection.

5. Secure – No pointers, JVM has security checks.

6. Multithreaded – Multiple threads can run concurrently.

Q4. Compare Java with C and C++ in terms of memory management, platform independence, and OOP
features.
• Memory Management:

o C: Manual (malloc/free)

o C++: Manual + destructors

o Java: Automatic Garbage Collection

• Platform Independence:

o C & C++: Compiled into machine code → platform dependent

o Java: Compiles to bytecode → platform independent

• OOP Features:

o C: Not OOP

o C++: Fully OOP + supports multiple inheritance

o Java: Pure OOP (except primitive types), no multiple inheritance (uses interfaces)

Q5. Explain the principles of Object-Oriented Programming with examples.

1. Encapsulation – Wrapping data & methods in a class.

class Student {

private int age;

public void setAge(int a){ age = a; }

public int getAge(){ return age; }

2. Abstraction – Hiding implementation, showing functionality. (e.g., Interfaces, Abstract Classes).

3. Inheritance – Reusing properties of a parent class.

class Animal { void sound(){ System.out.println("Animal sound"); } }

class Dog extends Animal { void sound(){ System.out.println("Bark"); } }

4. Polymorphism – One task, different forms (method overloading & overriding).

Q6. Write the syntax for declaring and initializing one-dimensional and two-dimensional arrays in Java.
Write a program to find the largest element in an array.
• 1D Array Syntax:

• int arr[] = {1, 2, 3, 4};

• 2D Array Syntax:

• int matrix[][] = { {1,2}, {3,4} };

Program – Largest element in an array

class LargestElement {

public static void main(String args[]) {

int arr[] = {10, 25, 7, 56, 89, 42};

int max = arr[0];

for(int i=1; i<arr.length; i++) {

if(arr[i] > max) {

max = arr[i];

System.out.println("Largest Element: " + max);

Output:

Largest Element: 89
UNIT II – Question Bank Answers
Q1. 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.

• Class: Blueprint for objects. Contains data (fields) & behavior (methods).

• Object: Instance of a class created using new.

• Object reference variable: Holds the memory address of the object.

Example:

class Car {

String brand;

int speed;

void display() {

System.out.println("Brand: " + brand + ", Speed: " + speed);

class Test {

public static void main(String args[]) {

Car c1 = new Car(); // object creation

c1.brand = "Honda";

c1.speed = 120;

Car c2 = c1; // reference assignment

c2.speed = 150; // changes reflect in c1 too (same memory)


c1.display(); // Brand: Honda, Speed: 150

Importance: Object reference variables ensure efficient memory use; multiple references can point
to the same object.

Q2. 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.

Feature Constructor Method

Purpose Initialize object Perform actions

Name Same as class Any valid identifier

Return Type No return type Must return value or void

Call Automatically on new Called explicitly

Example:

class Student {

String name;

int age;

// Default constructor

Student() {

name = "Unknown";

age = 0;

System.out.println("Default Constructor Called");

}
// Parameterized constructor

Student(String n, int a) {

name = n;

age = a;

System.out.println("Parameterized Constructor Called");

void display() {

System.out.println("Name: " + name + ", Age: " + age);

class Test {

public static void main(String args[]) {

Student s1 = new Student();

s1.display();

Student s2 = new Student("John", 20);

s2.display();

Q3. 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.

• Objects can be passed as parameters and returned from methods.

• This increases reusability & modularity.


Example:

class Box {

int length, breadth;

Box(int l, int b) {

length = l; breadth = b;

// Method with object parameter

boolean isEqual(Box obj) {

return (this.length == obj.length && this.breadth == obj.breadth);

// Returning object

Box doubleSize() {

return new Box(length * 2, breadth * 2);

class Test {

public static void main(String args[]) {

Box b1 = new Box(5, 10);

Box b2 = new Box(5, 10);

System.out.println("Are boxes equal? " + b1.isEqual(b2));


Box b3 = b1.doubleSize();

System.out.println("New Box: " + b3.length + " x " + b3.breadth);

Q4. 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.

Types of Constructors:

1. Default Constructor – No arguments.

2. Parameterized Constructor – Accepts arguments.

3. Overloaded Constructors – Multiple constructors with different parameter lists.

Program: Ticket Booking

class Ticket {

String passenger, source, destination;

double fare;

// Default Constructor

Ticket() {

passenger = "Unknown";

source = "N/A";

destination = "N/A";

fare = 0.0;

// Parameterized Constructor
Ticket(String p, String s, String d, double f) {

passenger = p;

source = s;

destination = d;

fare = f;

// Overloaded Constructor with discount

Ticket(String p, String s, String d, double f, boolean online) {

passenger = p; source = s; destination = d;

if(online) {

fare = f - (f * 0.10); // 10% discount

} else {

fare = f;

void display() {

System.out.println("Passenger: " + passenger);

System.out.println("From: " + source + " To: " + destination);

System.out.println("Fare: " + fare);

class BookingTest {
public static void main(String args[]) {

Ticket t1 = new Ticket();

Ticket t2 = new Ticket("John", "Delhi", "Mumbai", 1000);

Ticket t3 = new Ticket("Alice", "Chennai", "Bangalore", 800, true);

t1.display();

t2.display();

t3.display();

Q5. 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.

• Garbage Collection (GC):

o Automatic process in Java that deletes unused objects from memory.

o Runs in JVM → no need for manual delete.

• C++: Programmer manually manages memory (new/delete).

• Java Advantage: Prevents memory leaks, ensures efficient memory use in large applications.

• Example:

• Box b = new Box();

• b = null; // eligible for GC

• System.gc(); // suggest GC run

Q6. 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.

• static: Belongs to class, not object.

• final: Used for constants, prevents inheritance/overriding.


Example:

class Demo {

static int count = 0; // shared by all objects

final double PI = 3.14159;

Demo() { count++; }

void display() {

System.out.println("Object count: " + count);

System.out.println("Constant PI: " + PI);

class Test {

public static void main(String args[]) {

Demo d1 = new Demo();

Demo d2 = new Demo();

d1.display(); // count = 2

Q7. 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.

• String in Java: Immutable objects stored in the String Constant Pool.

• Immutability: Once created, a String cannot be changed. Any modification creates a new object.
• Memory: Helps in efficiency & security (e.g., passwords).

Common String Methods:

class StringMethods {

public static void main(String args[]) {

String s = "Java Programming";

System.out.println("Length: " + s.length()); // 1

System.out.println("Upper: " + s.toUpperCase()); // 2

System.out.println("Substring: " + s.substring(5, 16)); // 3

System.out.println("CharAt: " + s.charAt(2)); // 4

System.out.println("Replace: " + s.replace("Java", "C++")); // 5

Q8. 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.

Feature String StringBuffer

Mutability Immutable Mutable

Performance Slow for modifications Faster for repeated modifications

Thread-Safe Yes Yes (synchronized)

Example Program: Student Remarks

class StudentRemark {

public static void main(String args[]) {

StringBuffer sb = new StringBuffer("Student performance: ");


// Append

sb.append("Excellent");

System.out.println("After append: " + sb);

// Insert

sb.insert(0, "John - ");

System.out.println("After insert: " + sb);

// Delete

sb.delete(16, 27); // removes "performance"

System.out.println("After delete: " + sb);

// Final Remark

System.out.println("Final Remark: " + sb);

Output:

After append: Student performance: Excellent

After insert: John - Student performance: Excellent

After delete: John - Student : Excellent

Final Remark: John - Student : Excellent

Q9. 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 (Compile-time Polymorphism): Same method name, different parameter


lists.
• Method Overriding (Runtime Polymorphism): Child class redefines parent method.

Example (Overloading):

class Calculator {

int add(int a, int b) { return a+b; }

double add(double a, double b) { return a+b; } // overloaded

class Test {

public static void main(String args[]) {

Calculator c = new Calculator();

System.out.println(c.add(5, 10)); // 15

System.out.println(c.add(5.5, 4.5)); // 10.0

Example (Overriding):

class Animal {

void sound() { System.out.println("Animal makes sound"); }

class Dog extends Animal {

void sound() { System.out.println("Dog barks"); }

class Test2 {

public static void main(String args[]) {

Animal a = new Dog(); // Runtime polymorphism


a.sound(); // Dog barks

Q10. 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.

• StringTokenizer: Splits strings into tokens (words).

• Constructors:

o StringTokenizer(String str)

o StringTokenizer(String str, String delimiter)

Library Example:

import java.util.StringTokenizer;

class Library {

public static void main(String args[]) {

String book = "Java The Complete Reference,Herbert Schildt,2024";

StringTokenizer st = new StringTokenizer(book, ",");

System.out.println("Book Title: " + st.nextToken());

System.out.println("Author: " + st.nextToken());

System.out.println("Year: " + st.nextToken());

Output:

Book Title: Java The Complete Reference

Author: Herbert Schildt


Year: 2024

Q11. Explain the concept of nested and inner classes.

• Nested class: Class inside another class.

• Types:

1. Static nested class → behaves like a static member.

2. Inner class → non-static, can access outer class members.

Example:

class Outer {

int x = 10;

class Inner {

void display() {

System.out.println("Value of x: " + x); // can access outer variable

class Test {

public static void main(String args[]) {

Outer o = new Outer();

Outer.Inner in = o.new Inner();

in.display();

}
Q12. 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.

• Multilevel inheritance: Class inherits from another derived class.

• super: Refers to parent class members/constructors.

• this: Refers to current object.

Example: University Administration System

class Staff {

String name;

int id;

double salary;

Staff(String n, int i, double s) {

name = n; id = i; salary = s;

void display() {

System.out.println("Name: " + name + ", ID: " + id + ", Salary: " + salary);

class TeachingStaff extends Staff {

String subject;

TeachingStaff(String n, int i, double s, String sub) {

super(n, i, s); // call parent constructor

subject = sub;
}

void display() {

super.display();

System.out.println("Subject: " + subject);

class NonTeachingStaff extends Staff {

String department;

NonTeachingStaff(String n, int i, double s, String dept) {

super(n, i, s);

department = dept;

void display() {

super.display();

System.out.println("Department: " + department);

class University {

public static void main(String args[]) {

TeachingStaff t = new TeachingStaff("Alice", 101, 50000, "Math");

NonTeachingStaff nt = new NonTeachingStaff("Bob", 201, 30000, "Accounts");


t.display();

nt.display();

You might also like