Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views57 pages

Java Assignment 1 To 5

Uploaded by

pra3tughosh
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)
3 views57 pages

Java Assignment 1 To 5

Uploaded by

pra3tughosh
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/ 57

Assignment 1

1.What is Java?Explain Silent features of java


Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.

Features

1.Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because: Java syntax is
based on C++ (so easier for programmers to learn it after C++). Java has removed many
complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.

2.Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.

Basic concepts of OOPs are:Object, Class, Inheritance, Polymorphism, Abstraction,


Encapsulation

3.Robust

The English mining of Robust is strong. Java is robust because: It uses strong memory
management. There is a lack of pointers that avoids security problems. Java provides
automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.

4.High-performance

Java is faster than other traditional interpreted programming languages because Java
bytecode is “close” to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.

5.Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn’t occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.

6.Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Q.2 Define term JDK,JRE,JVM?

1.JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn’t physically exist. It is a specification that provides a runtime environment in which Java
bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java
is platform independent. There are three notions of the JVM: specification, implementation,
and instance.

2.JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.

The Implementation of JVM is also actively released by other companies besides Sun Micro
Systems.

3.JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:

Standard Edition Java Platform

Enterprise Edition Java Platform

Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
Q.3 Difference between C++ and Java?

Comparison index C++ Java

1.Platform 1.C++ is platform- 1.Java is platform-


Independent dependent. independent.

2. Multiple inheritance 2.C++ supports multiple 2.Java doesn’t support


inheritance. multiple inheritance
through class. It can be
achieved by using
interfaces in java.

3..Structure and union 3.C++supports 3.Java doesn’t support


structures and unions. structures and unions.

4.Hardware 4.C++ is nearer to 4.Java is not so


hardware. interactive

with hardware.
5.Operating 5.C++ supports operator 5.Java doesn’t support
overloading overloading. operator overloading.

Q.4 Define term

1.Final Class

The word final means that cannot be changed. The final class in Java can be declared using
the final keyword. Once we declare a class as final, the values remain the same throughout the
program. The purpose of the final class is to make the class immutable like the String class. It
is only a way to make the class immutable.

2.Static Class

In Java, static is a keyword that manage objects in the memory. The static object belongs to
the class instead of the instance of the class.

We can make a class static if and only if it is a nested class. We can also say that static classes
are known as nested classes. It means that a class that is declared as static within another class
is known as a static class.

3.Inner class
Java allows us to define a class within a class and such classes are known as nested classes. It
is used to group the classes logically and to achieve encapsulation. The outer class members
(including private) can be accessed by the inner class.

4. Outer Class

In Java, an outer class is a top-level class that contains another class, known as an inner class
or nested class. The outer class is the enclosing class that provides a scope for the inner class.

5. Public Class

In Java, a public class is a class that can be accessed from any other class, regardless of the
package in which it is defined. A public class is declared using the `public` access modifier.

6. Private Class (Inner Class)

In Java, a private class is an inner class that is declared with the `private` access modifier
within an outer class. A private inner class can only be accessed within the outer class and is
not visible to other classes.

Q.5 State and explain Access Modifier 1.public , 2.Private 3. Default 4.


Protected 5. Friendly

1. Public Access Modifier

- The `public` access modifier makes a class, method, or variable accessible from any other
class.

- Classes, methods, and variables declared as `public` can be accessed from any package.

2. Private Access Modifier

- The `private` access modifier restricts access to a class, method, or variable within the same
class..

- Classes, methods, and variables declared as `private` cannot be accessed from outside the
class.

3. Default (Package-Private) Access Modifier

- The default access modifier, also known as package-private, makes a class, method, or
variable accessible within the same package.

- Classes, methods, and variables declared without any access modifier (i.e., default) can be
accessed from within the same package.

4. Protected Access Modifier

- The `protected` access modifier makes a class, method, or variable accessible within the
same package and to subclasses in other packages.
- Classes, methods, and variables declared as `protected` can be accessed from within the
same package and by subclasses in other packages.

5. Friendly (Package-Private) Access Modifier

The package-private access modifier is the default access modifier in Java. It means that a
class, method, or variable can be accessed within the same package, but not from outside the
package.

Characteristics of Package-Private Access Modifier:

- Can be accessed within the same package.

- Cannot be accessed from outside the package.

- No explicit access modifier is required (it’s the default).

Q.6 write a short note on Garbage Collection on Java

Garbage Collection (GC) in Java is an automatic memory management process that helps in
reclaiming memory by removing objects that are no longer in use or reachable by the
application. This process is crucial for preventing memory leaks and optimizing the
performance of Java applications.

Key Features of Garbage Collection in Java:

1. Automatic Memory Management: Java developers do not need to manually allocate


and deallocate memory, as the JVM (Java Virtual Machine) handles this automatically.
2. Reachability Analysis: The GC identifies which objects are still reachable from the root
references (like local variables, static variables, and active threads). Objects that are no
longer reachable are considered eligible for garbage collection.
3. Garbage Collection Algorithms: Java employs various algorithms for garbage collection,
including
1. Mark-and-Sweep: Marks reachable objects and sweeps away unmarked objects.
2. Copying: Copies live objects from one space to another, compacting them in the
process.
4. Tuning and Performance: Developers can tune the garbage collection process by
adjusting JVM parameters (like heap size and GC algorithms) to optimize performance
based on application needs.
5. Finalization: Java provides a mechanism for cleanup through the finalize() method,
which can be overridden in classes.

Q.7 What is constructor explain it’s type with code slip

In Java, a constructor is a special method that is called when an object of a class is instantiated.
It is used to initialize the object’s properties and allocate memory for the object. Constructors
have the same name as the class and do not have a return type, not even void.

Types of Constructors
1.Default Constructor: A constructor that does not take any parameters. If no constructor is
defined in a class, Java provides a default constructor automatically.

