0% found this document useful (0 votes)
41 views15 pages

Java Key Answers

The document provides a comprehensive overview of Java programming concepts, including type casting, method binding, error handling, byte streams, packages, collection interfaces, thread synchronization, JDBC drivers, mouse events, and the delegation event model. It includes definitions, comparisons, examples, and explanations of various Java features and functionalities. Additionally, it presents code snippets to illustrate concepts such as exception handling, file I/O, and event handling.

Uploaded by

kathularajitha7
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)
41 views15 pages

Java Key Answers

The document provides a comprehensive overview of Java programming concepts, including type casting, method binding, error handling, byte streams, packages, collection interfaces, thread synchronization, JDBC drivers, mouse events, and the delegation event model. It includes definitions, comparisons, examples, and explanations of various Java features and functionalities. Additionally, it presents code snippets to illustrate concepts such as exception handling, file I/O, and event handling.

Uploaded by

kathularajitha7
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/ 15

Java Key answers

1. (a) Compare Type Casting and Type Conversion


• Type Conversion: Implicit conversion done automatically by the compiler (widening).
• Type Casting: Explicit conversion done by the programmer (narrowing).

(b) Define Method Binding and list the types of binding?


• Method Binding: Process of linking a method call with the method body.
• Types:
1. Static Binding (Early Binding)
2. Dynamic Binding (Late Binding)

(c) Compare Error and Exception


• Error: Serious problems beyond program control (e.g., OutOfMemoryError).
• Exception: Problems that can be handled in code using try-catch (e.g., IOException).

(d) Write a short note on Byte Stream


• Byte streams handle I/O of raw binary data (8-bit data).
• Example: FileInputStream, FileOutputStream.

(e) Define Package


• A package is a collection of related classes and interfaces in Java.
• Used for modularization and namespace management.

(f) Explain about StringTokenizer


• StringTokenizer is a utility class in java.util that splits a string into tokens based
on delimiters.

(g) What is the difference between Statement and PreparedStatement?


• Statement: Executes simple SQL queries without parameters.
• PreparedStatement: Precompiled, supports parameters, prevents SQL injection.
Java Key answers

(h) How does Java support inter-thread communication?


• Java supports inter-thread communication using wait(), notify(), notifyAll()
methods of the Object class.

(i) Explain hierarchy of AWT Container classes


• Hierarchy:
• Component → Container → Panel → Applet

• Container → Window → Frame → Dialog

(j) Give the hierarchy for Swing components


• Hierarchy:
• Component → Container → JComponent → Swing components (JButton,
JLabel, JTextField, etc.)

Q3. Explain the types of Inheritance used in Java with Neat


Sketch.
Definition
Inheritance in Java is a mechanism by which one class acquires the properties and behaviors (fields
and methods) of another class using the extends keyword.

Types of Inheritance in Java


1. Single Inheritance
• A subclass inherits from one superclass.
class A { }
class B extends A { }

Example: Class B inherits from Class A.

2. Multilevel Inheritance
• A class is derived from another class, which is also derived from another.
class A { }
class B extends A { }
class C extends B { }
Java Key answers

Example: A → B → C.

3. Hierarchical Inheritance
• Multiple classes inherit from a single parent class.
class A { }
class B extends A { }
class C extends A { }

Example: Both B and C inherit from A.

4. Hybrid Inheritance (Combination)


• A mix of above types, but Java does not support multiple inheritance with classes
to avoid ambiguity (diamond problem).
• Achieved using interfaces.

5. Multiple Inheritance (via Interfaces)


• A class can implement multiple interfaces.
interface X { }
interface Y { }
class A implements X, Y { }

Example: Class A implements both X and Y.

Neat Sketch (Hierarchy Diagram)


A
/ \
B C (Hierarchical)
|
D (Multilevel)

Q3 (OR). Explain the Types of Operators used in Java in


Detail.
Definition
Operators in Java are special symbols that perform operations on variables and values.
Java Key answers

Types of Operators in Java


1. Arithmetic Operators
• + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus).
int a = 10, b = 5;
System.out.println(a + b); // 15

2. Relational Operators
• Compare two values: ==, !=, <, >, <=, >=.
if(a > b) System.out.println("a is greater");

3. Logical Operators
• && (AND), || (OR), ! (NOT).
if(a > 0 && b > 0) System.out.println("Both positive");

4. Assignment Operators
• =, +=, -=, *=, /=, %=.
int c = 10;
c += 5; // c = 15

5. Unary Operators
• ++ (increment), -- (decrement), +, -, !.
int d = 5;
System.out.println(++d); // 6

6. Bitwise Operators
• & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
int x = 5 & 3; // 1

7. Conditional (Ternary) Operator


• condition ? expr1 : expr2
int max = (a > b) ? a : b;
Java Key answers

8. Instanceof Operator
• Tests whether an object is an instance of a specific class.
if(obj instanceof String) { ... }

9. Type Cast Operator


• Converts data from one type to another.
double pi = 3.14;
int n = (int) pi; // Explicit casting

