0% found this document useful (0 votes)
4 views41 pages

Java External Imp Answers

The document covers essential Java programming concepts, including JVM architecture, Java features, source file structure, operators, type conversion, decision-making statements, looping statements, and arrays. It provides detailed explanations and examples for each topic, emphasizing Java's robustness, security, and object-oriented nature. Additionally, it includes practical examples such as removing duplicates from an array and demonstrates various data types in Java.

Uploaded by

Legend
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)
4 views41 pages

Java External Imp Answers

The document covers essential Java programming concepts, including JVM architecture, Java features, source file structure, operators, type conversion, decision-making statements, looping statements, and arrays. It provides detailed explanations and examples for each topic, emphasizing Java's robustness, security, and object-oriented nature. Additionally, it includes practical examples such as removing duplicates from an array and demonstrates various data types in Java.

Uploaded by

Legend
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

Java Programming

Important Questions

UNIT – I: Introduction to Java

Q1. Describe the JVM architecture with a neat diagram. Explain the role of Class Loader,
Memory Areas, and Execution Engine.

The Java Virtual Machine (JVM) is the runtime environment that executes Java bytecode. It provides
platform independence by abstracting the underlying hardware and OS. The JVM architecture consists
of three main subsystems:

1. Class Loader Subsystem


The Class Loader is responsible for loading .class files into the JVM memory. It operates in three phases:
• Loading: Reads the .class file and creates a binary representation in method area.
• Linking: Verifies bytecode (Verification), allocates memory for static variables (Preparation), and
replaces symbolic references with direct references (Resolution).
• Initialization: Executes static initializers and assigns values to static variables.
Three built-in class loaders: Bootstrap ClassLoader (loads core Java API), Extension ClassLoader (loads
ext directory), Application ClassLoader (loads application classpath).

2. Memory Areas (Runtime Data Areas)


• Method Area: Stores class-level data – class name, field info, method info, static variables.
Shared among all threads.
• Heap Area: Stores all objects and instance variables. Shared among all threads. Managed by
Garbage Collector.
• Stack Area: Each thread has its own stack. Stores local variables, partial results, and method
call frames (Stack Frames).
• PC Register (Program Counter): Each thread has its own PC register, holding the address of
current executing instruction.
• Native Method Stack: Holds information for native (non-Java) methods.

3. Execution Engine
The Execution Engine reads and executes bytecode:
• Interpreter: Executes bytecode line by line. Fast startup but slow due to repeated interpretation.
• JIT Compiler (Just-In-Time): Compiles frequently used bytecode into native machine code for
faster execution.
• Garbage Collector: Automatically deallocates memory for objects no longer referenced.

JVM Architecture Diagram (Textual Representation)


┌───────────────────────────────────────────────────────────┐
│ JVM │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CLASS LOADER SUBSYSTEM │ │
│ │ Loading → Linking → Initialization │ │
│ └─────────────────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ RUNTIME DATA AREAS │ │
│ │ Method Area | Heap | Stack | PC Reg | Native Stack │ │
│ └─────────────────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ EXECUTION ENGINE │ │
│ │ Interpreter | JIT Compiler | Garbage Collector │ │
│ └─────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────┘
The JVM also interacts with the Native Method Interface (JNI) to call native libraries.

Q2. Discuss the features of Java (Java Buzzwords) in detail. How do these features
make Java robust and secure?

Java was designed with a set of features that distinguish it from other languages. These features are
often called 'Java Buzzwords':

1. Simple
Java has a clean, easy-to-learn syntax based on C/C++, but removes complex features like pointers,
operator overloading, and multiple inheritance, making it simpler to use.

2. Object-Oriented
Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction. Everything in
Java is an object (except primitives).

3. Platform Independent (Write Once, Run Anywhere)


Java source code is compiled into bytecode (.class), which runs on any machine with a JVM installed,
regardless of OS or hardware.

4. Robust
Java is robust due to: Strong type checking at compile time, exception handling mechanism, automatic
garbage collection (no memory leaks), and no pointer arithmetic.

5. Secure
Java provides security via: Bytecode verifier, Security manager, No explicit pointers, Classloader
(prevents unauthorized class loading), and sandbox execution for applets.

6. Architecture Neutral
Bytecode can run on any architecture. Data types have fixed sizes (e.g., int is always 32-bit), unlike
C/C++.

7. Portable
Java programs can run on any platform without modification. The JVM handles OS-specific details.

8. High Performance
Java uses JIT (Just-In-Time) compilation to convert bytecode to native machine code at runtime,
improving execution speed.

9. Multithreaded
Java has built-in support for multithreading. Multiple threads can run concurrently, enabling efficient use
of CPU resources.

10. Distributed
Java supports distributed computing through RMI (Remote Method Invocation), CORBA, and networking
APIs ([Link]), making it ideal for internet-based applications.

11. Dynamic
Java loads classes dynamically at runtime. Programs can adapt to new environments by loading new
classes without recompiling.

Q3. Explain Java source file structure and compilation process with an example.

Java Source File Structure


A Java source file (.java) follows this structure:
• Package declaration (optional): Must be the first statement.
• Import statements (optional): Import other classes/packages.
• Class declaration: At least one public class; file name must match the public class name.
• Fields, constructors, methods inside the class.

Example:
// Package Declaration
package [Link];
// Import Statement
import [Link];

