0% found this document useful (0 votes)
4 views50 pages

Java String and Thread Handling Guide

The document provides an overview of string handling and thread management in Java, detailing the characteristics of String, StringBuffer, and StringBuilder classes, as well as methods for string manipulation such as substring and replace. It also covers thread creation, lifecycle, priority, and synchronization, explaining how to implement threads using both the Thread class and Runnable interface. Additionally, it discusses the importance of synchronization in managing shared resources among threads to prevent data corruption.

Uploaded by

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

Java String and Thread Handling Guide

The document provides an overview of string handling and thread management in Java, detailing the characteristics of String, StringBuffer, and StringBuilder classes, as well as methods for string manipulation such as substring and replace. It also covers thread creation, lifecycle, priority, and synchronization, explaining how to implement threads using both the Thread class and Runnable interface. Additionally, it discusses the importance of synchronization in managing shared resources among threads to prevent data corruption.

Uploaded by

shaiksakeya2476
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STRING HANDLING IN JAVA

In Java, a String is an object that represents a sequence of characters. Java provides a robust and flexible
API for handling strings, allowing for various operations such as concatenation, comparison,
and manipulation.
CharSequence Interface

CharSequence Interface is used for representing the sequence of Characters in Java.


Classes that are implemented using the CharSequence interface are mentioned below and these provides
much of functionality like substring, lastoccurence, first occurence, concatenate, toupper, tolower etc.
[Link]