Class Dog {

String name;

Dog() {

Name = “Unknown”;

Void display() {

System.out.println(“Dog’s name: “ + name);

Public class Main {

Public static void main(String[] args) {

Dog dog1 = new Dog();

Dog1.display();

2.Parameterized Constructor: A constructor that takes parameters to initialize an object with


specific values.

Class Dog {

String name;

Dog(String dogName) {

Name = dogName;

Void display() {

System.out.println(“Dog’s name: “ + name);


}

Public class Main {

Public static void main(String[] args) {

Dog dog1 = new Dog(“Buddy”);

Dog1.display();

Dog dog2 = new Dog(“Max”);

Dog2.display();

Q.8 explain types of inheritance in Java along with syntax

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a


class to inherit properties and behaviors (methods) from another class. In Java, inheritance
promotes code reusability and establishes a relationship between classes. There are several
types of inheritance in Java:

1. Single Inheritance

In single inheritance, a class (subclass) inherits from one superclass. This is the simplest form
of inheritance.

Syntax

Class Animal {

Void eat() {

System.out.println(“Eating…”);

Class Dog extends Animal {

Void bark() {

System.out.println(“Barking…”);
}

Public class Main {

Public static void main(String[] args) {

Dog dog = new Dog();

Dog.eat();

Dog.bark();

2. Multilevel Inheritance

In multilevel inheritance, a class is derived from another class, which is also derived from
another class, forming a chain.

Syntax:

Class Animal {

Void eat() {

System.out.println(“Eating…”);

Class Dog extends Animal {

Void bark() {

System.out.println(“Barking…”);

Class Puppy extends Dog {

Void weep() {
System.out.println(“Weeping…”);

Public class Main {

Public static void main(String[] args) {

Puppy puppy = new Puppy();

Puppy.eat();

Puppy.bark();

Puppy.weep();

3. Hierarchical Inheritance

In hierarchical inheritance, multiple subclasses inherit from a single superclass.

Syntax:

Class Animal {

Void eat() {

System.out.println(“Eating…”);

Class Dog extends Animal {

Void bark() {

System.out.println(“Barking…”);

Class Cat extends Animal {


Void meow() {

System.out.println(“Meowing…”);

Public class Main {

Public static void main(String[] args) {

Dog dog = new Dog();

Dog.eat();

Dog.bark();

Cat cat = new Cat();

Cat.eat();

Cat.meow();

4. Multiple Inheritance (through Interfaces)

Java does not support multiple inheritance with classes to avoid ambiguity (the “Diamond
Problem”). However, it allows multiple inheritance through interfaces.

Syntax:

Interface CanRun {

Void run();

Interface CanBark {

Void bark();

Class Dog implements CanRun, CanBark {


Public void run() {

System.out.println(“Dog is running…”);

Public void bark() {

System.out.println(“Dog is barking…”);

Public class Main {

Public static void main(String[] args) {

Dog dog = new Dog();

Dog.run();

Dog.bark();

}
Assignment 2

Q.1 what is Java Interface? How to extend and implement Interface with example?

In Java, an interface is a reference type that is similar to a class, but it can only contain
constants, method signatures, default methods, static methods, and nested types. Interfaces
cannot contain instance fields or constructors. The methods in interfaces are abstract by
default, meaning they do not have a body and must be implemented by classes that choose
to implement the interface.

● Key Points about Interfaces:

1.Abstract Methods: All methods in an interface are abstract (unless they are default or static
methods).

2.Multiple Inheritance: A class can implement multiple interfaces, allowing for a form of
multiple inheritance.

3.No State: Interfaces cannot hold state (i.e., they cannot have instance variables).

4.Default Methods: Since Java 8, interfaces can have default methods with a body.

5.Static Methods: Interfaces can also have static methods.

● Extending and Implementing Interfaces

1.Extending an Interface

An interface can extend another interface. When an interface extends another interface, it
inherits all the abstract methods of the parent interface.

2.Implementing an Interface

A class implements an interface by providing the body for all the abstract methods defined in
the interface. A class can implement multiple interfaces.

For example

Interface Animal {

Void eat();

Void sleep();

Interface Mammal extends Animal {

Void walk();
}

Class Dog implements Mammal {

Public void eat() {

System.out.println(“Dog is eating.”);

Public void sleep() {

System.out.println(“Dog is sleeping.”);

Public void walk() {

System.out.println(“Dog is walking.”);

Class Cat implements Mammal {

Public void eat() {

System.out.println(“Cat is eating.”);

Public void sleep() {

System.out.println(“Cat is sleeping.”);

Public void walk() {

System.out.println(“Cat is walking.”);

Public class Main {

Public static void main(String[] args) {


Dog dog = new Dog();

Dog.eat();

Dog.sleep();

Dog.walk();

Cat cat = new Cat();

Cat.eat();

Cat.sleep();

Cat.walk();

Q.2 Difference between Abstract class and interface

Abstract class Interface


1. Abstract class can have abstract and 1. Interface can have only abstract
non-abstract methods. methods. Since Java 8, it can have
default and static methods also.

2. Abstract class doesn’t support 2. Interface supports multiple


multiple inheritance. inheritance.

3. Abstract class can have final, non- 3. Interface has only static and final
final, static and non-static variables. variables.

4. Abstract class can provide the 4. Interface can’t provide the


implementation of interface. implementation of abstract class

5. The abstract keyword is used to 5. The interface keyword is used to


declare abstract class. declare interface.

6. An abstract class can extend another 6. An interface can extend another


Java class and implement multiple Java interface only.
Java interfaces.

7. An abstract class can be extended 7. An interface can be implemented


using keyword “extends”. using keyword “implements”.
8. A Java abstract class can have class 8. Members of a Java interface are
members like private, protected, etc. public by default.

Q.3 State and explain multiple inheritance with example

Multiple inheritance is a feature of some object-oriented programming languages where a


class can inherit attributes and methods from more than one parent class. This allows for a
more flexible and reusable code structure, as a derived class can combine functionalities
from multiple base classes.

Key Points of Multiple Inheritance:

1. Interfaces: Java allows a class to implement multiple interfaces. This means that a class
can inherit method signatures from multiple sources, but it must provide implementations
for those methods.

2.No State Inheritance: Interfaces cannot have instance variables (state) like classes do. They
can only have method signatures (abstract methods) and static final variables (constants).

3.Default Methods: Since Java 8, interfaces can have default methods with implementations.
This allows interfaces to provide some common behavior while still allowing classes to
implement multiple interfaces

For example

Interface Animal {

Void speak();

Interface Pet {

Void play();

Class Dog implements Animal, Pet {

Public void speak() {

System.out.println(“Woof!”);

Public void play() {

System.out.println(“The dog is playing.”);


}

Public class Main {

Public static void main(String[] args) {

Dog myDog = new Dog();

myDog.speak(); // Output: Woof!

myDog.play(); // Output: The dog is playing.

Q. 4 write short note on multiple inheritance using interface

Multiple inheritance in Java refers to the ability of a class to implement multiple interfaces,
allowing it to inherit method signatures from more than one source. This mechanism
provides a way to achieve polymorphism and code reuse without the complications
associated with multiple inheritance of classes.

Features

1.Interface Definition: An interface in Java is a reference type that can contain only
constants, method signatures, default methods, static methods, and nested types. It cannot
contain instance variables or constructors.

2.Implementation: A class can implement multiple interfaces, which allows it to inherit the
abstract methods defined in those interfaces. The implementing class must provide concrete
implementations for all the methods declared in the interfaces.

3.No State Inheritance: Unlike classes, interfaces do not inherit state (instance variables).
This means that interfaces focus solely on behavior (methods) rather than data.

4.Default Methods: Introduced in Java 8, default methods allow interfaces to provide a


default implementation for methods. This feature enables interfaces to evolve without
breaking existing implementations.

5.Avoiding Diamond Problem: Since interfaces do not have state, the ambiguity associated
with the diamond problem (where a class inherits from two classes that have a common
superclass) is avoided. If a class implements two interfaces that have the same method
signature, the implementing class must provide its own implementation.

Q 5 what is inheritance? Explain inheritance in Java


Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a
new class (known as a subclass or derived class) to inherit properties (attributes) and
behaviors (methods) from an existing class (known as a superclass or base class). This
mechanism enables code reusability, establishes a hierarchical relationship between classes,
and allows for the creation of more complex data types based on simpler ones.

Features

1.Code Reusability: Inheritance promotes the reuse of existing code, which reduces
redundancy and improves maintainability. A subclass can use methods and attributes of its
superclass without having to rewrite them.

2.Hierarchical Classification: Inheritance allows for a natural hierarchical classification of


classes. For example, a Dog class can inherit from an Animal class, establishing a clear
relationship.

3.Method Overriding: Subclasses can provide specific implementations of methods that are
already defined in their superclass. This is known as method overriding and allows for
polymorphic behavior.

4.Access Control: Inheritance respects access modifiers (like public, protected, and private),
which control the visibility of class members. Subclasses can access public and protected
members of their superclass.

Inheritance in Java

In Java, inheritance is implemented using the extends keyword. A class can inherit from only
one superclass (single inheritance), but it can implement multiple interfaces, allowing for a
form of multiple inheritance.

Types of Inheritance in Java:

1.Single Inheritance: A class inherits from one superclass.

2.Multilevel Inheritance: A class inherits from a superclass, which in turn inherits from
another superclass.

3.Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.

4.Multiple Inheritance (via Interfaces): Java does not support multiple inheritance with
classes to avoid ambiguity. However, a class can implement multiple interfaces.

Q.6 write a java program to calculate square , cube , addition ,multiplication using
multilevel inheritance

Class Calculator {

Public int square(int number) {

Return number * number;


}

Public int cube(int number) {

Return number * number * number;

Class AdvancedCalculator extends Calculator {

Public int add(int a, int b) {

Return a + b;

Public int multiply(int a, int b) {

Return a * b;

Class ScientificCalculator extends AdvancedCalculator {

Public class Main {

Public static void main(String[] args) {

ScientificCalculator calc = new ScientificCalculator();

Int number = 5;

System.out.println(“Square of “ + number + “ is: “ + calc.square(number));

System.out.println(“Cube of “ + number + “ is: “ + calc.cube(number));

Int a = 10, b = 20;

System.out.println(“Addition of “ + a + “ and “ + b + “ is: “ + calc.add(a, b));

System.out.println(“Multiplication of “ + a + “ and “ + b + “ is: “ + calc.multiply(a, b));

}
}

Q 7 state and explain this and super keyword

In Java, the this and super keywords are used to refer to the current object and the
superclass of the current object, respectively. They play a crucial role in object-oriented
programming, especially in the context of inheritance and method overriding.

This Keyword

The this keyword is a reference variable that refers to the current object. It is commonly used
in the following scenarios:

1.Distinguishing Instance Variables from Parameters: When the parameter names are the
same as instance variable names, this is used to differentiate between them.

2.Invoking Instance Methods: It can be used to call instance methods of the current object.

3. Passing the Current Object: It can be passed as an argument to other methods or


constructors.

4. Constructor Chaining: It can be used to call another constructor in the same class.

Super Keyword

The super keyword is used to refer to the superclass (parent class) of the current object. It is
commonly used in the following scenarios:

1.Accessing Superclass Methods: It can be used to call methods of the superclass that have
been overridden in the subclass.

2.Accessing Superclass Constructors: It can be used to call the constructor of the


superclass.

3.Accessing Superclass Variables: It can be used to access instance variables of the


superclass when they are hidden by subclass variables.

Q.8 Difference between Java interface and Java class

Points Java interface Java class


1. Definition A contract that defines A blueprint for creating
method signatures without objects.
implementations

2. Implementation Cannot provide method Can provide method


implementations implementations and
maintain state.
3. Inheritance Supports multiple Supports single inheritance
inheritance (extends (extends one class).
multiple interfaces).

4. Access Modifiers Methods are implicitly public Can use public, protected,
and abstract; fields are private, or package-private
public, static, and final.

5. Fields Can only have constants (no Can have instance variables
instance variables). with various access levels.

6. Instantiation Cannot be instantiated Can be instantiated using


directly. the new keyword.

Assignment 3

Q.1 write a short note on thread synchronization

Thread synchronization in Java is a mechanism that ensures that multiple threads can safely
access shared resources without causing data inconsistency or corruption. In a
multithreaded environment, threads may attempt to read from or write to shared data
simultaneously, leading to race conditions. To prevent these issues, Java provides several
synchronization techniques.

Key Synchronization Mechanisms:

1.Synchronized Methods:

By declaring a method with the synchronized keyword, you ensure that only one thread can
execute that method on a given object at a time. Other threads attempting to access any
synchronized method on the same object will be blocked until the lock is released.

2.Synchronized Blocks:

Synchronized blocks allow for more granular control over synchronization. You can
synchronize only a specific section of code, which can improve performance by reducing the
scope of the lock.

3.Explicit Locks:

The java.util.concurrent.locks package provides more advanced locking mechanisms, such as


ReentrantLock. This allows for greater flexibility, such as trying to acquire a lock without
blocking and using condition variables for thread communication.

4.Condition Variables:
With explicit locks, you can use Condition objects to allow threads to wait for certain
conditions to be met before proceeding, facilitating better inter-thread communication.

5.Atomic Variables:

Java provides atomic classes (e.g., AtomicInteger, AtomicBoolean) in the


java.util.concurrent.atomic package, which allow for lock-free thread-safe operations on
single variables.

Q.2 how to extracting and implementing threading in java

Extracting and implementing threading in Java involves creating and managing multiple
threads to perform concurrent tasks. Java provides built-in support for multithreading,
allowing developers to create applications that can perform multiple operations
simultaneously. Below are the steps to extract and implement

1.Creating Threads

There are two primary ways to create threads in Java:

1. By Extending the Thread Class

You can create a new thread by extending the Thread class and overriding its run() method.

2. By Implementing the Runnable Interface

Another way to create a thread is by implementing the Runnable interface and


passing an instance of the class to a Thread object.

2.Thread Lifecycle

Understanding the thread lifecycle is crucial for managing threads effectively. A thread can
be in one of the following states:

1.New: The thread is created but not yet started.

2.Runnable: The thread is ready to run and waiting for CPU time.

3.Blocked: The thread is blocked waiting for a monitor lock.

4.Waiting: The thread is waiting indefinitely for another thread to perform a particular action.

5.Timed Waiting: The thread is waiting for another thread to perform an action for a
specified waiting time.

6.Terminated: The thread has completed its execution.

3.Thread Synchronization
When multiple threads access shared resources, synchronization is necessary to prevent data
inconsistency. You can use the synchronized keyword to ensure that only one thread can
access a block of code or method at a time.

4.Using Executor Framework

For more complex applications, Java provides the Executor framework, which simplifies
thread management. You can use ExecutorService to manage a pool of threads.

Q.3 State and explain exception handling keywords In Java

In Java, exception handling is a mechanism that allows developers to manage runtime


errors, ensuring that the program can continue to operate or fail gracefully. The primary
keywords used for exception handling in Java are:

1. Try

Purpose: The try block is used to enclose code that might throw an exception. It
allows you to define a block of code to be tested for exceptions while it is being
executed.

Usage: If an exception occurs within the try block, the control is transferred to the
corresponding catch block.

Syntax

Try {

// Code that may throw an exception

2. Catch

Purpose: The catch block is used to handle the exception that may be thrown by the
try block. You can have multiple catch blocks to handle different types of exceptions.

Usage: Each catch block specifies the type of exception it can handle. If an exception
occurs in the try block, the first matching catch block is executed.

Syntax

Catch (ExceptionType e) {

// Code to handle the exception

3. Finally
Purpose: The finally block is optional and is used to execute code after the try and
catch blocks, regardless of whether an exception was thrown or caught. It is typically
used for cleanup activities, such as closing files or releasing resources.

Usage: The finally block will execute even if there is a return statement in the try or
catch block.

Syntax

Finally {

// Code that will always execute

4. Throw

Purpose: The throw keyword is used to explicitly throw an exception. You can throw
either a checked or unchecked exception.

Usage: This is useful when you want to signal an error condition in your code

Syntax

Throw new ExceptionType(“Error message”);

5. Throws

Purpose: The throws keyword is used in a method signature to indicate that a method
can throw one or more exceptions. This informs the caller of the method that they
need to handle or declare the exception.

Usage: It is used for checked exceptions that are not handled within the method.

Syntax

Public void methodName() throws ExceptionType {

// Method code

Q.4 write a program to perform compile time exception with example

Import java.io.BufferedReader;

Import java.io.FileReader;

Import java.io.IOException;
Public class CompileTimeExceptionExample {

Public static void main(String[] args) {

String filePath = “non_existent_file.txt”;

Try {

// Attempt to read from the file

BufferedReader reader = new BufferedReader(new FileReader(filePath));

String line;

While ((line = reader.readLine()) != null) {

System.out.println(line);

Reader.close(); // Close the reader

} catch (IOException e) {

// Handle the IOException

System.out.println(“An IOException occurred: “ + e.getMessage());

Q.5 Difference between Thread and process

Sr.no Thread Process


1. Thread is a segment of a process or a A process is an instance of a program that is
lightweight process that is managed being executed or processed.
by the scheduler independently.
2. Threads are interdependent and share Processes are independent of each other and
memory. hence don’t share a memory or other
resources.
3. The operating system takes all the Each process is treated as a new process by
user-level threads as a single process the operating system.
4. If any user-level thread gets blocked, If one process gets blocked by the operating
all of its peer threads also get blocked system, then the other process can continue
because OS takes all of them as a the execution.
single process.
5. Context switching between the Context switching between two processes
threads is fast because they are very takes much time as they are heavy compared
lightweight. to thread.
6. A thread needs less time for creation. New process creation is more time taking as
each new process takes all the resources.
7. Threads can be terminated in very little The operating system takes more time to
time. terminate a process.

Q.6 write short note on interthread communication

Inter-thread communication is a mechanism that allows threads to communicate with each


other and coordinate their actions. In Java, this is particularly important in multi-threaded
applications where threads may need to share resources or synchronize their activities to
avoid conflicts and ensure data consistency.

Key Concepts

1.Wait and Notify Mechanism:

Java provides a built-in mechanism for inter-thread communication using the wait(), notify(),
and notifyAll() methods, which are defined in the Object class.

These methods allow threads to communicate about the availability of resources or the
completion of tasks.

2.Wait:

A thread can call the wait() method on an object to release the lock it holds and enter a
waiting state. The thread will remain in this state until another thread calls notify() or
notifyAll() on the same object.

The wait() method must be called from a synchronized context (i.e., within a synchronized
block or method).

3.Notify:

The notify() method wakes up a single thread that is waiting on the object’s monitor (the
thread that called wait() on that object).

If multiple threads are waiting, one of them is chosen at random to be awakened.

4.NotifyAll:

The notifyAll() method wakes up all threads that are waiting on the object’s monitor. This is
useful when multiple threads need to be notified of a change in state.

Q.7 what is thread? Explain thread lifecycle with suitable diagram


A thread in Java is a lightweight process that allows concurrent execution of code. It is a
separate path of execution within a program, enabling multiple operations to run
simultaneously. Threads share the same memory space but have their own stack, which
allows them to execute independently. This makes threads an essential part of Java’s ability
to perform multitasking and improve the performance of applications.

Thread Lifecycle

The main states of a thread lifecycle are:

1.New (Born) State:

A thread is in the new state when it is created but not yet started. In this state, the thread is
not yet eligible for execution.

Example: Thread t = new Thread();

2.Runnable State:

A thread enters the runnable state when the start() method is called. In this state, the thread
is ready to run and waiting for CPU time. It can be in this state either because it is currently
executing or waiting to be executed.

Example: t.start();

3.Blocked State:

A thread enters the blocked state when it is waiting for a monitor lock to enter a
synchronized block or method. This occurs when another thread holds the lock on the object
that the blocked thread is trying to access.

Example: A thread trying to enter a synchronized method while another thread is already
executing it.

4.Waiting State:

A thread enters the waiting state when it is waiting for another thread to perform a particular
action (like notifying it). This can happen when a thread calls wait(), join(), or
LockSupport.park().

Example: t.join(); or object.wait();

5.Timed Waiting State:

A thread enters the timed waiting state when it is waiting for another thread to perform an
action for a specified waiting time. This can happen when a thread calls sleep(milliseconds),
wait(milliseconds), or join(milliseconds).

Example: Thread.sleep(1000);
6.Terminated (Dead) State:

A thread enters the terminated state when it has completed its execution or has been
terminated due to an exception. Once a thread is in this state, it cannot be restarted.

Example: The run() method has completed or an unhandled exception has occurred.

Q.8 write a program to change multiple colors when clicking on submit button using
random function?

Import javax.swing.*;

Import java.awt.*;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;

Import java.util.Random;

Public class ColorChanger extends JFrame {

Private JButton submitButton;

Public ColorChanger() {

setTitle(“Random Color Changer”);

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

submitButton = new JButton(“Submit”);

submitButton.addActionListener(new ActionListener() {

Public void actionPerformed(ActionEvent e) {

changeBackgroundColor();

});

Add(submitButton);

Private void changeBackgroundColor() {

Random random = new Random();

Int red = random.nextInt(256);

Int green = random.nextInt(256);

Int blue = random.nextInt(256);

getContentPane().setBackground(new Color(red, green, blue));

Public static void main(String[] args) {

ColorChanger colorChanger = new ColorChanger();

colorChanger.setVisible(true);

Q.9 what is package? Explain types of java package

In Java, a package is a namespace that organizes a set of related classes and interfaces.
Conceptually, you can think of a package as a folder in a file system that contains related files.
Packages help avoid name conflicts, control access, and make it easier to locate and use
classes, interfaces, and sub-packages.
Types of Java Packages

Java packages can be broadly classified into two types:

1.Built-in Packages:

These are packages that are part of the Java Standard Library and are provided by the Java
Development Kit (JDK). They contain pre-defined classes and interfaces that can be used in
Java programs.

Some commonly used built-in packages include:

● Java.lang: Contains fundamental classes such as String, Math, System, and Object. This
package is automatically imported into every Java program.

● Java.util: Contains utility classes such as collections framework classes (ArrayList, HashMap),
date and time facilities, and random number generation

● Java.io: Contains classes for input and output through data streams, serialization, and file
handling (e.g., File, InputStream, OutputStream).

● Java.net: Contains classes for networking applications, such as Socket, ServerSocket, and
URL.

● Java.awt: Contains classes for creating graphical user interfaces (GUIs) and handling events.

● Javax.swing: Contains classes for building lightweight GUI components

2.User -defined Packages:

These are packages created by developers to organize their own classes and interfaces. User-
defined packages help in structuring the codebase of an application.

To create a user-defined package, you need to follow these steps:

● Declare the Package: At the top of your Java source file, use the package keyword followed
by the package name.

● Compile the Class: Use the javac command with the -d option to specify the destination
directory for the package structure.

● Use the Package: Import the package in other classes using the import statement

ASSIGNMENT 4

Q.1 State and explain features of java communication classes

Features of Java Communication Classes

1.Networking Classes (java.net package)


The java.net package provides classes for implementing networking applications. Here are
some of its key features:

1.1 Socket Communication:

● Socket Class: Represents a client socket that can connect to a server. It allows for sending
and receiving data over a network.

● ServerSocket Class: Represents a server socket that listens for incoming client connections.
It accepts client requests and establishes a connection.

1.2 URL Handling:

● URL Class: Represents a Uniform Resource Locator (URL) and provides methods to access
the content of the resource pointed to by the URL.

● URLConnection Class: Represents a communication link between the application and the
URL. It allows for reading from and writing to the resource.

1.3 Datagram Communication:

● DatagramSocket Class: Used for sending and receiving datagram packets. It is suitable for
connectionless communication (UDP).

● DatagramPacket Class: Represents a packet of data sent or received over a


DatagramSocket.

1.4 Multicast Communication:

● MulticastSocket Class: A subclass of DatagramSocket that allows for multicast


communication, enabling a single packet to be sent to multiple recipients

1.5 HTTP Communication:

● The java.net package provides classes for handling HTTP requests and responses, making it
easier to build web applications and services.

2. Inter-Thread Communication Classes (java.util.concurrent package)

The java.util.concurrent package provides classes and interfaces for managing concurrent
programming and inter-thread communication. Key features include:

2.1 Locks and Synchronizers:

● ReentrantLock: A flexible lock implementation that allows threads to acquire and release
locks in a more sophisticated manner than synchronized blocks.

● CountDownLatch: A synchronization aid that allows one or more threads to wait until a set
of operations being performed in other threads completes.
● CyclicBarrier: A synchronization aid that allows a set of threads to all wait for each other to
reach a common barrier point.

2.2 Blocking Queues:

● BlockingQueue Interface: Represents a thread-safe queue that supports operations that


wait for the queue to become non-empty when retrieving an element and wait for space to
become available when storing an element.

● Implementations include ArrayBlockingQueue, LinkedBlockingQueue, and


PriorityBlockingQueue.

2.3 Executors:

● Executor Framework: Provides a higher-level replacement for managing threads. It allows


you to decouple task submission from the mechanics of how each task will be run.

● ExecutorService: A subinterface of Executor that provides methods for managing the


lifecycle of tasks and retrieving results.

2.4 Atomic Variables:

● Classes like AtomicInteger, AtomicBoolean, and AtomicReference provide a way to perform


atomic operations on single variables without using synchronization.

Q.2 Define types of swing Container with example

1.JFrame

Description: JFrame is the top-level container that represents a window on the screen. It can
hold other components and is typically used as the main window of an application.

Import javax.swing.*;

Public class JFrameExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“JFrame Example”);

Frame.setSize(400, 300);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Frame.setVisible(true);

}
2.JPanel

Description: JPanel is a generic container that can hold a group of components. It is often
used for organizing components within a JFrame or other containers. You can set layout
managers on a JPanel to control the arrangement of its components.

Import javax.swing.*;

Import java.awt.*;

Public class JPanelExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“JPanel Example”);

JPanel panel = new JPanel();

Panel.setLayout(new FlowLayout());

Panel.add(new JButton(“Button 1”));

Panel.add(new JButton(“Button 2”));

Frame.add(panel);

Frame.setSize(400, 300);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Frame.setVisible(true);

3.JScrollPane

Description: JScrollPane is a container that provides a scrollable view of another component.


It is useful for displaying large amounts of data that do not fit within the visible area of the
container.

Import javax.swing.*;

Public class JScrollPaneExample {

Public static void main(String[] args) {


JFrame frame = new JFrame(“JScrollPane Example”);

JTextArea textArea = new JTextArea(20, 30);

JScrollPane scrollPane = new JScrollPane(textArea);

Frame.add(scrollPane);

Frame.setSize(400, 300);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Frame.setVisible(true);

4.JTabbedPane

Description: JTabbedPane is a container that allows you to create a tabbed interface. Each
tab can contain different components, making it easy to switch between different views or
sections of an application.

Import javax.swing.*;

Public class JTabbedPaneExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“JTabbedPane Example”);

JTabbedPane tabbedPane = new JTabbedPane();

tabbedPane.addTab(“Tab 1”, new JLabel(“Content for Tab 1”));

tabbedPane.addTab(“Tab 2”, new JLabel(“Content for Tab 2”));

frame.add(tabbedPane);

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}
5.JToolBar

Description: JToolBar is a container that holds a set of tool buttons, which can be used for
quick access to common actions in an application

Import javax.swing.*;

Public class JToolBarExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“JToolBar Example”);

JToolBar toolBar = new JToolBar();

toolBar.add(new JButton(“Button 1”));

toolBar.add(new JButton(“Button 2”));

frame.add(toolBar, “North”);

frame.setSize(400, 300);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

Q.3 Difference between Checkbox and radio Button

Sr. No Check box Radio Button

1. A checkbox is a UI element that allows the user to A radio button is a UI element


make a binary choice, i.e., to select or deselect an that allows the user to select
option. It can be checked (selected) or unchecked one option from a predefined
(deselected). set of options. When a radio
button is selected, any
previously selected radio
button in the same group is
automatically deselected.
2. Checkboxes allow multiple selections. Users can Radio buttons allow only one
check or uncheck any number of checkboxes selection within a group. Users
independently of each other. can select one option, and
selecting another option will
deselect the previously
selected one.
3. Checkboxes are typically used when the user can Radio buttons are typically
select multiple options from a list. For example, used when the user must
selecting multiple interests or preferences. choose one option from a list.
For example, selecting a
payment method or choosing a
gender.
4. A checkbox is usually represented as a small A radio button is usually
square box that can contain a checkmark when represented as a small circle
selected. that is filled when selected
5. Each checkbox has two states: checked (true) and Each radio button has two
unchecked (false). states: selected (true) and
unselected (false). However,
only one radio button in a
group can be selected at a
time.

Q.4 what is layout? Explain types of layout?

In Java Swing, a layout is a mechanism that determines how components are arranged
within a container. Layout managers control the size and position of components, ensuring a
well-organized user interface.

Types of Layout Managers

1.FlowLayout

Description: Arranges components in a left-to-right flow, wrapping to the next line as


needed.

Usage: Simple layouts with components in a row.

2.BorderLayout

Description: Divides the container into five regions: North, South, East, West, and Center.

Usage: Main window layouts with distinct areas.

3.GridLayout

Description: Arranges components in a grid with equal-sized cells.

Usage: Uniform layouts like calculators.

4.GridBagLayout

Description: A flexible grid-based layout allowing components to span multiple


rows/columns.

Usage: Complex forms requiring precise control.


5.BoxLayout

Description: Arranges components in a single line, either vertically or horizontally.

Usage: Simple vertical or horizontal layouts.

6.CardLayout

Description: Stacks components (cards) on top of each other, showing one at a time.

Usage: Wizards or tabbed interfaces.

Q.5 write short note on event delegation model

The Event Delegation Model is a design pattern used in Java’s event handling system,
particularly in GUI applications with Swing and AWT. It allows for efficient and flexible
handling of user interactions, such as mouse clicks and key presses.

Key Concepts

1.Event Source:

An object that generates events (e.g., buttons, text fields).

2.Event Listener:

An interface that defines methods for handling specific events (e.g., ActionListener for button
clicks). Classes implement these interfaces to respond to events.

3.Event Object:

Contains information about the event, such as its source and type, and is passed to the
listener’s method when an event occurs.

4.Delegation:

The event source delegates event handling to registered listeners, promoting a decoupled
architecture.

How It Works

1.Registering Listeners:

Listeners are registered with event sources using methods like addActionListener().

2.Event Generation:

User interactions generate events, creating event objects.


3.Event Notification:

The event source notifies the registered listener, passing the event object for handling

Q.6 Write a program to perform mouse Listener

Import javax.swing.*;

Import java.awt.event.MouseEvent;

Import java.awt.event.MouseListener;

Public class MouseListenerExample extends JFrame implements MouseListener {

Private JLabel label;

Public MouseListenerExample() {

setTitle(“MouseListener Example”);

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(null);

Label = new JLabel(“Mouse Events will be displayed here”);

Label.setBounds(50, 100, 300, 30);

Add(label);

addMouseListener(this);

Public void mouseClicked(MouseEvent e) {

Label.setText(“Mouse Clicked at: (“ + e.getX() + “, “ + e.getY() + “)”);

Public void mousePressed(MouseEvent e) {

Label.setText(“Mouse Pressed at: (“ + e.getX() + “, “ + e.getY() + “)”);

Public void mouseReleased(MouseEvent e) {


Label.setText(“Mouse Released at: (“ + e.getX() + “, “ + e.getY() + “)”);

Public void mouseEntered(MouseEvent e) {

Label.setText(“Mouse Entered the Frame”);

Public void mouseExited(MouseEvent e) {

Label.setText(“Mouse Exited the Frame”);

Public static void main(String[] args) {

MouseListenerExample frame = new MouseListenerExample();

Frame.setVisible(true);

Q.7 Difference between list and combo box

Content List Combo box


Definition A list is a GUI component that displays a A combo box is a combination
set of items in a vertical or horizontal of a drop-down list and a text
arrangement box.

Visibility All items in a list are typically visible at Only the selected item is
once (depending on the size of the list visible until the user clicks on
and the display area) the combo box, which then
displays a drop-down list of
options.
Selection Users can select one or multiple items Users can select only one item
directly from the list. This is useful when from the drop-down list at a
multiple selections are needed. time.
Use Cases Best used when there are many options Ideal for situations where
to choose from, and the user may need space is limited, and the user
to see all options at once. needs to select one option
from a relatively small set of
choices.
Implementation Often implemented using components Implemented using
like JList in Java Swing components like JComboBox
in Java Swing
Q.8 what is border layout explain it with example

Border Layout is a layout manager in Java’s AWT (Abstract Window Toolkit) and Swing that
arranges components in five distinct regions: North, South, East, West, and Center. Each
region can hold one component, and the layout manager automatically sizes and positions
the components based on the available space

Example of Border Layout

Import javax.swing.*;

Import java.awt.*;

Public class BorderLayoutExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“Border Layout Example”);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Frame.setSize(400, 300);

Frame.setLayout(new BorderLayout());

JButton buttonNorth = new JButton(“North”);

JButton buttonSouth = new JButton(“South”);

JButton buttonEast = new JButton(“East”);

JButton buttonWest = new JButton(“West”);

JButton buttonCenter = new JButton(“Center”);

Frame.add(buttonNorth, BorderLayout.NORTH);

Frame.add(buttonSouth, BorderLayout.SOUTH);

Frame.add(buttonEast, BorderLayout.EAST);

Frame.add(buttonWest, BorderLayout.WEST);

Frame.add(buttonCenter, BorderLayout.CENTER);

Frame.setVisible(true);

}
}

Q.9 Define any 10 JFC Classes in detail

1. JFrame

Description: A top-level window container.

Usage: JFrame frame = new JFrame(“Title”);

2.JPanel

Description: A generic container for organizing components.

Usage: JPanel panel = new JPanel();

3.JButton

Description: A clickable button that triggers actions.

Usage: JButton button = new JButton(“Click Me”);

4.JLabel

Description: Displays text or an image.

Usage: JLabel label = new JLabel(“Hello, World!”);

5.JTextField

Description: A single-line text input field.

Usage: JTextField textField = new JTextField(20);

6.JTextArea

Description: A multi-line text input area.

Usage: JTextArea textArea = new JTextArea(5, 20);

7.JComboBox

Description: A drop-down list for selecting items.

Usage: JComboBox<String> comboBox = new JComboBox<>(new String[]{“Option 1”, “Option


2”});

8.JCheckBox
Description: A box that can be checked or unchecked.

Usage: JCheckBox checkBox = new JCheckBox(“Accept Terms”);

9.JRadioButton

Description: A button for selecting one option from a group.

Usage: JRadioButton radioButton = new JRadioButton(“Option A”);

10.JMenuBar

Description: A menu bar for adding menus to a frame.

Usage: JMenuBar menuBar = new JMenuBar();

Q.10 what is text components? Explain types of text components with code snippet

In Java, text components are GUI elements that allow users to enter, edit, and display text.
They are part of the Java Foundation Classes (JFC) and are primarily used in Swing
applications. The main types of text components in Swing are:

1. JTextField

Description: A single-line text input field that allows users to enter and edit text.

Usage: Typically used for short text inputs like names, email addresses, etc.

2. JTextArea

Description: A multi-line area that allows users to enter and edit text. It is useful for larger text
inputs.

Usage: Commonly used for comments, descriptions, or any text that requires more space.

3. JPasswordField

Description: A text field that hides the input text, typically used for password entry.

Usage: Used when sensitive information like passwords needs to be entered.

4. JEditorPane

Description: A versatile text component that can display and edit HTML and plain text.

Usage: Useful for displaying formatted text or simple HTML content.

5. JTextPane
Description: A text component that supports styled text and can handle various types of
content, including images and text with different styles.

Usage: Useful for applications that require rich text editing capabilities.

Code snippet

Import javax.swing.*;

Import javax.swing.text.*;

Public class TextPaneExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“JTextPane Example”);

JTextPane textPane = new JTextPane();

StyledDocument doc = textPane.getStyledDocument();

SimpleAttributeSet attrs = new SimpleAttributeSet();

StyleConstants.setBold(attrs, true);

StyleConstants.setFontSize(attrs, 16);

Try {

Doc.insertString(doc.getLength(), “Bold Text\n”, attrs);

StyleConstants.setItalic(attrs, true);

Doc.insertString(doc.getLength(), “Italic Text\n”, attrs);

} catch (BadLocationException e) {

e.printStackTrace();

Frame.add(new JScrollPane(textPane));

Frame.setSize(300, 200);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Frame.setVisible(true);
}

Q.11 write a program to create basic calculator using java Swing

Import javax.swing.*;

Import java.awt.*;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;

Public class BasicCalculator extends JFrame implements ActionListener {

Private JTextField display;

Private String operator;

Private double num1, num2, result;

Public BasicCalculator() {

setTitle(“Basic Calculator”);

setSize(400, 600);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

Display = new JTextField();

Display.setEditable(false);

Display.setFont(new Font(“Arial”, Font.BOLD, 24));

Add(display, BorderLayout.NORTH);

JPanel panel = new JPanel();

Panel.setLayout(new GridLayout(4, 4, 10, 10));

String[] buttonLabels = {

“7”, “8”, “9”, “/”,

“4”, “5”, “6”, “*”,


“1”, “2”, “3”, “-“,

“0”, “C”, “=”, “+”

};

For (String label : buttonLabels) {

JButton button = new JButton(label);

Button.setFont(new Font(“Arial”, Font.BOLD, 24));

Button.addActionListener(this);

Panel.add(button);

Add(panel, BorderLayout.CENTER);

Public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

If (command.charAt(0) >= ‘0’ && command.charAt(0) <= ‘9’) {

Display.setText(display.getText() + command);

} else if (command.equals(“C”)) {

Display.setText(“”);

} else if (command.equals(“=”)) {

Num2 = Double.parseDouble(display.getText());

Switch (operator) {

Case “+”:

Result = num1 + num2;

Break;

Case “-“:

Result = num1 – num2;


Break;

Case “*”:

Result = num1 * num2;

Break;

Case “/”:

Result = num1 / num2;

Break;

Display.setText(String.valueOf(result));

} else {

If (!display.getText().isEmpty()) {

Num1 = Double.parseDouble(display.getText());

Operator = command;

Display.setText(“”);

Public static void main(String[] args) {

BasicCalculator calculator = new BasicCalculator();

Calculator.setVisible(true);

Assignment 5

Q.1 what is JDBC? Explain JDBC architecture with diagram


JDBC (Java Database Connectivity) is a Java-based API that allows Java applications to
interact with a wide range of databases. It provides methods for querying and updating data
in a database, enabling developers to execute SQL statements, retrieve results, and manage
database connections. JDBC is part of the Java Standard Edition platform and is essential for
building database-driven applications in Java.

Architecture of JDBC

1.Application: It is the Java servlet or an applet that communicates with the data source.

2.The JDBC API: It allows the Java programs to perform the execution of the SQL statements
and then get the results.

A few of the crucial interfaces and classes defined in the JDBC API are the following:

Drivers , DriverManager , Statement , Connection , Callable Statement , Prepared Statement,


ResultSet , SQL data

3.DriverManager: DriverManager plays a crucial role in the architecture of JDBC.

4.It uses database-specific drivers to connect the enterprise applications to various


databases.

JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC
driver which conveniently interacts with the respective data source.

Q.2 Difference between AWT and Swing

Content AWT Swing


Component Type AWT components are heavyweight Swing components are
components, lightweight

Look and Feel AWT uses the look and feel of the Swing provides a pluggable
underlying operating system. look and feel

Functionality AWT provides a limited set of Swing offers a rich set of


components and lacks advanced components, including
features. advanced features like tables,
trees, and text panes

.
Event Handling AWT uses a simpler event handling Swing provides a more
model, sophisticated event handling
model

Performance Because AWT components are Swing components are


heavyweight and rely on native generally more efficient in
resources, they can be slower and terms of memory usage and
consume more memory. performance, as they are
lightweight and managed
entirely in Java.

Development AWT is simpler and easier to learn for Swing has a steeper learning
Complexity beginners, but it is limited in curve due to its rich set of
functionality. features and components, but
it allows for the development
of more complex and feature-
rich applications.

Q.3 what is J color chooser class ? How to create with example

The JColorChooser class in Java Swing is a component that allows users to select a color from
a color palette. It provides a dialog that displays a variety of colors and allows users to create
custom colors

Example

Import javax.swing.*;

Import java.awt.*;

Import java.awt.event.ActionEvent;

Import java.awt.event.ActionListener;
Public class ColorChooserExample extends JFrame {

Private JPanel colorPanel;

Private JButton chooseColorButton;

Public ColorChooserExample() {

setTitle(“JColorChooser Example”);

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

colorPanel = new JPanel();

colorPanel.setPreferredSize(new Dimension(200, 100));

colorPanel.setBackground(Color.WHITE);

chooseColorButton = new JButton(“Choose Color”);

chooseColorButton.addActionListener(new ActionListener() {

Public void actionPerformed(ActionEvent e) {

Color selectedColor = JColorChooser.showDialog(null, “Select a Color”,


colorPanel.getBackground());

If (selectedColor != null) {

colorPanel.setBackground(selectedColor);

});

Add(colorPanel);

Add(chooseColorButton);

Public static void main(String[] args) {


ColorChooserExample example = new ColorChooserExample();

Example.setVisible(true);

Q.4 what is J table ? How to create j table with constructor and method

JTable is a component in Java Swing that displays data in a tabular format, consisting of rows
and columns. It is part of the javax.swing package and is commonly used to present and
manipulate data in a structured way, such as displaying records from a database or showing
data in a spreadsheet-like format

J table using constructor and method

Import javax.swing.*;

Import javax.swing.table.DefaultTableModel;

Import java.awt.*;

Public class JTableExample extends JFrame {

Private JTable table;

Private JScrollPane scrollPane;

Public JTableExample() {

setTitle(“JTable Example”);

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

createTable();

Add(scrollPane, BorderLayout.CENTER);

Private void createTable() {

String[] columnNames = {“ID”, “Name”, “Age”};


Object[][] data = {

{1, “Alice”, 30},

{2, “Bob”, 25},

{3, “Charlie”, 35},

{4, “Diana”, 28}

};

DefaultTableModel model = new DefaultTableModel(data, columnNames);

Table = new JTable(model);

scrollPane = new JScrollPane(table);

Public static void main(String[] args) {

JTableExample example = new JTableExample();

Example.setVisible(true);

}}}

Q.5 write a short note on JDBC driver

A JDBC Driver is a software component that enables Java applications to interact with a
database. It acts as a bridge between the Java application and the database, translating Java
calls into database-specific calls and vice versa. JDBC drivers are essential for executing SQL
statements, retrieving results, and managing database connections in Java applications.

Types of JDBC Drivers

1.JDBC-ODBC Bridge Driver

Translates JDBC calls into ODBC calls.

Advantages: Easy to use.

Disadvantages: Performance overhead; deprecated in Java 8.

2.Native-API Driver

Converts JDBC calls into database-specific native calls.


Advantages: Better performance than Type 1.

Disadvantages: Requires native database libraries.

3.Network Protocol Driver

Translates JDBC calls into a database-independent protocol.

Advantages: No client-side libraries needed.

Disadvantages: Requires a server-side component.

4.Thin Driver

Converts JDBC calls directly into the database-specific protocol.

Advantages: Platform-independent and lightweight; best performance.

Disadvantages: Tied to a specific database vendor.

Q.6 what is result set? how to create result set explain with method

A ResultSet in JDBC (Java Database Connectivity) is an object that represents the result set of
a query executed against a database. It provides methods to read and manipulate the data
returned by a SQL query. The ResultSet object is created by executing a SQL statement using
a Statement or PreparedStatement object.

Creating a ResultSet

To create a ResultSet, you typically follow these steps:

1.Establish a Connection: Connect to the database using JDBC.

2.Create a Statement or PreparedStatement: Use this object to execute SQL queries.

3.Execute a SQL Query: Use the executeQuery() method to obtain a ResultSet.

4.Process the ResultSet: Iterate through the ResultSet to retrieve data.

5.Close Resources: Always close the ResultSet, Statement, and Connection to free up
resources.

For example

Import java.sql.Connection;

Import java.sql.DriverManager;
Import java.sql.ResultSet;

Import java.sql.SQLException;

Import java.sql.Statement;

Public class ResultSetExample {

Public static void main(String[] args) {

String url = “jdbc:mysql://localhost:3306/your_database”;

String user = “your_username”;

String password = “your_password”;

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

Try {

Class.forName(“com.mysql.cj.jdbc.Driver”);

Connection = DriverManager.getConnection(url, user, password);

Statement = connection.createStatement();

String sql = “SELECT id, name, age FROM users”;

resultSet = statement.executeQuery(sql);

While (resultSet.next()) {

Int id = resultSet.getInt(“id”);

String name = resultSet.getString(“name”);

Int age = resultSet.getInt(“age”);

System.out.println(“ID: “ + id + “, Name: “ + name + “, Age: “ + age);

} catch (SQLException e) {
e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} finally {

Try {

If (resultSet != null) resultSet.close();

If (statement != null) statement.close();

If (connection != null) connection.close();

} catch (SQLException e) {

e.printStackTrace();

Q.7 Define JDBC connection steps Java with example

Steps to Establish a JDBC Connection

1.Load the JDBC Driver: This step involves loading the database driver class into memory. This
is often done using Class.forName().

2.Establish a Connection: Use the DriverManager.getConnection() method to create a


connection to the database. You need to provide the database URL, username, and
password.

3.Create a Statement: Once the connection is established, create a Statement or


PreparedStatement object to execute SQL queries.

4.Execute SQL Queries: Use the Statement object to execute SQL queries (e.g., SELECT,
INSERT, UPDATE, DELETE).

5.Process the Results: If the query returns results (like a SELECT query), process the ResultSet.
6.Close the Resources: Finally, close the ResultSet, Statement, and Connection objects to free
up resources.

Q.8 Write JDBC program to fetch employee details from employee database

Import java.sql.Connection;

Import java.sql.DriverManager;

Import java.sql.ResultSet;

Import java.sql.SQLException;

Import java.sql.Statement;

Public class FetchEmployeeDetails {

Public static void main(String[] args) {

String url = “jdbc:mysql://localhost:3306/employee_db”;

String user = “your_username”;

String password = “your_password”;

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

Try {

Class.forName(“com.mysql.cj.jdbc.Driver”);

Connection = DriverManager.getConnection(url, user, password);

Statement = connection.createStatement();

String sql = “SELECT id, name, age, department FROM employee”;

resultSet = statement.executeQuery(sql);

System.out.println(“Employee Details:”);

System.out.println(“ID\tName\t\tAge\tDepartment”);
System.out.println(“-----------------------------------------“);

While (resultSet.next()) {

Int id = resultSet.getInt(“id”);

String name = resultSet.getString(“name”);

Int age = resultSet.getInt(“age”);

String department = resultSet.getString(“department”);

System.out.printf(“%d\t%s\t\t%d\t%s%n”, id, name, age, department);

} catch (SQLException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

} finally {

Try {

If (resultSet != null) resultSet.close();

If (statement != null) statement.close();

If (connection != null) connection.close();

} catch (SQLException e) {

e.printStackTrace();

Q.9 write short note on adapter class With example


In Java, an Adapter Class is a design pattern that allows you to create a bridge between two
incompatible interfaces. It is commonly used in GUI programming, especially in frameworks
like Swing and AWT, to simplify the implementation of event listeners. Instead of
implementing all methods of an interface, you can extend an adapter class that provides
default (empty) implementations for some or all of the methods.

For example

Import javax.swing.*;

Import java.awt.event.*;

Public class AdapterClassExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“Adapter Class Example”);

Frame.setSize(400, 300);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JButton button = new JButton(“Click Me”);

Button.addMouseListener(new MouseAdapter() {

Public void mouseClicked(MouseEvent e) {

System.out.println(“Button clicked!”);

Public void mouseEntered(MouseEvent e) {

System.out.println(“Mouse entered the button!”);

})

Frame.getContentPane().add(button);

Frame.setVisible(true);

Q.10 write a program to perform key listener


Import javax.swing.*;

Import java.awt.event.*;

Public class KeyListenerExample {

Public static void main(String[] args) {

JFrame frame = new JFrame(“KeyListener Example”);

Frame.setSize(400, 300);

Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextArea textArea = new JTextArea();

textArea.setLineWrap(true);

textArea.setWrapStyleWord(true);

textArea.addKeyListener(new KeyAdapter() {

Public void keyPressed(KeyEvent e) {

Int keyCode = e.getKeyCode();

Char keyChar = e.getKeyChar();

textArea.append(“Key Pressed: “ + keyChar + “ (Key Code: “ + keyCode + “)\n”);

Public void keyReleased(KeyEvent e) {

Int keyCode = e.getKeyCode();

textArea.append(“Key Released: (Key Code: “ + keyCode + “)\n”);

});

Frame.getContentPane().add(new JScrollPane(textArea));

Frame.setVisible(true);

You might also like