// Class Declaration
public class HelloWorld {
// Field
String message = "Hello";

// Main Method
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Compilation Process
• Step 1 - Write source code: Save as [Link]
• Step 2 - Compile: Use javac [Link] → produces [Link] (bytecode)
• Step 3 - Execute: Use java HelloWorld → JVM loads .class and executes it
The Java compiler (javac) checks syntax and semantics. Bytecode is platform-neutral and
interpreted/compiled by the JVM on the target machine.

Q4. Discuss various operators in Java. Explain in detail about Bitwise operators with
suitable examples.

Types of Operators in Java


• Arithmetic Operators: +, -, *, /, % (modulus)
• Relational/Comparison Operators: ==, !=, <, >, <=, >=
• Logical Operators: && (AND), || (OR), ! (NOT)
• Assignment Operators: =, +=, -=, *=, /=, %=
• Unary Operators: ++, --, +, -, ~, !
• Ternary Operator: condition ? true_val : false_val
• Bitwise Operators: &, |, ^, ~, <<, >>, >>>

Bitwise Operators in Detail


Bitwise operators work at the binary (bit) level on integer types.
• & (Bitwise AND): Sets bit to 1 if both bits are 1. Example: 5 & 3 = 0101 & 0011 = 0001 = 1
• | (Bitwise OR): Sets bit to 1 if at least one bit is 1. Example: 5 | 3 = 0101 | 0011 = 0111 = 7
• ^ (Bitwise XOR): Sets bit to 1 if bits are different. Example: 5 ^ 3 = 0101 ^ 0011 = 0110 = 6
• ~ (Bitwise NOT/Complement): Flips all bits. Example: ~5 = ~0101 = 1010 = -6 (2's complement)
• << (Left Shift): Shifts bits left, fills with 0. Example: 5 << 1 = 0101 << 1 = 1010 = 10 (multiplies
by 2)
• >> (Right Shift): Shifts bits right, fills with sign bit. Example: 10 >> 1 = 5 (divides by 2)
• >>> (Unsigned Right Shift): Shifts right, fills with 0 regardless of sign.
Example Program:
public class BitwiseDemo {
public static void main(String[] args) {
int a = 5, b = 3;
[Link]("a & b = " + (a & b)); // 1
[Link]("a | b = " + (a | b)); // 7
[Link]("a ^ b = " + (a ^ b)); // 6
[Link]("~a = " + (~a)); // -6
[Link]("a << 1 = " + (a << 1)); // 10
[Link]("a >> 1 = " + (a >> 1)); // 2
}
}

Q5. Explain type conversion and type casting in Java. Differentiate between implicit and
explicit conversion.

Java allows values to be converted from one data type to another. This is called type conversion or type
casting.

1. Implicit (Widening) Conversion


Automatically done by Java when converting a smaller type to a larger type. No data loss occurs.
Widening order: byte → short → int → long → float → double
int i = 100;
long l = i; // int to long (implicit)
float f = l; // long to float (implicit)
[Link](f); // 100.0

2. Explicit (Narrowing) Type Casting


Manually converting a larger type to a smaller type. May result in data loss. Requires a cast operator.
double d = 9.99;
int i = (int) d; // Explicit cast: truncates decimal
[Link](i); // 9

Comparison Table
Implicit: Automatic, no data loss, smaller to larger type.
Explicit: Manual, possible data loss, larger to smaller type, requires cast operator.

Type Promotion in Expressions


In expressions, byte and short are automatically promoted to int. If one operand is long, float, or double,
the other is promoted to match.
byte b = 50;
byte result = (byte)(b * b); // must cast, b*b is int

Q6. Discuss the selection (decision-making) statements in Java with suitable examples.

Java provides several decision-making statements that allow conditional execution of code blocks:

1. if Statement
Executes a block if condition is true.
int x = 10;
if (x > 5) { [Link]("Greater"); }

2. if-else Statement
if (x % 2 == 0) { [Link]("Even"); }
else { [Link]("Odd"); }

3. if-else-if Ladder
int marks = 75;
if (marks >= 90) [Link]("A Grade");
else if (marks >= 75) [Link]("B Grade");
else if (marks >= 60) [Link]("C Grade");
else [Link]("Fail");

4. Nested if
if (x > 0) {
if (x < 100) [Link]("Between 0 and 100");
}

5. switch Statement
Evaluates an expression and executes the matching case. Supports int, char, String, and enum.
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Other day");
}
The break statement prevents fall-through to the next case. The default clause handles unmatched
values.

Q7. Describe the looping statements in Java with suitable examples.

Loops allow repeated execution of a block of code. Java provides four types of loops:

1. for Loop
Used when the number of iterations is known. Syntax: for(init; condition; update)
for (int i = 1; i <= 5; i++) {
[Link](i + " "); // 1 2 3 4 5
}

2. while Loop
Condition is checked before execution. Used when number of iterations is unknown.
int i = 1;
while (i <= 5) {
[Link](i + " ");
i++;
}
3. do-while Loop
Executes at least once. Condition checked after execution.
int i = 1;
do {
[Link](i + " ");
i++;
} while (i <= 5);

4. Enhanced for Loop (for-each)


Used to iterate through arrays or collections easily.
int[] arr = {10, 20, 30, 40};
for (int x : arr) {
[Link](x + " ");
}

Jump Statements
• break: Terminates the loop or switch immediately.
• continue: Skips the rest of the current iteration and moves to next.
• return: Exits from the current method.

Q8. Write a Java program to remove duplicate elements from an integer array.
import [Link];
import [Link];

public class RemoveDuplicates {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 1, 5, 3};
[Link]("Original Array: ");
for (int x : arr) [Link](x + " ");

// Use LinkedHashSet to preserve order & remove duplicates


Set<Integer> set = new LinkedHashSet<>();
for (int x : arr) [Link](x);

[Link]("\nArray after removing duplicates: ");


for (int x : set) [Link](x + " ");
// Output: 1 2 3 4 5
}
}
Explanation: LinkedHashSet automatically removes duplicates and maintains insertion order. We iterate
the original array, add elements to the set (duplicates are ignored), then print the set.

Q9. Briefly explain about different Data types in Java.

Java is a strongly-typed language. Every variable must have a declared type. Java data types are divided
into two categories:

A. Primitive Data Types (8 types)


• byte: 1 byte, range -128 to 127. Used for saving memory in large arrays.
• short: 2 bytes, range -32,768 to 32,767.
• int: 4 bytes, range -2^31 to 2^31-1. Most common integer type.
• long: 8 bytes, for large integers. Suffix L used (e.g., 100L).
• float: 4 bytes, single-precision decimal. Suffix f (e.g., 3.14f).
• double: 8 bytes, double-precision decimal. Default for decimal values.
• char: 2 bytes, single Unicode character (e.g., 'A').
• boolean: 1 bit logically, stores true or false only.

B. Non-Primitive (Reference) Data Types


• String: Sequence of characters. Immutable. Example: String s = "Java";
• Arrays: Collection of same-type elements.
• Classes and Objects: User-defined types.
• Interfaces: Reference type defining a contract.
int age = 25; // int
double salary = 45000.50; // double
char grade = 'A'; // char
boolean isActive = true; // boolean
String name = "Alice"; // String (reference type)

Q10. Explain about arrays in Java. Discuss one-dimensional and multi-dimensional


arrays with examples.

An array is a fixed-size, ordered collection of elements of the same data type. Arrays are objects in Java,
stored in heap memory.

1. One-Dimensional Array
Syntax: dataType[] arrayName = new dataType[size];
int[] marks = new int[5]; // Declaration + creation
marks[0] = 90; marks[1] = 85; // Initialization

// Combined declaration and initialization


int[] scores = {80, 75, 90, 65, 70};

// Accessing elements
for (int i = 0; i < [Link]; i++) {
[Link]("Score " + i + ": " + scores[i]);
}

2. Two-Dimensional (Multi-dimensional) Array


A 2D array is an array of arrays. Used to represent matrices and tables.
int[][] matrix = new int[3][3]; // 3x3 matrix

// Initializing a 2D array
int[][] mat = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
// Displaying using nested loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](mat[i][j] + " ");
}
[Link]();
}

Key Properties of Arrays


• Index starts at 0. Last index = length - 1.
• Fixed size once created. Use ArrayList for dynamic size.
• ArrayIndexOutOfBoundsException thrown for invalid index.
• [Link]() can sort arrays; [Link]() prints array.

UNIT – II: Classes, Objects & Strings

Q1. Discuss the use of this, static and final keywords with suitable examples.

1. 'this' Keyword
The 'this' keyword refers to the current instance of the class. Uses:
• Distinguish instance variables from local variables with same name.
• Call another constructor of the same class (constructor chaining).
• Pass current object as argument to a method.
class Student {
int id; String name;
Student(int id, String name) {
[Link] = id; // '[Link]' is instance variable
[Link] = name;
}
void display() { [Link](id + " " + name); }
}

2. 'static' Keyword
'static' members belong to the class, not any instance. Uses:
• Static variable: Shared across all objects.
• Static method: Called without creating an object.
• Static block: Executed once when class is loaded.
class Counter {
static int count = 0; // shared among all objects
Counter() { count++; }
static void display() { [Link]("Count: " + count); }
}
// main: [Link](); // called without object