String is an immutable class which means a constant and cannot be changed once created and
if wish to change , we need to create an new object and even the functionality it provides like
toupper, tolower, etc
Syntax
String str= “Hello";
or
String str= new String(“Hello")
ACS06-R23 OOP through JAVA Prepared by
[Link]
[Link]

StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we can use it when
we have multi threaded environment and shared object of string buffer i.e, used by mutiple thread.

Syntax: StringBuffer demoString = new StringBuffer(“Welcome to Java Programming");

[Link]

StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a mutable
sequence of characters and it is not thread safe. It is used only within the thread, so there is no extra
overhead , so it is mainly used for single threaded program.

Syntax: StringBuilder demoString = new StringBuilder();


[Link](“Java");

Java String compareTo() Method:

ACS06-R23 OOP through JAVA Prepared by


[Link]
String Extraction:
substring()
The substring() method returns a new string that is a substring of the original string. It takes one or two
arguments: the start index and optionally the end index.
Syntax:
public String substring(int beginIndex) public String substring(int beginIndex, int endIndex)
Example:
public class SubstringExample
{
public static void main(String[] args)
{
String str = "Hello, World!";
String substr1 = [Link](7);
String substr2 = [Link](0, 5);
[Link]("Substring from index 7: " + substr1);
[Link]("Substring from index 0 to 5: " + substr2);
}
}
Output:
Substring from index 7: World!
ACS06-R23 OOP through JAVA Prepared by
Substring from index 0 to 5: Hello [Link]
String Modifying:
replace()
The replace() method replaces all occurrences of a specified character or substring with a new character or
substring.
Syntax:
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
Example:
public class ReplaceExample
{
public static void main(String[] args)
{
String str = "Hello, World!";
String result1 = [Link]('o', '0’);
String result2 = [Link]("World", "Java");
[Link]("Replaced 'o' with '0': " + result1);
[Link]("Replaced 'World' with 'Java': " + result2);
} }
Output:
Replaced 'o' with '0’:
Hell0, W0rld! Replaced 'World' with 'Java': ACS06-R23 OOP through JAVA Prepared by
Hello,[Link]
Java!
Compare two Strings:
Comparing strings is the most common task in different scenarios such as input validation or searching
algorithms. The most common method to compare two strings in Java is equals(). This method compares
the content of two strings for equality.
public class CompareStrings
{
public static void main(String[] args)
{
String s1 = "Hello";
String s2 = "Geeks";
String s3 = "Hello";
// Comparing strings
[Link]([Link](s2));
[Link]([Link](s3));
}
}
Output:
false
true
ACS06-R23 OOP through JAVA Prepared by
[Link]
Searching String:
indexOf()
The indexOf() method returns the index within the string of the first occurrence of the specified substring or
character. It returns -1 if the substring or character is not found.
Syntax:
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
Example: // Case-sensitive
public class IndexOfExample [Link]("Index of 'o': " + index1);
{ [Link]("Index of 'o' from index 5: " + index2);
public static void main(String[] args) [Link]("Index of 'World': " + index3);
{ [Link]("Index of 'world': " + index4);
String str = "Hello, World!"; }
int index1 = [Link]('o’); }
int index2 = [Link]('o', 5); int index3 =
[Link]("World");
int index4 = [Link]("world"); ': -1
Output:
Index of 'o': 4 Index of 'o' from index 5: 8 Index of 'World':
ACS06-R23 7 Index
OOP through JAVA of 'world
Prepared by
[Link]
THREAD
A thread is a:
• Referred as a lightweight process.
• Facility to allow multiple activities within a single process.
• A thread is a series of executed statements.
• Each thread has its own program counter, stack, and local variables.
• A thread is a nested sequence of method calls.
• It shares memory, files, and per-process state.
• Every Java program creates at least one thread [ main() thread ]. Additional
threads are created through the Thread constructor or by instantiating classes
that extend the Thread class.

ACS06-R23 OOP through JAVA Prepared by


[Link]
Life cycle of a Thread (Thread States):
• A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.

• But for better understanding the threads, we are explaining it in the 5 states.

• The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:
 New
 Runnable
 Running
 Non-Runnable (Blocked)
 Terminated
ACS06-R23 OOP through JAVA Prepared by
[Link]
ACS06-R23 OOP through JAVA Prepared by
[Link]
Creating Threads:
Thread implementation in java can be achieved in two ways:
[Link] the Thread class
[Link] the Runnable Interface
Note: The Thread and Runnable are available in the [Link].* package.

1) By extending thread class:


•The class should extend Java Thread class.
•The class should override the run() method.
•The functionality that is expected by the Thread to be executed is written in the
run() method.
void start(): Creates a new thread and makes it runnable.
void run(): The new thread begins its life inside this method.
ACS06-R23 OOP through JAVA Prepared by
[Link]
Example:
public class MyThread extends Thread
{
public void run()
{
[Link]("thread is running...");
}
public static void main(String[] args)
{
MyThread obj = new MyThread();
[Link]();
}
}

Output: thread is running…


ACS06-R23 OOP through JAVA Prepared by
[Link]
class SimpleThread extends Thread {
public SimpleThread(String str) { Output:
0 My first Thread
super(str); 1 My first Thread
} 2 My first Thread
public void run() { 3 My first Thread
4 My first Thread
for (int i = 0; i < 5; i++) { DONE! My first Thread
[Link]( i + " " + getName());
try {
sleep(5000);
} catch (InterruptedException e) {}
}
[Link]("DONE! " + getName());
}
public static void main(String args[])
{ SimpleThread st=new SimpleThread("My first Thread");
[Link]();
} ACS06-R23 OOP through JAVA Prepared by
} [Link]
•Start(): Creation of thread object never starts execution, we need to
call 'start()' method to run a thread.
•Sleep(): It makes current executing thread to sleep for a specified
interval of time. Time is in milliseconds.

•Yield(): It makes current executing thread object to pause temporarily


and gives control to other thread to execute.
notify(): This wakes up threads that called wait() on the same object
and moves the thread to ready state.
•notifyAll(): This method is inherited from Object class. This method
wakes up all threads that are waiting on this object's monitor to acquire
lock.
wait(): when wait() method is invoked on an object, the thread
executing that code gives up its lock on the object immediately and
moves the thread to the wait state.
ACS06-R23 OOP through JAVA Prepared by
[Link]
2) By Implementing Runnable interface:
• The class should implement the Runnable interface.
• The class should implement the run() method in the Runnable interface.
• Create an instance of the Thread class and pass your Runnable Object to its
constructor as a parameter. A Thread object is created that can run your
Runnable class.
• The functionality that is expected by the Thread to be executed is put in the run()
method

class Multi3 implements Runnable


{ public void run()
{ [Link]("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
} ACS06-R23 OOP through JAVA Prepared by
[Link]
Priority of a Thread (Thread Priority):
There are 3 constants defined in Thread class:

Each thread have a priority. Priorities are represented by a number


between 1 and 10. In most cases, thread schedular schedules the threads
according to their priority (known as preemptive scheduling). But it is not
guaranteed because it depends on JVM specification that which scheduling
it chooses.
[Link] static int MIN_PRIORITY
[Link] static int NORM_PRIORITY
[Link] static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of


MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
ACS06-R23 OOP through JAVA Prepared by
[Link]
class TestMultiPriority1 extends Thread
{ public void run()
{
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());
}
public static void main(String args[])
{ TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
TestMultiPriority1 m3=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.NORM_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
[Link]();
}
}
ACS06-R23 OOP through JAVA Prepared by
[Link]
• Thread Synchronization:
• When two or more threads need access to a shared
resource, they need some way to ensure that the resource
will be used by only one thread at a time.
• The process by which this is achieved is called
synchronization. Synchronization is the concept of the
monitor(also called a semaphore).
• For example, if multiple threads try to write within a
same file then they may corrupt the data because one of
the threads can override data or while one thread is
opening the same file at the same time another thread
might be closing the same file.
• So there is a need to synchronize the action of multiple
threads and make sure that only one thread can access the
resource at a given point in time. This is implemented
using a concept called monitors.
ACS06-R23 OOP through JAVA Prepared by
[Link]
A monitor is an object that is used as a mutually exclusive
lock. Only one thread can own a monitor at a given time.
When a thread acquires a lock, it is said to have entered the
monitor.

All other threads attempting to enter the locked monitor will


be suspended until the first thread exits the monitor. These
other threads are said to be waiting for the monitor.

ACS06-R23 OOP through JAVA Prepared by


[Link]
Types of Synchronization
There are two types of synchronization
[Link] Synchronization
[Link] Synchronization
Thread Synchronization:
- There are two types of thread synchronization
1. Mutual Exclusive
2. Inter-thread communication.
• Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
• Cooperation (Inter-thread communication in java)
ACS06-R23 OOP through JAVA Prepared by
[Link]
Output:
class Table{ class MyThread2 extends Thread{ 5
100
void printTable(int n){//method not synchronized Table t;
10
for(int i=1;i<=5;i++){ MyThread2(Table t){ 200
15
[Link](n*i); this.t=t; }
300
try{ public void run(){ 20
400
[Link](400); [Link](100); }
25
}catch(Exception e){[Link](e);} } 500
} } } class TestSynchronization1{
class MyThread1 extends Thread{ public static void main(String args[]){
Table t; Table obj = new Table();//only one object
MyThread1(Table t){ MyThread1 t1=new MyThread1(obj);
this.t=t; MyThread2 t2=new MyThread2(obj);
} [Link]();
public void run(){ [Link](); }
[Link](5); } }
ACS06-R23 OOP through JAVA Prepared by
} [Link]
Java synchronized method:
• If you declare any method as synchronized, it is known as synchronized
method.
• Synchronized method is used to lock an object for any shared resource.
• When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its
task.

Concept of Lock:
Synchronization is built around an internal entity known as the lock
or monitor. Every object has an lock associated with it. By convention, a
thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's
ACS06-R23 OOP through JAVA Prepared by
done with them. [Link]
class Table{ class MyThread2 extends Thread{
synchronized void printTable(int n){ Table t;
for(int i=1;i<=5;i++){ MyThread2(Table t){
[Link](n*i); this.t=t; }
try{ public void run(){
[Link](400); [Link](100);
}catch(Exception e){[Link](e);} } }
} } } public class TestSynchronization2{
class MyThread1 extends Thread{ Output: public static void main(String args[]){
5
Table t; Table obj = new Table();//only one object
10
MyThread1(Table t){ 15 MyThread1 t1=new MyThread1(obj);
this.t=t; 20 MyThread2 t2=new MyThread2(obj);
25
} 100 [Link]();
public void run(){ 200 [Link]();
[Link](5); 300 } }
ACS06-R23 400
OOP through JAVA Prepared by
} } [Link]
500
Inter-thread communication:
• Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
• Polling is usually implemented with the help of loops to check whether
a particular condition is true or not. If it is true, certain action is taken.
This wastes CPU times and makes the implementation inefficient.
• Cooperation is a mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or lock) in the
same critical section to be executed.
- It is implemented by following methods of Object class:
• final void wait() throws InterruptedException
• final void notify()
• final void notifyAll()
ACS06-R23 OOP through JAVA Prepared by
[Link]
1) wait() method:
Causes current thread to release the lock and wait until either
another thread invokes the notify() method or the notifyAll() method for
this object, or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be
called from the synchronized method only, otherwise it will throw
exception.

2) notify() method:
Wakes up a single thread that is waiting on this object's monitor. If
any threads are waiting on this object, one of them is chosen to be
awakened.
Syntax:
public final void notify()

3) notifyAll() method:
Wakes up all threads that are waiting on this object's monitor.
Syntax:
public final void notifyAll()
ACS06-R23 OOP through JAVA Prepared by
[Link]
The following Diagram shows the process of inter-thread communication

4. If you call notify() or notifyAll() method,


[Link] enter to acquire lock.
thread moves to the notified state (runnable
[Link] is acquired by on thread.
state).
[Link] thread goes to waiting state if you call
[Link] thread is available to acquire lock.
wait() method on the object. Otherwise it
[Link] completion of the task, thread releases
releases the lock and exits.
the lock and exits the monitor state of the object.
ACS06-R23 OOP through JAVA Prepared by
[Link]
class Customer class Test
{ {
int amount=10000; public static void main(String args[])
synchronized void withdraw(int amount) {
{ final Customer c=new Customer();
[Link]("going to withdraw..."); new Thread()
if([Link]<amount) {
{ public void run()
[Link]("Less balance; waiting for deposit"); {
try [Link](15000);
{ wait(); } }
catch(Exception e){} }.start();
} new Thread()
[Link]-=amount; {
[Link]("withdraw completed..."); public void run()
} {
synchronized void deposit(int amount)
{ [Link]("going to deposit..."); [Link](10000);
[Link]+=amount; }
[Link]("deposit completed... "); }.start();
notify(); }
} }
} Output: going to withdraw... Less JAVA
ACS06-R23 OOP through balance; waiting for deposit...
Prepared by
going to deposit... deposit completed... withdraw completed
[Link]
DEADLOCK IN JAVA
• Deadlock in Java is a situation where two or more processes wait indefinitely for one another's action.
Deadlock situation takes place mainly in Multithreaded programming.
• For example, a deadlock can occur when the first thread is waiting to acquire an object's lock which
is acquired already by the second thread, and the second thread is waiting to acquire another object's
lock which is already acquired by the first thread. Hence, both threads are waiting for each other to
release the lock, creating a deadlock situation.
• The following program shows how deadlock
occurred in multithreading.

ACS06-R23 OOP through JAVA Prepared by


[Link]
public class TestDeadlockExample1 { // t2 tries to lock resource2 then resource1
public static void main(String[] args) { Thread t2 = new Thread() {
final String resource1 = “file1"; public void run() {
final String resource2 = “printer"; synchronized (resource2) {
// t1 tries to lock resource1 then resource2 [Link]("Thread 2: locked resource 2");

Thread t1 = new Thread() { try { [Link](100);}


catch (Exception e) {}
public void run() {
synchronized (resource1) {
synchronized (resource1) {
[Link]("Thread 2: locked resource 1");
[Link]("Thread 1: locked resource 1");
}
try { [Link](100);}
}
catch (Exception e) {}
}
synchronized (resource2) {
};
[Link]("Thread 1: locked resource 2");
[Link]();
}
[Link](); Output:
}
} } Thread 1: locked resource 1
} Thread 2: locked resource 2
ACS06-R23 OOP through JAVA Prepared by
}; [Link]
JAVA DATABASE CONNECTIVITY:
- JDBC (Java Database Database Connectivity) is a Sun Microsystems specification. The
Java API is responsible for connecting to a database, issuing queries and commands, and
processing database result sets.

