0% found this document useful (0 votes)
11 views91 pages

Java Dip Lab2 25 Feb

The document contains a series of Java programming experiments demonstrating various concepts such as class definition, matrix operations, command line arguments, method overloading, inheritance, and GUI components. Each experiment includes code snippets and expected output, covering topics like constructors, static methods, string manipulation, and event handling. The document serves as a comprehensive guide for learning Java programming through practical examples.

Uploaded by

rasulkhan723492
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)
11 views91 pages

Java Dip Lab2 25 Feb

The document contains a series of Java programming experiments demonstrating various concepts such as class definition, matrix operations, command line arguments, method overloading, inheritance, and GUI components. Each experiment includes code snippets and expected output, covering topics like constructors, static methods, string manipulation, and event handling. The document serves as a comprehensive guide for learning Java programming through practical examples.

Uploaded by

rasulkhan723492
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/ 91

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) {
this.name = name;
this.age = age;
}
// Method to set the name
public void setName(String name)
{ this.name = name;
}
// Method to get the name
public String getName() {
return name;
}

// Method to set the age


public void setAge(int age) {
this.age = 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
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Set new values
person.setName("Bob");
person.setAge(25);
// Retrieve and print updated values
System.out.println("Updated Name: " + person.getName());
System.out.println("Updated Age: " + person.getAge());
// Demonstrate using operators
int yearsToAdd = 5;
person.setAge(30);
System.out.println("Age after " + yearsToAdd + " years: " + person.getAge());
}
}
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
System.out.println("Addition of matrices:");
displayMatrix(resultAddition);

System.out.println("Subtraction of matrices:");
displayMatrix(resultSubtraction);

System.out.println("Multiplication of matrices:");
displayMatrix(resultMultiplication);
}

public static void displayMatrix(int[][] matrix)


{ for (int[] row : matrix) {
for (int element : row)
{ System.out.print(element + " ");
}

System.out.println();
}
}
}
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<args.length;i++)
System.out.println(args[i]);
}
}

compile by > javac A.java


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( )
{
System.out.println(“Default Constructor”);
}
Constructor(int a)

{
System.out.println(a);
}
Constructor(int a,int b)
{

System.out.println(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


System.out.println("Sum of 10 and 20: " + example.add(10, 20));
// Calling the overloaded add method with three integers
System.out.println("Sum of 10, 20 and 30: " + example.add(10, 20, 30));

// Calling the overloaded add method with two double values


System.out.println("Sum of 10.5 and 20.5: " + example.add(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()
{
System.out.println(“show method”);
}

public static void main(String args[])


{
System.out.println(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 = str.length();
System.out.println("Length of the string: " + length);

// 2. Character at a specific index


char charAt5 = str.charAt(5);
System.out.println("Character at index 5: " + charAt5);

// 3. Substring from the string


String substring = str.substring(7, 12);
System.out.println("Substring from index 7 to 12: " + substring);

// 4. Concatenation of strings
String str2 = " How are you?";
String concatenated = str.concat(str2);
System.out.println("Concatenated string: " + concatenated);

// 5. Index of a character or substring


int indexOfW = str.indexOf('W');
System.out.println("Index of 'W': " + indexOfW);
// 6. Replace characters in the string
String replacedString = str.replace('o', '0');
System.out.println("String after replacement: " + replacedString);

// 7. Convert to uppercase
String upperCaseString = str.toUpperCase();
System.out.println("Uppercase string: " + upperCaseString);

// 8. Convert to lowercase
String lowerCaseString = str.toLowerCase();
System.out.println("Lowercase string: " + lowerCaseString);

// 9. Trim whitespace from the string


String strWithWhitespace = " Hello, World! ";
String trimmedString = strWithWhitespace.trim();
System.out.println("Trimmed string: '" + trimmedString + "'");

// 10. Check if the string contains a substring


boolean containsHello = str.contains("Hello");
System.out.println("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() {
System.out.println("This animal eats food.");
}
}

// Derived class
class Dog extends Animal {
// Method in the derived class
void bark() {
System.out.println("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


myDog.eat(); // Method from the base class
myDog.bark(); // 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){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{

System.out.println(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); s1.display();
s2.display();
}

}
Output:
111 ankit 5000.0
112 sumit 6000.0
Experiment-10
Write a java program to illustrate method overriding
class Super

{
void display()
{
System.out.println(“Super class method”);
}

}
class Sub extends Super
{
void display()
{

System.out.println(“Sub class method”);


}
public static void main(String args[])
{
Sub s=new Sub();
s.display();
}
}
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() {
System.out.println("Bat is eating.");
}
// Implement the fly method from Bird interface
public void fly() {
System.out.println("Bat is flying.");

}
}

// Main class to test the implementation


public class MultipleInheritanceDemo
{ public static void main(String[] args) {
Bat bat = new Bat();
bat.eat();
bat.fly();
}

}
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 class1.java.
package pack1;
public class Class1{
public void display(){
System.out.println("Inside class1 method.")
}

//save by Class2.java
package pack2;
import pack1.*;
class Class2{
public static void main(String args[])
{ Class1 obj = new Class1();
obj.display();
}

}
Output:
Inside class1 method.
Experiment-13
Write a Java program using util package classes.
import java.util.ArrayList;

import java.util.Collections;
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
numbers.add(5);
numbers.add(3);
numbers.add(8);
numbers.add(1);
numbers.add(6);
// Print the original list
System.out.println("Original list: " + numbers);
// Sort the list using Collections.sort()
Collections.sort(numbers);
// Print the sorted list
System.out.println("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 java.applet.Applet;

import java.awt.Graphics;
public class AppletLifeCycle extends Applet {
// Called when the applet is first loaded
public void init() {
System.out.println("Applet initialized");

}
// Called when the applet is started or restarted
public void start() {
System.out.println("Applet started");
}

// Called when the applet is stopped


public void stop() {
System.out.println("Applet stopped");
}
// Called when the applet is destroyed
public void destroy() {
System.out.println("Applet destroyed");
}
// Called to paint the applet
public void paint(Graphics g) {
g.drawString("Applet Life Cycle Demo", 20, 20);
}
}
To Compile: javac AppletLifeCycle.java
//LifeCycle.html
<!DOCTYPE html>

<html>
<body>
<applet code="AppletLifeCycle.class" width="300" height="200">
</applet>
</body>

</html>

To Execute: appletviewer LifeCycle.html


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 java.awt.*;
import java.awt.event.*;
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


btnClick.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ label.setText("Button clicked");
}
});

// Event handling for checkbox state change


checkbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (checkbox.getState()) {
label.setText("Checkbox selected");
} else {
label.setText("Checkbox unselected");
}
}
});

// Event handling for radio button state change


radio1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (radio1.getState()) {
label.setText("Radio Button 1 selected");

}
}
});