3. 'final' Keyword
• Final variable: Value cannot be changed once assigned (constant).
• Final method: Cannot be overridden in subclass.
• Final class: Cannot be extended (inherited).
final double PI = 3.14159; // cannot reassign
final class Math { } // cannot extend

Q2. What are the special characteristics of constructors in Java? Explain different types
of constructors with example.

Characteristics of Constructors
• Same name as the class.
• No return type (not even void).
• Called automatically when an object is created.
• Cannot be static, abstract, or final.
• Can be overloaded (multiple constructors with different parameters).
• If no constructor is defined, Java provides a default constructor.

Types of Constructors
1. Default Constructor (No-argument)
class Car {
String brand;
Car() { // default constructor
brand = "Unknown";
[Link]("Default Constructor called");
}
}

2. Parameterized Constructor
class Car {
String brand; int year;
Car(String brand, int year) { // parameterized
[Link] = brand;
[Link] = year;
}
}

3. Copy Constructor
class Car {
String brand;
Car(Car c) { // copy constructor
[Link] = [Link];
}
}
// Usage: Car c1 = new Car("Toyota", 2020);
// Car c2 = new Car(c1); // copy of c1

Q3. Discuss the significance of StringTokenizer class and write a Java program to
extract numbers from a comma-separated string using StringTokenizer and find their
sum.

StringTokenizer Class
StringTokenizer (in [Link]) is used to break a string into tokens based on a delimiter. It is simpler than
split() for basic tokenization and doesn't use regular expressions.
• StringTokenizer(String str): Default delimiter is whitespace.
• StringTokenizer(String str, String delim): Custom delimiter.
• hasMoreTokens(): Returns true if more tokens exist.
• nextToken(): Returns the next token.
• countTokens(): Returns number of remaining tokens.

Program: Extract numbers and find sum


import [Link];

public class TokenizerDemo {


public static void main(String[] args) {
String input = "10,20,30,40,50";
StringTokenizer st = new StringTokenizer(input, ",");
int sum = 0;
[Link]("Numbers extracted:");
while ([Link]()) {
int num = [Link]([Link]());
[Link](num + " ");
sum += num;
}
[Link]("\nSum = " + sum); // Sum = 150
}
}

Q4. Explain the concept of method overloading using suitable example.

Method overloading allows a class to have multiple methods with the same name but different parameter
lists. The Java compiler determines which method to call based on the number, type, and order of
arguments. This is an example of compile-time polymorphism (static binding).

Rules for Method Overloading


• Methods must have the same name.
• Methods must differ in number of parameters, type of parameters, or order of parameters.
• Return type alone is NOT sufficient to overload a method.

Example:
public class Calculator {
// Add two integers
int add(int a, int b) { return a + b; }
// Add three integers (different number of params)
int add(int a, int b, int c) { return a + b + c; }

// Add two doubles (different type)


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

// Add int and double (different order/type)


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

public static void main(String[] args) {


Calculator c = new Calculator();
[Link]([Link](2, 3)); // 5
[Link]([Link](1, 2, 3)); // 6
[Link]([Link](1.5, 2.5)); // 4.0
[Link]([Link](2, 3.5)); // 5.5
}
}
Advantages: Improves readability, avoids creating multiple method names for similar operations,
supports polymorphism.

Q5. Explain about String class and discuss various methods in String class with an
example.

The String class in [Link] represents a sequence of characters. Strings in Java are immutable — once
created, their value cannot be changed.
String s = "Hello, Java!"; // String literal
String s2 = new String("Hello"); // String object

Commonly Used String Methods


• length(): Returns the length. [Link]() → 12
• charAt(int i): Returns char at index i. [Link](0) → 'H'
• substring(int start): Returns substring from start. [Link](7) → "Java!"
• substring(int start, int end): [Link](0,5) → "Hello"
• toUpperCase() / toLowerCase(): Changes case.
• trim(): Removes leading and trailing whitespace.
• equals(String s): Compares content. equalsIgnoreCase() ignores case.
• contains(String s): Checks if substring exists.
• replace(old, new): Replaces characters/substrings.
• split(String regex): Splits string into array.
• indexOf(String s): First occurrence index.
• isEmpty(): Returns true if length is 0.
• concat(String s): Appends string.

Example Program:
public class StringDemo {
public static void main(String[] args) {
String s = " Hello Java ";
[Link]([Link]()); // Hello Java
[Link]([Link]().length()); // 10
[Link]([Link]()); // HELLO JAVA
[Link]([Link]("Java","World")); // Hello World
String[] words = [Link]().split(" ");
for(String w : words) [Link](w);
}
}

Q6. Explain constructor overloading in Java with a suitable example.

Constructor overloading means having multiple constructors in a class with different parameter lists. Java
distinguishes them based on the number and types of arguments. It provides flexibility to create objects
in different ways.
public class Employee {
int id;
String name;
double salary;

// Constructor 1: No parameters
Employee() {
id = 0; name = "Unknown"; salary = 0.0;
}

// Constructor 2: id and name only


Employee(int id, String name) {
[Link] = id;
[Link] = name;
[Link] = 0.0;
}

// Constructor 3: All three parameters


Employee(int id, String name, double salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}

void display() {
[Link](id + " " + name + " " + salary);
}

public static void main(String[] args) {


Employee e1 = new Employee();
Employee e2 = new Employee(101, "Alice");
Employee e3 = new Employee(102, "Bob", 55000.0);
[Link](); [Link](); [Link]();
}
}
Constructor chaining using this(): Inside a constructor, this() can call another constructor of the same
class.

Q7. Compare String, StringBuffer and StringBuilder in Java with suitable examples.