- JDBC and database drivers operate together to access spreadsheets and databases. The
design of JDBC defines the components that are utilized to connect to the database.

- The JDBC API classes and interfaces enable an application to send a request to a specific
database.

Applications of JDBC:
JDBC enables you to create Java applications that handle the following three programming tasks:

 Make a connection to a data source, such as a database.

 Send database queries and update statements.


ACS06-R23 OOP through JAVA Prepared by
 Retrieve and process the returned database [Link]
results in response to your query.
ARCHITECTURE OF JDBC

Application
(Java servlet, applet, etc)

JDBC API

JDBC Driver Manager

JDBC Drivers

SQL Server Data Source


Oracle

ACS06-R23 OOP through JAVA Prepared by


[Link]
1. Application: It is a java applet or a servlet that communicates with a data source.

2. The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve
results. Some of the important interfaces defined in JDBC API are as follows: Driver interface,
ResultSet Interface, RowSet Interface, PreparedStatement interface, Connection interface, and
Classes defined in JDBC API are as follows: DriverManager class, Types class, Blob class, clob
class.

3. DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific
drivers to connect enterprise applications to databases effectively.

4. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.

ACS06-R23 OOP through JAVA Prepared by


[Link]
Types of JDBC Architecture(2-tier and 3-tier)

