4131 Object Oriented Programming(Java)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Module 1

1. Characteristics of OOP
❖ Object-Oriented Development (OOD):
OOD organizes software design around objects, combining data and behavior.
❖ Classes and Objects:
Classes define blueprints for objects, while objects are instances of classes.
❖ Encapsulation:
Encapsulation hides internal object details and exposes only necessary
functionality, enhancing security and modifiability.
❖ Abstraction:
Abstraction hides complex implementation details, focusing on essential object
features.
❖ Inheritance:
Inheritance allows a new class to inherit attributes and methods from an existing
class, promoting code reuse and extensibility.
❖ Polymorphism:
Polymorphism allows objects of different classes to be treated uniformly,
enabling methods to behave differently based on object type.
2. Features of Java programming or advantages of Java

❖ Object Oriented: In Java, everything is an object, making it easily extendable and


based on a consistent object model.
❖ Platform Independent: Java code can run on multiple platforms due to its
compilation into bytecode, which is platform-independent.
❖ Simple: Java has a clean and straightforward syntax, making it easy to learn and
understand compared to languages like C++. It removes complex features like
explicit pointers and operator overloading.
❖ Secure: Java's security features help in developing virus-free systems.
❖ Architecture-neutral: Java's compiler generates architecture-neutral object files,
allowing the code to run on various processors with the Java runtime system.
❖ Portable: Java bytecode can be carried to any platform, making Java highly
portable without requiring reimplementation.
❖ Robust: Java employs strong memory management, lacks pointers to avoid
security issues, and includes features like exception handling and type checking,
ensuring robustness.
❖ Multithreaded: Java supports multithreading, enabling the development of
programs that can perform multiple tasks simultaneously, leading to
smooth-running interactive applications.
❖ Interpreted: Java's development process is rapid and analytical, thanks to
incremental and lightweight linking.
❖ High Performance: Java bytecode contributes to its high performance compared
to other languages.
❖ Distributed: Java is designed for the distributed environment of the internet.
❖ Dynamic: Java is dynamic, supporting the dynamic loading of classes on demand.

3. Class
Class is a blueprint for which objects are created. It defines all properties and behavior of
the object.
Syntax:
class class_name{
// body of the class
}
Eg:
Class Example{
public static void main (String[] args){
System.out.println(“Hello world”);
}
}
4. Object
An object is the entity of the class it has its properties and behaviors.
The syntax of creating an object is given below:
class_name object_name = new class_name();
Eg: Consider a class Example the object of the class is created as
Example obj = new Example();
5. Overloading in Java
In a class more than one method with the same name and different arguments is called
overloading. It is identified by the Java compiler based on the method's differing number
or types of arguments.

Eg :
class Calculator {
public void add(int a, int b) {
System.out.println(“Sum of the 2 numbers = ”+(a+b));
}
public void add(int a, int b, int c) {
System.out.println(“Sum of the 3 numbers = ”+(a+b+c));
}
public static void main(String[] args){
Calculator obj= new Calculator();
obj.add(5, 10);
obj.add(5, 10, 15);
}
}

6. Constructor:
A constructor is a special type of member function with the same name as the class. It is
used to initialize the members of the class. In Java, constructors have no explicit return
type. Unlike methods, constructors are automatically invoked when objects are created.
There are two types of constructors in Java:

1. Default constructor: Default constructors or no argument constructors of


Java do not accept any parameters. Using these constructors the instance
variables of a method will be initialized with fixed values for all objects.
Eg:
class MyClass {
int num;
MyClass() {
num = 100;
}
}

2. Parameterized constructor: This constructor accepts one or more


parameters.
Eg: code for constructor overloading
class Area
{
public Area(int l, int b)
{
System.out.println(“Area of rectangle = ”+(l*b));
}
public Area(float r)
{
System.out.println(“Area of circle = ”+(3.14*r*r));
}
Area obj1 = new Area(4,5);
Area obj2 = new Area(3.5);
}

7. Static keyword in Java


