0% found this document useful (0 votes)
7 views63 pages

Java Training Report

java programming training report

Uploaded by

hemantbaghel061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views63 pages

Java Training Report

java programming training report

Uploaded by

hemantbaghel061
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Training Report

in the partial fulfillment of the requirements for the four weeks Summer Institutional
Training of Bachelor of Technology in Computer Science & Engineering

By

Hemant Baghel

23100030031

Submitted to

CSE Department

UNIVERSITY SCHOOL OF ENGINEERING & TECHNOLOGY

1
23100030031 Java Training Report
Completion Certificate

Verify link address https://verify.onwingspan.com/

2
23100030031 Java Training Report
Acknowledgement

I would like to express my sincere gratitude to Prof. Aruna Bhatia for her
invaluable guidance during my summer training in Java. Despite the training
being conducted independently through the Infosys springboard platform,
her consistent support, timely feedback, and insightful suggestions greatly
enhanced my learning experience. Her encouragement motivated me to
deepen my understanding and to successfully complete the "Learn
programming with java – An interactive way" course.

I would also like to acknowledge Lamrin Tech Skills University for


fostering a learning environment that encourages self-directed study and
continuous improvement. The university's emphasis on practical knowledge
and real-world applications has been instrumental in shaping my approach to
this training. The skills and knowledge I have acquired during this period
will undoubtedly contribute to my academic and professional growth.

This training experience has not only broadened my technical expertise but
also strengthened my ability to work independently and efficiently, which I
consider to be invaluable assets for my future

3
23100030031 Java Training Report
Table of Contents Page no.
1. Object Oriented Programming and Java Fundamentals: 6-13
a. is Java ,History of Java ,
b. Features of Java ,
c. Comparison in Java with and C++ ,
d. What JDK,
e. JRE & JVM ,
f. Data Statements Types,
g. Variables,
h. Arrays,
i. Operators and
j. Control Structures
2. Interfaces and Packages: 14-20
a. Interface basics; Defining,
b. implementing and extending interfaces,
c. differences between classes and interfaces,
d. Implementing multiple inheritance using interfaces ,
e. Basics of packages,
f. Creating and accessing packages,
g. System packages,
h. Creating user defined packages,
i. Exploring packages – Java.io, Java.util.
3. Exception Handling: 21-26
a. Using the main keywords of exception handling:
b. try,
c. catch,
d. throw,
e. throws and finally;
f. Nested try,
g. Multiple catch statements.
4. Multithreading: 27-29
a. Differences between multi-threading and multitasking,
b. thread life cycle,
c. creating threads,
d. synchronizing threads,
e. daemon threads,
f. thread groups.

5. Event Handling and AWT: 30-33

4
23100030031 Java Training Report
a. The AWT class hierarchy ,
b. Events, Event sources,
c. Event classes,
d. Event Listeners,
e. Relationship between Event sources and Listeners,
f. Delegation event model,
g. Creating GUI applications using AWT,
h. Creating GUI applications using AWT.
6. Swing: 34-37
a. Introduction,
b. exploring swing-JApplet,JFrame and JComponent,
c. Icons and Labels,
d. Text fields, buttons – The Jbutton class,
e. Check boxes,
f. Radio buttons,
g. Combo boxes,
h. Tabbed Panes,
i. Scroll Panes,
j. Trees, and
k. Tables.

7. Applets and Servlets: 38-42


a. Concepts of Applets,
b. differences between applets and applications,
c. life cycle of an applet,
d. types of applets,
e. creating applets,
f. passing parameters to applets.Life Cycle of a Servlet,
g. The Servlet API,
h. Reading Servlet Parameters,
i. Handling HTTP Requests and Responses,
j. Cookies & Session Tracking.

5
23100030031 Java Training Report
Module 1. Object-Oriented Programming and Java
Fundamentals

a. What is Java?

o Java is a high-level, object-oriented programming language developed by Sun Microsystems


(now owned by Oracle). It is designed to have as few implementation dependencies as
possible, making it a "write once, run anywhere" language.

b. History of Java

o Java was initiated by James Gosling and his team at Sun Microsystems in the early 1990s.
Initially called "Oak," the language was later renamed "Java." The first version was released
in 1995, and it quickly became popular due to its platform independence, thanks to the Java
Virtual Machine (JVM).

c. Features of Java

o Platform Independence: Java code is compiled into bytecode, which can run on any system
with a JVM.
o Object-Oriented: Everything in Java is treated as an object.

6
23100030031 Java Training Report
o Simple and Secure: Java provides a simple and secure environment for developing
applications.
o Robust: Java has strong memory management, exception handling, and garbage collection.
o Multithreaded: Java supports multithreaded programming, allowing concurrent execution of
two or more threads.
o High Performance: Java achieves high performance with the help of the Just-In-Time (JIT)
compiler.
o Distributed: Java supports networking and can handle distributed applications.

d. Comparison of Java with C++

o Memory Management: Java has automatic garbage collection, whereas C++ requires
manual memory management.
o Syntax: Both have similar syntax, but Java is simpler as it lacks pointers and multiple
inheritance (which is handled by interfaces).
o Platform Independence: Java is platform-independent due to the JVM, while C++ is
platform-dependent.
o Object-Oriented: Both are object-oriented, but Java is purely object-oriented (with no global
functions or variables), whereas C++ supports both procedural and object-oriented
programming.

e. JDK, JRE & JVM

o JDK (Java Development Kit): It includes tools to develop Java applications, such as the
compiler and libraries.
o JRE (Java Runtime Environment): It provides the libraries and JVM required to run Java
applications.
o JVM (Java Virtual Machine): It executes Java bytecode and provides platform
independence.