The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are
as described below:

[Link]-tier model: A Java application communicates directly to the data source. The JDBC driver enables
the communication between the application and the data source. When a user sends a query to the data
source, the answers for those queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a user is connected. This is
known as a client/server configuration, where the user’s machine acts as a client, and the machine has
the data source running acts as the server.

[Link]-tier model: The user’s queries are sent to middle-tier services, from which the commands are
again sent to the data source. The results are sent back to the middle tier and then to the user.
This type of model is found very useful by management information system directors.
ACS06-R23 OOP through JAVA Prepared by
[Link]
INSTALLING MYSQL:
- Download the MySQL software from the following link.
[Link]

After downloading, unzip it, and double-click the MSI installer .exe file.
Then follow the steps below:
1. "Choosing a Setup Type" screen: Choose "Full" setup type. This installs all MySQL products and features.
Then click the "Next" button to continue.
2. "Check Requirements" screen: The installer checks if your PC has the requirements needed. If there are
some failing requirements, click on each item to try to resolve them by clicking on the Execute button which
will install all requirements automatically. Click "Next".
3. "Installation" screen: See what products that will be installed. Click "Execute" to download and install the
Products. After finishing the installation, click "Next".
4. "Product Configuration" screen: See what products that will be configured. Click the "MySQL Server
8.0.23" option to configure the MySQL Server. Click the "Next" button. Choose the "Standalone MySQL
Server/Classic MySQL Replication" option and click on the "Next" button. On page "Type and Networking"
set Config Type to "Development Computer" and "Connectivity" to "TCP/IP" and "Port" to "3006". Then,
click the "Next" button.
5. "Authentication Method" screen: Choose "Use Strong Password Encryption for Authentication". Click
"Next". ACS06-R23 OOP through JAVA Prepared by
[Link]
6. "Accounts and Roles" screen: Set a password for the root account. Click "Next".
7. "Windows Service" screen: Here, you configure the Windows Service to start the server. Keep the
default setup, then click "Next".
8. "Apply Configuration" screen: Click the "Execute" button to apply the Server configuration. After
finishing, click the "Finish" button.
9. "Product Configuration" screen: See that the Product Configuration is completed. Keep the default
setting and click on the "Next" and "Finish" buttons to complete the MySQL package installation.
10. In the next screen, you can choose to configure the Router. Click on "Next", and "Finish" and then
click the "Next" button.
11. "Connect To Server" screen: Type in the root password (from step 6). Click the "Check" button to
check if the connection is successful or not. Click on the "Next" button.
12. "Apply Configuration" screen: Select the options and click the "Execute" button. After finishing,
click the "Finish" button.
13. "Installation Complete" screen: The installation is complete. Click the "Finish" button.
INSTALLING MYSQL CONNECTOR/J:
Note: You must use MySQL Connector/J version 5.1 or later.
Steps:
[Link] the MySQL Connector/J drivers at [Link].
[Link] the .jar file and note its location for future reference.
For example, install the .jar file at C:\Program Files\MySQL\MySQL Connector J\mysql-connector-
ACS06-R23 OOP through JAVA Prepared by
[Link]. [Link]
JDBC - ENVIRONMENT SETUP (Windows platform):
• To start developing with JDBC, you should set up your JDBC environment by following the steps
shown below.
• Install the latest version of Java on your machine. Once you have installed Java on your machine, you
must set environment variables to point to the correct installation directories.
• Right-click on 'My Computer' and select 'Properties'.
• Click on the 'Environment variables' button under the 'Advanced' tab.
• Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it.
• For example, if the path is currently set to C:\Windows\System32, then edit it in the following way,
C:\Windows\System32;c:\Program Files\java\jdk\bin
Note: Download and install the same version of the JDK software jar file.

