JAVA_sem ans
JAVA_sem ans
class Example {
static int counter = 0;
}
o Static Methods: These methods belong to the class, not to any
specific instance, so they can be called directly on the class itself.
Static methods cannot access non-static (instance) variables
directly.
class Example {
static void display() {
System.out.println("Static method");
}
}
o Static Blocks: Static blocks execute when the class is first loaded.
They are typically used for static initialization of variables.
class Example {
static int count;
static {
count = 10;
}
1
}
o Static Nested Classes: A static class within a class can access only
static members of the outer class. It helps in logically grouping
classes and controlling the visibility of inner classes.
class Outer {
static class Inner {
void display() {
System.out.println("Static Nested Class");
}
}
}
2
defined by the class. Each object has its own set of values for the
fields defined in the class.
Jagged arrays, also known as arrays of varying lengths, are arrays where
each row can have a different number of elements. In Java, a jagged array
is created by defining an array of arrays, where each sub-array can be of
different length. This structure is useful for representing data that
naturally fits an irregular grid.
3
1f) Explain why abstract classes are used in Java.
Abstract classes are used in Java to provide a base for other classes to extend
and to enforce a particular structure for subclasses. They are especially useful
when creating a hierarchy of classes with shared behavior, but where some
methods may not have a meaningful default implementation. Abstract classes
can contain both abstract methods (which subclasses must implement) and
concrete methods (which provide a default implementation).
Packages are used to organize classes and interfaces in a structured way, often
reflecting the project’s structure or functionality. To define a package, the
package keyword is used at the top of the Java file, followed by the package
name. This not only helps in organizing code but also prevents naming
conflicts by creating unique namespaces.
package com.example.project;
public class MyClass {
// Class implementation
}
4
After defining a package, the class can be accessed in other parts of the
project by importing the package or using the full package name.
1h) Explain the use of try, catch, and finally blocks in Java.
o try block: This block contains code that may throw an exception.
o catch block: When an exception occurs in the try block, it is
caught by the appropriate catch block. Each catch block can
handle a specific type of exception.
o finally block: This block executes regardless of whether an
exception occurred. It’s useful for cleanup operations, like closing
resources.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
The Thread class is the primary way to create and manage threads in Java. A
thread represents a separate path of execution in a program. You can create a
thread by:
o Extending the Thread class and overriding its run method.
5
o Implementing the Runnable interface and passing it to a Thread
instance.
import java.sql.*;
Connection connection = DriverManager.getConnection(url, username,
password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM myTable");
6
Class Definition: The blueprint or structure for the program,
encapsulating data and behaviors.
Main Method: The entry point of the program (public static void
main(String[] args)).
Variables and Data Types: Used to store data and perform
operations.
Statements and Expressions: Instructions that control the flow of
the program, perform calculations, etc.
Comments: For documentation and readability, using // for single-
line comments and /* ... */ for multi-line comments.
1b) Write a Java program to take an integer and a string as input from the
console using the Scanner class.
Here’s a simple program that uses Scanner to take an integer and a string
as input.
import java.util.Scanner;
7
System.out.println("You entered: " + number + " and \"" + text +
"\"");
scanner.close();
}
}
1c) Describe the components that can be part of a Java class, such as
fields, methods, and constructors.
class Animal {
8
void sound() {
System.out.println("Animal sound");
}
}
The super keyword is used in Java to refer to the superclass of the current
class. It has several uses:
Accessing Superclass Methods: super.methodName() can call a
method from the superclass that has been overridden in the
subclass.
Calling Superclass Constructor: super() is used to invoke the
superclass constructor from the subclass constructor.
Accessing Superclass Fields: It allows access to fields in the
superclass when there’s a naming conflict.
class Animal {
String color = "brown";
}
9
class Dog extends Animal {
String color = "black";
void printColor() {
System.out.println(super.color); // Access superclass color
}
}
1f) Define the term "annotation" and list examples of commonly used
annotations in Java.
10
The methods in the Math class are static, allowing for quick access without
creating an instance of the class.
Example Usage:
if (value < 0) {
throw new IllegalArgumentException("Value cannot be negative");
}
11
independent manner. JDBC is widely used for database operations in Java
applications.
javac CommandLineExample.java
2. Run it with command-line arguments:
Command-line arguments:
Argument 0: Hello
Argument 1: World
Argument 2: 123
Explanation:
In this example, args holds the command-line arguments, which are
accessed by their index in the array (args[i]).
13
Using command-line arguments allows flexible input during runtime
without modifying the code.
14
o Needed when converting a larger or more precise data type to a
smaller or less precise one.
o Must be done manually by the programmer to avoid potential
data loss.
o Example: Converting a double to an int.
OR
3. a) Explain the use of the final keyword in Java. What are its implications
when applied to variables, methods, and classes? (5 Marks)
In Java, the final keyword is used to enforce immutability and prevent
modifications to variables, methods, or classes.
1. Final Variable:
o A final variable can only be assigned once; after that, it becomes
a constant.
o Trying to modify a final variable will result in a compilation error.
15
2. Final Method:
o A final method cannot be overridden by subclasses.
o This is often used to prevent altering essential behavior in
subclasses.
class Animal {
public final void makeSound() {
System.out.println("Animal sound");
}
}
16
Implication: Final classes provide security and prevent undesired
modifications in large applications.
Example:
class Car {
private String color;
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
}
Explanation: The color attribute is private, accessed only through getter
and setter methods.
2. Inheritance:
o Allows one class (subclass) to inherit properties and behaviors
(methods) from another class (superclass).
o Supports code reusability and a logical hierarchy of classes.
Example:
17
class Animal {
void eat() { System.out.println("Eating"); }
}
UNIT-2
19
Types of Constructors:
1. Default Constructor: This constructor has no parameters. If no
constructor is defined in a class, Java provides a default constructor
that initializes objects with default values.
class Example {
int value;
// Default Constructor
Example() {
value = 10;
}
}
2. Parameterized Constructor: This constructor takes parameters to
initialize an object with specific values. It provides flexibility to initialize
objects in different ways.
class Example {
int value;
// Parameterized Constructor
Example(int val) {
value = val;
}
}
3. Copy Constructor: This constructor creates an object by copying values
from another object of the same class. Java does not provide an in-built
copy constructor, so it must be defined explicitly.
class Example {
20
int value;
// Copy Constructor
Example(Example e) {
this.value = e.value;
}
}
class Example {
int value;
Example(int value) {
this.value = value; // Refers to instance variable
}
}
2. To call another constructor in the same class: It’s used to invoke a
different constructor within the same class, helping avoid code
duplication.
class Example {
int value;
Example() {
this(10); // Calls the parameterized constructor
}
21
Example(int value) {
this.value = value;
}
}
3. To pass the current object as a parameter: this can be used to pass the
current object as an argument to another method or constructor.
void display(Example e) {
// method body
}
void callDisplay() {
display(this); // Passes the current object
}
4. To return the current instance: It can be used to return the current
instance of a class, often used in method chaining.
Example getInstance() {
return this;
}
OR
22
Key Components of Recursion:
1. Base Case: This is the condition under which the recursive method stops
calling itself, preventing infinite recursion. Without a base case,
recursion would continue indefinitely, leading to a stack overflow error.
2. Recursive Call: In each recursive step, the method calls itself with a
modified parameter, bringing the problem closer to the base case with
each call.
3. Stack Mechanism: When a recursive method calls itself, Java places each
call on the call stack. The stack keeps track of each method call until it
reaches the base case, then it begins to unwind the calls, completing
each one in reverse order.
Example:
A recursive method to calculate the factorial of a number:
class FactorialExample {
// Recursive method to calculate factorial
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
23
}
}
Output:-
Passing by Value means that a copy of the variable is passed, so any changes
made within the method do not affect the original variable.
For primitive data types (like int, float), the value of the variable is
passed, and modifications inside the method do not affect the original
variable.
For objects, the reference (or address) of the object is passed by value.
While the reference itself cannot be changed to point to a different
24
object, the fields within the object can be modified, affecting the
original object.
Example:
class Example {
int data;
void modifyPrimitive(int x) {
x = 20; // Change does not affect the original
}
UNIT-3
25
Using Arrays.copyOf() method:
Using System.arraycopy():
26
6 b) Write different types of inheritance in Java and
give an example for each.
Example:
class Animal {
void eat() {
System.out.println("Eating...");
}
}
o Example:
27
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Animal {
void eat() {
System.out.println("Eating...");
}
28
}
o Example:
interface Animal {
void eat();
}
interface Mammal {
void giveBirth();
}
29
public void eat() {
System.out.println("Eating...");
}
public void giveBirth() {
System.out.println("Giving birth...");
}
}
OR
1. Instantiation:
2. Abstract Methods:
30
o Abstract classes can have abstract methods
(without implementation).
o Concrete classes cannot have abstract methods
(all methods must have implementation).
3. Purpose:
Example:
31
In Java, an interface can be defined within a class
(nested interface). To implement it, a subclass of the
outer class must implement the nested interface.
Example:
class OuterClass {
interface NestedInterface {
void greet();
}
32
UNIT – 4
33
Math.random() – Generates a double value between
0.0 (inclusive) and 1.0 (exclusive).
// Power
System.out.println("2 to the power of 3: " +
Math.pow(2, 3));
// Square root
System.out.println("Square root of 25: " +
Math.sqrt(25));
// Rounding operations
System.out.println("Ceiling of 5.3: " +
Math.ceil(5.3));
System.out.println("Floor of 5.7: " +
Math.floor(5.7));
System.out.println("Round of 5.5: " +
Math.round(5.5));
34
// Trigonometric functions
System.out.println("Sine of 45 degrees: " +
Math.sin(Math.toRadians(45)));
}
}
EXAMPLE:
35
int data = 100 / 0; // This will cause an
ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " +
e.getMessage());
} finally {
System.out.println("This is always executed,
regardless of an exception.");
}
}
}
36
applications with specific requirements, where built-in
exceptions might not be descriptive enough.
Steps to Create and Use a Custom Exception:
1. Define a Custom Exception Class – Extend the
Exception class if it should be a checked exception
(requiring handling) or extend RuntimeException for
an unchecked exception.
2. Use the Custom Exception – Throw the custom
exception when a specific error condition occurs.
Example: Custom Exception for Bank Withdrawal
Imagine a banking application where an exception needs
to be thrown if someone tries to withdraw more money
than is available in their account.
Step 1: Define the custom exception class.
Step 2: Use the custom exception in a method that
performs the withdrawal.
EXAMPLE:
// Define and use a custom exception
class UnderageException extends Exception {
public UnderageException(String message) {
super(message);
}
}
37
if (age < 18) {
throw new UnderageException("You must be at
least 18 to vote.");
}
System.out.println("You are eligible to vote.");
}
Explanation:
1. Custom Exception (InsufficientFundsException) – A
specific exception that represents an insufficient
balance.
2. Withdrawal Method – Checks if the withdrawal
amount exceeds the balance; if it does, throws
InsufficientFundsException.
3. Usage in main Method – Calls withdraw with an
amount exceeding the balance, triggering the
exception and displaying an error message.
38
9. b) Packages in Java
Packages in Java are a way to group related classes and
interfaces, providing a modular structure to Java
applications. They also help in resolving naming
conflicts and controlling access through encapsulation.
Benefits of Using Packages:
1. Organized Codebase – Packages group classes
logically, making it easier to locate and maintain
code.
2. Avoid Naming Conflicts – Different packages can
have classes with the same name without collision.
3. Access Control – By organizing classes into
packages, you can control which classes are
accessible to other parts of the application.
Creating and Using Packages:
1. Defining a Package – Use the package keyword at
the beginning of a Java file.
EXAMPLE:
// File: utilities/MathUtilities.java
package utilities;
39
EXAMPLE:
import utilities.MathUtilities;
40
Example:
42
Issues: Unsafe as it stops a thread without
releasing resources, potentially causing memory
leaks.
Alternative: Use a flag to signal the thread to
terminate gracefully.
Example of Safe Thread Management Using Flags:
Instead of suspend() and resume(), we can use a
boolean flag to control thread execution.
43
public class ThreadExample {
public static void main(String[] args) {
SafeThread thread = new SafeThread();
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stopThread(); // Stops the thread safely
}
}
In this example, stopThread() changes the running flag,
allowing the thread to exit its loop safely.
OR
44
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:33
06/mydb", "user", "password");
2. Connection:
o Role: Represents the connection session with
the database. It allows creating statements and
managing transactions.
o Example:
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:33
06/mydb", "user", "password");
} catch (SQLException e) {
System.out.println("Database connection failed: " +
e.getMessage());
}
These components work together to open a connection,
perform SQL operations, and handle any potential
database-related exceptions.
45
JavaFX provides a modern GUI toolkit with controls for
displaying text and images, such as Label, Text, and
ImageView.
1. Label:
Purpose: Displays a single line of read-only text.
Example:
2. Text:
Purpose: Displays text with more formatting options
and can support multi-line text.
Example:
46
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
47
}
}
MODEL PAPER-2
UNIT-1
48
They do not have a fixed size and are stored in the
heap memory.
Example: String str = "Hello"; stores a reference to
the String object.
Example
public class DataTypesExample {
public static void main(String[] args) {
// Primitive data type
int primitiveInt = 50;
// Reference data type
Integer referenceInt =
Integer.valueOf(50);
// Use primitive data type
System.out.println("Primitive value: " +
primitiveInt);
// Use reference data type
System.out.println("Reference value: " +
referenceInt.toString());
}
}
Output:
Primitive value: 50
Reference value: 50
49
Instead of declaring and initializing a loop counter
variable, you declare a variable that is the same
type as the base type of the array, followed by a
colon, which is then followed by the array name.
In the loop body, you can use the loop variable you
created rather than using an indexed array
element.
Syntax:
for (type var : array)
{
statements using var;
}
50
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}
OR
3a) Role of Each Type of Token in Java:
Keywords:
Keywords are pre-defined or reserved words in a
programming language. Each keyword is meant to
perform a specific function in a program. Since keywords
are referred names for a compiler, they can’t be used as
variable names
Identifiers:
51
Identifiers are used as the general terminology for
naming of variables, functions and arrays. These are
user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the
underscore (_) as a first character. Identifier names must
differ in spelling and case from any keywords.
3. Constants/Literals:
Constants are also like normal variables. But the only
difference is, their values cannot be modified by the
program once they are defined. Constants refer to fixed
values. They are also called as literals.
Syntax:
final data_type variable_name;
4. Comments:
In Java, Comments are the part of the program which are
ignored by the compiler while compiling the Program.
They are useful as they can be used to describe the
operation or methods in the program. The Comments
are classified as follows:
Single Line Comments
Multiline Comments
SYNTAX
// This is a Single Line Comment
/*
52
This is a Multiline Comment
*/
5.Separators:
Separators are used to separate different parts of the
codes. It tells the compiler about completion of a
statement in the program. The most commonly and
frequently used separator in java is semicolon (;).
SYNTAX:
int variable; //here the semicolon (;) ends the
declaration of the variable
SYNTAX:
if (condition) {
// code block
}
if-else statement: Executes one block of code if the
condition is true, and another if the condition is
false.
SYNTAX:
53
if (condition) {
// code block
} else {
// code block
}
SYNTAX:
if (condition1) {
// code block
} else if (condition2) {
// code block
} else {
// code block
}
switch statement: Selects one of many code blocks
to execute based on the value of a variable.
SYNTAX:
switch (variable) {
case value1:
// code block
54
break;
case value2:
// code block
break;
default:
// code block
}
2. Looping (Repetition) Statements:
These are used to repeat a block of code multiple times
based on certain conditions.
for loop: Repeats a block of code a specific number
of times.
SYNTAX:
SYNTAX:
while (condition) {
// code block
}
do-while loop: Executes a block of code once before
checking the condition, and then repeats as long as
the condition is true.
55
SYNTAX:
do {
// code block
} while (condition);
3. Jump Statements:
These are used to transfer control to another part of the
program.
break statement: Exits from a loop or a switch
statement.
SYNTAX:
break;
continue statement: Skips the current iteration of a
loop and continues with the next iteration.
SYNTAX:
continue;
SYNTAX:
56
return;
UNIT-2
4a.) Distinguish Between Method Overloading and
Method Overriding
class MathOperations {
// Overloaded methods
int add(int a, int b) {
return a + b;
}
57
double add(double a, double b) {
return a + b;
}
}
2. Method Overriding:
Definition: Method overriding occurs when a
subclass provides a specific implementation for a
method that is already defined in its superclass,
with the same method signature (name, return
type, and parameters).
Purpose: It allows a subclass to modify or extend
the behavior of an inherited method from the
superclass.
Parameters: The method in the subclass must have
the same parameter list as in the superclass.
Binding Type: It is resolved at runtime, also known
as runtime polymorphism.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
58
void sound() {
System.out.println("Bark");
}
}
// Final method
final void finalMethod() {
System.out.println("This is a final method.");
}
OUTPUT:
60
Static method: Can be called without creating an
instance of the class (i.e., Example.staticMethod()).
Final method: Cannot be overridden in any subclass,
but can be called like any other method from the
instance of the class (i.e., obj.finalMethod()).
OR
5. a) Discuss the Concept of Access Control in Methods.
How do Access Modifiers Affect Method Visibility?
In Java, access modifiers control the visibility and
accessibility of methods to other classes or packages.
The main access modifiers are:
61
1. Public (public): The method is accessible from
anywhere, both within the same package and from
other packages.
EXAMPLE:
class AccessControlExample {
62
System.out.println("Private method can only be
accessed within the same class.");
}
// Accessing methods
obj.publicMethod(); // Accessible
// obj.privateMethod(); // Error: privateMethod()
has private access in AccessControlExample
obj.protectedMethod(); // Accessible
obj.defaultMethod(); // Accessible within the
same package
}
63
}
64
o A static nested class is associated with its
enclosing class, but it does not have access to
the instance variables and methods of the
outer class.
o It can be instantiated without an instance of
the enclosing class.
Example:
class Outer {
static int outerVar = 10;
65
2. Inner Class:
o An inner class is associated with an instance of
its enclosing class. It has access to the instance
variables and methods of the outer class.
o It must be instantiated through an instance of
the enclosing class.
Example:
class Outer {
int outerVar = 10;
class Inner {
void display() {
System.out.println("Inner Class: " + outerVar);
}
}
}
66
Aspect Static Nested Class Inner Class
Belongs to the
Requires an instance
enclosing class, but
of the enclosing
Association does not need an
class to be
instance of the
instantiated.
enclosing class.
Cannot access non- Can access both
Access to static members of the static and non-static
Outer Class enclosing class members of the
directly. enclosing class.
Can be instantiated Must be instantiated
Instantiatio
without an object of through an instance
n
the outer class. of the outer class.
UNIT III
67
Accessing: You access elements using the row and
column index. Arrays in Java are zero-indexed,
meaning the first element of the array is at index 0.
Types of Two-Dimensional Arrays:
1. Rectangular Arrays: All rows have the same number
of columns.
2. Jagged Arrays: Each row can have a different
number of columns.
Detailed Example:
68
System.out.println("Element at [1][2]: " + matrix[1]
[2]);
69
provides a specific implementation of a method declared
in its superclass.
When a method in a subclass overrides a method in the
superclass, the decision about which method to invoke
is made dynamically based on the actual object type, not
the reference type.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
70
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal
reference and object
Animal myDog = new Dog(); // Animal reference
but Dog object
Animal myCat = new Cat(); // Animal reference
but Cat object
Explanation:
The sound() method is dynamically dispatched to
the correct subclass method based on the actual
object type.
At runtime, Java decides which version of sound() to
invoke, even though the reference type is Animal.
OR
71
1. Declare the interface using the interface keyword.
2. Use the implements keyword in the class to
implement the interface.
3. The class must provide concrete implementations
for all abstract methods of the interface.
Example:
interface Animal {
void sound(); // Abstract method
}
72
Animal myDog = new Dog(); // Reference of type
Animal, object of type Dog
Animal myCat = new Cat(); // Reference of type
Animal, object of type Cat
Explanation:
The Animal interface defines a method sound(),
which both Dog and Cat classes implement.
The classes provide their own implementations of
the sound() method.
The classes are able to be referenced as Animal,
demonstrating polymorphism.
class Animal {
void eat() {
73
System.out.println("Animal eats");
}
}
74
The Puppy class extends Dog, which itself extends
Animal.
The Puppy class inherits methods from both Dog
and Animal.
This demonstrates multilevel inheritance as the
Puppy class forms the third level of the inheritance
chain.
UNIT-4
1. java.lang:
o Contains fundamental classes like String, Math,
System, and Thread.
o Automatically imported into every Java
program.
o Contribution: Provides essential classes for
basic programming tasks (e.g., string
manipulation, system operations, and
threading).
2. java.util:
75
o Contains utility classes like ArrayList, HashMap,
Date, Calendar, and Random.
o Contribution: Provides tools for working with
collections, data structures, and dates. It is
crucial for managing data efficiently in Java.
3. java.io:
o Includes classes for input and output
operations like File, BufferedReader,
PrintWriter, and FileReader.
o Contribution: Provides classes for reading from
and writing to files, handling streams, and
serializing objects.
4. javax.swing:
o Used for building graphical user interfaces
(GUIs) with components like JFrame, JButton,
and JLabel.
o Contribution: Enables the development of
desktop applications with rich user interfaces.
Example: Here’s a small example using the java.util
package to demonstrate the use of ArrayList:
import java.util.ArrayList;
76
System.out.println("Fruits List: " + list); // Output
the list
}
}
OUTPUT:
Explanation:
The ArrayList class from the java.util package is
used to store a dynamic list of strings.
The program demonstrates adding items to the list
and printing them. The ArrayList class helps
manage collections of data more efficiently than
arrays in Java.
77
general Exception because the latter can catch any
exception, including specific ones.
Improved Readability and Maintainability: Multiple
catch clauses allow for cleaner, more maintainable
code by clearly defining the response to different
exceptions.
Example:
import java.io.*;
public class MultipleCatchExample {
public static void main(String[] args) {
try {
// Attempting to open a file
FileReader file = new
FileReader("nonexistentfile.txt");
BufferedReader reader = new
BufferedReader(file);
} catch (FileNotFoundException e) {
// This block will execute if the file does not exist
System.out.println("Error: File not found.");
} catch (IOException e) {
// This block will execute for other I/O issues
System.out.println("Error: An I/O error
occurred.");
78
} catch (Exception e) {
// This block will catch any other exceptions
System.out.println("Error: Something went
wrong.");
}
}
}
Explanation:
In this example, the program tries to open a file and
read a line from it.
Three catch clauses are provided:
o The first catch block handles a
FileNotFoundException, which is thrown if the
specified file does not exist.
o The second catch block handles any
IOException that may occur during the file
reading process (e.g., problems with file
access).
o The third catch block catches any other
exceptions that are not specifically handled by
the previous blocks.
Output (when the file doesn't exist):
Error: File not found.
OR
79
In Java, exceptions are objects that are instances of the
Throwable class. The hierarchy of exception classes is as
follows:
Throwable (Base class for all errors and exceptions)
o Error (Represents serious errors that a program
should not catch)
Examples: OutOfMemoryError,
StackOverflowError
o Exception (Represents conditions that a
program can catch and handle)
Checked Exceptions (Exceptions that are
checked at compile-time and must be
handled explicitly)
Examples: IOException, SQLException,
ClassNotFoundException
Unchecked Exceptions (Also called runtime
exceptions, they do not need to be caught
or declared in a method signature)
Examples: NullPointerException,
ArrayIndexOutOfBoundsException,
IllegalArgumentException
Difference Between Exception and RuntimeException:
Exception:
o Represents checked exceptions that must be
either caught using a try-catch block or
declared in the method signature using throws.
o These exceptions occur due to conditions that
are outside the program’s control, such as IO
errors, database errors, etc.
o Example: IOException, SQLException.
RuntimeException:
80
o Represents unchecked exceptions that are
typically caused by programming bugs.
o These exceptions do not require explicit
handling (no need for a try-catch block or
throws declaration).
o They occur during the program's execution due
to errors like invalid array access, null
references, etc.
o Example: NullPointerException,
ArithmeticException.
Example:
81
they handle the conversion between characters and
bytes automatically.
Reading and Writing Using Character Streams:
FileReader and FileWriter are the primary classes
for reading and writing character data in Java.
Example of Writing Data to a Text File:
import java.io.FileWriter;
import java.io.IOException;
82
o The FileWriter object is used to write text to a
file. The text is written in the form of
characters, so no encoding/decoding is needed.
o Always ensure that you close the stream using
the close() method to prevent resource leaks.
Example of Reading Data from a Text File:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
83
Explanation:
o FileReader is used to read characters from a
file.
o The BufferedReader is often used to wrap
around FileReader for efficient reading
(buffering).
o The readLine() method reads a line of text, and
it returns null when the end of the file is
reached.
UNIT 5
84
Mutability: StringBuffer objects are mutable,
meaning their values can be changed after creation
without creating new objects. This is more efficient
when performing many modifications to the text.
Performance: More efficient than String when
performing repeated modifications, as it does not
create new objects each time.
Use Case: Suitable for scenarios where the string
content needs to be modified multiple times (e.g.,
in loops).
Example:
85
Output:
86
multiple processes. This helps in improving system
efficiency.
3. Increased Responsiveness: Multithreading is
essential for creating responsive applications, such
as GUI applications, where the main thread can
remain responsive to user actions while other tasks
(e.g., downloading files, processing data) continue
in the background.
4. Concurrency: Multiple threads can handle
independent tasks concurrently, such as handling
multiple user requests in a web server or
performing multiple computations in parallel.
Example of Multithreading:
Here is a simple example demonstrating multithreading
in Java by extending the Thread class:
System.out.println(Thread.currentThread().getId() + "
Value: " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
87
public class ThreadExample {
public static void main(String[] args) {
// Creating two threads
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
1 Value: 1
2 Value: 1
1 Value: 2
2 Value: 2
1 Value: 3
2 Value: 3
...
In this example, two threads (t1 and t2) run
concurrently. Each thread prints numbers from 1 to 5
with a delay of 1 second. The exact order of output
might vary because the threads execute independently,
demonstrating multithreading.
Key Concepts:
88
Thread: The basic unit of execution in a program.
Thread.sleep(): A static method used to pause the
current thread for a specified amount of time.
Thread Scheduling: The operating system’s thread
scheduler manages the execution of threads. Java
provides mechanisms to control thread behavior
(like priority).
Importance in Modern Software Development:
OR
1. JDBC Drivers:
89
Type 1 (JDBC-ODBC Bridge Driver): Uses
ODBC driver to connect with the database.
Type 2 (Native-API Driver): Uses database-
specific API to connect directly.
Type 3 (Network Protocol Driver): Uses a
middleware server to communicate with
the database.
Type 4 (Thin Driver): Directly
communicates with the database using
database's native protocol.
2. DriverManager:
90
o There are different types of Statement objects:
Statement, PreparedStatement, and
CallableStatement.
5. ResultSet:
91
Example of JDBC Code:
import java.sql.*;
92
// Step 6: Close the resources
rs.close();
stmt.close();
conn.close();
93
o Lays out children in a single vertical column.
o All children are stacked on top of each other,
and you can set the spacing between them.
Example:
3. GridPane:
o Lays out children in a flexible grid of rows and
columns.
o Each child can be placed in a specific cell in the
grid.
Example:
94
grid.add(new Button("Button 1"), 0, 0); // Row 0,
Column 0
grid.add(new Button("Button 2"), 1, 0); // Row 0,
Column 1
4. BorderPane:
o Divides the layout into five regions: top,
bottom, left, right, and center.
o Each region can contain one child.
Example:
Conclusion:
These layout panes help organize the GUI in a flexible
and structured manner. They automatically manage the
positioning and resizing of the UI components.
95