Java Assignment 1 To 5
Java Assignment 1 To 5
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
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:
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?
with hardware.
5.Operating 5.C++ supports operator 5.Java doesn’t support
overloading overloading. operator overloading.
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.
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.
- 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.
- 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.
- 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.
- 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.
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.
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.
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() {
Dog1.display();
Class Dog {
String name;
Dog(String dogName) {
Name = dogName;
Void display() {
Dog1.display();
Dog2.display();
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…”);
Void bark() {
System.out.println(“Barking…”);
}
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…”);
Void bark() {
System.out.println(“Barking…”);
Void weep() {
System.out.println(“Weeping…”);
Puppy.eat();
Puppy.bark();
Puppy.weep();
3. Hierarchical Inheritance
Syntax:
Class Animal {
Void eat() {
System.out.println(“Eating…”);
Void bark() {
System.out.println(“Barking…”);
System.out.println(“Meowing…”);
Dog.eat();
Dog.bark();
Cat.eat();
Cat.meow();
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();
System.out.println(“Dog is running…”);
System.out.println(“Dog is barking…”);
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.
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.
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();
Void walk();
}
System.out.println(“Dog is eating.”);
System.out.println(“Dog is sleeping.”);
System.out.println(“Dog is walking.”);
System.out.println(“Cat is eating.”);
System.out.println(“Cat is sleeping.”);
System.out.println(“Cat is walking.”);
Dog.eat();
Dog.sleep();
Dog.walk();
Cat.eat();
Cat.sleep();
Cat.walk();
3. Abstract class can have final, non- 3. Interface has only static and final
final, static and non-static variables. variables.
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();
System.out.println(“Woof!”);
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.
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.
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.
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.
2.Multilevel Inheritance: A class inherits from a superclass, which in turn inherits from
another 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 {
Return a + b;
Return a * b;
Int number = 5;
}
}
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.
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.
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.
Assignment 3
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.
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:
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:
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
You can create a new thread by extending the Thread class and overriding its run() method.
2.Thread Lifecycle
Understanding the thread lifecycle is crucial for managing threads effectively. A thread can
be in one of the following states:
2.Runnable: The thread is ready to run and waiting for CPU time.
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.
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.
For more complex applications, Java provides the Executor framework, which simplifies
thread management. You can use ExecutorService to manage a pool of threads.
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 {
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) {
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 {
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
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
// Method code
Import java.io.BufferedReader;
Import java.io.FileReader;
Import java.io.IOException;
Public class CompileTimeExceptionExample {
Try {
String line;
System.out.println(line);
} catch (IOException e) {
Key Concepts
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).
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.
Thread Lifecycle
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.
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().
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 ColorChanger() {
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
submitButton.addActionListener(new ActionListener() {
changeBackgroundColor();
});
Add(submitButton);
colorChanger.setVisible(true);
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
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.
● 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.
These are packages created by developers to organize their own classes and interfaces. User-
defined packages help in structuring the codebase of an application.
● 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
● 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.
● 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.
● DatagramSocket Class: Used for sending and receiving datagram packets. It is suitable for
connectionless communication (UDP).
● The java.net package provides classes for handling HTTP requests and responses, making it
easier to build web applications and services.
The java.util.concurrent package provides classes and interfaces for managing concurrent
programming and inter-thread communication. Key features include:
● 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.3 Executors:
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.*;
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.*;
Panel.setLayout(new FlowLayout());
Frame.add(panel);
Frame.setSize(400, 300);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setVisible(true);
3.JScrollPane
Import javax.swing.*;
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.*;
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.*;
frame.add(toolBar, “North”);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
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.
1.FlowLayout
2.BorderLayout
Description: Divides the container into five regions: North, South, East, West, and Center.
3.GridLayout
4.GridBagLayout
6.CardLayout
Description: Stacks components (cards) on top of each other, showing one at a time.
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:
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:
The event source notifies the registered listener, passing the event object for handling
Import javax.swing.*;
Import java.awt.event.MouseEvent;
Import java.awt.event.MouseListener;
Public MouseListenerExample() {
setTitle(“MouseListener Example”);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
Add(label);
addMouseListener(this);
Frame.setVisible(true);
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
Import javax.swing.*;
Import java.awt.*;
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setSize(400, 300);
Frame.setLayout(new BorderLayout());
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);
}
}
1. JFrame
2.JPanel
3.JButton
4.JLabel
5.JTextField
6.JTextArea
7.JComboBox
8.JCheckBox
Description: A box that can be checked or unchecked.
9.JRadioButton
10.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.
4. JEditorPane
Description: A versatile text component that can display and edit HTML and plain text.
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.*;
StyleConstants.setBold(attrs, true);
StyleConstants.setFontSize(attrs, 16);
Try {
StyleConstants.setItalic(attrs, true);
} catch (BadLocationException e) {
e.printStackTrace();
Frame.add(new JScrollPane(textPane));
Frame.setSize(300, 200);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setVisible(true);
}
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.ActionEvent;
Import java.awt.event.ActionListener;
Public BasicCalculator() {
setTitle(“Basic Calculator”);
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
Display.setEditable(false);
Add(display, BorderLayout.NORTH);
String[] buttonLabels = {
};
Button.addActionListener(this);
Panel.add(button);
Add(panel, BorderLayout.CENTER);
Display.setText(display.getText() + command);
} else if (command.equals(“C”)) {
Display.setText(“”);
} else if (command.equals(“=”)) {
Num2 = Double.parseDouble(display.getText());
Switch (operator) {
Case “+”:
Break;
Case “-“:
Case “*”:
Break;
Case “/”:
Break;
Display.setText(String.valueOf(result));
} else {
If (!display.getText().isEmpty()) {
Num1 = Double.parseDouble(display.getText());
Operator = command;
Display.setText(“”);
Calculator.setVisible(true);
Assignment 5
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:
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.
Look and Feel AWT uses the look and feel of the Swing provides a pluggable
underlying operating system. look and feel
.
Event Handling AWT uses a simpler event handling Swing provides a more
model, sophisticated event handling
model
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.
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 {
Public ColorChooserExample() {
setTitle(“JColorChooser Example”);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
colorPanel.setBackground(Color.WHITE);
chooseColorButton.addActionListener(new ActionListener() {
If (selectedColor != null) {
colorPanel.setBackground(selectedColor);
});
Add(colorPanel);
Add(chooseColorButton);
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
Import javax.swing.*;
Import javax.swing.table.DefaultTableModel;
Import java.awt.*;
Public JTableExample() {
setTitle(“JTable Example”);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
createTable();
Add(scrollPane, BorderLayout.CENTER);
};
Example.setVisible(true);
}}}
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.
2.Native-API Driver
4.Thin Driver
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
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;
Try {
Class.forName(“com.mysql.cj.jdbc.Driver”);
Statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
While (resultSet.next()) {
Int id = resultSet.getInt(“id”);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
Try {
} catch (SQLException e) {
e.printStackTrace();
1.Load the JDBC Driver: This step involves loading the database driver class into memory. This
is often done using Class.forName().
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;
Try {
Class.forName(“com.mysql.cj.jdbc.Driver”);
Statement = connection.createStatement();
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”);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
Try {
} catch (SQLException e) {
e.printStackTrace();
For example
Import javax.swing.*;
Import java.awt.event.*;
Frame.setSize(400, 300);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Button.addMouseListener(new MouseAdapter() {
System.out.println(“Button clicked!”);
})
Frame.getContentPane().add(button);
Frame.setVisible(true);
Import java.awt.event.*;
Frame.setSize(400, 300);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.addKeyListener(new KeyAdapter() {
});
Frame.getContentPane().add(new JScrollPane(textArea));
Frame.setVisible(true);