Ooptj r23 Unit 5
Ooptj r23 Unit 5
Storage of Strings :
The objects of class String have a special storage facility, which is not available to
objects of other two String classes or to objects of any other class. The memory allocated to a
Java program is divided into two segments:
i. Stack
ii. Heap
2
The variables are stored on heap, whereas the program is stored on stack. Within the heap, there
is a memory segment called ‘String constant pool’. The String class objects can be created in two
different ways:
String strx = “abcd”;
String strz = new String(“abcd”);
The strings that are defined with String strx=“abcd”; are stored in “String Constant Pool”, where
as the strings created String strz=new String(“abcd”); are stored in heap portion as shown in the
following figure 1.
The String Constant Pool stores only the unique strings. If you define another string as:
String stry=“abcd”;
Then no duplicate String object is created, but a reference is assigned to stry, since the “abcd” is
already existing in the pool. This is not the case with outside the pool. If we create string with
new operator with same value that is already existing then memory is allocated to this new object
being created.
Output:
D:\CSE>javac StringTest.java
D:\CSE>java StringTest
Are references of strx and stry same?true
Are references of stry and strz same?false
Are references of strz and str1 same?false
Are references of s1 and s2 same?false
2. Interface CharSequence
CharSequence is an interface in java.lang package. It is implemented by several classes
including the classes String, StringBuffer, and StringBuilder. It has the following four methods.
i). charAt(int index): The method returns character value at specified index value.
ii). int length(): This method returns the length of this (invoking) character sequence.
iii).CharSequence subSequence(int startIndex, endIndex): The method returns a subsequence
from start index to end index of this sequence. Throws IndexOutOfBoundsException.
4
iv). String toString(): The method returns a string containing characters of the sequence in the
same.
3. String class
The String, StringBuffer, and StringBuilder classes are defined in java.lang package. Java
implements strings as objects of type String.
String represents fixed-length, immutable character sequences. The class String is used to
represent strings in Java.
It is declared as:
public final class String extends Object implements serializable, comparable<String>,
charSequence
String() - The String class supports several constructors. This constructor creates a string
without any characters. To create an empty String, call the default constructor. See the following
examples.
String str = new String();
String str1 = “”;
String (byte [] barray) - It constructs a new string by decoding the specified byte[] barray by
using a computer’s default character set. The following code
5
String (byte [] barray, Charset specifiedset) -It constructs a new string by decoding the
specified byte array (bray) by using specified character set. Some of the Charsets supported by
Java are UTF8, UTF16, UTF32, and ASCII. These may be written in lower case such as utf8,
utf16, utf32, and ascii.
String(byte[] bray, int offset, int length, String charsetName) -The constructor constructs
String object by decoding the specified part of byte array using specified Charset.
For example, String str4 = new String(barray,1, 3, “ascii”);
String (byte[] barray, string charsetName) -The constructor constructs a string by decoding
the byte array using specified Charset. String str3 = new String(barray, “UTF8”);
3.1 Methods for Extracting Characters from Strings (or) Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Although the characters that comprise a string within a String object cannot be
indexed as if they were a character array, many of the String methods employ an index (or offset)
into the string for their operation. Like arrays, the string indexes begin at zero.
i) charAt( ) - To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It returns the character at the specified index location. It has
this general form: char charAt(int where) Here, where is the index of the character that you want
to obtain. The value of where must be nonnegative and specify a location within the string.
For example, char ch;
ch = "abc".charAt(1); assigns the value b to ch.
6
ii) getChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method. The
general form is: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd specifies
an index that is one past the end of the desired substring. The array that will receive the
characters is specified by target. The index within target at which the substring will be copied is
passed in targetStart.
iii) getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This
method is called getBytes( ), and it uses the default character-to-byte conversions provided by
the platform. Here is its simplest form: byte[ ] getBytes( )
iv) toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest way
is to call toCharArray( ). It returns an array of characters for the entire string.
It has this general form: char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the
same result.
i) equals( )
To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str) Here, str is the String object being compared with the invoking
String object. It returns true if the strings contain the same characters in the same order, and
false otherwise. The comparison is case-sensitive.
7
ii) equalsIgnoreCase( )
To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it
compares two strings, it considers A-Z to be the same as a-z. It has this general form: boolean
equalsIgnoreCase(String str) Here, str is the String object being compared with the invoking
String object. It, too, returns true if the strings contain the same characters in the same order, and
false otherwise.
iii) regionMatches( )
The regionMatches( ) method compares a specific region inside a string with another specific
region in another string. There is an overloaded form that allows you to ignore case in such
comparisons.
Here are the general forms for these two methods:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String str2, int str2StartIndex,
int numChars)
For both versions, startIndex specifies the index at which the region begins within the
invoking String object. The String being compared is specified by str2. The index at which the
comparison will start within str2 is specified by str2StartIndex. The length of the substring being
compared is passed in numChars. In the second version, if ignoreCase is true, the case of the
characters is ignored. Otherwise, case is significant.
vi) compareTo( )
For sorting applications, you need to know which is less than, equal to, or greater than the
next. A string is less than another if it comes before the other in dictionary order. A string is
greater than another if it comes after the other in dictionary order.
The method compareTo( ) serves this purpose. It is specified by the Comparable<T>
interface, which String implements. It has this general form: int compareTo(String str) Here, str
is the String being compared with the invoking String. The result of the comparison is returned
and is interpreted as shown here:
8
If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( )
method, as shown here: int compareToIgnoreCase(String str) This method returns the same
results as compareTo( ), except that case differences are ignored.
i) substring( )
You can extract a substring using substring( ). It has two forms. The first is String
substring(int startIndex) Here, startIndex specifies the index at which the substring will begin.
This form returns a copy of the substring that begins at startIndex and runs to the end of the
invoking string. The second form of substring( ) allows you to specify both the beginning and
ending index of the substring: String substring(int startIndex, int endIndex) Here, startIndex
specifies the beginning index, and endIndex specifies the stopping point. The string returned
contains all the characters from the beginning index, up to, but not including, the ending index.
ii) concat( )
You can concatenate two strings using concat( ), shown here: String concat(String str)
This method creates a new object that contains the invoking string with the contents of str
appended to the end. concat( ) performs the same function as +.
For example, String s1 = "one"; String s2 = s1.concat("two"); puts the string "onetwo" into s2.
iii) replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character
in the invoking string with another character. It has the following general form: String
replace(char original, char replacement) Here, original specifies the character to be replaced
by the character specified by replacement. The resulting string is returned.
9
For example, String s = "Hello".replace('l', 'w'); puts the string "Hewwo" into s.
The second form of replace( ) replaces one character sequence with another. It has this
general form: String replace(CharSequence original, CharSequence replacement)
iv) trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed. It has this general form: String trim( ) For example,
String s = " Hello World ".trim(); This puts the string "Hello World" into s.
chars is the array that holds the characters, startIndex is the index into the array of characters at
which the desired substring begins, and numChars specifies the length of the substring.
String toLowerCase( )
String toUpperCase( ) Both methods return a String object that contains the uppercase
or lowercase equivalent of the invoking String. The default locale governs the conversion in both
cases.
// Example, Demonstrate toUpperCase() and toLowerCase().
class ChangeCase
{
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
4. Class StringBuffer
StringBuffer supports a modifiable string. StringBuffer represents growable and writable
character sequences. StringBuffer may have characters and substrings inserted in the middle or
appended to the end. It defines the strings that can be modified as well as the number of
characters that may be changed, replaced by another, a string that may be appended, etc. The
strings are also thread safe. For the strings created by class StringBuffer, the compiler allocates
extra capacity for 16 more characters so that small modifications do not involve relocation of the
string. The class is declared as follows:
public final class StringBuffer extends Object implements Serializable, CharSequence
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
public synchronized append(String s) is used to append the specified string with this string. The
StringBuffer append() method is overloaded like append(char),
append(boolean),append(int),append(float),append(double
) etc.
public synchronized insert(int offset, String s) is used to insert the specified string with this string at the
StringBuffer specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public synchronized replace(int startIndex, int is used to replace the string from specified startIndex and
StringBuffer endIndex, String str) endIndex.
publicsynchronized delete(int startIndex, int is used to delete the string from specified startIndex and
StringBuffer endIndex) endIndex.
public synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() is used to return the current capacity.
public void ensureCapacity(int is used to set the minimum size of the buffer.
minimumCapacity)
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number
of characters.
public String substring(int beginIndex, is used to return the substring from the specified
int endIndex) beginIndex and endIndex.
5. Class StringBuilder
The StringBuilder class is the subclass of Object in java.lang package. StringBuilder is
similar to StringBuffer except for one important difference: it is not synchronized, which means
that it is not thread-safe. The advantage of StringBuilder is faster performance. This class is used
for creating and modifying strings.
Its declaration is as follows: public final class StringBuilder extends Object implements
Serializable, CharSequence
Constructors of Class StringBuilder:
The four constructors of the class are described as follows:
StringBuilder() -- Creates a StringBuilder object with no characters but with initial capacity of
16 characters.
StringBuilder(CharSequence chSeq) -- Creates a StringBuilder object with characters as
specified in CharSequence chSeq.
StringBuilder(int capacity) -- Creates a StringBuilder object with specified capacity. It throws
NegativeArraySizeException.
StringBuilder(String str) -- Creates a StringBuilder object initialized with contents of a
specified string. It throws NullPointException if str is null.
public StringBuilder append(String s) is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double)
etc.
public StringBuilder insert(int offset, is used to insert the specified string with this string at the
String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public StringBuilder replace(int is used to replace the string from specified startIndex and
startIndex, int endIndex, String str) endIndex.
public StringBuilder delete(int is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.
public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int is used to return the substring from the specified beginIndex
beginIndex, int endIndex) and endIndex.
1. Single-core Processor- The tasks are executed one after the other in the queue.
2. Time-sharing of CPU –Thread1 starts first, after few seconds, Thread2 starts, and
Thread1 sleeps, and after few milliseconds Thread3 starts, Thread2 goes to sleep.
Similarly Thread1 wakes up, and Thread3 sleeps. This way CPU time is shared.
3. Four-core CPU- Core 0, loads the program, and forwards the three independent threads to
other three cores –one to each. All the tasks are executed simultaneously.
8. Multi-process programming Vs Multithreaded Programming
9.Thread class
In java, threads are based on the class ‘Thread” that belongs to the java.lang package. It
has number of methods. One thread will be always running and is created by the system for
executing the main() method. That is called ‘main’ Thread. A thread will not work up on
creation, but it has to be called explicitly using the start() method. This start() method makes a
call to the run() method automatically which is the entry point for thread execution.
Constructors of Thread class:
Thread ()-without arguments, default constructor
Thread(String str)- Thread contains name given as argument
Thread(Thread obj, String str) -takes thread object and string
Thread(class Obj) – takes the runnable class as target object
Thread(ThreadGroup group, String name) –Every thread belongs to a group, it can be
made as group using this constructor.
}
}
catch(InterruptedException e)
{
System.out.println("Interruption raised");
}
}
}
i) Newborn State
When we create a thread it is said to be in the new born state. At this state we can do the
following:
Schedule it for running using the start() method.
Kill it using stop() method.
19
}
}
}
class Thread2 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Welcome ");
try
{
sleep(500);
}
catch(InterruptedException e)
{
}
}
}
class Multi1
{
public static void main(String[]args)
{
Thread1 t1=new Thread1();
Thread2 t2=new Thread2();
t1.start();
t2.start();
}
}
OUTPUT:
Hello World
Welcome
Welcome
Hello World
Welcome
Welcome
Hello World
Welcome
Welcome
Hello World
21
Welcome
Welcome
Hello World
Welcome
Welcome
Hello World
Hello World
Hello World
Hello World
Hello World
}
}
}
class Run2 implements Runnable
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Welcome ");
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
}
22
}
}
}
class Multi2
{
public static void main(String[]args)
{
Run1 r1=new Run1();
Run2 r2=new Run2();
Thread t1=new Thread(r1);
Thread t2=new Thread(r2);
t1.start();
t2.start();
}
}
{
public void run()
{
System.out.println(" Child 3 is started");
}
}
class PriorityTest
{
public static void main(String args[])
{
Thread1 t1=new Thread1(); //setting the priorities using the setPriority() method
t1.setPriority(1);
Thread2 t2=new Thread2();
t2.setPriority(9);
Thread3 t3=new Thread3();
t3.setPriority(6);
t1.start();
t2.start();
t3.start();
System.out.println("The t1 thread priority is :"+t1.getPriority()); //getting the priority
}
}
14. Synchronization
In multithreaded programming threads require to access a same resource, for example a
memory object. One thread wants to update it, while the other thread wants to read it.
In this situation the result may not be as expected when the sequence of operations
followed are different then desired.
Only one thread must be allowed to use the critical resource at a time to avoid this race
condition. The second thread must be allowed after the first thread has finished its work.
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.
Thread synchronization is important in multithreaded programming in order to maintain
the data consistency. In Java, synchronization is achieved using synchronized keyword.
Every thread object has a monitor associated with it, which is the key to the
synchronization, and when it enters the synchronized method it suspends the other
threads from entering the synchronized method.
A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one
thread can own a monitor at a given time. When a thread acquires a lock, it is said to have
24
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.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}
// Program for create a Bank application to illustrate the multithreading using Synchronization
class BankAccount
{
int accountNumber;
double balance;
BankAccount(int n, double y)
{
accountNumber=n;
balance =y;
}
synchronized boolean deposit(int amount)
{
if(amount<0.0)
return false;
else
{
balance=balance+amount;
System.out.println("Balance after deposit="+balance);
return true;
}
}
synchronized boolean withDraw(int amount)
{
if(amount<0.0)
return false;
else
{
balance =balance - amount;
System.out.println("Balance after withdrawal ="+balance);
return true;
}
}
public static void main(String[]args)
{
BankAccount ba=new BankAccount(2345,1000.0);
System.out.println("Initial balance ="+balance);
new Thread(()->deposit(500)).start();
new Thread(()->withDraw(400)).start();
25
}
}
Disadvantages of Synchronization:
This way of communications between the threads competing for same resource is called
implicit communication.
This has one disadvantage due to polling. The polling wastes the CPU time.
To save the CPU time, it is preferred to go to the inter-thread communication (explicit
communication).
Producer-Consumer Problem:
26
The producer should produce data only when the buffer is not full. In case it is found that
the buffer is full, the producer is not allowed to store any data into the memory buffer. Data can
only be consumed by the consumer if and only if the memory buffer is not empty. In case it is
found that the buffer is empty, the consumer is not allowed to use any data from the memory
buffer.
class Q
{
int n;
boolean valueSet = false;
synchronized int get()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
JDBC API and JDBC Driver form important components to fetch and store the
information in the Database. The JDBC API is installed in the client side. Therefore, when the
user wants to fetch some data from the Database, the user sets up the connection to the JDBC
Driver Manager using the JDBC JDBC API through Java Application. The JDBC Manager needs
a medium to communicate with Database. The JDBC Driver provides this medium and required
information to the JDBC Manager. Through JDBC API we can connect to different types of
Database systems including Relational and Non-relational Database system. Some of the most
widely used RDBMS are MySQL Server, Oracle, and IBM’s DB2.
Two-tier Architecture for Data Access: In this model java application directly communicates
with Database. Both Java Application and JDBC API are located on the Client Machine. The
Database is located on the Database Server. User sends the commands to the Database. The
Commands are processed and the results of these statements are sent to the user.
Three-tier Architecture for Data Access: In this model user commands are first sent to the
application server forming the middle tier. The applications server containing the JDBC API
sends the SQL statements to the database located on the database server. The commands are
processed and result is sent to the middle tier, which then sends it to the user.
It is considered to be one of the best RDBMS systems for developing web-based software
applications as it provides speed, flexibility, and reliability.
The MySQL comes with two variations such as MySQL Community, and MySQL Web
Community and can be downloaded from www.mysql.com.
MySQL database system can operate on many platforms including Linux, Windows, Mac
OS, Sun Solaris and so on. We can select appropriate platform and download. Here we
are going to learn installing on windows platform.
Steps to download and Install MySQL :
Go to the web site www.mysql.com
Select the appropriate platform / operating system.
Select mysql-installer-community or mysql-installer-web-community
Click on download.
The following installer will be downloaded: mysql-installer-web-community-8.0.25.0
Double click on the above installer to start installation.
Step 1: After downloading the setup, unzip it anywhere and double click the MSI
installer .exe file.
Step 2: In the next wizard, choose the Setup Type. There are several types available, and
you need to choose the appropriate option to install MySQL product and features. Here,
we are going to select the Full option and click on the Next button.
Step 3: Once we click on the Next button, it may give information about some features
that may fail to install on your system due to a lack of requirements. We can resolve them
by clicking on the Execute button that will install all requirements automatically or can
skip them. Now, click on the Next button.
Step 4: In the next wizard, we will see a dialog box that asks for our confirmation of a
few products not getting installed. Here, we have to click on the Yes button.
Step 5: Once we click on the Execute button, it will download and install all the
products. After completing the installation, click on the Next button.
Step 6: In the next wizard, we need to configure the MySQL Server and Router. Here, I
am not going to configure the Router because there is no need to use it with MySQL. We
are going to show you how to configure the server only. Now, click on the Next button.
32
Step 7: As soon as you will click on the Next button, you can see the screen below. Here,
we have to configure the MySQL Server. Now, choose the Standalone MySQL
Server/Classic MySQL Replication option and click on Next. Here, you can also choose
the InnoDB Cluster based on your needs.
Step 8: In the next screen, the system will ask you to choose the Config Type and other
connectivity options. Here, we are going to select the Config Type as 'Development
Machine' and Connectivity as TCP/IP, and Port Number is 3306, then click on Next.
Step 9: Now, select the Authentication Method and click on Next. Here, I am going to
select the first option.
Step 10: The next screen will ask you to mention the MySQL Root Password. After
filling the password details, click on the Next button.
Step 11: The next screen will ask you to configure the Windows Service to start the
server. Keep the default setup and click on the Next button.
Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If
you agree with this configuration, click on the Execute button.
Step 13: Once the configuration has completed, you will get the screen below. Now,
click on the Finish button to continue.
Step 14: In the next screen, you can see that the Product Configuration is completed.
Keep the default setting and click on the Next-> Finish button to complete the MySQL
package installation.
Step 15: In the next wizard, we can choose to configure the Router. So click on Next-
>Finish and then click the Next button.
Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to
mention the root password, which we had set in the previous steps.
Step 17: In the next wizard, select the applied configurations and click on the Execute
button.
Step 18: After completing the above step, we will get the following screen. Here, click
on the Finish button.
PreparedStatement pstmt =
Connection.prepareStatement("SELECT * FROM
yourTable");
ResultSet rs = pstmt.executeQuery();
public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.
public boolean execute(String sql): is used to execute queries that may return multiple results.
public int[] executeBatch(): is used to execute batch of commands.
vi) Process the results - The results are processed using the while loop as shown in the java
example program.
vii) Closing the Connection- After completion of the task the connection is closed with close()
method of Connection interface.
public boolean last() is used to move the cursor to the last row in result set object.
public boolean absolute(int row) is used to move the cursor to the specified row number in the
ResultSet object.
public boolean relative(int row) is used to move the cursor to the relative row number in the
ResultSet object, it may be positive or negative.
36
public int getInt(int is used to return the data of specified column index of the current
columnIndex) row as int.
public int getInt(String is used to return the data of specified column name of the current
columnName) row as int.
public String getString(int is used to return the data of specified column index of the current
columnIndex) row as String.
public String getString(String is used to return the data of specified column name of the current
columnName) row as String.
import java.sql.*;
class MysqlCon{
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver"); //loading and registering
String url="jdbc:mysql://localhost:8080/college"; //Defining URL
Connection con=DriverManager.getConnection(url,"root","root"); //Establishing
connection
//here url is database name, root is username and password
Statement stmt=con.createStatement(); //create statement
ResultSet rs=stmt.executeQuery("select * from student"); //Execute Query
while(rs.next()) //process result
System.out.println(rs.getInt("id")+" "+rs.getString("fname")+"
"+rs.getInt("marks"));
con.close(); //closing the connection
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Compiling and Running MysqlCon.java
D:/CSE> javac MysqlCon.java
D:/CSE> java MysqlCon
345 Riya 60
346 Rohit 75
346 Rohit 75
348 preethi 84
400 divya 90
37
JAVAFX GUI
25. 1. JavaFX Scene Builder
Definition: JavaFX Scene Builder is a visual layout tool for designing JavaFX application
interfaces. It allows you to drag and drop UI components, set properties, and generate FXML
files.
Usage:
Download and install JavaFX Scene Builder.
Open Scene Builder and create a new FXML file.
Design the layout by dragging UI components like buttons, labels, and text fields.
Save the design, which generates an FXML file to be loaded into your JavaFX
application.
Structure Example:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
39
// Create a Scene
Scene scene = new Scene(root, 400, 300);
Displaying Text:
Example:
import javafx.scene.text.Text;
Displaying Images:
Use Image and ImageView classes to display an image.
Example:
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
4. Event Handling
40
Definition: Event handling in JavaFX enables responding to user interactions such as clicks, key
presses, and mouse movements.
Example:
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
6. Mouse Events
Definition: Mouse events detect and respond to mouse actions, such as clicks, movements, and
drags.
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Rectangle;
// Add Text
Text text = new Text("Welcome to JavaFX!");
42
root.getChildren().add(text);
// Add Image
Image image = new Image("file:yourImagePath.jpg");
ImageView imageView = new ImageView(image);
root.getChildren().add(imageView);