ACS06-R23 OOP through JAVA Prepared by


[Link]
JDBC CONNECTIVITY
JDBC:
- JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.

There are four types of JDBC drivers:


• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver

- We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

ACS06-R23 OOP through JAVA Prepared by


[Link]
Purpose of JDBC:
- Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

- We can use JDBC API to handle database using Java program and can perform the following
activities:
[Link] to the database
[Link] queries and update statements to the database
[Link] the result received from the database.

API Definition:
- API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.

ACS06-R23 OOP through JAVA Prepared by


[Link]
WORKING OF JDBC:
Java application that needs to communicate with the database has to be programmed using JDBC API. JDBC Driver
supporting data sources such as Oracle and SQL server has to be added in java application for JDBC support which can
be done dynamically at run time. This JDBC driver intelligently communicates the respective data source.
import [Link].*; Creating a simple JDBC application:
class MysqlCon {
public static void main(String args[]) {
try{ [Link]("[Link]");
Connection con=[Link](
"jdbc:mysql://localhost:3306/Employee","root",“tiger");
Statement stmt=[Link]();
ResultSet rs=[Link]("select * from emp");
while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e); }
ACS06-R23 OOP through JAVA Prepared by
} } [Link]
import [Link];
import [Link];
import [Link];
JAVA code to insert records into MySQL
import [Link]; database.
import [Link];
import [Link];
public class JavaInsertDemo {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
try {
[Link]("[Link]");
}
catch (Exception e) {
[Link](e);
ACS06-R23 OOP through JAVA Prepared by
} [Link]
conn = (Connection) [Link]("jdbc:mysql://localhost/business", "Manish", "123456");
[Link]("Connection is created successfully:");
stmt = (Statement) [Link]();
String query1 = "INSERT INTO InsertDemo " + "VALUES (1, 'John', 34)";
[Link](query1);
query1 = "INSERT INTO InsertDemo " + "VALUES (2, 'Carol', 42)";
[Link](query1);
[Link]("Record is inserted in the table successfully..................");
}
catch (SQLException excep) {
[Link]();
} catch (Exception excep) {
[Link]();
}