In Java, static is used to declare members (variables and methods) that belong to the class
itself. Static keywords are used to create static methods and static variables the properties
of the static methods and variables are given below:
Properties of Static Variables:
❖ Shared among all instances.
❖ Stored in a common memory location.
❖ Declared with the static keyword.
❖ Initialized only once.
Properties of Static Methods:
❖ Belong to the class, not to instances.
❖ Cannot access instance variables directly.
❖ Cannot be overridden.
❖ Can access other static members directly.
❖ Cannot access instant members directly.
Eg:
class ct4
{
public int rollno;
public String name;

static String class_teacher;

public static void main(String[] args) {


ct4 obj1 = new ct4();
obj1.rollno = 1;
obj1.name = "Abhinad";
ct4 obj2 = new ct4();
obj2.rollno = 2;
obj1.name = "Abhinav";

ct4.class_teacher = "Jayalekshmi Miss";

}
}

7. Access Modifiers
In Java, access modifiers are keywords used to control the visibility or accessibility of
classes, variables, methods, and constructors. They define who can access a particular
class, member, or constructor. The four access levels are −
❖ default: Visible to the package. No modifiers are needed.
❖ private: Visible to the class only
❖ public: Visible to the world.
❖ protected: Visible to the package and all subclasses
The table given below shows the detailed behaviour of the access specifiers:

8. Exception Handling
Exception handling in Java is a mechanism to handle runtime errors, known as exceptions,
gracefully. An exception is an event that disrupts the normal flow of a program's execution.
Keywords used for Exception Handling:
❖ try: The try block is used to enclose the code that may throw exceptions.
❖ catch: The catch block is used to handle exceptions caught by the try block. It specifies
the type of exception to catch and the code to execute when that exception occurs.
❖ finally: The finally block is used to execute code that should always run, regardless of
whether an exception is thrown or not. It is typically used for cleanup tasks such as
closing files or releasing resources.
Eg:
class DivisionExample {
public static void main(String[] args) {
int a= 10;
int b= 0;
try {
System.out.println("Result of division: " + (a/b));
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
finally{
System.out.println(“This code will always execute.”);
}
}
}
9. Polymorphism (Static and dynamic binding)
Polymorphism is derived from two Greek words, “poly” and “morph”, which mean
“many” and “forms”, respectively. Hence, polymorphism meaning in Java refers to the
ability of objects to take on many forms.. There are two types:

Compile-time polymorphism(static binding): Achieved through method overloading,


where multiple methods with the same name but different parameters exist in a class.
Overloading can be done by changing the number or data type of arguments.

Runtime polymorphism(Dynamic Binding): Also known as Dynamic Method Dispatch,


it resolves overridden methods at runtime rather than compile-time. Here, an overridden
method is called through the reference variable of a superclass.

Module 2
1. Inheritance
The ability of the class to derive the property and attributes from another class
inheritance. It promotes code reusability and avoids redundancy. There are mainly
4 types of inheritance in Java.
1. Single Level Inheritance:
Single level inheritance refers to the inheritance relationship where a subclass
inherits from only one superclass. In this type of inheritance, there is a single level
of hierarchy between classes. Example: Class B extends Class A.
2. Multi-level Inheritance:
Multi-level inheritance refers to the inheritance relationship where a subclass
inherits from another subclass, creating a chain of inheritance. In this type of
inheritance, there are multiple levels of hierarchy between classes. Example:
Class C extends Class B, and Class B extends Class A.

3. Hierarchical Inheritance:
Hierarchical inheritance refers to the inheritance relationship where multiple
subclasses inherit from the same superclass. In this type of inheritance, there is a
single superclass with multiple subclasses branching out from it. Example: Class
B and Class C both extend Class A.

4. Hybrid Inheritance:
Hybrid inheritance refers to a combination of two or more types of inheritance,
such as single level, multi-level, or hierarchical inheritance. It involves the use of
multiple inheritance paths to create complex class hierarchies. Example: Class D
extends Class B and Class C, where Class B extends Class A, resulting in a
combination of hierarchical and multi-level inheritance.
Eg : program to demo Hybrid inheritance
class A{
public void functionA()
{
System.out,println(“This is a method of class A”);
}
}
class B extends A{
public void functionB()
{
System.out,println(“This is a method of class B”);
}
}
class C extends A{
public void functionC()
{
System.out,println(“This is a method of class C”);
}
}
class D extends B{
public void functionD()
{
System.out,println(“This is a method of class D”);
}
}
class Hybrid{

public static void main(String[] args)


{
D objD = new D();
objD.functionA();
objD.functionB();
objD.functionD();
}
}

2. Over Riding in java


Method overriding in Java is a feature that allows a subclass to provide a specific
implementation of a method that is already defined in its superclass. The subclass method
must have the same name, return type, and parameter list as the superclass method it overrides.
Eg:
class A {
public void functionA() {
System.out.println("FunctionA in class A");
}
}

class B extends A {
public void functionA() {
System.out.println("FunctionA in class B");
}
}

public class Main {


public static void main(String[] args) {
A objA = new A();
B objB = new B();
objA.functionA(); // Calls functionA from class A
objB.functionA(); // Calls overridden functionA from class B
}
}

3. Super Keyword Or How to invoke super class constructor using super keyword
It can be used to access superclass members (variables or methods) and constructor from within
the subclass.
Super Keyword to invoke super class members
We can use super keyword to access a variable or method from base class using the super
keyword see the program given below.

class Parent {

// Parameterized constructor in parent class


Parent(String name) {
System.out.println("Parent name: " + name);
}
}
class Child extends Parent {
Child() {
super("John"); // Invoking superclass constructor
System.out.println("Child name : Roy");
}
}
public class SuperConstructorDemo {
public static void main(String[] args) {
Child obj = new Child();
}
}

Output
Parent name: John
Child name : Roy

4. Abstract class in Java


❖ Abstract classes in Java cannot be instantiated directly and serve as blueprints for other
classes to inherit from.
❖ They are created using the keyword 'abstract' and can include both normal methods with
implementations and abstract methods ,which are declared without implementations (only
method signature).
❖ When a class inherits from an abstract class, it must either provide implementations for
all the abstract methods or be declared abstract itself.

Eg:
abstract class A {
public abstract void displayOne();

public void displayTwo() {


System.out.println("This is method of the abstract class A");
}
}
class B extends A {
public void displayOne() {
System.out.println("This is the abstract method of class A");
}
}

class Example {
public static void main(String[] args) {
B objB = new B();
objB.displayOne();
objB.displayTwo();
}
}

5. Final Keyword in Java


The `final` keyword in Java is used to restrict certain functionalities, such as inheritance,
method overriding, and changing variable values, depending on where it's applied:

1. Final Class: When a class is declared as `final`, it means that it cannot be subclassed or
inherited by other classes. It serves as a complete, unchangeable entity. For example:

final class FinalClass {


// Class members and methods
}

2. Final Method: When a method is declared as `final`, it means that it cannot be


overridden by subclasses. This is often used when a method in a superclass should not be
modified or extended. For example:
class Parent {
final void finalMethod() {
// Method implementation
}
}
class Child extends Parent {
// This will cause a compilation error
void finalMethod() {
// Method implementation
}
}

3. Final Variable: When a variable is declared as `final`, its value cannot be changed after
it's initialized, making it a constant. For instance:
class Example {
final int constantValue = 10;
}
Here, `constantValue` cannot be reassigned to a different value once initialized.
6. Interface in Java
In Java, an interface is a reference type similar to a class, but it only contains abstract method
declarations. Here are some key properties of interfaces:

❖ Abstract Methods: Interfaces can only contain method signatures without method bodies.
These methods are implicitly public and abstract.
❖ Default Access Modifier: By default, all members (methods and constants) in interfaces
are public and abstract, meaning they can be accessed by any class that implements the
interface.
❖ Constants: Interfaces can also contain constants, which are implicitly public, static, and
final.
❖ Multiple Inheritance: In java multiple inheritance is posible using inheritance.
❖ Polymorphism: Interfaces enable polymorphism, allowing different classes to implement
the same interface with their specific implementations.

Eg:
interface ExampleInterface {
// Method signatures
public abstract void method1();
public abstract void method2();

// Constant declaration
static final int CONSTANT_VALUE = 10;
}
7. Package in Java
Package in Java is a collection of related classes, interfaces, and methods. It promotes code
modularity and prevents naming conflicts.
Types of packers
1. Built-in packages: These are the packages provided by Java, such as java.lang, java.util,
etc., which contain essential classes and interfaces for Java programming.
2. User-defined Packages: These are custom packages created by developers to organize their
classes and interfaces. User-defined packages help manage larger projects by grouping
related classes together.
Eg:
package mathOperations;

public class Arithmetic {


public int add(int a, int b) {
return a + b;
}

public int subtract(int a, int b) {


return a - b;
}

public int multiply(int a, int b) {


return a * b;
}
}

import mathOperations.Arithmetic;

public class Calculator {


public static void main(String[] args) {
int num1 = 10;
int num2 = 5;

Arithmetic obj= new Arithmetic();

// Use methods from the mathOperations package


int sum = obj.add(num1, num2);
int difference = obj.subtract(num1, num2);
int product = obj.multiply(num1, num2);

// Display the results


System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
}
}

Module 3
1. What is GUI?
GUI is a user interface that allows users to interact with digital devices, software, or
operating systems using graphical elements such as icons, buttons, and menus.
2. What is swing? What are the features?
Swing is a GUI tool kit in Java used by developers to create graphical user interfaces. It
provides a set of components like buttons, text fields, and panels, which can be used to
build interactive graphical interfaces.
Features of swing
1. Swing is a part of JFC (Java Foundation Classes)
2. Swing is built on top of AWT (Abstract Window Toolkit)
3. Swing components are lightweight
4. Swing components have pluggable look and feel
5. Swing components are platform-independent
6. Swing components are included in the package javax.swing
3. Components of swing
Swing as has many components which helps to build user interfaces in java some of the main
components of the swings are:
1. JButton: Used for triggering actions or events.
2. JLabel: Displays text or images on the interface.
3. JTextField: Enables users to input single-line text.
4. JTextArea: Allows users to input and display multi-line text.
5. JCheckBox: Presents options for selection in a checkbox format.
6. JRadioButton: Enables users to select a single option from multiple choices.
7. JComboBox: Offers a drop-down list for selecting from multiple options.
8. JList: Displays a list of items for selection.
9. JTable: Presents data in a tabular format with rows and columns.
10. JPanel: Acts as a container for organizing and grouping other components.
4. Describe steps to create and manipulate GUI controls.
1. Create Frame: Instantiate a JFrame object to serve as the main window.
2. Add Components: Add Swing components (e.g., JButton, JLabel) to the frame using
layout managers like BorderLayout or GroupLayout.
3. Set Component Properties: Customize each component by setting properties such as size,
text, font, color, etc.
4. Register Event Listeners: Attach event listeners (e.g., ActionListener) to components to
handle user interactions like button clicks.
5. Pack and Display: Pack the frame to adjust its size based on the components and make it
visible to the user.
5. How can we handle Mouse events in Java?
Mouse events in Java are handled by two interfaces MouseListener and MouseMotionListener
these interfaces have various methods to handle different events of mouse they are listed below.
MouseListener Interface:
1. void mouseClicked(MouseEvent e): Called when the mouse is clicked on a component.
2. void mousePressed(MouseEvent e): Called when a mouse button is pressed on a
component.
3. void mouseReleased(MouseEvent e): Called when a mouse button is released on a
component.
4. void mouseEntered(MouseEvent e): Called when the mouse enters a component.
5. void mouseExited(MouseEvent e): Called when the mouse exits a component.
MouseMotionListener Interface:
1. void mouseDragged(MouseEvent e): Called when the mouse is dragged (moved with a
button pressed) on a component.
2. void mouseMoved(MouseEvent e): Called when the mouse is moved (without any button
pressed) on a component.
6. How can we handle keyboard events in Java?
Keyboard events in Java are handled using the KeyListener interface. This interface provides
methods to respond to various keyboard interactions. Here are the methods:
KeyListener Interface:
1. void keyPressed(KeyEvent e): Called when a key is pressed.
2. void keyReleased(KeyEvent e): Called when a key is released.
3. void keyTyped(KeyEvent e): Called when a key is typed (pressed and released).

7. Explain Common GUI event type and Listener types.


Common GUI Event Types:
1. Action Events: Happen when users interact with components, like clicking a button or
selecting a menu item.
2. Mouse Events: Occur when users interact with components using the mouse, such as
clicking, moving, or dragging.
3. Keyboard Events: Generated when users interact with components using the keyboard,
like pressing keys or typing characters.
4. Focus Events: Related to the activation or deactivation of components for user input.
5. Window Events: Associated with the lifecycle of windows, including opening, closing,
resizing, and moving.
Common GUI Listener Types:
1. Action Listeners: Handle action events, such as button clicks or menu selections.
2. Mouse Listeners: Respond to mouse events like clicks, movements, and button presses.
3. Mouse Motion Listeners: Specifically track continuous mouse movements, useful for
dragging and moving.
4. Key Listeners: Manage keyboard events like key presses, releases, and typed characters.
5. Focus Listeners: Triggered when components gain or lose focus, used to manage
activation and deactivation.
6. Window Listeners: Manage window-related events such as opening, closing, activating,
and deactivating windows.

8. Create a GUI program using Swing to add two numbers.


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

public class AddTwoNumbersGUI {

public static void main(String[] args) {


JFrame frame = new JFrame("ADD");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JLabel lbl1 = new JLabel("Enter Number One");
lbl1.setBounds(100,100,150,30);
JTextField tf1 = new JTextField();
tf1.setBounds(250,100,100,30);
JLabel lbl2 = new JLabel("Enter Number Two");
lbl2.setBounds(100,200,150,30);
JTextField tf2 = new JTextField();
tf2.setBounds(250,200,100,30);
JButton btn = new JButton("Sum");

btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int x = Integer.parseInt(tf1.getText());
int y = Integer.parseInt(tf2.getText());
JOptionPane.showMessageDialog(frame, "Sum = " + (x + y));
}
});