f. Data Types,

o Data Types: Java supports primitive data types like int, char, float, etc., and non-primitive
data types like arrays and objects.

Java provides two types of data types:

7
23100030031 Java Training Report
Primitive Data Types: byte, short, int, long, float, double, char, boolean

Non-Primitive Data Types: String, Arrays, Classes, Interfaces

Programs for datatypes of java

public class DataTypesExample {

public static void main(String[] args) {

// Primitive Data Types

int age = 25;

double salary = 55000.50;

char grade = 'A';

boolean isPassed = true;

// Non-Primitive Data Types

String name = "John Doe";

// Output

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Salary: " + salary);

System.out.println("Grade: " + grade);

System.out.println("Passed: " + isPassed);

8
23100030031 Java Training Report
g. Variables,

o Variables: Variables are containers for storing data values.

Variables store data values. Java has three types:

 Local Variables: Declared inside a method.


 Instance Variables: Declared inside a class but outside any method.
 Static Variables: Declared with the static keyword.

Programs for java variales

public class VariablesExample {

// Instance Variable

int instanceVar = 10;

// Static Variable

static int staticVar = 20;

public void display() {

// Local Variable

int localVar = 30;

System.out.println("Local Variable: " + localVar);

public static void main(String[] args) {

VariablesExample obj = new VariablesExample();

9
23100030031 Java Training Report
obj.display();

System.out.println("Instance Variable: " + obj.instanceVar);

System.out.println("Static Variable: " + staticVar);

h. Arrays

o Arrays: Arrays in Java are objects that hold multiple values of the same type..An array is a
collection of variables of the same type.

Programs for array

public class ArraysExample {

public static void main(String[] args) {

// Array of integers

int[] numbers = {10, 20, 30, 40, 50};

// Accessing array elements

for (int i = 0; i < numbers.length; i++) {

System.out.println("Element at index " + i + ": " + numbers[i]);

10
23100030031 Java Training Report
i. Operators

Operators: Operators are used to perform operations on variables and values. Java supports
various operators:

 Arithmetic Operators: +, -, *, /, %
 Relational Operators: ==, !=, >, <, >=, <=
 Logical Operators: &&, ||, !
 Bitwise Operators: &, |, ^, ~, <<, >>, >>>
 Assignment Operators: =, +=, -=, *=, /=, %=

Program for java operators

public class OperatorsExample {

public static void main(String[] args) {

int a = 10, b = 5;

// Arithmetic Operators

System.out.println("Addition: " + (a + b));

System.out.println("Subtraction: " + (a - b));

System.out.println("Multiplication: " + (a * b));

System.out.println("Division: " + (a / b));

System.out.println("Modulus: " + (a % b));

// Relational Operators

System.out.println("a == b: " + (a == b));

System.out.println("a != b: " + (a != b));

11
23100030031 Java Training Report
// Logical Operators

System.out.println("a > 5 && b < 10: " + (a > 5 && b < 10));

// Bitwise Operators

System.out.println("a & b: " + (a & b));

j. Control Structures

o Control Structures: Java includes control structures like if, else, switch, while, for, do-
while, and break/continue for controlling the flow of the program.

Program for conditional statements

public class ConditionalExample {

public static void main(String[] args) {

int number = 10;

if (number > 0) {

System.out.println("Number is positive.");

} else if (number < 0) {

System.out.println("Number is negative.");

} else {

System.out.println("Number is zero.");

12
23100030031 Java Training Report
}

Program for looping statements


public class LoopsExample {
public static void main(String[] args) {
// For loop
for (int i = 1; i <= 5; i++) {
System.out.println("For Loop Iteration: " + i);
}

// While loop
int i = 1;
while (i <= 5) {
System.out.println("While Loop Iteration: " + i);
i++;
}

// Do-While loop
int j = 1;
do {
System.out.println("Do-While Loop Iteration: " + j);
j++;
} while (j <= 5);
}
}

13
23100030031 Java Training Report
Module 2. Interfaces and Packages

Interfaces in Java

 Basics: An interface in Java is a reference type, similar to a class, that can contain only
abstract methods and final static variables.

 Defining, Implementing, and Extending Interfaces: You define an interface using the
interface keyword, implement it using the implements keyword, and extend it using the
extends keyword.

Programs for Defining and Implementing an Interface

// Define an interface

interface Animal {

void sound(); // abstract method

// Implement the interface in a class

class Dog implements Animal {

// Providing the implementation of the sound() method

public void sound() {

System.out.println("Dog barks");

public class InterfaceExample {

14
23100030031 Java Training Report
public static void main(String[] args) {

// Creating an object of Dog class

Dog myDog = new Dog();

myDog.sound(); // Output: Dog barks

Program for Extending Interfaces

// Define an interface

interface Animal {

void sound();

// Extend the interface

interface Pet extends Animal {

void play();

// Implement the extended interface in a class

class Cat implements Pet {

public void sound() {

System.out.println("Cat meows");

public void play() {

15
23100030031 Java Training Report
System.out.println("Cat plays");

public class InterfaceExtensionExample {

public static void main(String[] args) {

// Creating an object of Cat class

Cat myCat = new Cat();

myCat.sound(); // Output: Cat meows

myCat.play(); // Output: Cat plays

Implementing Multiple Inheritance Using Interfaces: Java does not support multiple inheritance
with classes but allows it with interfaces.

// Define first interface

interface Printable {

void print();

// Define second interface

interface Showable {

void show();

// Implement both interfaces in a single class

16
23100030031 Java Training Report
class Document implements Printable, Showable {

public void print() {

System.out.println("Printing document");

public void show() {

System.out.println("Showing document");

public class MultipleInheritanceExample {

public static void main(String[] args) {

// Creating an object of Document class

Document doc = new Document();

doc.print(); // Output: Printing document

doc.show(); // Output: Showing document

 Differences between Classes and Interfaces:

Aspect Classes Interfaces


Defines contracts (what a class
Purpose Represents concrete implementations. must do).
Method Can have both concrete methods and Only abstract methods (method
Definitions abstract methods. signatures).
Declared using the interface
Keyword Declared using the class keyword. keyword.
Inheritance Supports single inheritance (extends one Supports multiple inheritance

17
23100030031 Java Training Report
class). (implements multiple interfaces).
Cannot have instance variables
Fields Can have instance variables (fields). (only constants).
Constructo Can have constructors for object No constructors (no object
r initialization. instantiation).
Access Methods and fields can have different
Modifiers access specifiers (public, private, etc.). All methods are implicitly public.
Example java class Dog { /* ... */ } java interface Car { /* ... */ }

Packages in Java

 Basics: Packages are used to group related classes and interfaces, making it easier to manage
large codebases.

 Creating and Accessing Packages:

Creating the Package


Save this file as MyPackage.java in a folder named mypack. You can create a package using the
package keyword and access it using the import statement.

Program

// Package declaration

package mypack;

public class MyPackage {

public void display() {

System.out.println("This is my package!");

Program for accessing packages

// Import the package

18
23100030031 Java Training Report
import mypack.MyPackage;

public class PackageExample {

public static void main(String[] args) {

// Create an object of the class in the package

MyPackage obj = new MyPackage();

obj.display(); // Output: This is my package!

 System Packages:

Java has several built-in packages, such as java.io, java.util, etc.

 User-Defined Packages: You can create your own packages to organize your code.
 Exploring Packages: Commonly used packages include:
o java.io: For input and output operations.
o java.util: For utility classes like collections, date, and time.

Using Built-in Packages (java.util, java.io)

import java.util.ArrayList; // Importing ArrayList from java.util package

import java.io.File; // Importing File class from java.io package

public class BuiltInPackagesExample {

public static void main(String[] args) {

// Using ArrayList from java.util package

ArrayList<String> list = new ArrayList<>();

list.add("Java");

19
23100030031 Java Training Report
list.add("Python");

System.out.println("Programming Languages: " + list);

// Using File class from java.io package

File file = new File("example.txt");

System.out.println("File exists: " + file.exists());

20
23100030031 Java Training Report
Module 3. Exception Handling
1. Exception Handling in Java
o Basics: Exceptions are unwanted or unexpected events that occur during program
execution. Java provides a robust mechanism to handle exceptions.
o Key Keywords:
 try: Encloses the code that might throw an exception.
 catch: Used to handle the exception thrown by the try block.
 throw: Used to explicitly throw an exception.
 throws: Indicates the exceptions that a method can throw.
 finally: Executes code after try and catch, regardless of whether an exception was
thrown.
o Nested try and Multiple catch Statements: Java allows nesting of try-catch blocks and
provides multiple catch blocks to handle different types of exceptions.

Basic Exception Handling (try-catch)

public class BasicExceptionHandling {

public static void main(String[] args) {

try {

// Code that may throw an exception

int divide = 10 / 0; // This will throw ArithmeticException

System.out.println("Result: " + divide);

} catch (ArithmeticException e) {

21
23100030031 Java Training Report
// Handling the exception

System.out.println("Cannot divide by zero. Exception: " + e);

System.out.println("Program continues after exception handling.");

2. Multiple Catch Blocks

public class MultipleCatchExample {

public static void main(String[] args) {

try {

int[] arr = {1, 2, 3};

System.out.println(arr[5]); // This will throw


ArrayIndexOutOfBoundsException

} catch (ArithmeticException e) {

System.out.println("Arithmetic Exception: " + e);

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array Index Out of Bounds Exception: " + e);

} catch (Exception e) {

System.out.println("General Exception: " + e);

22
23100030031 Java Training Report
3. Nested try-catch

public class NestedTryCatchExample {

public static void main(String[] args) {

try {

// Outer try block

try {

// Inner try block 1

int divide = 10 / 0; // This will throw ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Arithmetic Exception caught in inner try block


1: " + e);

try {

// Inner try block 2

int[] arr = {1, 2, 3};

System.out.println(arr[5]); // This will throw


ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array Index Out of Bounds Exception caught


in inner try block 2: " + e);

} catch (Exception e) {

System.out.println("Exception caught in outer try block: " + e);

23
23100030031 Java Training Report
}

4. Using `throw` Keyword

public class ThrowExample {

// Method that throws an exception

static void validateAge(int age) {

if (age < 18) {

// Throw an exception manually

throw new ArithmeticException("Age must be 18 or older.");

} else {

System.out.println("Eligible to vote");

public static void main(String[] args) {

// Call the method with an invalid value

try {

validateAge(16);

} catch (ArithmeticException e) {

System.out.println("Caught Exception: " + e);

24
23100030031 Java Training Report
5. Using `throws` Keyword

public class ThrowsExample {

// Method that declares exception using 'throws'

static void divide(int a, int b) throws ArithmeticException {

if (b == 0) {

throw new ArithmeticException("Cannot divide by zero");

} else {

System.out.println("Result: " + (a / b));

public static void main(String[] args) {

try {

divide(10, 0); // This will throw an ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Exception caught: " + e);

6. `finally` Block

public class FinallyBlockExample {

public static void main(String[] args) {

try {

int divide = 10 / 0; // This will throw an ArithmeticException

25
23100030031 Java Training Report
} catch (ArithmeticException e) {

System.out.println("Caught Exception: " + e);

} finally {

// This block will always execute

System.out.println("This is the finally block. It always runs.");

System.out.println("Program continues...");

7. Multiple Exceptions in Single `catch` Block (Java 7 and later)

public class MultiExceptionCatchExample {

public static void main(String[] args) {

try {

int divide = 10 / 0; // This will throw ArithmeticException

int[] arr = new int[5];

System.out.println(arr[10]); // This will throw


ArrayIndexOutOfBoundsException

} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {

System.out.println("Exception caught: " + e);

26
23100030031 Java Training Report
Module 4. Multithreading

1. Differences between Multithreading and Multitasking


Aspect Multitasking Multithreading
Manages multiple independent Divides a single process into multiple
Definition processes concurrently. threads that can run concurrently.
Resource Processes share separate Threads share the same memory space and
Sharing memory and resources. resources of the parent process.
Granularity Coarse-grained (process-level). Fine-grained (within a process).
Switching Higher overhead due to
Overhead frequent task switching. Lower overhead as threads share resources.
Performanc May be slower due to separate
e memory areas. Faster execution due to shared resources.
Running multiple applications Improving performance within a single
Example simultaneously. application.

2. Thread Life Cycle

 New: Thread is created but not yet started.


 Runnable: After calling start(), the thread is ready to run.
 Running: Thread is executing.
 Blocked/Waiting: Thread is waiting for some resources.
 Terminated: Thread has completed execution.

2. Creating Threads

Extending Thread Class

27
23100030031 Java Training Report
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}

public class ThreadExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start(); // Start the thread
}
}
Implementing Runnable Interface

class MyRunnable implements Runnable {


public void run() {
System.out.println("Runnable thread is running...");
}
}

public class RunnableExample {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}

4. Synchronizing Threads
class Counter {
synchronized void printCounter(int n) {
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
}
}
}

class MyThread1 extends Thread {


Counter counter;

MyThread1(Counter counter) {
this.counter = counter;
}

public void run() {

28
23100030031 Java Training Report
counter.printCounter(5);
}
}

public class SynchronizationExample {


public static void main(String[] args) {
Counter counter = new Counter();
MyThread1 t1 = new MyThread1(counter);
t1.start();
}
}
5. Daemon Threads
class DaemonThread extends Thread {
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println("Daemon thread is running.");
} else {
System.out.println("User thread is running.");
}
}

public static void main(String[] args) {


DaemonThread t1 = new DaemonThread();
DaemonThread t2 = new DaemonThread();
t1.setDaemon(true); // Setting t1 as Daemon thread

t1.start();
t2.start();
}
}

29
23100030031 Java Training Report
Module 5. Event Handling and AWT

1. Advanced AWT Event Handling


Event Handling in Java AWT:

Purpose: Crucial for building interactive graphical user interfaces.

Events: Respond to user actions (e.g., mouse clicks, key presses, window events).

Java AWT: Provides event listener interfaces and adapters for effective event handling.

AWT Class Hierarchy:

Components: Elements like buttons, text fields, scroll bars.

Containers: Organize components (e.g., panels, frames, dialogues).

Layout Managers: Arrange components within containers (e.g., BorderLayout,


FlowLayout).

Event Sources and Listeners:

Sources: Components (e.g., buttons, checkboxes) that generate events.

Listeners: Objects that handle specific types of events.

Delegation Event Model: Loose coupling between sources and listeners.

Common Event Classes in AWT: ActionEvent: Button clicks, menu item selections.

KeyEvent: Key presses on the keyboard.

MouseEvent: Mouse-related actions (clicks, movements).

WindowEvent: Window-related changes (closing, resizing).

30
23100030031 Java Training Report
Example: Tracking Mouse Movement

import java.awt.*;
import java.awt.event.*;

public class MouseMotionExample extends Frame implements MouseMotionListener {


Label label;

MouseMotionExample() {
label = new Label();
label.setBounds(50, 50, 200, 20);

// Add MouseMotionListener to Frame


addMouseMotionListener(this);

// Add components to Frame


add(label);

// Frame properties
setSize(400, 400);
setLayout(null);
setVisible(true);
}

public void mouseDragged(MouseEvent e) {


label.setText("Mouse dragged at (" + e.getX() + ", " + e.getY() + ")");
}

public void mouseMoved(MouseEvent e) {


label.setText("Mouse moved at (" + e.getX() + ", " + e.getY() + ")");
}

public static void main(String[] args) {


new MouseMotionExample();
}
}

Explanation:

 mouseDragged(): Called when the mouse is dragged.


 mouseMoved(): Called when the mouse is moved.

Handling Key Events

You can handle keyboard events using KeyListener.

Example: Handling Key Press and Release

31
23100030031 Java Training Report
import java.awt.*;
import java.awt.event.*;

public class KeyEventExample extends Frame implements KeyListener {


TextArea ta;

KeyEventExample() {
ta = new TextArea();
ta.setBounds(50, 50, 300, 200);
add(ta);

// Add KeyListener to TextArea


ta.addKeyListener(this);

// Frame properties
setSize(400, 300);
setLayout(null);
setVisible(true);
}

public void keyPressed(KeyEvent e) {


ta.append("Key Pressed: " + e.getKeyChar() + "\n");
}
public void keyReleased(KeyEvent e) {
ta.append("Key Released: " + e.getKeyChar() + "\n");
}

public void keyTyped(KeyEvent e) {}

public static void main(String[] args) {


new KeyEventExample();
}
}

Explanation:

 keyPressed(): Called when a key is pressed.


 keyReleased(): Called when a key is released.

2. Handling Focus Events

Focus events occur when a component gains or loses keyboard focus.

Example: Handling Focus Events

import java.awt.*;
import java.awt.event.*;

public class FocusEventExample extends Frame implements FocusListener {


TextField tf1, tf2;

32
23100030031 Java Training Report
FocusEventExample() {
tf1 = new TextField("Focus on me");
tf1.setBounds(50, 50, 150, 30);

tf2 = new TextField("Or focus on me");


tf2.setBounds(50, 100, 150, 30);

tf1.addFocusListener(this);
tf2.addFocusListener(this);
add(tf1);
add(tf2);
setSize(300, 200);
setLayout(null);
setVisible(true);
}

public void focusGained(FocusEvent e) {


TextField tf = (TextField) e.getSource();
tf.setBackground(Color.YELLOW);
}

public void focusLost(FocusEvent e) {


TextField tf = (TextField) e.getSource();
tf.setBackground(Color.WHITE);
}

public static void main(String[] args) {


new FocusEventExample();
}
}

Explanation:

 focusGained(): Called when the component gains focus.


 focusLost(): Called when the component loses focus.

33
23100030031 Java Training Report
Module 6. Swing

1. Introduction to Swing Components

Swing components are more flexible and feature-rich compared to AWT components. They provide a
more consistent look and feel across different platforms.

2. Exploring Swing Components


JFrame and JComponent

Example: Creating a Basic Swing Application

java
Copy code
import javax.swing.*;

public class SwingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Hello, Swing!");


JButton button = new JButton("Click Me");

JPanel panel = new JPanel();


panel.add(label);
panel.add(button);

frame.add(panel);
frame.setVisible(true);
}
}

34
23100030031 Java Training Report
Explanation:

 JFrame: A top-level window with standard decorations.


 JLabel: Displays a short string or an image icon.
 JButton: A push button that can trigger an action.
 JPanel: A container that can hold and organize other components.

JButton, JTextField, JCheckBox, JRadioButton

Example: Using Various Swing Components

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

public class SwingComponentsExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components Example");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

JTextField textField = new JTextField();


textField.setBounds(50, 50, 200, 30);

JButton button = new JButton("Submit");


button.setBounds(50, 100, 100, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Text: " + textField.getText());
}
});

JCheckBox checkBox = new JCheckBox("Check me");


checkBox.setBounds(50, 150, 100, 30);

JRadioButton radioButton = new JRadioButton("Select me");


radioButton.setBounds(50, 200, 100, 30);

ButtonGroup group = new ButtonGroup();


group.add(radioButton);

frame.add(textField);
frame.add(button);
frame.add(checkBox);
frame.add(radioButton);

frame.setVisible(true);
}

35
23100030031 Java Training Report
}

Explanation:

 JTextField: Allows user to input text.


 JButton: A button that can trigger actions.
 JCheckBox: Allows the user to select or deselect an option.
 JRadioButton: Allows the user to select one option from a group of options.

JComboBox, JTabbedPane, JScrollPane

Example: Using ComboBox, TabbedPane, and ScrollPane

java
Copy code
import javax.swing.*;

public class SwingAdvancedComponents {


public static void main(String[] args) {
JFrame frame = new JFrame("Advanced Swing Components");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

// JComboBox
JComboBox<String> comboBox = new JComboBox<>(new String[]{"Option 1", "Option 2",
"Option 3"});
comboBox.setBounds(50, 50, 150, 30);

// JTabbedPane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setBounds(50, 100, 300, 100);
tabbedPane.addTab("Tab 1", new JLabel("Content of Tab 1"));
tabbedPane.addTab("Tab 2", new JLabel("Content of Tab 2"));

// JScrollPane
JTextArea textArea = new JTextArea("Scrollable content goes here...");
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(50, 220, 300, 100);

frame.add(comboBox);
frame.add(tabbedPane);
frame.add(scrollPane);

frame.setVisible(true);
}
}

Explanation:

36
23100030031 Java Training Report
 JComboBox: Provides a drop-down list of options.
 JTabbedPane: Allows for tabbed navigation between different panels.
 JScrollPane: Provides a scrollable view of another component, like a JTextArea.

JTree and JTable

Example: Using JTree and JTable

java
Copy code
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.table.DefaultTableModel;

public class SwingTreeTableExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Tree and Table Example");
frame.setSize(500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

// JTree
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
root.add(child1);
root.add(child2);
JTree tree = new JTree(root);
tree.setBounds(50, 50, 150, 150);

// JTable
String[] columnNames = {"Name", "Age", "City"};
Object[][] data = {
{"Alice", 30, "New York"},
{"Bob", 25, "San Francisco"},

37
23100030031 Java Training Report
Module 7. Applets and Servlets

1. Applets

An applet is a Java program that runs inside a web browser or an applet viewer. It is a client-side
program, meaning it is executed on the client machine. Applets are embedded in HTML pages and can be
executed via a browser with Java support.

Concepts of Applets

 Applets differ from standard Java applications because they don't have a main() method. Instead,
they rely on several lifecycle methods, such as init(), start(), stop(), and destroy().

Life Cycle of an Applet

The life cycle of an applet consists of four main methods:

1. init(): This method is called when the applet is first loaded. It is used to initialize variables or set
up resources.
2. start(): Called after init(), or when the applet is restarted. It is where the execution starts or
resumes.
3. stop(): This method is called when the applet is stopped or the user navigates away from the
page.
4. destroy(): This method is called when the applet is about to be removed permanently from
memory.

Example: Simple Applet Program


import java.applet.Applet;
import java.awt.Graphics;

public class SimpleApplet extends Applet {

// init() method - called when applet is loaded


public void init() {
System.out.println("Applet Initialized");
}

// start() method - called after init() or when applet is restarted


public void start() {
System.out.println("Applet Started");
}

// stop() method - called when applet is stopped or user navigates away


public void stop() {
System.out.println("Applet Stopped");
}

38
23100030031 Java Training Report
// destroy() method - called before applet is removed from memory
public void destroy() {
System.out.println("Applet Destroyed");
}

// paint() method - used to draw graphics


public void paint(Graphics g) {
g.drawString("Hello Applet!", 50, 50);
}
}

Types of Applets

1. Local Applet: These applets are stored on the user's local machine. They don't need any network
access.
2. Remote Applet: These applets are stored on a remote web server and downloaded to the client's
machine when the web page containing the applet is loaded.

Differences between Applets and Applications

Feature Applet Application

Runs inside
Runs
a web
independently
Execution browser or
as a Java
applet
program
viewer

main() No main() Contains the


method method main() method

Has init(),
Lifecycle start(), Uses only
methods stop(), main() method
destroy()

Limited
Full access to
access to
Security system
system
resources
resources

39
23100030031 Java Training Report
2. Servlets

 Servlets are Java programs that run on a server and handle client requests and responses.
 They are used to create dynamic web content, process form data, and interact with databases.
 Servlets are managed by a web container (e.g., Tomcat, Jetty).

Life Cycle of a Servlet

1. Initialization: The servlet is loaded and initialized using the init() method.
2. Request Handling: The servlet processes client requests using the service() method.
3. Destruction: The servlet is destroyed using the destroy() method when it is no longer needed.

The Servlet API

 HttpServlet: A class that extends GenericServlet and is used for handling HTTP requests.
 HttpServletRequest: Represents the request made by the client.
 HttpServletResponse: Represents the response to be sent to the client.

Example: A Simple Servlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, Servlet!</h1>");
out.println("</body></html>");
}
}

Explanation:

 doGet(HttpServletRequest request, HttpServletResponse response): Handles GET requests.


Writes HTML content to the response.

Deploying and Running the Servlet:

1. Compile the Servlet: Use javac HelloWorldServlet.java.


2. Package into a WAR file: Create a WAR file containing the compiled servlet and a web.xml
deployment descriptor.

40
23100030031 Java Training Report
3. Deploy to a Web Container: Place the WAR file in the webapps directory of a web container like
Tomcat.
4. Access the Servlet: Open a web browser and navigate to
http://localhost:8080/your-app/HelloWorldServlet.

3. Parameters and Session Tracking


Reading Servlet Parameters

Example: Reading Form Data

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FormServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");

response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h2>Form Data</h2>");
response.getWriter().println("Name: " + name + "<br>");
response.getWriter().println("Email: " + email);
response.getWriter().println("</body></html>");
}
}

Explanation:

 request.getParameter(String name): Retrieves form data from the request.

Handling Cookies and Sessions

 Cookies: Used to store small pieces of data on the client side.

Example: Creating a Cookie

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServlet extends HttpServlet {

41
23100030031 Java Training Report
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie cookie = new Cookie("user", "JohnDoe");
response.addCookie(cookie);
response.getWriter().println("Cookie has been set.");
}
}

 Sessions: Used to track user sessions across multiple requests.

Example: Using Sessions

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("username", "JohnDoe");

response.getWriter().println("Session data has been set.");


}
}

Explanation:

 HttpSession: Represents a session between a client and server.

42
23100030031 Java Training Report
Practicle 1
1.A Write a java program to find the Fibonacci series

public class FibonacciSeries {

public static void main(String[] args) {

int terms = 10; // Number of terms in the Fibonacci series

printFibonacci(terms);

public static void printFibonacci(int terms) {

int a = 0, b = 1;

System.out.print("Fibonacci Series: " + a);

for (int i = 1; i < terms; i++) {

System.out.print(", " + b);

int next = a + b;

a = b;

b = next;

}
1.B Write a java program to multiply two given matrices.

public class MatrixMultiplication {

public static void main(String[] args) {

int[][] matrixA = {

{1, 2}, {3, 4}

};

int[][] matrixB = {

{2, 0}, {1, 3} };

43
23100030031 Java Training Report
int[][] result = multiplyMatrices(matrixA, matrixB);

System.out.println("Resultant Matrix:");

for (int[] row : result) {

for (int value : row) {

System.out.print(value + " ");

System.out.println();

public static int[][] multiplyMatrices(int[][] a, int[][] b) {

int rowsA = a.length;

int colsA = a[0].length;

int rowsB = b.length;

int colsB = b[0].length;

if (colsA != rowsB) {

throw new IllegalArgumentException("Matrix dimensions do not match for multiplication.");

int[][] result = new int[rowsA][colsB];

for (int i = 0; i < rowsA; i++) {

for (int j = 0; j < colsB; j++) {

for (int k = 0; k < colsA; k++) {

result[i][j] += a[i][k] * b[k][j];

return result;

44
23100030031 Java Training Report
2.A Write a java program for Method overloads and Constructor overloading.
public class OverloadingExample {

// Constructor Overloading

public OverloadingExample() {

System.out.println("No-argument constructor");

public OverloadingExample(int a) {

System.out.println("Constructor with int: " + a);

public OverloadingExample(double b) {

System.out.println("Constructor with double: " + b);

// Method Overloading

public void display() {

System.out.println("No-argument method");

public void display(int x) {

System.out.println("Method with int: " + x);

public void display(double y) {

System.out.println("Method with double: " + y);

public static void main(String[] args) {

OverloadingExample obj1 = new OverloadingExample();

OverloadingExample obj2 = new OverloadingExample(10);

OverloadingExample obj3 = new OverloadingExample(15.5);

45
23100030031 Java Training Report
obj1.display();

obj1.display(100);

obj1.display(200.5);

2.B Write a Java program that checks whether a given string is a palindrome
or not. Ex: MADAM is a palindrome.
public class PalindromeChecker {

public static boolean isPalindrome(String str) {

str = str.toLowerCase();

int start = 0, end = str.length() - 1;

while (start < end) {

if (str.charAt(start) != str.charAt(end)) return false;

start++;

end--;

return true;

public static void main(String[] args) {

String[] testStrings = {"MADAM", "HELLO", "RACECAR", "WORLD"};

for (String str : testStrings) {

if (isPalindrome(str)) {

System.out.println(str + " is a palindrome.");

} else {

System.out.println(str + " is not a palindrome.");

46
23100030031 Java Training Report
3.A Write a Java program to create an abstract class named Shape that
contains two integers and an empty method named print Area ().
Provide three classes named Rectangle, Triangle, and Circle such
that each one of the classes extends the class Shape. Each one of the
classes contains only the method print Area () that prints the area of the
given shape

// Abstract class Shape

abstract class Shape {

protected int dimension1;

protected int dimension2;

abstract void printArea();

// Rectangle class

class Rectangle extends Shape {

public Rectangle(int width, int height) {

this.dimension1 = width;

this.dimension2 = height;

@Override

void printArea() {

System.out.println("Area of Rectangle: " + (dimension1 * dimension2));

// Triangle class

class Triangle extends Shape {

public Triangle(int base, int height) {

this.dimension1 = base;

47
23100030031 Java Training Report
this.dimension2 = height;

@Override

void printArea() {

System.out.println("Area of Triangle: " + (0.5 * dimension1 * dimension2));

// Circle class

class Circle extends Shape {

public Circle(int radius) {

this.dimension1 = radius;

@Override

void printArea() {

System.out.println("Area of Circle: " + (Math.PI * dimension1 * dimension1));

public class ShapeDemo {

public static void main(String[] args) {

Shape rect = new Rectangle(5, 10);

Shape tri = new Triangle(6, 8);

Shape circ = new Circle(7);

rect.printArea();

tri.printArea();

circ.printArea(); }

48
23100030031 Java Training Report
3.B Write a Java program to implement Inheritance,
// Base class Animal

class Animal {

void eat() {

System.out.println("This animal eats food.");

// Derived class Dog

class Dog extends Animal {

void bark() {

System.out.println("The dog barks.");

// Derived class Cat

class Cat extends Animal {

void meow() {

System.out.println("The cat meows.");

public class InheritanceDemo {

public static void main(String[] args) {

Dog dog = new Dog();

Cat cat = new Cat();

dog.eat();

cat.eat();

dog.bark();

cat.meow(); }}

49
23100030031 Java Training Report
4. Write a Java program to implement interfaces and packages.

// Define an interface

interface Animal {

void makeSound();

// Implement the interface in the Dog class

class Dog implements Animal {

@Override

public void makeSound() {

System.out.println("Dog barks");

// Implement the interface in the Cat class

class Cat implements Animal {

@Override

public void makeSound() {

System.out.println("Cat meows");

public class InterfaceDemo {

public static void main(String[] args) {

Animal dog = new Dog();

Animal cat = new Cat();

dog.makeSound();

cat.makeSound();

50
23100030031 Java Training Report
package mypackage;

public interface Animal {

void makeSound();

package mypackage;

public class Dog implements Animal {

@Override

public void makeSound() {

System.out.println("Dog barks");

package mypackage;

public class Cat implements Animal {

@Override

public void makeSound() {

System.out.println("Cat meows");

package mypackage;

public class Main {

public static void main(String[] args) {

Animal dog = new Dog();

Animal cat = new Cat();

dog.makeSound();

cat.makeSound();

51
23100030031 Java Training Report
5. Write a program which will explain the concept of try, catch and throw.

public class ExceptionDemo {

// Method to demonstrate throwing an exception


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}

public static void main(String[] args) {


int[] ages = {15, 20, 17};

for (int age : ages) {


try {
// Try to check age
checkAge(age);
} catch (ArithmeticException e) {
// Catch block to handle the exception
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
}

52
23100030031 Java Training Report
6. Write a java program that handles all mouse events and shows the event
name at the center of the window when a mouse event is fired.
import javax.swing.*;

import java.awt.*;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

public class MouseEventDemo extends JFrame implements MouseListener {

private String eventName = "";

public MouseEventDemo() {

setTitle("Mouse Event Demo");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

addMouseListener(this);

@Override

public void paint(Graphics g) {

super.paint(g);

Graphics2D g2d = (Graphics2D) g;

FontMetrics fm = g2d.getFontMetrics();

int x = (getWidth() - fm.stringWidth(eventName)) / 2;

int y = (getHeight() + fm.getAscent()) / 2;

g2d.drawString(eventName, x, y);

53
23100030031 Java Training Report
@Override

public void mouseClicked(MouseEvent e) { eventName = "Mouse Clicked"; repaint(); }

@Override

public void mousePressed(MouseEvent e) { eventName = "Mouse Pressed"; repaint(); }

@Override

public void mouseReleased(MouseEvent e) { eventName = "Mouse Released"; repaint(); }

@Override

public void mouseEntered(MouseEvent e) { eventName = "Mouse Entered"; repaint(); }

@Override

public void mouseExited(MouseEvent e) { eventName = "Mouse Exited"; repaint(); }

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new MouseEventDemo().setVisible(true));

54
23100030031 Java Training Report
7. showing concept of threads by importing thread class
import javax.swing.*;

import java.awt.*;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

public class MouseEventDemo extends JFrame implements MouseListener {

private String eventName = "";

public MouseEventDemo() {

setTitle("Mouse Event Demo");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

addMouseListener(this);

@Override

public void paint(Graphics g) {

super.paint(g);

Graphics2D g2d = (Graphics2D) g;

FontMetrics fm = g2d.getFontMetrics();

int x = (getWidth() - fm.stringWidth(eventName)) / 2;

int y = (getHeight() + fm.getAscent()) / 2;

g2d.drawString(eventName, x, y);

55
23100030031 Java Training Report
@Override

public void mouseClicked(MouseEvent e) { eventName = "Mouse Clicked"; repaint(); }

@Override

public void mousePressed(MouseEvent e) { eventName = "Mouse Pressed"; repaint(); }

@Override

public void mouseReleased(MouseEvent e) { eventName = "Mouse Released"; repaint(); }

@Override

public void mouseEntered(MouseEvent e) { eventName = "Mouse Entered"; repaint(); }

@Override

public void mouseExited(MouseEvent e) { eventName = "Mouse Exited"; repaint(); }

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new MouseEventDemo().setVisible(true));

56
23100030031 Java Training Report
8. a) Write an applet program that displays a simple message.
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="SimpleMessageApplet" width="300" height="100">
</applet>
*/
public class SimpleMessageApplet extends Applet {
@Override
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
}}
8. b) Write a Java program compute factorial value using Applet.
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="FactorialApplet" width="300" height="100">
</applet>
*/
public class FactorialApplet extends Applet {
@Override
public void paint(Graphics g) {
int number = 5; // Example number
g.drawString("Factorial of " + number + " is: " + factorial(number), 20, 50);
}
private int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}}
8. c) Write a program for passing parameters using Applet.
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="ParamApplet" width="300" height="100">
<param name="message" value="Default message">
</applet>
*/
public class ParamApplet extends Applet {
private String message;

@Override

public void init() {

message = getParameter("message"); // Get parameter from HTML

if (message == null) {
message = "No message provided";
}}
@Override
public void paint(Graphics g) {
g.drawString(message, 50, 50);
}}

57
23100030031 Java Training Report
9.a) Write a program to describe AWT Class, Frames, Panels and Drawing.
import java.awt.*;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class AWTExample extends Frame {

public AWTExample() {

setTitle("AWT Example");

setSize(400, 300);

setLayout(new BorderLayout());

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0); }

});

Panel panel = new Panel();

panel.add(new Label("AWT Example Label"));

add(panel, BorderLayout.CENTER);

add(new Canvas() {

public void paint(Graphics g) {

g.setColor(Color.RED);

g.fillRect(50, 50, 100, 100);

g.setColor(Color.BLUE);

g.drawLine(50, 50, 150, 150);

}, BorderLayout.SOUTH);

public static void main(String[] args) {

new AWTExample().setVisible(true);

58
23100030031 Java Training Report
}

9.b) Write a Java program that works as a simple calculator. Use a grid layout
to arrange buttons for the digits and for the, -,*, % operations. Add a text field
to display the result. Handle any possible exceptions like divided by zero.
import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {

private JTextField display = new JTextField();

private StringBuilder currentInput = new StringBuilder();

private double result = 0;

private String operator = "";

public Calculator() {

setTitle("Calculator");

setSize(400, 500);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout());

add(display, BorderLayout.NORTH);

JPanel panel = new JPanel(new GridLayout(4, 4));

String[] buttons = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "C", "0", "=", "+" };

for (String text : buttons) {

JButton button = new JButton(text);

button.addActionListener(this);

panel.add(button);

add(panel, BorderLayout.CENTER);

59
23100030031 Java Training Report
public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if ("0123456789".contains(command)) {

currentInput.append(command);

display.setText(currentInput.toString());

} else if (command.equals("C")) {

currentInput.setLength(0);

display.setText("");

result = 0;

operator = "";

} else if (command.equals("=")) {

try {

double input = Double.parseDouble(currentInput.toString());

switch (operator) {

case "+": result += input; break;

case "-": result -= input; break;

case "*": result *= input; break;

case "/": result = (input != 0) ? result / input : Double.NaN; break;

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

currentInput.setLength(0);

} catch (NumberFormatException ex) {

display.setText("Error");

} else {

if (currentInput.length() > 0) {

result = Double.parseDouble(currentInput.toString());

currentInput.setLength(0);

60
23100030031 Java Training Report
}

operator = command;

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> new Calculator().setVisible(true));

61
23100030031 Java Training Report
10.Write a program to demonstrate JDBC and build an application.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class JdbcDemo {

// JDBC URL, username, and password

private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USER = "root";

private static final String PASSWORD = "password";

public static void main(String[] args) {

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

try {

// Load the JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection

connection = DriverManager.getConnection(URL, USER, PASSWORD);

// Create a statement

statement = connection.createStatement();

// Execute a query

String sql = "SELECT id, name FROM mytable";

resultSet = statement.executeQuery(sql);

62
23100030031 Java Training Report
// Process the result set

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

System.out.println("ID: " + id + ", Name: " + name);

} catch (ClassNotFoundException e) {

System.out.println("JDBC Driver not found.");

e.printStackTrace();

} catch (SQLException e) {

System.out.println("SQL Exception.");

e.printStackTrace();

} finally {

// Clean up resources

try {

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

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

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

} catch (SQLException e) {

e.printStackTrace();

63
23100030031 Java Training Report

You might also like