radio2.addItemListener(new ItemListener()
{ public void itemStateChanged(ItemEvent e) {
if (radio2.getState()) {
label.setText("Radio Button 2 selected");
}
}

});

// Event handling for text field input


textField.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {

label.setText("Text Field updated");


}
});
// Event handling for window closing
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {

System.exit(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 java.awt.*;
import java.awt.event.*;
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) {
mouseLabel.setText("Mouse clicked at: (" + e.getX() + ", " + e.getY() + ")");
}

public void mousePressed(MouseEvent e) {

mouseLabel.setText("Mouse pressed at: (" + e.getX() + ", " + e.getY() + ")");


}

public void mouseReleased(MouseEvent e) {

mouseLabel.setText("Mouse released at: (" + e.getX() + ", " + e.getY() + ")");


}

public void mouseEntered(MouseEvent e)


{ mouseLabel.setText("Mouse entered the window");
}

public void mouseExited(MouseEvent e)


{ mouseLabel.setText("Mouse exited the window");
}

});

// Key event handling


addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{ keyboardLabel.setText("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e)


{ keyboardLabel.setText("Key Released: " + e.getKeyChar());
}

public void keyTyped(KeyEvent e) {


// Optional: This event will trigger when a key is typed (character is produced)
//keyboardLabel.setText("Key Typed: " + e.getKeyChar());
}
});

// 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)
{ System.out.println("ArithmeticException => " + e.getMessage());
}