1. String
• Immutable: Content cannot be changed once created.
• Thread-safe (since it's immutable).
• New object created on every modification (uses more memory).
String s = "Hello";
s = s + " World"; // Creates a new String object

2. StringBuffer
• Mutable: Can be modified without creating new objects.
• Thread-safe: All methods are synchronized.
• Slower than StringBuilder due to synchronization overhead.
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies same object
[Link](5, ","); // Insert at index 5
[Link](); // Reverses content
[Link](sb); // dlroW ,olleH

3. StringBuilder
• Mutable: Like StringBuffer, modifiable in-place.
• Not thread-safe: Methods not synchronized.
• Faster than StringBuffer. Preferred in single-threaded scenarios.
StringBuilder sb = new StringBuilder("Hello");
[Link](" Java");
[Link](0, 5); // Removes "Hello"
[Link](sb); // Java

Comparison Summary
• String: Immutable, thread-safe, slow for frequent modifications.
• StringBuffer: Mutable, thread-safe (synchronized), moderate speed.
• StringBuilder: Mutable, not thread-safe, fastest for single-threaded use.

Q8. Write a Java program to check if a given string is a Pangram or not.

A Pangram is a sentence that contains every letter of the English alphabet at least once. Example: 'The
quick brown fox jumps over the lazy dog'
public class PangramCheck {
static boolean isPangram(String s) {
boolean[] letters = new boolean[26];
s = [Link]();
for (char c : [Link]()) {
if (c >= 'a' && c <= 'z') {
letters[c - 'a'] = true;
}
}
for (boolean b : letters) {
if (!b) return false; // some letter missing
}
return true;
}

public static void main(String[] args) {


String s1 = "The quick brown fox jumps over the lazy dog";
String s2 = "Hello World";
[Link](s1 + " -> Pangram: " + isPangram(s1)); // true
[Link](s2 + " -> Pangram: " + isPangram(s2)); // false
}
}

Q9. Write a Java program to check if a given string is an Anagram or not.

Two strings are anagrams if one is formed by rearranging the letters of the other. Example: 'listen' and
'silent' are anagrams.
import [Link];

public class AnagramCheck {


static boolean isAnagram(String s1, String s2) {
// Remove spaces and convert to lowercase
s1 = [Link]("\\s", "").toLowerCase();
s2 = [Link]("\\s", "").toLowerCase();
if ([Link]() != [Link]()) return false;
// Sort both strings and compare
char[] a1 = [Link]();
char[] a2 = [Link]();
[Link](a1);
[Link](a2);
return [Link](a1, a2);
}

public static void main(String[] args) {


[Link](isAnagram("listen", "silent")); // true
[Link](isAnagram("hello", "world")); // false
[Link](isAnagram("Triangle", "Integral")); // true
}
}

Q10. Write a Java program to display details of a person (personal details in one
method, qualification in another).
public class PersonDetails {
String name, dob, address, phone;
String degree, college, year;
double percentage;
PersonDetails(String n, String d, String a, String p,
String deg, String col, String yr, double pct) {
name=n; dob=d; address=a; phone=p;
degree=deg; college=col; year=yr; percentage=pct;
}

void displayPersonal() {
[Link]("--- Personal Details ---");
[Link]("Name : " + name);
[Link]("DOB : " + dob);
[Link]("Address : " + address);
[Link]("Phone : " + phone);
}

void displayQualification() {
[Link]("--- Qualification Details ---");
[Link]("Degree : " + degree);
[Link]("College : " + college);
[Link]("Year : " + year);
[Link]("Percentage : " + percentage + "%");
}

public static void main(String[] args) {


PersonDetails p = new PersonDetails(
"Ravi Kumar", "15-08-2000", "Hyderabad", "9876543210",
"[Link]", "JNTUK", "2022", 82.5
);
[Link]();
[Link]();
}
}

Q11. Write a Java program to count number of vowels and consonants in the given text.
public class VowelConsonantCount {
public static void main(String[] args) {
String text = "Java Programming is Fun and Exciting";
int vowels = 0, consonants = 0;
String vowelStr = "aeiouAEIOU";
for (char c : [Link]()) {
if ([Link](c)) {
if ([Link](c) != -1)
vowels++;
else
consonants++;
}
}
[Link]("Text: " + text);
[Link]("Vowels: " + vowels);
[Link]("Consonants: " + consonants);
}
}
Output: Vowels: 11, Consonants: 19 (for the given string)

UNIT – III: Inheritance, Polymorphism & Interfaces

Q1. Explain inheritance in Java. Discuss different types of inheritance with examples.

Inheritance is a fundamental OOP concept where a class (subclass/child) acquires the properties and
behaviors of another class (superclass/parent). It promotes code reusability and establishes an IS-A
relationship.
Syntax: class ChildClass extends ParentClass { }

Types of Inheritance in Java


1. Single Inheritance
One class inherits from one parent class.
class Animal { void eat() { [Link]("Eating"); } }
class Dog extends Animal { void bark() { [Link]("Barking"); } }
// Dog d = new Dog(); [Link](); [Link]();

2. Multilevel Inheritance
A class inherits from a derived class (chain of inheritance).
class A { void m1() { [Link]("A"); } }
class B extends A { void m2() { [Link]("B"); } }
class C extends B { void m3() { [Link]("C"); } }

3. Hierarchical Inheritance
Multiple classes inherit from a single parent class.
class Shape { void draw() { [Link]("Drawing"); } }
class Circle extends Shape { void area() { [Link]("Circle area"); } }
class Rectangle extends Shape { void area() { [Link]("Rect area"); } }

4. Multiple Inheritance (via Interfaces)


Java does NOT support multiple inheritance through classes (to avoid the Diamond Problem). However,
it is achieved through interfaces.
interface Flyable { void fly(); }
interface Swimmable { void swim(); }
class Duck implements Flyable, Swimmable {
public void fly() { [Link]("Flying"); }
public void swim() { [Link]("Swimming"); }
}

5. Hybrid Inheritance
Combination of two or more types of inheritance. Achieved in Java using interfaces. Not supported
directly through classes.

Q2. Write a Java program using an abstract class to calculate the area of different
geometric shapes.
abstract class Shape {
String color;
Shape(String color) { [Link] = color; }
abstract double area(); // abstract method
void displayColor() { [Link]("Color: " + color); }
}

class Circle extends Shape {


double radius;
Circle(String color, double r) { super(color); [Link] = r; }
double area() { return [Link] * radius * radius; }
}

class Rectangle extends Shape {


double length, breadth;
Rectangle(String color, double l, double b) {
super(color); length = l; breadth = b;
}
double area() { return length * breadth; }
}

class Triangle extends Shape {


double base, height;
Triangle(String color, double b, double h) {
super(color); base = b; height = h;
}
double area() { return 0.5 * base * height; }
}

public class ShapeDemo {


public static void main(String[] args) {
Shape[] shapes = {
new Circle("Red", 5),
new Rectangle("Blue", 4, 6),
new Triangle("Green", 3, 8)
};
for (Shape s : shapes) {
[Link]();
[Link]("Area: %.2f%n", [Link]());
}
}
}

Q3. What is method overriding? Explain dynamic method dispatch with an example.
Method overriding occurs when a subclass provides its own implementation of a method already defined
in its superclass, with the same name, return type, and parameters. This is runtime polymorphism.

Rules for Method Overriding


• Method name, parameter list, and return type must be the same.
• Access modifier cannot be more restrictive than the parent's.
• Static and final methods cannot be overridden.
• Constructors cannot be overridden.
• Use @Override annotation for clarity and safety.

Dynamic Method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
runtime (not compile time). The object's actual type determines which method version runs.
class Animal {
void sound() { [Link]("Animal makes a sound"); }
}
class Dog extends Animal {
@Override
void sound() { [Link]("Dog barks"); }
}
class Cat extends Animal {
@Override
void sound() { [Link]("Cat meows"); }
}

public class DispatchDemo {


public static void main(String[] args) {
Animal a; // Reference of parent type
a = new Dog(); [Link](); // Dog barks
a = new Cat(); [Link](); // Cat meows
a = new Animal(); [Link](); // Animal makes a sound
}
}
Here, even though 'a' is declared as Animal, the JVM invokes the method of the actual object at runtime
— this is dynamic dispatch.

Q4. Discuss the advantage of the super keyword with a Java program.

The super keyword in Java refers to the immediate parent class of the current class. It is used to access
parent class members that are hidden by the child class.

Uses of super
• 1. Access parent class variables (when child class has same-named field).
• 2. Call parent class method (when overridden in child class).
• 3. Call parent class constructor (using super() in child constructor).
class Vehicle {
String brand = "Generic Vehicle";
int speed;
Vehicle(int speed) {
[Link] = speed;
[Link]("Vehicle constructor: speed = " + speed);
}
void display() { [Link]("Brand: " + brand); }
}

class Car extends Vehicle {


String brand = "Toyota";
Car(int speed) {
super(speed); // calls Vehicle(int speed)
[Link]("Car constructor");
}
void display() {
[Link](); // calls parent's display()
[Link]("Car Brand: " + brand); // child's brand
[Link]("Parent Brand: " + [Link]); // parent's brand
}
}

public class SuperDemo {


public static void main(String[] args) {
Car c = new Car(120);
[Link]();
}
}

Q5. Is it possible to implement multiple inheritances in Java? Justify your answer.

Java does NOT support multiple inheritance through classes. This is a deliberate design decision to avoid
the Diamond Problem.

The Diamond Problem


If class C inherits from both A and B, and both A and B have a method with the same name, there is
ambiguity about which method C should inherit. This is the Diamond Problem.
// This is NOT allowed in Java:
// class C extends A, B { } // Compile ERROR

Multiple Inheritance via Interfaces


Java achieves multiple inheritance through interfaces. A class can implement multiple interfaces, and
since interfaces (before Java 8) didn't have method bodies, there was no ambiguity.
interface Printable {
void print();
}
interface Showable {
void show();
}
class Document implements Printable, Showable {
public void print() { [Link]("Printing..."); }
public void show() { [Link]("Showing..."); }
}
public class MultipleInheritanceDemo {
public static void main(String[] args) {
Document d = new Document();
[Link](); [Link]();
}
}
Note: Java 8+ allows default methods in interfaces. If two interfaces have the same default method, the
implementing class must override it to resolve the conflict.

Q6. How to design and implement an interface in Java? Give an example.

An interface is a reference type in Java that contains abstract methods, constants, default methods (Java
8+), and static methods. It defines a contract that implementing classes must fulfill.

Declaring an Interface
interface InterfaceName {
// Constants (public static final by default)
int MAX = 100;
// Abstract methods (public abstract by default)
void methodName();
}

Implementing an Interface
interface Drawable {
double PI = 3.14; // constant
void draw(); // abstract method
default void info() { // default method (Java 8+)
[Link]("Drawing shape...");
}
}

class Circle implements Drawable {


double radius;
Circle(double r) { radius = r; }
public void draw() {
[Link]("Circle: Area = %.2f%n", PI * radius * radius);
}
}

class Square implements Drawable {


double side;
Square(double s) { side = s; }
public void draw() {
[Link]("Square: Area = %.2f%n", side * side);
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Drawable d1 = new Circle(5);
Drawable d2 = new Square(4);
[Link](); [Link]();
[Link](); [Link]();
}
}

Q7. Explain about abstract methods and abstract classes in Java with suitable
examples.

Abstract Method
An abstract method is a method declared without an implementation (no body). It must be overridden by
any concrete subclass.
abstract void methodName(); // no body, ends with semicolon

Abstract Class
• Declared with abstract keyword.
• Cannot be instantiated directly.
• May contain both abstract and concrete (regular) methods.
• May have constructors and instance variables.
• A subclass must implement all abstract methods (or itself be abstract).
abstract class Animal {
String name;
Animal(String name) { [Link] = name; }
abstract void sound(); // abstract method
void breathe() { // concrete method
[Link](name + " breathes air");
}
}

class Dog extends Animal {


Dog(String name) { super(name); }
void sound() { [Link](name + " says: Woof!"); }
}
class Cat extends Animal {
Cat(String name) { super(name); }
void sound() { [Link](name + " says: Meow!"); }
}

public class AbstractDemo {


public static void main(String[] args) {
Animal a1 = new Dog("Rex");
Animal a2 = new Cat("Kitty");
[Link](); [Link]();
[Link](); [Link]();
}
}

Q8. Differentiate between interfaces and abstract classes with suitable examples.
• Abstract class can have concrete methods; Interface (pre-Java 8) can only have abstract
methods. Java 8+ allows default/static methods in interfaces.
• Abstract class can have constructors; Interface cannot have constructors.
• Abstract class supports single inheritance (extend one); Interface supports multiple
implementation (implement many).
• Abstract class can have any access modifiers; Interface members are public by default.
• Abstract class can have instance variables; Interface can only have public static final constants.
• Use abstract class when classes share common behavior; use interface to define a
capability/contract.
// Abstract class example
abstract class Vehicle {
int speed; // instance variable
Vehicle(int s) { speed = s; } // constructor
abstract void fuelType();
void move() { [Link]("Moving at " + speed); }
}

// Interface example
interface Electric { void charge(); }
interface GPS { void navigate(); }

class Tesla extends Vehicle implements Electric, GPS {


Tesla() { super(200); }
public void fuelType() { [Link]("Electric"); }
public void charge() { [Link]("Charging..."); }
public void navigate() { [Link]("Navigating..."); }
}

Q9. Illustrate various uses of 'final' keyword with suitable code segments.

1. final Variable
Value cannot be changed once assigned. Acts as a constant.
final double PI = 3.14159;
// PI = 3.0; // ERROR: cannot assign a value to final variable

2. final Method
Cannot be overridden in a subclass.
class Parent {
final void display() { [Link]("Parent display"); }
}
class Child extends Parent {
// void display() {} // ERROR: cannot override final method
}

3. final Class
Cannot be subclassed (inherited).
final class MathUtils {
static int square(int n) { return n * n; }
}
// class AdvancedMath extends MathUtils { } // ERROR

4. final Parameter
A method parameter declared final cannot be modified inside the method.
void greet(final String name) {
// name = "New"; // ERROR
[Link]("Hello " + name);
}

5. Blank final Variable


Declared without initialization, must be assigned in the constructor.
class Circle {
final double radius; // blank final
Circle(double r) { [Link] = r; } // must initialize here
}

UNIT – IV: Packages, I/O, Collections & Wrapper Classes

Q1. Explain the steps involved in creating and working with user-defined packages with
an example.

A package in Java is a namespace that groups related classes and interfaces. User-defined packages
help organize code and prevent naming conflicts.

Steps to Create a User-Defined Package


• Step 1: Declare the package at the top of the source file using: package packageName;
• Step 2: Define the class inside the package.
• Step 3: Compile with: javac -d . [Link] (creates folder structure)
• Step 4: In another file, import the package: import [Link];
• Step 5: Compile and run the main file.

Example:
File: mypackage/[Link]
package mypackage;

public class Calculator {


public int add(int a, int b) { return a + b; }
public int multiply(int a, int b) { return a * b; }
public double divide(double a, double b) {
if (b == 0) throw new ArithmeticException("Divide by zero");
return a / b;
}
}
File: [Link]
import [Link];

public class Main {


public static void main(String[] args) {
Calculator c = new Calculator();
[Link]("Sum: " + [Link](10, 5));
[Link]("Product: " + [Link](4, 3));
[Link]("Division: " + [Link](10, 2));
}
}
Compile: javac -d . mypackage/[Link] && javac [Link] && java Main

Q2. Discuss access control for class members across different packages. Illustrate with
examples.

Java provides four access modifiers to control the visibility of class members:
• private: Accessible only within the same class.
• default (no modifier): Accessible within the same package only.
• protected: Accessible within same package AND subclasses in other packages.
• public: Accessible from anywhere.

Access Control Table


• private: Same class only.
• default: Same package only.
• protected: Same package + subclasses (any package).
• public: Everywhere.
// package pack1
package pack1;
public class Parent {
private int priv = 1; // only in Parent
int def = 2; // only in pack1
protected int prot = 3; // pack1 + subclasses
public int pub = 4; // everywhere
}

// package pack2
package pack2;
import [Link];
public class Child extends Parent {
void test() {
// [Link](priv); // ERROR: private
// [Link](def); // ERROR: default
[Link](prot); // OK: protected + subclass
[Link](pub); // OK: public
}
}
Q3. Write a Java program to copy Even numbers into [Link] file and Odd Numbers
into [Link] file.
import [Link].*;

public class EvenOddFiles {


public static void main(String[] args) throws IOException {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

BufferedWriter evenWriter =
new BufferedWriter(new FileWriter("[Link]"));
BufferedWriter oddWriter =
new BufferedWriter(new FileWriter("[Link]"));

for (int num : numbers) {


if (num % 2 == 0) {
[Link](num + "\n");
} else {
[Link](num + "\n");
}
}
[Link]();
[Link]();
[Link]("Even numbers written to [Link]");
[Link]("Odd numbers written to [Link]");
}
}
[Link] contains: 2, 4, 6, 8, 10. [Link] contains: 1, 3, 5, 7, 9

Q4. Briefly explain FileReader, FileWriter, BufferedReader, and BufferedWriter.

1. FileReader
FileReader is a character-based input stream used to read character data from a file. Reads one
character at a time.
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) [Link]((char) ch);
[Link]();