frame.add(lbl1);
frame.add(lbl2);
frame.add(tf1);
frame.add(tf2);
frame.add(btn);
}
}

9. Create a program to handle a button clicked event


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

public class ButtonClickEventExample {

public static void main(String[] args) {


JFrame frame = new JFrame("Button Click Event Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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


button.setBounds(100, 50, 100, 30);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});

frame.add(button);
frame.setLayout(null);
frame.setVisible(true);
}
}

10. Create a program for handling Mouse events


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

public class AllEventsExample {

public static void main(String[] args) {


JFrame frame = new JFrame("All Events Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);

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


button.setBounds(100, 50, 100, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});

frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}

public void mouseDragged(MouseEvent e) {


System.out.println("Mouse Dragged");
}
});

frame.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


// Not used in this example
}

public void keyTyped(KeyEvent e) {


// Not used in this example
}
});

frame.add(button);
// Set the frame focusable and request focus
frame.setFocusable(true);
frame.requestFocusInWindow();

}
}

11. Create a program for handling Keyboard events

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

public class AllEventsExample {

public static void main(String[] args) {


JFrame frame = new JFrame("All Events Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setVisible(true);

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


button.setBounds(100, 50, 100, 30);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});

frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
System.out.println("Mouse Moved");
}

public void mouseDragged(MouseEvent e) {


System.out.println("Mouse Dragged");
}
});

