Experiment-1
a Java Program to define a class, define instance methods for setting and
retrieving values of instance variables , instantiate its object and operators.
public class Person {
// Instance
variables private
String name; private
int age;
// Constructor
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
// Method to set the name
public void setName(String name)
{ [Link] = name;
}
// Method to get the name
public String getName() {
return name;
}
// Method to set the age
public void setAge(int age) {
[Link] = age;
}
// Method to get the age
public int getAge() {
return age;
}
// Main method to demonstrate the class functionality
public static void main(String[] args) {
// Instantiate an object of the Person class
Person person = new Person("Alice", 30);
// Retrieve and print initial values
[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
// Set new values
[Link]("Bob");
[Link](25);
// Retrieve and print updated values
[Link]("Updated Name: " + [Link]());
[Link]("Updated Age: " + [Link]());
// Demonstrate using operators
int yearsToAdd = 5;
[Link](30);
[Link]("Age after " + yearsToAdd + " years: " + [Link]());
}
}
Output:
Name: Alice
Age: 30
Updated Name: Bob
Updated Age: 25
Age after 5 years: 30
Experiment-2
Write a java program to find the transpose, addition, subtraction and
multiplication of a two-dimensional matrix using loops.
class Main {
public static void main(String[] args) {
int[][] matrixA = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] matrixB = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int[][] resultAddition = new int[3][3]; int[]
[] resultSubtraction = new int[3][3]; int[][]
resultMultiplication = new int[3][3];
// Addition
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 3; j++)
{
resultAddition[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
// Subtraction
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 3; j++)
{
resultSubtraction[i][j] = matrixA[i][j] - matrixB[i][j];
}
}
// Multiplication
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 3; j++)
{
resultMultiplication[i][j] = 0;
for (int k = 0; k < 3; k++) {
resultMultiplication[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Display results
[Link]("Addition of matrices:");
displayMatrix(resultAddition);
[Link]("Subtraction of matrices:");
displayMatrix(resultSubtraction);
[Link]("Multiplication of matrices:");
displayMatrix(resultMultiplication);
}
public static void displayMatrix(int[][] matrix)
{ for (int[] row : matrix) {
for (int element : row)
{ [Link](element + " ");
}
[Link]();
}
}
}
Output:
Addition of matrices:
10 10 10
10 10 10
10 10 10
Subtraction of matrices:
-8 -6 -4
-2 0 2
468
Multiplication of matrices:
30 24 18
84 69 54
138 114 90
Experiment-3
Write a Java program on command line arguments.
class A{
public static void main(String args[])
{ for(int i=0;i<[Link];i++)
[Link](args[i]);
}
}
compile by > javac [Link]
run by > java A sonoo jaiswal 1 3 abc
output:
sonoo
jaiswal
1
3
abc
Experiment-4
Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.
class Constructor
{
Constructor( )
{
[Link](“Default Constructor”);
}
Constructor(int a)
{
[Link](a);
}
Constructor(int a,int b)
{
[Link](a+b);
}
public static void main(String[] args)
{ Constructor c1=new Constructor();
Constructor c1=new Constructor(10);
Constructor c1=new Constructor(20,50);
}
}
Output:
Default Constructor
10
70
Experiment-5
Write a Java Program to illustrate method overloading
public class MethodOverloadingExample {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Overloaded method to add two double values
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
MethodOverloadingExample example = new MethodOverloadingExample();
// Calling the add method with two integers
[Link]("Sum of 10 and 20: " + [Link](10, 20));
// Calling the overloaded add method with three integers
[Link]("Sum of 10, 20 and 30: " + [Link](10, 20, 30));
// Calling the overloaded add method with two double values
[Link]("Sum of 10.5 and 20.5: " + [Link](10.5, 20.5));
}
}
Output:
Sum of 10 and 20: 30
Sum of 10, 20 and 30: 60
Sum of 10.5 and 20.5: 31.0
Experiment-6
Write a java program to demonstrate static variables and static methods.
class Main
{
static int x=10;
static void show()
{
[Link](“show method”);
}
public static void main(String args[])
{
[Link](x);
show();
}
}
Output:
10
show method
Experiment-7
Write a Java program to practice using String class and its methods.
public class StringMethodsDemo
{ public static void main(String[] args)
{
// Creating a string
String str = "Hello, World!";
// 1. Length of the string
int length = [Link]();
[Link]("Length of the string: " + length);
// 2. Character at a specific index
char charAt5 = [Link](5);
[Link]("Character at index 5: " + charAt5);
// 3. Substring from the string
String substring = [Link](7, 12);
[Link]("Substring from index 7 to 12: " + substring);
// 4. Concatenation of strings
String str2 = " How are you?";
String concatenated = [Link](str2);
[Link]("Concatenated string: " + concatenated);
// 5. Index of a character or substring
int indexOfW = [Link]('W');
[Link]("Index of 'W': " + indexOfW);
// 6. Replace characters in the string
String replacedString = [Link]('o', '0');
[Link]("String after replacement: " + replacedString);
// 7. Convert to uppercase
String upperCaseString = [Link]();
[Link]("Uppercase string: " + upperCaseString);
// 8. Convert to lowercase
String lowerCaseString = [Link]();
[Link]("Lowercase string: " + lowerCaseString);
// 9. Trim whitespace from the string
String strWithWhitespace = " Hello, World! ";
String trimmedString = [Link]();
[Link]("Trimmed string: '" + trimmedString + "'");
// 10. Check if the string contains a substring
boolean containsHello = [Link]("Hello");
[Link]("Does the string contain 'Hello'? " + containsHello);
}
}
Output:
Length of the string: 13
Character at index 5:
Substring from index 7 to 12: World
Concatenated string: Hello, World! How are you?
Index of 'W': 7
String after replacement: Hell0, W0rld!
Uppercase string: HELLO, WORLD!
Lowercase string: hello, world!
Does the string contain 'Hello'?
true
Experiment-8
Write a Java Program to implement single inheritance.
class Animal {
// Method in the base class
void eat() {
[Link]("This animal eats food.");
}
}
// Derived class
class Dog extends Animal {
// Method in the derived class
void bark() {
[Link]("The dog barks.");
}
public static void main(String[] args) {
// Create an object of the derived class
Dog myDog = new Dog();
// Call methods from both the base and derived class
[Link](); // Method from the base class
[Link](); // Method from the derived class
}
}
Output:
This animal eats food.
The dog barks.
Experiment-9
Write a Java program using ‘this’ and ‘super’ keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](rollno+" "+name+" "+fee);
}
}
class Main{
public static void main(String[] args){
Student s1=new Student(111,"ankit",5000f);
Student s2=new
Student(112,"sumit",6000f); [Link]();
[Link]();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0
Experiment-10
Write a java program to illustrate method overriding
class Super
{
void display()
{
[Link](“Super class method”);
}
}
class Sub extends Super
{
void display()
{
[Link](“Sub class method”);
}
public static void main(String args[])
{
Sub s=new Sub();
[Link]();
}
}
Output:
Sub class method
Experiment-11
Write a java program to implement multiple inheritance using the concept of
interface.
// Define the first interface
interface Animal {
void eat();
}
// Define the second interface
interface Bird {
void fly();
}
// Implement both interfaces in a single class
class Bat implements Animal, Bird {
// Implement the eat method from Animal interface
public void eat() {
[Link]("Bat is eating.");
}
// Implement the fly method from Bird interface
public void fly() {
[Link]("Bat is flying.");
}
}
// Main class to test the implementation
public class MultipleInheritanceDemo
{ public static void main(String[] args) {
Bat bat = new Bat();
[Link]();
[Link]();
}
}
Output:
Bat is eating.
Bat is flying.
Experiment-12
Write a Java program to implement the concept of importing classes from user
defined package and creating packages , creating sub packages.
//save by [Link].
package pack1;
public class Class1{
public void display(){
[Link]("Inside class1 method.")
}
//save by [Link]
package pack2;
import pack1.*;
class Class2{
public static void main(String args[])
{ Class1 obj = new Class1();
[Link]();
}
}
Output:
Inside class1 method.
Experiment-13
Write a Java program using util package classes.
import [Link];
import [Link];
public class UtilPackageExample
{
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
// Add some numbers to the list
[Link](5);
[Link](3);
[Link](8);
[Link](1);
[Link](6);
// Print the original list
[Link]("Original list: " + numbers);
// Sort the list using [Link]()
[Link](numbers);
// Print the sorted list
[Link]("Sorted list: " + numbers);
}
}
Output:
Original list: [5, 3, 8, 1, 6]
Sorted list: [1, 3, 5, 6, 8]
Experiment-14
Write a Java program on applet life cycle
import [Link];
import [Link];
public class AppletLifeCycle extends Applet {
// Called when the applet is first loaded
public void init() {
[Link]("Applet initialized");
}
// Called when the applet is started or restarted
public void start() {
[Link]("Applet started");
}
// Called when the applet is stopped
public void stop() {
[Link]("Applet stopped");
}
// Called when the applet is destroyed
public void destroy() {
[Link]("Applet destroyed");
}
// Called to paint the applet
public void paint(Graphics g) {
[Link]("Applet Life Cycle Demo", 20, 20);
}
}
To Compile: javac [Link]
//[Link]
<!DOCTYPE html>
<html>
<body>
<applet code="[Link]" width="300" height="200">
</applet>
</body>
</html>
To Execute: appletviewer [Link]
Output:
Applet initialized
Applet started
Applet stopped
Applet destroyed
Experiment-15
Write a Java program on all AWT controls along with Events and its Listeners.
import [Link].*;
import [Link].*;
public class AWTControlsExample extends Frame {
// Declare AWT components
Button btnClick;
TextField textField;
Label label;
Checkbox checkbox;
CheckboxGroup radioGroup;
Checkbox radio1, radio2;
TextArea textArea;
public AWTControlsExample() {
// Set the frame layout
setLayout(new FlowLayout());
// Initialize components
btnClick = new Button("Click Me");
textField = new TextField(20);
label = new Label("This is a label");
checkbox = new Checkbox("Accept Terms and Conditions");
radioGroup = new CheckboxGroup();
radio1 = new Checkbox("Option 1", radioGroup, false);
radio2 = new Checkbox("Option 2", radioGroup, false);
textArea = new TextArea("Type something here...");
// Add components to the frame
add(btnClick);
add(textField);
add(label);
add(checkbox);
add(radio1);
add(radio2);
add(textArea);
// Event handling for button click
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e)
{ [Link]("Button clicked");
}
});
// Event handling for checkbox state change
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if ([Link]()) {
[Link]("Checkbox selected");
} else {
[Link]("Checkbox unselected");
}
}
});
// Event handling for radio button state change
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if ([Link]()) {
[Link]("Radio Button 1 selected");
}
}
});
[Link](new ItemListener()
{ public void itemStateChanged(ItemEvent e) {
if ([Link]()) {
[Link]("Radio Button 2 selected");
}
}
});
// Event handling for text field input
[Link](new TextListener() {
public void textValueChanged(TextEvent e) {
[Link]("Text Field updated");
}
});
// Event handling for window closing
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0); // Close the window when the close button is clicked
}
});
// Set frame properties
setTitle("AWT Controls and Events Example");
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
new AWTControlsExample();
}
}
Output:
Experiment-16
Write a Java program on mouse and keyboard events.
import [Link].*;
import [Link].*;
public class MouseKeyboardEventsExample extends Frame {
// Declare components
Label mouseLabel, keyboardLabel;
public MouseKeyboardEventsExample() {
// Set the frame layout
setLayout(new FlowLayout());
// Initialize components
mouseLabel = new Label("Mouse Event not yet triggered");
keyboardLabel = new Label("Keyboard Event not yet triggered");
// Add components to the frame
add(mouseLabel);
add(keyboardLabel);
// Mouse event handling
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at: (" + [Link]() + ", " + [Link]() + ")");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed at: (" + [Link]() + ", " + [Link]() + ")");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released at: (" + [Link]() + ", " + [Link]() + ")");
}
public void mouseEntered(MouseEvent e)
{ [Link]("Mouse entered the window");
}
public void mouseExited(MouseEvent e)
{ [Link]("Mouse exited the window");
}
});
// Key event handling
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{ [Link]("Key Pressed: " + [Link]());
}
public void keyReleased(KeyEvent e)
{ [Link]("Key Released: " + [Link]());
}
public void keyTyped(KeyEvent e) {
// Optional: This event will trigger when a key is typed (character is produced)
//[Link]("Key Typed: " + [Link]());
}
});
// Set frame properties
setTitle("Mouse and Keyboard Events Example");
setSize(400, 200);
setVisible(true);
// Make the frame focusable so it can receive keyboard events
setFocusable(true);
}
public static void main(String[] args)
{ new
MouseKeyboardEventsExample();
}
}
Output:
Experiment-17
Write a Java program on Exception handling.
class Main {
public static void main(String[] args)
{ try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{ [Link]("ArithmeticException => " + [Link]());
}
finally {
[Link]("This is the finally block");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block
Experiment-18
Write a program to implement multi-catch statements
public class MultipleCatchBlock3
{ public static void main(String[] args)
{
try{
int a[]=new int[5];
a[5]=30/0;
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Experiment-19
Write a java program on nested try statements.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
Output:
Experiment-20
Write a java program to create user-defined exceptions.
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws
InvalidAgeException{ if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote");
}
else {
[Link]("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
[Link]("Caught the exception");
// printing the message from InvalidAgeException object
[Link]("Exception occured: " + ex);
}
[Link]("rest of the code...");
}
}
Output:
Experiment-21
Write a program to create thread (i)extending Thread class (ii) implementing
Runnable interface
// Implementing Runnable interface
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++)
{ [Link]("Runnable thread: " + i);
try {
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
// Extending Thread class
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++)
{ [Link]("Thread class: " +
i); try {
[Link](500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
[Link](e);
}
}
}
}
public class ThreadExample {
public static void main(String[] args) {
// Create an object of MyRunnable (implementing Runnable)
MyRunnable myRunnable = new MyRunnable();
// Create an object of Thread using MyRunnable
Thread threadFromRunnable = new Thread(myRunnable);
// Create an object of MyThread (extending Thread class)
MyThread myThread = new MyThread();
// Start both threads
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Both threads have finished execution.");
}
}
Output:
Experiment-22
Write a java program to create multiple threads and thread priorities,
ThreadGroup.
class MyThread extends Thread
{
public void run()
{
[Link]("Thread Running...");
}
public static void main(String[]args)
{
MyThread p1 = new MyThread();
[Link]();
[Link]("max thread priority : " + p1.MAX_PRIORITY);
[Link]("min thread priority : " + p1.MIN_PRIORITY);
[Link]("normal thread priority : " + p1.NORM_PRIORITY);
}
}
Output:
Experiment-23
Write a java program to implement thread synchronization.
class Table {
// Synchronized method to print the table
synchronized void printTable(int n) {
for(int i = 1; i <= 5; i++) {
// Print the multiplication result
[Link](n * i);
try {
// Pause execution for 400 milliseconds
[Link](400);
} catch(Exception e) {
// Handle any exceptions
[Link](e);
}
}
}
}
class MyThread1 extends Thread
{ Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 5
[Link](5);
}
}
class MyThread2 extends Thread
{ Table t;
// Constructor to initialize Table object
MyThread2(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 100
[Link](100);
}
}
public class TestSynchronization2
{ public static void main(String args[])
{
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2 objects with the same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
[Link]();
[Link]();
}
}
Output:
Experiment-24
Write a java program on Inter Thread Communication.
class Customer{
int amount=10000;
synchronized void withdraw(int amount)
{ [Link]("going to withdraw...");
if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link]-=amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount)
{ [Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run()
{
[Link](15000);
}
}.start();
new Thread()
{ public void
run()
{
[Link](10000);
}
}.start();
}
}
Output:
Experiment-25
Write a java program on deadlock.
public class TestDeadlockExample1
{ public static void main(String[] args)
{ final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run()
{ synchronized (resource1)
{
[Link]("Thread 1: locked resource 1");
try {
[Link](100);
} catch (Exception e) {}
synchronized (resource2) {
[Link]("Thread 1: locked resource 2");
}
}
}
};
// t2 tries to lock resource2 then resource1
Thread t2 = new Thread() {
public void run()
{ synchronized (resource2) {
[Link]("Thread 2: locked resource 2");
try {
[Link](100);
} catch (Exception e) {}
synchronized (resource1) {
[Link]("Thread 2: locked resource 1");
}
}
}
};
[Link]();
[Link]();
}
}
Output:
Experiment-26
Write a Java program to establish connection with database.
import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{
[Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
}
}
Output:
Experiment-27
Write a Java program on different types of statements.
// Java Program illustrating Create Statement in JDBC
import [Link].*;
public class Geeks {
public static void main(String[] args) {
try {
// Load the driver
[Link]("[Link]");
// Establish the connection
Connection con = [Link](
"jdbc:mysql://localhost:3306/world", "root", "12345");
// Create a statement
Statement st = [Link]();
// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = [Link](sql);
// Process the results
while ([Link]()) {
[Link]("Name: " + [Link]("name") +
", Age: " + [Link]("age"));
}
// Close resources
[Link]();
[Link]();
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
Output:
// Java Program illustrating Prepared Statement in JDBC
import [Link].*;
import
[Link]; class
Geeks {
public static void main(String[] args) {
// try block to check for exceptions
try {
// Loading drivers using forName() method
[Link]("[Link]");
// Scanner class to take input from user
Scanner sc = new Scanner([Link]);
[Link](
"What age do you want to search?? ");
// Reading age an primitive datatype from user
// using nextInt() method
int age = [Link]();
// Registering drivers using DriverManager
Connection con = [Link](
"jdbc:mysql:///world", "root", "12345");
// Create a statement
PreparedStatement ps =
[Link]( "select name from
[Link] where age = ?");
// Execute the query
[Link](1, age);
ResultSet res = [Link]();
// Condition check using next() method
// to check for element
while ([Link]()) {
// Print and display elements(Names)
[Link]("Name : "
+ [Link](1));
}
}
// Catch block to handle database exceptions
catch (SQLException e) {
// Display the DB exception if any
[Link](e);
}
// Catch block to handle class exceptions
catch (ClassNotFoundException e) {
// Print the line number where exception occurred
// using printStackTrace() method if any
[Link]();
}
}
}
Output:
// Java Program illustrating
// Callable Statement in JDBC
import [Link].*;
public class Geeks {
public static void main(String[] args) {
// Try block to check if any exceptions occur
try {
// Load and register the driver
[Link]("[Link]");
// Establish a connection
Connection con = DriverManager
.getConnection("jdbc:mysql:///world", "root", "12345");
// Create a CallableStatement
CallableStatement cs =
[Link]("{call GetPeopleInfo()}");
// Execute the stored procedure
ResultSet res = [Link]();
// Process the results
while ([Link]()) {
// Print and display elements (Name and Age)
[Link]("Name : " + [Link]("name"));
[Link]("Age : " + [Link]("age"));
}
// Close resources
[Link]();
[Link]();
[Link]();
}
// Catch block for SQL exceptions
catch (SQLException e) {
[Link]();
}
// Catch block for ClassNotFoundException
catch (ClassNotFoundException e) {
[Link]();
}
}
}
Output:
Experiment-28
Write a Java program to perform DDL and DML statements using JDBC.
// Java program to illustrate
// inserting to the Database
import [Link].*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "geeks for geeks";
String email = "geeks@[Link]";
try
{
[Link]("[Link]");
Connection con = [Link]("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = [Link]();
// Inserting data in database
String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = [Link](q1);
if (x > 0)
[Link]("Successfully Inserted");
else
[Link]("Insert Failed");
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
Successfully Registered
// Java program to illustrate
// updating the Database
import [Link].*;
public class update1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String newPwd = "newpwd";
try
{
[Link]("[Link]");
Connection con = [Link]("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1"); Statement stmt = [Link]();
// Updating database
String q1 = "UPDATE userid set pwd = '" + newPwd +
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = [Link](q1);
if (x > 0)
[Link]("Password Successfully Updated");
else
[Link]("ERROR OCCURRED :(");
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
Password Successfully Updated
// Java program to illustrate
// deleting from Database
import [Link].*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
[Link]("[Link]");
Connection con = [Link]("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = [Link]();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
int x = [Link](q1);
if (x > 0)
[Link]("One User Successfully Deleted");
else
[Link]("ERROR OCCURRED :(");
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
One User Successfully Deleted
// Java program to illustrate
// selecting from Database
import [Link].*;
public class select
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
try
{
[Link]("[Link]");
Connection con = [Link]("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1"); Statement stmt = [Link]();
// SELECT query
String q1 = "select * from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
ResultSet rs = [Link](q1);
if ([Link]())
{
[Link]("User-Id : " + [Link](1));
[Link]("Full Name :" +
[Link](3)); [Link]("E-mail :" +
[Link](4));
}
else
{
[Link]("No such user id is already registered");
}
[Link]();
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
User-Id : id1
Full Name : Java Programming
E-mail : Programming@[Link]