2. FileWriter
FileWriter is a character-based output stream used to write character data to a file. Creates or overwrites
the file.
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello, Java!");
[Link]();

3. BufferedReader
BufferedReader wraps a Reader to provide buffered character input. The readLine() method reads a full
line at a time, making I/O faster.
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) [Link](line);
[Link]();

4. BufferedWriter
BufferedWriter wraps a Writer for buffered output. Provides write() and newLine() methods for efficient
file writing.
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));
[Link]("First Line");
[Link]();
[Link]("Second Line");
[Link]();
Buffered streams improve performance by reducing the number of actual disk I/O operations.

Q5. Discuss in detail about various Wrapper classes available in Java with suitable
examples.

Wrapper classes convert Java primitive types into objects. They are in the [Link] package. Each
primitive type has a corresponding wrapper class:
• byte → Byte
• short → Short
• int → Integer
• long → Long
• float → Float
• double → Double
• char → Character
• boolean → Boolean

Need for Wrapper Classes


• Collections (ArrayList, etc.) work only with objects, not primitives.
• Utility methods for parsing, converting types.
• Autoboxing and Unboxing.

Autoboxing and Unboxing


int a = 10;
Integer obj = a; // Autoboxing (primitive → object)
int b = obj; // Unboxing (object → primitive)