frame.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


// Not used in this example
}

public void keyTyped(KeyEvent e) {


// Not used in this example
}
});

frame.add(button);

// Set the frame focusable and request focus


frame.setFocusable(true);
frame.requestFocusInWindow();
}
}
Module 4
1. Explain Relational Database
Relational Databases
A relational database structures data into tables, each representing a concept, with rows
indicating individual instances. This setup allows for efficient data storage, retrieval, and
relationship establishment.

2. Explain the basic commands in sql


The basic commands of the sql are listed below:
Data Definition Language (DDL):
1. CREATE TABLE: Defines a new table with specified columns and constraints.
Example: CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50),
age INT);
2. ALTER TABLE: Modifies the structure of an existing table (e.g., adding columns).
Example: ALTER TABLE employees ADD COLUMN department VARCHAR(50);
3. DROP TABLE: Deletes an entire table and its data from the database.
Example: DROP TABLE employees;
Data Manipulation Language (DML):
1. INSERT: Adds new records into a table.
Example: INSERT INTO employees (name, age, department) VALUES ('John', 30,
'Sales');
2. UPDATE: Modifies existing records in a table.
Example: UPDATE employees SET age = 35 WHERE name = 'John';
3. DELETE: Removes records from a table based on specified conditions.
Example: DELETE FROM employees WHERE age > 60;
Data Control Language (DCL):
1. GRANT: Provides specific privileges to users or roles for database objects.
Example: GRANT SELECT ON employees TO marketing;
2. REVOKE: Revokes previously granted privileges from users or roles.
Example: REVOKE SELECT ON employees FROM marketing;