Q4. Write a program that includes a try block and a catch


clause which processes the arithmetic exception generated by
division-by-zero error.
Explanation
• Exception handling in Java is done using try, catch, finally.

• Division by zero generates an ArithmeticException.


• We can handle it gracefully without program crash.

Program
class DivisionExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int result = a / b; // division by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed!");
} finally {
System.out.println("Execution completed.");
}
}
}

Output
Error: Division by zero is not allowed!
Execution completed.
Java Key answers

Q5. Explain the concept of Byte Streams in Java. How are


FileInputStream and FileOutputStream used? Provide
examples.
Byte Streams in Java
• Byte streams handle 8-bit data.
• Used for reading and writing binary data (images, audio, video, executables).
• Main classes:
• FileInputStream (reading from a file).

• FileOutputStream (writing to a file).

• Belong to java.io package.

1. FileInputStream
• Reads bytes from a file.
• Methods:
• int read() → Reads one byte.

• int read(byte[] b) → Reads bytes into array.

• close() → Closes the stream.


Example:
import java.io.*;

class FileReadExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("input.txt");
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
}
fis.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Java Key answers

2. FileOutputStream
• Writes bytes to a file.
• Methods:
• write(int b) → Writes one byte.

• write(byte[] b) → Writes array of bytes.

• close() → Closes the stream.

Example:
import java.io.*;

class FileWriteExample {
public static void main(String[] args) {
try {
FileOutputStream fos = new FileOutputStream("output.txt");
String data = "Hello, Java Byte Streams!";
fos.write(data.getBytes());
fos.close();
System.out.println("Data written successfully.");
} catch (Exception e) {
System.out.println(e);
}
}
}

Advantages of Byte Streams


• Suitable for binary data transfer.
• Can handle any type of file (text, image, audio, etc.).

Q6. How to define a package? How to access, import a


package? Explain with examples.
Definition of Package
• A package in Java is a collection of related classes and interfaces.
• It helps in modularity, reusability, and avoiding name conflicts.
• Declared using the package keyword.

1. Defining a Package
package mypackage;

public class MyClass {


Java Key answers

public void display() {


System.out.println("Hello from MyClass in mypackage!");
}
}

• File should be saved as: mypackage/MyClass.java.

2. Compiling and Creating Package


javac -d . MyClass.java

This creates the mypackage folder with compiled .class files.

3. Accessing a Package
There are three ways to use a package:
1. Importing entire package
import mypackage.*;

class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}

2. Importing a specific class


import mypackage.MyClass;

3. Using fully qualified name


class Test {
public static void main(String[] args) {
mypackage.MyClass obj = new mypackage.MyClass();
obj.display();
}
}

Advantages of Packages
• Avoids name conflicts.
• Easier to maintain large projects.
• Provides access protection (public, protected, etc.).

• Supports reusability.
Java Key answers

Q7. Describe the Collection Interfaces in Java. Explain the


characteristics and use-cases of each.
Definition
• The Collections Framework in Java (java.util package) provides a set of interfaces
and classes for storing and manipulating groups of objects.

Main Collection Interfaces


1. Collection (root interface)
• Base interface for all collections.
• Methods: add(), remove(), size(), iterator().

2. List Interface
• Ordered collection (allows duplicates).
• Index-based access.
• Implementations: ArrayList, LinkedList, Vector.

• Use-case: When order matters (e.g., student roll numbers).

3. Set Interface
• Unordered collection, no duplicates.
• Implementations: HashSet, LinkedHashSet, TreeSet.

• Use-case: Storing unique items (e.g., employee IDs).

4. Queue Interface
• Follows FIFO (First-In-First-Out) order.
• Implementations: PriorityQueue, ArrayDeque.

• Use-case: Task scheduling, buffering.

5. Deque Interface (Double-Ended Queue)


Java Key answers

• Elements can be inserted/removed at both ends.


• Implementation: ArrayDeque.

• Use-case: Undo/Redo operations.

6. Map Interface (not child of Collection, but part of framework)


• Stores key-value pairs (like dictionary).
• Keys are unique, values can be duplicate.
• Implementations: HashMap, LinkedHashMap, TreeMap, Hashtable.

• Use-case: Storing student roll number → name.

Diagram (Hierarchy)
Collection
|-- List (ArrayList, LinkedList, Vector)
|-- Set (HashSet, LinkedHashSet, TreeSet)
|-- Queue (PriorityQueue, ArrayDeque)

Map (HashMap, TreeMap, LinkedHashMap, Hashtable)

Q8. Analyze the need of thread synchronization. How is it


achieved in Java programming? Explain with a suitable
program.
Need for Synchronization
• In multithreading, multiple threads access shared resources (variables, objects, files).
• Without synchronization, this causes data inconsistency and race conditions.
• Example: Two threads updating a bank balance simultaneously may cause wrong results.

How Synchronization is Achieved in Java


1. Synchronized method → Declaring methods with synchronized keyword.