Key Methods of Integer Class


int n = [Link]("42"); // String to int
String s = [Link](42); // int to String
int max = Integer.MAX_VALUE; // 2147483647
int min = Integer.MIN_VALUE; // -2147483648
int bin = [Link]("1010", 2); // binary to decimal = 10
String hex = [Link](255); // "ff"

Example Program
import [Link];
public class WrapperDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
[Link](10); [Link](20); [Link](30); // autoboxing
for (int x : list) [Link](x + " "); // unboxing
[Link]();
Double d = [Link]("3.14");
[Link]("Parsed double: " + d);
[Link]("Max int: " + Integer.MAX_VALUE);
}
}

Q6. Write a Java program to illustrate the usage of protected members in a package.
// File: pack1/[Link]
package pack1;
public class ParentClass {
protected String name = "Java";
protected void display() {
[Link]("Protected method: " + name);
}
}

// File: pack2/[Link]
package pack2;
import [Link];
public class ChildClass extends ParentClass {
public void access() {
name = "Java Programming"; // can access protected variable
display(); // can call protected method
[Link]("Name from child: " + name);
}
}

// File: pack2/[Link]
package pack2;
public class TestProtected {
public static void main(String[] args) {
ChildClass c = new ChildClass();
[Link]();
}
}

Q7. Write a Java program to read and display student details stored in a Collection
using the Iterator interface.
import [Link].*;

class Student {
int rollNo; String name; double marks;
Student(int r, String n, double m) { rollNo=r; name=n; marks=m; }
public String toString() {
return "Roll: " + rollNo + " | Name: " + name + " | Marks: " + marks;
}
}

public class StudentIterator {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
[Link](new Student(101, "Alice", 88.5));
[Link](new Student(102, "Bob", 75.0));
[Link](new Student(103, "Carol", 92.3));
[Link](new Student(104, "David", 65.8));

[Link]("Student Details:");
[Link]("-----------------------------------");
Iterator<Student> it = [Link]();
while ([Link]()) {
Student s = [Link]();
[Link](s);
}
}
}

Q8. Explain ArrayList and LinkedList. Compare their features, performance, and
applications.

ArrayList
ArrayList is a resizable array implementation of the List interface. Internally uses a dynamic array.
• Fast random access: O(1) using index.
• Slow insertion/deletion in middle: O(n) due to shifting.
• Better for read-heavy operations.
ArrayList<String> list = new ArrayList<>();
[Link]("Apple"); [Link]("Banana"); [Link]("Cherry");
[Link]([Link](1)); // Banana
[Link]("Banana");

LinkedList
LinkedList is a doubly linked list implementation of List and Deque interfaces.
• Slow random access: O(n) - must traverse from head.
• Fast insertion/deletion: O(1) at beginning and end.
• Better for frequent insert/delete operations.
• Can also be used as Queue, Deque, Stack.
LinkedList<String> ll = new LinkedList<>();
[Link]("A"); [Link]("Z"); [Link]("M");
[Link]([Link]()); // Z
[Link]();

Comparison
• Underlying structure: ArrayList uses dynamic array; LinkedList uses doubly-linked nodes.
• get(index): ArrayList O(1) vs LinkedList O(n).
• add/remove (middle): ArrayList O(n) vs LinkedList O(1).
• Memory: ArrayList less overhead; LinkedList more (each node has prev/next pointers).
• Use ArrayList when: frequent reads, random access needed.
• Use LinkedList when: frequent insertions/deletions, used as queue/stack.

Q9. Explain Comparable and Comparator interfaces with suitable examples.

Comparable Interface
Comparable ([Link]) is used to define natural ordering of objects. The class must implement the
compareTo() method.
class Student implements Comparable<Student> {
String name; int marks;
Student(String n, int m) { name = n; marks = m; }
public int compareTo(Student other) {
return [Link] - [Link]; // ascending by marks
}
public String toString() { return name + "(" + marks + ")"; }
}
// [Link](list); // uses compareTo

Comparator Interface
Comparator ([Link]) is used to define custom/multiple orderings without modifying the class. Implement
the compare() method.
import [Link].*;
class NameComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return [Link]([Link]); // alphabetical by name
}
}
// [Link](list, new NameComparator());
// Or using lambda: [Link]((a,b) -> [Link]([Link]));

Key Differences
• Comparable: in [Link], single natural ordering, modifies class, uses compareTo.
• Comparator: in [Link], multiple custom orderings, external class, uses compare.

Q10. Explain about HashSet and TreeSet. How do they store elements and maintain
uniqueness?

HashSet
HashSet implements Set interface using a hash table. Stores elements in no particular order and does
not allow duplicates.
• Allows one null element.
• O(1) for add, remove, contains (average).
• No guaranteed insertion or sorted order.
HashSet<String> hs = new HashSet<>();
[Link]("Banana"); [Link]("Apple"); [Link]("Cherry"); [Link]("Apple");
[Link](hs); // [Apple, Cherry, Banana] (unordered)
// 'Apple' added only once - duplicate ignored