3. What is JDBC
JDBC (Java Database Connectivity) is a Java API for connecting Java applications to
databases. It provides methods for establishing connections, executing SQL queries, and
processing results. With JDBC, Java programs can interact with various databases, making
it a crucial tool for database-driven applications.
4. What are the steps or stages of implementing JDBC
1. Load JDBC Driver: Use `Class.forName()` to load the JDBC driver class for your
database.
- Example: `Class.forName("com.mysql.jdbc.Driver");`

2. Establish Connection: Use `DriverManager.getConnection()` to establish a connection


to the database.
- Example: `Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username",
"password");`
3. Create Statement: Use `Connection.createStatement()` to create a Statement object for
executing SQL statements.
- Example: `Statement stmt = conn.createStatement();`

4. Execute SQL Statements: Use `Statement.executeQuery()` to execute SELECT queries


and get a ResultSet object.
- Example: `ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");`

5. Process Results: Retrieve data from the ResultSet using `rs.getXXX()` methods and
iterate through the results.`

6. Close Connection: Close the connection when done with database operations using
`Connection.close()`.
- Example: `conn.close();`
5. Explain the Prepared statement, execute statement and result set in JDBC
❖ PreparedStatement
In JDBC, a PreparedStatement is a precompiled SQL statement that allows
parameterized queries to be executed more efficiently. It helps prevent SQL
injection attacks and improves performance by preparing the query once and
executing it multiple times with different parameters.
❖ ExecuteStatement
An ExecuteStatement is a general interface for executing SQL statements. It's used
to execute static SQL queries, such as INSERT, UPDATE, DELETE, or any other
SQL statement that doesn't require parameters.
❖ ResultSet
A ResultSet is an object that represents the result set of a database query. It
provides methods to traverse through the data retrieved from the database, retrieve
column values, and navigate through rows. ResultSet objects are typically returned
when executing SELECT queries using either Statement or PreparedStatement.

6. Write a program to perform a select query in JDBC.

import java.sql.*;

public class DemoClass {


public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3307/aliens";
String uname = "root";
String pass = "";
String query = "select username from student where userid=3";

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);

rs.next();
String name = rs.getString("username");
System.out.println(name);

st.close();
con.close();
}
}

7. Write a program to perform a insert query in JDBC.


import java.sql.*;

public class InsertDemo {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3307/aliens";
String username = "root";
String password = "";
String query = "INSERT INTO student (userid, username) VALUES (?, ?)";

try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(query);

preparedStatement.setInt(1, 5); // userid


preparedStatement.setString(2, "John"); // username

int rowsAffected = preparedStatement.executeUpdate();


System.out.println(rowsAffected + " row(s) affected");

preparedStatement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
8. Write a program to perform an update query in JDBC.
import java.sql.*;

public class UpdateDemo {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3307/aliens";
String username = "root";
String password = "";
String query = "UPDATE student SET username = ? WHERE userid = ?";

Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement preparedStatement = connection.prepareStatement(query);

preparedStatement.setString(1, "UpdatedName"); // New username


preparedStatement.setInt(2, 5); // userid

int rowsAffected = preparedStatement.executeUpdate();


System.out.println(rowsAffected + " row(s) updated");

preparedStatement.close();
connection.close();

}
}

You might also like