ACS06-R23 OOP through JAVA Prepared by


[Link]
finally {
try {
if (stmt != null)
[Link]();
}
catch (SQLException se) {}
try {
if (conn != null)
[Link]();
}
catch (SQLException se) {
[Link]();
}
}
[Link]("Please check it in the MySQL Table......... ……..");
}
ACS06-R23 OOP through JAVA Prepared by
} [Link]
RESULTSET INTERFACE:
• The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the
first row.
• By default, ResultSet object can be moved forward only and it is not updatable.
• But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as
well as we can make this object as updatable by:
1. Statement stmt = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface:

ACS06-R23 OOP through JAVA Prepared by


[Link]
Simple example of ResultSet interface to retrieve the data of 3rd row.
import [Link].*;
class FetchRecord
{
public static void main(String args[])throws Exception
{
[Link]("[Link]");
Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=[Link]("select * from emp765");
//getting the record of 3rd row
[Link](3);
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
} } ACS06-R23 OOP through JAVA Prepared by
[Link]
JAVAFX:
• JavaFX is a Java library used to develop Desktop applications and Rich Internet Applications (RIA).
The applications built in JavaFX can run on multiple platforms including Web, Mobile, and Desktops.
JavaFX is a comprehensive set of graphics and media packages bundled with the Java SE
Development Kit (JDK).

• A fundamental feature of JavaFX is its declarative language, FXML. It allows developers to define their
applications’ user interface (UI) using an XML-based syntax. This separation of UI from application
logic simplifies the design and maintenance of complex interfaces, enhancing development efficiency.

• JavaFX applications are structured around stages and scenes. A stage represents the application’s main
window, while a scene defines the content within that window. Various nodes, such as buttons, labels,
text fields, etc., can be added to the scene to create a visually appealing and interactive UI.

• JavaFX is intended to replace Swing in Java applications as a GUI