How HashSet Maintains Uniqueness


When adding an element, HashSet calls hashCode() to find the bucket, then uses equals() to check for
duplicates. If a matching element exists, the new element is rejected.

TreeSet
TreeSet implements SortedSet interface using a Red-Black Tree. Stores elements in sorted (ascending)
order.
• Does NOT allow null elements.
• O(log n) for add, remove, contains.
• Elements are always in sorted order.
• Supports range operations: headSet(), tailSet(), subSet().
TreeSet<Integer> ts = new TreeSet<>();
[Link](50); [Link](10); [Link](30); [Link](10); [Link](40);
[Link](ts); // [10, 30, 40, 50] (sorted, no duplicate)
[Link]([Link]()); // 10
[Link]([Link]()); // 50

Comparison
• HashSet: Unordered, O(1) ops, allows 1 null, uses hashCode/equals.
• TreeSet: Sorted order, O(log n) ops, no null, uses Comparable/Comparator.

UNIT – V: Exception Handling, Multithreading & JDBC

Q1. What are the five keywords used in Java exception handling? Explain their usage
with code snippets.

Java exception handling uses five keywords: try, catch, finally, throw, and throws.

1. try
Encloses the code that might throw an exception.
try {
int result = 10 / 0; // might throw ArithmeticException
}

2. catch
Handles the specific exception thrown in the try block.
catch (ArithmeticException e) {
[Link]("Error: " + [Link]()); // / by zero
}

3. finally
Always executes after try-catch, regardless of whether an exception occurred. Used for cleanup (closing
files, connections, etc.).
finally {
[Link]("Finally block always runs");
}

4. throw
Used to explicitly throw an exception (user-defined or predefined).
void checkAge(int age) {
if (age < 18) throw new IllegalArgumentException("Under age");
}

5. throws
Declares that a method may throw certain checked exceptions. The caller must handle them.
void readFile(String path) throws IOException {
FileReader fr = new FileReader(path); // may throw IOException
}

Complete Example:
public class ExceptionDemo {
static void divide(int a, int b) throws ArithmeticException {
if (b == 0) throw new ArithmeticException("Cannot divide by 0");
[Link]("Result: " + (a / b));
}
public static void main(String[] args) {
try {
divide(10, 2);
divide(10, 0);
} catch (ArithmeticException e) {
[Link]("Caught: " + [Link]());
} finally {
[Link]("Done");
}
}
}

Q2. Explain multiple catch clauses in Java and write a program to illustrate handling
different exceptions using multiple catch blocks.

Java allows multiple catch blocks for a single try block, each handling a different type of exception. The
JVM matches the exception to the first compatible catch block from top to bottom.

Rules
• More specific (child) exceptions must be caught before more general (parent) ones.
• Java 7+ allows multi-catch: catch (IOException | SQLException e)
• At most one catch block executes per exception.
import [Link];
import [Link];

public class MultipleCatch {


public static void main(String[] args) {
int[] arr = {10, 20, 30};
String str = null;
try {
[Link](arr[5]); // ArrayIndexOutOfBoundsException
int result = 10 / 0; // ArithmeticException
[Link]([Link]()); // NullPointerException
int n = [Link]("abc"); // NumberFormatException
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array error: " + [Link]());
}
catch (ArithmeticException e) {
[Link]("Arithmetic error: " + [Link]());
}
catch (NullPointerException e) {
[Link]("Null pointer error");
}
catch (NumberFormatException e) {
[Link]("Number format error: " + [Link]());
}
catch (Exception e) { // catch-all for any other exception
[Link]("General error: " + [Link]());
}
finally {
[Link]("Program execution complete");
}
}
}

Q3. Write a Java program to explain user-defined Exceptions.

User-defined (custom) exceptions extend the Exception class (for checked) or RuntimeException class
(for unchecked). They allow meaningful, domain-specific error messages.
// Custom checked exception
class InsufficientBalanceException extends Exception {
double amount;
InsufficientBalanceException(double amount) {
super("Insufficient balance! Needed: " + amount);
[Link] = amount;
}
}

class BankAccount {
String owner; double balance;
BankAccount(String owner, double balance) {
[Link] = owner; [Link] = balance;
}
void withdraw(double amount) throws InsufficientBalanceException {
if (amount > balance) {
throw new InsufficientBalanceException(amount);
}
balance -= amount;
[Link]("Withdrew %.2f. New balance: %.2f%n", amount, balance);
}
}

public class CustomExceptionDemo {


public static void main(String[] args) {
BankAccount acc = new BankAccount("Alice", 1000.0);
try {
[Link](500); // OK
[Link](800); // throws exception
} catch (InsufficientBalanceException e) {
[Link]("Error: " + [Link]());
}
}
}

Q4. What are unchecked exceptions in Java? Explain the commonly used built-in
unchecked exceptions with examples.

Unchecked exceptions (also called runtime exceptions) are subclasses of RuntimeException. They are
not checked at compile time — the compiler does not force you to handle or declare them. They typically
represent programming errors.

1. ArithmeticException
int x = 10 / 0; // ArithmeticException: / by zero

2. NullPointerException
String s = null;
[Link]([Link]()); // NullPointerException

3. ArrayIndexOutOfBoundsException
int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBoundsException

4. NumberFormatException
int n = [Link]("abc"); // NumberFormatException

5. ClassCastException
Object obj = "Hello";
Integer i = (Integer) obj; // ClassCastException

6. StackOverflowError
void recurse() { recurse(); } // StackOverflowError

7. IllegalArgumentException
void setAge(int age) {
if (age < 0) throw new IllegalArgumentException("Invalid age");
}

8. StringIndexOutOfBoundsException
String s = "Java";
char c = [Link](10); // StringIndexOutOfBoundsException
Best practice: Fix the logic to avoid unchecked exceptions rather than just catching them.

Q5. Write a Java Program to Solve Producer-Consumer problem using synchronization


and Inter Thread Communication.
class SharedBuffer {
int item;
boolean hasItem = false;

synchronized void produce(int val) throws InterruptedException {


while (hasItem) wait(); // wait if buffer full
item = val;
hasItem = true;
[Link]("Produced: " + val);
notify(); // notify consumer
}

synchronized int consume() throws InterruptedException {


while (!hasItem) wait(); // wait if buffer empty
hasItem = false;
[Link]("Consumed: " + item);
notify(); // notify producer
return item;
}
}

class Producer extends Thread {


SharedBuffer buf;
Producer(SharedBuffer b) { buf = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
try { [Link](i); [Link](500); }
catch (InterruptedException e) { [Link](); }
}
}
}

class Consumer extends Thread {


SharedBuffer buf;
Consumer(SharedBuffer b) { buf = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
try { [Link](); [Link](600); }
catch (InterruptedException e) { [Link](); }
}
}
}

public class ProducerConsumerDemo {


public static void main(String[] args) {
SharedBuffer buffer = new SharedBuffer();
new Producer(buffer).start();
new Consumer(buffer).start();
}
}

Q6. Illustrate JDBC architecture with a neat sketch.

JDBC (Java Database Connectivity) is an API that enables Java applications to interact with relational
databases. It provides a standard interface for database operations regardless of the database vendor.

JDBC Architecture Components


1. Java Application
The program that initiates database requests through JDBC API calls.