finally {
System.out.println("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;
System.out.println(a[10]);
}
catch(ArithmeticException e)

{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{

System.out.println("ArrayIndexOutOfBounds Exception occurs");


}
catch(Exception e)
{
System.out.println("Parent Exception occurs");

}
System.out.println("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{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(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)
{
System.out.println(e);
}
System.out.println("other statement");

}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");

}
System.out.println("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 {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{

try
{
// calling the method
validate(13);
}

catch (InvalidAgeException ex)


{
System.out.println("Caught the exception");

// printing the message from InvalidAgeException object

System.out.println("Exception occured: " + ex);


}
System.out.println("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++)
{ System.out.println("Runnable thread: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

// Extending Thread class


class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++)
{ System.out.println("Thread class: " +
i); try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(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


threadFromRunnable.start();
myThread.start();

try {
threadFromRunnable.join();
myThread.join();
} catch (InterruptedException e) {
System.out.println(e);
}

System.out.println("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()


{
System.out.println("Thread Running...");
}

public static void main(String[]args)


{
MyThread p1 = new MyThread();
p1.start();
System.out.println("max thread priority : " + p1.MAX_PRIORITY);
System.out.println("min thread priority : " + p1.MIN_PRIORITY);
System.out.println("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


System.out.println(n * i);
try {
// Pause execution for 400 milliseconds
Thread.sleep(400);
} catch(Exception e) {
// Handle any exceptions
System.out.println(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
t.printTable(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
t.printTable(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

t1.start();
t2.start();
}
}
Output:
Experiment-24

Write a java program on Inter Thread Communication.

class Customer{
int amount=10000;

synchronized void withdraw(int amount)


{ System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount)


{ System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{ public void
run()
{
c.deposit(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)
{
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(100);
} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {
public void run()
{ synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try {
Thread.sleep(100);
} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}

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

}
Output:
Experiment-26

Write a Java program to establish connection with database.

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:
Experiment-27

Write a Java program on different types of statements.

// Java Program illustrating Create Statement in JDBC


import java.sql.*;
public class Geeks {
public static void main(String[] args) {
try {
// Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/world", "root", "12345");

// Create a statement

Statement st = con.createStatement();

// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = st.executeQuery(sql);

// Process the results


while (rs.next()) {
System.out.println("Name: " + rs.getString("name") +
", Age: " + rs.getInt("age"));
}
// Close resources
rs.close();
st.close();

con.close();
} catch (Exception e) {
e.printStackTrace();
}
}

}
Output:
// Java Program illustrating Prepared Statement in JDBC
import java.sql.*;
import
java.util.Scanner; class
Geeks {
public static void main(String[] args) {
// try block to check for exceptions
try {
// Loading drivers using forName() method
Class.forName("com.mysql.cj.jdbc.Driver");

// Scanner class to take input from user


Scanner sc = new Scanner(System.in);

System.out.println(
"What age do you want to search?? ");

// Reading age an primitive datatype from user


// using nextInt() method
int age = sc.nextInt();

// Registering drivers using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Create a statement
PreparedStatement ps =
con.prepareStatement( "select name from
world.people where age = ?");
// Execute the query
ps.setInt(1, age);
ResultSet res = ps.executeQuery();

// Condition check using next() method


// to check for element
while (res.next()) {
// Print and display elements(Names)
System.out.println("Name : "
+ res.getString(1));
}

}
// Catch block to handle database exceptions
catch (SQLException e) {
// Display the DB exception if any
System.out.println(e);
}
// Catch block to handle class exceptions
catch (ClassNotFoundException e) {
// Print the line number where exception occurred
// using printStackTrace() method if any

e.printStackTrace();
}
}
}
Output:
// Java Program illustrating
// Callable Statement in JDBC
import java.sql.*;
public class Geeks {
public static void main(String[] args) {
// Try block to check if any exceptions occur
try {
// Load and register the driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish a connection
Connection con = DriverManager
.getConnection("jdbc:mysql:///world", "root", "12345");

// Create a CallableStatement
CallableStatement cs =
con.prepareCall("{call GetPeopleInfo()}");

// Execute the stored procedure


ResultSet res = cs.executeQuery();

// Process the results


while (res.next()) {
// Print and display elements (Name and Age)
System.out.println("Name : " + res.getString("name"));
System.out.println("Age : " + res.getInt("age"));
}
// Close resources
res.close();
cs.close();
con.close();
}
// Catch block for SQL exceptions
catch (SQLException e) {
e.printStackTrace();
}
// Catch block for ClassNotFoundException
catch (ClassNotFoundException e) {
e.printStackTrace();

}
}
}
Output:
Experiment-28

Write a Java program to perform DDL and DML statements using JDBC.

// Java program to illustrate


// inserting to the Database
import java.sql.*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "geeks for geeks";
String email = "[email protected]";

try

{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();

// Inserting data in database


String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else

System.out.println("Insert Failed");

con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Successfully Registered
// Java program to illustrate
// updating the Database
import java.sql.*;
public class update1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String newPwd = "newpwd";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1"); Statement stmt = con.createStatement();

// Updating database

String q1 = "UPDATE userid set pwd = '" + newPwd +


"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);

if (x > 0)

System.out.println("Password Successfully Updated");


else

System.out.println("ERROR OCCURRED :(");


con.close();
}
catch(Exception e)

{
System.out.println(e);
}
}
}
Output:
Password Successfully Updated
// Java program to illustrate
// deleting from Database
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";

int x = stmt.executeUpdate(q1);

if (x > 0)
System.out.println("One User Successfully Deleted");

else
System.out.println("ERROR OCCURRED :(");

con.close();
}
catch(Exception e)
{

System.out.println(e);
}
}
}
Output:
One User Successfully Deleted
// Java program to illustrate
// selecting from Database
import java.sql.*;

public class select


{
public static void main(String args[])
{

String id = "id1";
String pwd = "pwd1";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1"); Statement stmt = con.createStatement();

// SELECT query

String q1 = "select * from userid WHERE id = '" + id +


"' AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);
if (rs.next())
{

System.out.println("User-Id : " + rs.getString(1));


System.out.println("Full Name :" +
rs.getString(3)); System.out.println("E-mail :" +
rs.getString(4));
}
else
{

System.out.println("No such user id is already registered");


}
con.close();
}
catch(Exception e)
{

System.out.println(e);
}
}
}
Output:
User-Id : id1
Full Name : Java Programming
E-mail : [email protected]

You might also like