2. Synchronized block → Synchronizing only a part of code.


3. Static synchronization → Synchronizing static methods.

Program (Bank Example)


class Bank {
Java Key answers

private int balance = 1000;

synchronized void withdraw(int amount) {


if (balance >= amount) {
System.out.println(Thread.currentThread().getName() + " withdrawing
" + amount);
balance -= amount;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println("Insufficient funds for " +
Thread.currentThread().getName());
}
}
}

class Customer extends Thread {


Bank bank;
int amount;

Customer(Bank b, int amt, String name) {


super(name);
bank = b;
amount = amt;
}

public void run() {


bank.withdraw(amount);
}
}

public class SyncExample {


public static void main(String[] args) {
Bank bank = new Bank();
Customer c1 = new Customer(bank, 700, "Customer-1");
Customer c2 = new Customer(bank, 500, "Customer-2");

c1.start();
c2.start();
}
}

Output (Sample)
Customer-1 withdrawing 700
Remaining balance: 300
Insufficient funds for Customer-2
Java Key answers

Q9. Explain the different types of JDBC drivers in detail.


Compare their advantages and disadvantages.
Definition
• JDBC (Java Database Connectivity) drivers are used to connect Java applications with
databases.
• Four types exist.

Types of JDBC Drivers


1. Type-1: JDBC-ODBC Bridge Driver
• Translates JDBC calls into ODBC calls.
• Requires ODBC installed.
• Advantage: Easy to use, good for prototyping.
• Disadvantage: Slow, platform-dependent, deprecated.

2. Type-2: Native-API Driver


• Converts JDBC calls into database-specific native API calls.
• Advantage: Faster than Type-1.
• Disadvantage: Requires native DB libraries, not portable.

3. Type-3: Network Protocol Driver


• Uses middleware server to translate JDBC calls into DB-specific protocol.
• Advantage: No client-side libraries required.
• Disadvantage: Middleware increases overhead.

4. Type-4: Thin Driver (Pure Java)


• Converts JDBC calls directly into database protocol using Java.
• Advantage: Platform-independent, fastest, widely used.
• Disadvantage: Database-specific implementation needed.
Java Key answers

Comparison Table
Driver Type Speed Portability Requirement Status
Type-1 (Bridge) Slow Low ODBC driver Deprecated
Type-2 (Native) Faster Medium Native libs Not portable
Type-3 (Network) Medium High Middleware Rare use
Type-4 (Thin) Fastest High Pure Java Most used

Q10. Write a Java program to demonstrate the handling


Mouse events. [10M]
Concept
• Mouse events are handled in Java using MouseListener and
MouseMotionListener interfaces.

• Events include: mouseClicked, mousePressed, mouseReleased,


mouseEntered, mouseExited, mouseDragged, mouseMoved.

Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventDemo extends JFrame implements MouseListener,


MouseMotionListener {
JLabel label;

MouseEventDemo() {
label = new JLabel("Perform Mouse Actions");
label.setBounds(50, 50, 200, 30);
add(label);

addMouseListener(this);
addMouseMotionListener(this);

setSize(400, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void mouseClicked(MouseEvent e) { label.setText("Mouse Clicked"); }


public void mousePressed(MouseEvent e) { label.setText("Mouse Pressed"); }
public void mouseReleased(MouseEvent e) { label.setText("Mouse Released"); }
public void mouseEntered(MouseEvent e) { label.setText("Mouse Entered
Window"); }
Java Key answers

public void mouseExited(MouseEvent e) { label.setText("Mouse Exited


Window"); }
public void mouseDragged(MouseEvent e) { label.setText("Mouse Dragged"); }
public void mouseMoved(MouseEvent e) { label.setText("Mouse Moved"); }

public static void main(String[] args) {


new MouseEventDemo();
}
}

Q11. With neat sketch explain Delegation Event Model and


Write a program for events implementing the event delegation
model.
Delegation Event Model (DEM)
• Used in Java AWT/Swing for event handling.
• Three components:
1. Event Source → Component that generates event (e.g., button).
2. Event Object → Encapsulates event details (ActionEvent, MouseEvent).

3. Event Listener → Object that receives event and defines its handling.

Diagram (Sketch)
[Event Source] ---- generates ---> [Event Object] ---- sent to ---> [Event
Listener]

Steps in DEM
1. User performs action (e.g., clicks button).
2. Event Source creates an Event Object.
3. Event Object is passed to registered Listener.
4. Listener executes event-handling code.

Program (Button Example)


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DEMExample extends JFrame implements ActionListener {


Java Key answers

JButton btn;
JLabel label;

DEMExample() {
btn = new JButton("Click Me");
label = new JLabel("No Action Yet");

btn.setBounds(100, 100, 100, 40);


label.setBounds(100, 150, 200, 30);

add(btn); add(label);

btn.addActionListener(this); // Register listener

setSize(400, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


label.setText("Button Clicked! Event handled.");
}

public static void main(String[] args) {


new DEMExample();
}
}

You might also like