framework. However, It provides more functionalities than swing.
JavaFX also provides its components and doesn't depend upon the
operating system. It is lightweight and hardware-accelerated.
ACS06-R23 OOP through JAVA Prepared by
[Link]
FEATURES OF JAVAFX
Feature Description
Java Library It is a Java library which consists of many classes and interfaces that are written in Java.
FXML is the XML based Declarative mark-up language. The coding can be done in FXML to
FXML
provide the more enhanced GUI to the user.
Scene Builder Scene Builder generates FXML mark-up which can be ported to an IDE.
Web pages can be embedded with JavaFX applications. Web View uses WebKitHTML
Web view
technology to embed web pages.
Built-in UI JavaFX contains built-in components that are not dependent on operating system. The UI
Controls component are just enough to develop a full featured application.
JavaFX code can be embedded with the CSS to improve the style of the application. We can
CSS like styling
enhance the view of our application with the simple knowledge of CSS.
Swing The JavaFX applications can be embedded with swing code using the Swing Node class. We
interoperability can update the existing swing application with the powerful features of JavaFX.
Canvas API Canvas API provides the methods for drawing directly in an area of a JavaFX scene.
Rich Set of APIs JavaFX provides a rich set of API's to develop GUI applications.
Integrated
An integrated set of classes are provided
ACS06-R23 to deal
OOP through JAVA with
Prepared by 2D and 3D graphics.
Graphics Library [Link]
Program to build a GUI that displays text in label and image in an ImageView
import [Link]; @Override
import [Link]; public void start(Stage primaryStage) throws Exception {
import [Link]; StackPane root = new StackPane();
import [Link]; FileInputStream input= new FileInputStream(“D:/Image/[Link]");
import [Link]; Image image = new Image(input);

import [Link]; ImageView imageview=new ImageView(image);

import [Link]; Label my_label=new Label("Home",imageview);

import [Link]; Scene scene=new Scene(root,300,300);

public class LabelTest extends Application [Link]().add(my_label);

{ [Link](scene);
[Link]("Label Class Example");
[Link]();
}
public static void main(String[] args) {
launch(args);
ACS06-R23 OOP through JAVA Prepared by
} } [Link]
JAVAFX - EVENT HANDLING
• In JavaFX, we can develop GUI applications, web applications and graphical applications. In such
applications, whenever a user interacts with the application (nodes), an event is said to have been occurred.
• For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
Types of Events:
The events can be broadly classified into the following two categories :−
• Foreground Events − Those events which require the direct interaction of a user. They are generated as
consequences of a person interacting with the graphical components in a Graphical User Interface. For
example, clicking on a button, moving the mouse, entering a character through keyboard, selecting
an item from list, scrolling the page, etc.
• Background Events − Those events that don't require the interaction of end-user are known as background
events. The operating system interruptions, hardware or software failure, timer expiry, operation
ACS06-R23 OOP through JAVA Prepared by
completion are the example of background events.
[Link]
HANDLING MOUSE EVENT
Mouse event is fired when the mouse button is pressed, released, clicked, moved or dragged on the node.
Following table shows the user actions and associated event-handling activities -

User Action Event Type EventHandler Properties


onKeypressed
Pressing, releasing, or typing a
KeyEvent onKeyReleased
key on keyboard.
onKeyTyped
onMouseClicked
onMouseMoved
Moving, Clicking, or dragging onMousePressed
MouseEvent
the mouse. onMouseReleased
onMouseEntered
onMouseExited
onMouseDragged
onMouseDragEntered
Pressing, Dragging, and onMouseDragExited
MouseDragEvent
Releasing of the mouse button. onMouseDragged
onMouseDragOver
ACS06-R23 OOP through JAVA PreparedonMouseDragReleased
by
[Link]
package myjavafxapplication; public class MyJavaFXApplication extends Application {
import [Link]. Application; @Override
import [Link]; public void start(Stage primaryStage) {
import [Link]; Rectangle rect = new Rectangle(50,50,100,100);
import [Link]; [Link](20);
import [Link]. MouseEvent; [Link](20);
import [Link]; [Link]([Link]);
import [Link]: Rectangle; Text text = new Text (20,20,"Click on the rectangle to change its color");
import [Link]; //Handling the mouse event
import [Link]; [Link](e->{
[Link]([Link]);
});

ACS06-R23 OOP through JAVA Prepared by


[Link]
Group root = new Group (rect,text);
Scene scene = new Scene(root,300,200);
[Link](scene);
[Link]("Mouse Event Demo");
[Link]();
}
public static void main(String[] args)
{ launch(args);
} }

Program Explanation: In the above program,


(1) We have created one rectangular object and it is colored using blue color.
(2) The mouse click event is used. When the user clicks over the rectangle, the color of the rectangle gets
changed to red.
(3) Mouse Event is created and handled using the following code
[Link](e->{
[Link]([Link]);
}); ACS06-R23 OOP through JAVA Prepared by
[Link]

You might also like