2. JDBC API
Provides classes and interfaces (in [Link] and [Link]): DriverManager, Connection, Statement,
PreparedStatement, ResultSet, CallableStatement.

3. JDBC Driver Manager


Manages a list of database drivers. Matches connection requests from Java applications to the proper
database driver.

4. JDBC Driver
A driver translates JDBC calls into database-specific protocol. Types: Type 1 (JDBC-ODBC Bridge), Type
2 (Native API), Type 3 (Network Protocol), Type 4 (Thin/Pure Java — most common).

5. Database
The actual database server (MySQL, Oracle, PostgreSQL, etc.) that executes the SQL queries.

JDBC Architecture Diagram


┌──────────────────────────────────────────────────┐
│ Java Application │
└─────────────────────┬────────────────────────────┘
│ uses
┌─────────────────────▼────────────────────────────┐
│ JDBC API │
│ (DriverManager, Connection, Statement, ResultSet) │
└─────────────────────┬────────────────────────────┘

┌─────────────────────▼────────────────────────────┐
│ JDBC Driver Manager │
└─────────────────────┬────────────────────────────┘
│ selects
┌─────────────────────▼────────────────────────────┐
│ JDBC Driver (Type 4) │
│ (e.g., MySQL Connector/J) │
└─────────────────────┬────────────────────────────┘
│ connects
┌─────────────────────▼────────────────────────────┐
│ Database │
│ (MySQL / Oracle / PostgreSQL) │
└──────────────────────────────────────────────────┘

Q7. Write a Java program to create threads by extending Thread class — three threads
displaying Good Morning, Hello, and Welcome at different intervals. (Also using
Runnable Interface)

Method 1: Extending Thread Class


class GoodMorningThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Good Morning!");
try { [Link](1000); } // 1 second
catch (InterruptedException e) { }
}
}
}
class HelloThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Hello!");
try { [Link](2000); } // 2 seconds
catch (InterruptedException e) { }
}
}
}
class WelcomeThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Welcome!");
try { [Link](3000); } // 3 seconds
catch (InterruptedException e) { }
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
new GoodMorningThread().start();
new HelloThread().start();
new WelcomeThread().start();
}
}

Method 2: Implementing Runnable Interface


class MessageRunnable implements Runnable {
String message; int interval;
MessageRunnable(String msg, int interval) {
[Link] = msg; [Link] = interval;
}
public void run() {
for (int i = 0; i < 5; i++) {
[Link](message);
try { [Link](interval); }
catch (InterruptedException e) { }
}
}
}
public class RunnableDemo {
public static void main(String[] args) {
new Thread(new MessageRunnable("Good Morning", 1000)).start();
new Thread(new MessageRunnable("Hello", 2000)).start();
new Thread(new MessageRunnable("Welcome", 3000)).start();
}
}

Q8. Write the steps involved in setting up the JDBC environment for developing Java
database applications.

Steps to Set Up JDBC Environment


• Step 1 - Install Java Development Kit (JDK): Ensure JDK (version 8 or above) is installed. Set
JAVA_HOME environment variable.
• Step 2 - Install Database Server: Install a database like MySQL, PostgreSQL, or Oracle. Create
a database and tables.
• Step 3 - Download JDBC Driver: Download the JDBC driver (e.g., [Link] for
MySQL) from the vendor website.
• Step 4 - Add Driver to Classpath: Add the .jar file to the project classpath: javac -cp .;mysql-
[Link] [Link]
• Step 5 - Load the JDBC Driver: (Optional from JDBC 4.0)
[Link]("[Link]");
• Step 6 - Establish Connection: Connection conn = [Link](url, user,
password);
• Step 7 - Create Statement: Statement stmt = [Link]();
• Step 8 - Execute Query: ResultSet rs = [Link]("SELECT * FROM students");
• Step 9 - Process Results: while([Link]()) { [Link]([Link]("name")); }
• Step 10 - Close Resources: [Link](); [Link](); [Link]();

Complete Example:
import [Link].*;
public class JDBCSetup {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/school";
Connection conn = [Link](url, "root", "pass");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM students");
while ([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
[Link](); [Link](); [Link]();
}
}

Q9. Discuss in detail about various types of JDBC drivers available in Java with suitable
examples.

JDBC drivers translate JDBC calls into database-specific network protocols or native library calls. There
are four types:

Type 1: JDBC-ODBC Bridge Driver


• Translates JDBC calls to ODBC calls using ODBC driver.
• Requires ODBC to be installed on client machine.
• Platform dependent, slow, not recommended for production.
• Removed from Java 8 onwards.
[Link]("[Link]"); // Type 1

Type 2: Native API (Partly Java) Driver


• Converts JDBC calls to database vendor-specific native (C/C++) API calls.
• Faster than Type 1 but requires native libraries on client.
• Platform dependent.

Type 3: Network Protocol (Middleware) Driver


• Translates JDBC calls into a database-independent middleware protocol.
• Middleware server converts them to database-specific protocol.
• Pure Java, platform independent, good for applets.
• Requires middleware server to be installed.

Type 4: Thin Driver (Pure Java Driver) — Most Used


• Directly converts JDBC calls to database vendor-specific network protocol.
• 100% Java, no native library or middleware required.
• Platform independent, fast, widely used in production.
• Examples: MySQL Connector/J, PostgreSQL JDBC Driver, Oracle Thin Driver.
// Type 4 example - MySQL
[Link]("[Link]");
Connection conn = [Link](
"jdbc:mysql://localhost:3306/mydb", "root", "password");
Recommendation: Always use Type 4 (Thin) drivers for modern Java database applications — they are
portable, efficient, and don't require any additional software on the client machine.

Q10. Define synchronization in Java. Discuss its importance in multithreaded


programming and explain how it is achieved using synchronized methods and blocks.
What is Synchronization?
Synchronization is the capability to control the access of multiple threads to shared resources. When
multiple threads access shared data simultaneously, it can lead to data inconsistency — this is called a
race condition. Synchronization prevents this by allowing only one thread to access the shared resource
at a time.

Importance
• Prevents race conditions and data corruption.
• Ensures thread safety for shared resources.
• Maintains consistency of shared data.
• Enables inter-thread communication via wait(), notify(), notifyAll().

1. Synchronized Method
Declaring a method with the synchronized keyword ensures only one thread can execute it at a time.
class Counter {
private int count = 0;
synchronized void increment() { // only 1 thread at a time
count++;
}
int getCount() { return count; }
}
public class SyncDemo {
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Thread t1 = new Thread(() -> { for(int i=0;i<1000;i++) [Link](); });
Thread t2 = new Thread(() -> { for(int i=0;i<1000;i++) [Link](); });
[Link](); [Link]();
[Link](); [Link]();
[Link]("Count: " + [Link]()); // Always 2000
}
}

2. Synchronized Block
Synchronizes only a specific block of code rather than the entire method. This is more efficient when only
a portion of the method needs synchronization.
class Printer {
void printDoc(String doc) {
[Link]("Preparing document...");
synchronized(this) { // only this block is synchronized
[Link]("Printing: " + doc);
try { [Link](500); } catch (InterruptedException e) {}
}
[Link]("Done.");
}
}

Key Points
• Every Java object has an intrinsic lock (monitor). synchronized acquires this lock.
• wait(), notify(), notifyAll() must be called from synchronized context.
• Over-synchronization reduces performance — use only when necessary.

You might also like