0% found this document useful (0 votes)
5 views42 pages

R23 JAVA Programs

The document contains multiple Java programming exercises covering various concepts such as quadratic equations, binary search, bubble sort, string manipulation, class mechanisms, inheritance, abstract classes, interfaces, and exception handling. Each exercise includes code examples demonstrating the implementation of these concepts, such as calculating roots of quadratic equations, performing binary search, and showcasing inheritance and polymorphism. Additionally, it explains the use of the 'super' keyword and the characteristics of the StringBuffer class.

Uploaded by

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

R23 JAVA Programs

The document contains multiple Java programming exercises covering various concepts such as quadratic equations, binary search, bubble sort, string manipulation, class mechanisms, inheritance, abstract classes, interfaces, and exception handling. Each exercise includes code examples demonstrating the implementation of these concepts, such as calculating roots of quadratic equations, performing binary search, and showcasing inheritance and polymorphism. Additionally, it explains the use of the 'super' keyword and the characteristics of the StringBuffer class.

Uploaded by

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

Exercise-1:

1)b) Write a Java Program that Display the roots of a Quadratic Equation ax2+bx+c=0.
Calculate the Discriminate D and basing on the value of D, Describe the nature of the root.
import [Link];
public class QuadraticEquationSolver {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input coefficients a, b, and c
[Link]("Enter coefficient a: ");
double a = [Link]();
[Link]("Enter coefficient b: ");
double b = [Link]();
[Link]("Enter coefficient c: ");
double c = [Link]();
// Calculate the discriminant
double discriminant = b * b - 4 * a * c;
// Find the roots based on the discriminant
if (discriminant > 0)
{
// Two distinct real roots
double root1 = (-b + [Link](discriminant)) / (2 * a);
double root2 = (-b - [Link](discriminant)) / (2 * a);
[Link]("Roots are real and different.");
[Link]("Root 1: %.2f\n", root1);
[Link]("Root 2: %.2f\n", root2);
}
else if (discriminant == 0)
{
// One real root (or two identical real roots)
double root = -b / (2 * a);
[Link]("Roots are real and the same.");
[Link]("Root: %.2f\n", root);
}
Else
{
// Two complex roots
double realPart = -b / (2 * a);
double imaginaryPart = [Link](-discriminant) / (2 * a);
[Link]("Roots are complex and different.");
[Link]("Root 1: %.2f + %.2fi\n", realPart, imaginaryPart);
[Link]("Root 2: %.2f - %.2fi\n", realPart, imaginaryPart);
}
[Link]();
}
}

Exercise-2:
2)a) BinarySearch:
public class BinarySearch {
public static void main(String[] args) {
int[] sortedArray = {2, 3, 4, 10, 40};
int target = 10;
int left = 0;
int right = [Link] - 1;
int result = -1;
// Binary search loop
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if the target is present at mid
if (sortedArray[mid] == target) {
result = mid;
break;
}
// If the target is greater, ignore the left half
if (sortedArray[mid] < target) {
left = mid + 1;
}
// If the target is smaller, ignore the right half
else {
right = mid - 1;
}
}
// Output the result
if (result == -1) {
[Link]("Element not present in the array");
} else {
[Link]("Element found at index: " + result);
}
}
}

2b)BubbleSort:
public class BubbleSort {
public static void main(String[] args) {
int[] array = {64, 34, 25, 12, 22, 11, 90};
int n = [Link];
// Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
// Swap array[j] and array[j + 1]
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// Print sorted array
[Link]("Sorted array:");
for (int i = 0; i < n; i++) {
[Link](array[i] + " ");
}
}
}

2c)String buffer:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello, World!");
// Delete character at index 5 (',' in this case)
[Link](5);
[Link]("After deleting character at index 5: " + stringBuffer);
// Remove all occurrences of a character (e.g., 'l')
char charToRemove = 'l';
for (int i = 0; i < [Link](); i++) {
if ([Link](i) == charToRemove) {
[Link](i);
i--; // Adjust the index after removal
}
}
[Link]("After removing all occurrences of 'l': " + stringBuffer);
}
}

StringBuffer is a class in Java used for creating and manipulating strings that can be modified
after they are created. Unlike String, which is immutable (cannot be changed once created),
StringBuffer allows for dynamic modification of strings, making it more efficient for certain
operations like appending, inserting, or deleting characters.

Here are some key characteristics and features of StringBuffer:

1. Mutability:
o StringBuffer objects can be modified after they are created. This means you
can change the contents of the string without creating a new object.
2. Thread-Safety:
o StringBuffer is synchronized, meaning it is thread-safe. Multiple threads can
safely access a StringBuffer object without causing data corruption.
3. Efficiency:
o For operations that involve a lot of modifications to strings, StringBuffer is
more efficient than using String. This is because String creates a new object
for each modification, while StringBuffer modifies the existing object.
4. Common Methods:
o append(String str): Appends the specified string to this character sequence.
o insert(int offset, String str): Inserts the specified string at the specified
position.
o delete(int start, int end): Removes the characters in a substring of this
sequence.
o deleteCharAt(int index): Removes the character at the specified position.
o reverse(): Reverses the sequence of characters.
o toString(): Converts the StringBuffer to a String.
o

public class StringBufferExample {


public static void main(String[] args) {
// Create a StringBuffer object with initial content
StringBuffer stringBuffer = new StringBuffer("Hello, World!");
// Append a string to the StringBuffer
[Link](" How are you?");
[Link]("After append: " + stringBuffer);
// Insert a string at a specific position
[Link](7, "beautiful ");
[Link]("After insert: " + stringBuffer);

// Delete a substring from the StringBuffer


[Link](7, 17);
[Link]("After delete: " + stringBuffer);

// Delete a character at a specific position


[Link](5);
[Link]("After deleteCharAt: " + stringBuffer);
// Reverse the contents of the StringBuffer
[Link]();
[Link]("After reverse: " + stringBuffer);

// Convert StringBuffer to String


String result = [Link]();
[Link]("Final string: " + result);
}
}

Exercise-3:
3A)CLASS MECHANISM:
public class MyClass
{
private String name;
private int age;
public MyClass(String name, int age)
{
[Link] = name;
[Link] = age;
}
public void displayDetails()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
public boolean isAdult() {
return age >= 18;
}
public static void main(String[] args) {
// Creating an object of MyClass
MyClass person = new MyClass("Alice", 20);

// Invoking methods on the object


[Link]();

if ([Link]()) {
[Link]([Link] + " is an adult.");
} else {
[Link]([Link] + " is not an adult.");
}
}
}

3b)method over loading:


public class Add {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public double add(int a, double b) {
return a + b;
}
public static void main(String[] args) {
Add example = new Add();
int sum1 = [Link](5, 10);
int sum2 = [Link](5, 10, 15);
double sum3 = [Link](5.5, 4.5);
double sum4 = [Link](10, 5.5);
[Link]("Sum of 5 and 10 is: " + sum1);
[Link]("Sum of 5, 10 and 15 is: " + sum2);
[Link]("Sum of 5.5 and 4.5 is: " + sum3);
[Link]("Sum of 10 and 5.5 is: " + sum4);
}
}

3c) IMPLEMENTATION OF CONSTRUCTOR:


public class Person {
private String name;
private int age;
public Person() {
[Link] = "Unknown";
[Link] = 0;
}
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
public void displayDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
public static void main(String[] args) {
// Using default constructor
Person person1 = new Person();
[Link]();
Person person2 = new Person("Alice", 30);
[Link]();
}
}

3d)CONSTRUCTOR OVER LOADING:


public class Car {

// Instance variables
private String brand;
private String model;
private int year;

// Default constructor
public Car() {
[Link] = "Unknown";
[Link] = "Unknown";
[Link] = 0;
}
// Constructor with one parameter
public Car(String brand) {
[Link] = brand;
[Link] = "Unknown";
[Link] = 0;
}

// Constructor with two parameters


public Car(String brand, String model) {
[Link] = brand;
[Link] = model;
[Link] = 0;
}

// Constructor with three parameters


public Car(String brand, String model, int year) {
[Link] = brand;
[Link] = model;
[Link] = year;
}

// Method to display the details


public void displayDetails() {
[Link]("Brand: " + brand);
[Link]("Model: " + model);
[Link]("Year: " + year);
}

// Main method
public static void main(String[] args) {
// Using default constructor
Car car1 = new Car();
[Link]();

// Using constructor with one parameter


Car car2 = new Car("Toyota");
[Link]();

// Using constructor with two parameters


Car car3 = new Car("Toyota", "Camry");
[Link]();

// Using constructor with three parameters


Car car4 = new Car("Toyota", "Camry", 2022);
[Link]();
}
}
Exercise-4:
4a)Write a java program to implement single inheritance?
Program:
class Animal
{
String name;
Animal(String name)
{
[Link] = name;
}
void eat()
{
[Link](name + " is eating.");
}
void sleep()
{
[Link](name + " is sleeping.");
}
}
class Dog extends Animal
{
Dog(String name)
{
super(name);
}
void bark()
{
[Link](name + " is barking.");
}
}

public class SingleInheritanceDemo


public static void main(String[] args)
{
Dog myDog = new Dog("Buddy")
[Link]();
[Link]();
[Link]();
}
}

4B)Write a java program to implement multi level inheritance?


Program:
class Vehicle
{
String type;
Vehicle(String type)
{
[Link] = type;
}
void displayType()
{
[Link]("Vehicle type: " + type);
}
}
class Car extends Vehicle
{
int numberOfWheels;
Car(String type, int numberOfWheels)
{
super(type);
[Link] = numberOfWheels;
}
void displayCarInfo()
{
[Link]("Number of wheels: " + numberOfWheels);
}
}
int batteryCapacity;
ElectricCar(String type, int numberOfWheels, int batteryCapacity)
{
super(type, numberOfWheels);
[Link] = batteryCapacity;
}
void displayElectricCarInfo()
{
[Link]("Battery capacity: " + batteryCapacity + " kWh");
}
}
public class MultilevelInheritanceDemo
{
public static void main(String[] args)
{
ElectricCar myElectricCar = new ElectricCar("Electric", 4, 75);

[Link]();
[Link]();
[Link]();
}
}
4C)Write a java program for abstract class to find area of different shapes?
Program:
abstract class Shape
{
abstract double calculateArea();
}
class Circle extends Shape
{
private double radius;
Circle(double radius)
{
[Link] = radius;
}
@Override
double calculateArea() {
return [Link] * radius * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;

Rectangle(double length, double width) {


[Link] = length;
[Link] = width;
}
@Override
double calculateArea()
{
return length * width;
}
}
public class AbstractShapeDemo
{
public static void main(String[] args)
{
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
[Link]("Area of the circle: " + [Link]());
[Link]("Area of the rectangle: " + [Link]());
}
}
Exercise-5:
5A)Write a java program to give example for “Super”keyword?
Program:
class Animal {
void eat() {
[Link]("This animal eats food.");
}
Animal() {
[Link]("Animal class constructor called.");
}
}
class Dog extends Animal
{
@Override
void eat()
{
[Link]();
[Link]("This dog eats dog food.");
}
Dog()
{
super();
[Link]("Dog class constructor called.");
}
}
public class SuperKeywordExample
{
public static void main(String[] args)
{
Dog myDog = new Dog();
[Link]();
}}
5B)Write a java program to implement a interface. What kind of inheritance can be
achieved?
Program:
interface Animal {
void makeSound();
default void eat() {
[Link]("This animal eats food.");
}
static void sleep() {
[Link]("This animal sleeps.");
}
}
class Dog implements Animal {
@Override
public void makeSound() {
[Link]("The dog barks.");
}
@Override
public void eat() {
[Link]("The dog eats dog food.");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
[Link]();
[Link]();
}
}
5C)Write a java program to implement Runtime polymorphism?
Program:
class Animal {
void makeSound() {
[Link]("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks.");
}
}

class Cat extends Animal {


@Override
void makeSound() {
[Link]("Cat meows.");
}
}
public class RuntimePolymorphismExample {
public static void main(String[] args) {
Animal myAnimal;
myAnimal = new Dog();
[Link]();
myAnimal = new Cat();
[Link]();
}
}
Exercise-6:
6A)Write a java program that describes exception handling mechanism?
Program:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionHandlingExample {
static void riskyMethod(boolean shouldThrow) throws CustomException {
if (shouldThrow) {
throw new CustomException("This is a custom exception.");
}
[Link]("No exception was thrown.");
}
public static void main(String[] args) {
try {
riskyMethod(true);
} catch (CustomException e) {
[Link]("Caught exception: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
try {
riskyMethod(false);
} catch (CustomException e) {
[Link]("Caught exception: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
}
}

6B)Write a java program illustrating multiple catch clauses?


Program:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = new int[5];
numbers[10] = 25;
String text = null;
int length = [Link]();
int result = 10 / 0;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught an ArrayIndexOutOfBoundsException: " + [Link]());
} catch (NullPointerException e) {
[Link]("Caught a NullPointerException: " + [Link]());

} catch (ArithmeticException e) {
[Link]("Caught an ArithmeticException: " + [Link]());
} catch (Exception e) {
[Link]("Caught an Exception: " + [Link]());
} finally {
[Link]("Finally block executed.");
}
}
}
6C)Write a java program for creation of java built-in exceptions?
Program:
public class BuiltInExceptionsExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Caught an ArithmeticException: " + [Link]());
}
try {
int[] numbers = new int[5];
numbers[10] = 25;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught an ArrayIndexOutOfBoundsException: " + [Link]());
}
try {
String text = null;
int length = [Link]();
} catch (NullPointerException e) {
[Link]("Caught a NullPointerException: " + [Link]());
}
try {
String numberString = "abc";
int number = [Link](numberString);
} catch (NumberFormatException e) {
[Link]("Caught a NumberFormatException: " + [Link]());
}
}
}
6D)Write a java program for creation of User Defined Exceptions?
Program:
class AgeNotValidException extends Exception {
public AgeNotValidException(String message) {
super(message);
}
}
public class UserDefinedExceptionExample {
static void validateAge(int age) throws AgeNotValidException {
if (age < 0 || age > 150) {
throw new AgeNotValidException("Invalid age: " + age);
} else {
[Link]("Age is valid.");
}
}

public static void main(String[] args) {


try {
validateAge(200);
} catch (AgeNotValidException e) {
[Link]("Caught an AgeNotValidException: " + [Link]());
}
try {
validateAge(25);
} catch (AgeNotValidException e) {
[Link]("Caught an AgeNotValidException: " + [Link]());
}
}
}
Exercise:7
7A)Write a java program that creates threads by extending Thread [Link] thread
display “Good Morning”every 1 second,the second thread display “Hello”every 2
seconds and the third display”Welcome”every 3 seconds,(Repeat the same by
implementing Runnable)
Program:
class GoodMorningThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("GoodMorningThread interrupted.");
}
}
}
class HelloThread extends Thread {
public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000);
}
} catch (InterruptedException e) {
[Link]("HelloThread interrupted.");
}
}
}

class WelcomeThread extends Thread {


public void run() {
try {
while (true) {
[Link]("Welcome");
[Link](3000);
}
} catch (InterruptedException e) {
[Link]("WelcomeThread interrupted.");
}
}
}

public class ThreadExample {


public static void main(String[] args) {
Thread goodMorning = new GoodMorningThread();
Thread hello = new HelloThread();
Thread welcome = new WelcomeThread();
[Link]();
[Link]();
[Link]();
}
}
//Creating Threads by Implementing the Runnable Interface
class GoodMorningRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Good Morning");
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("GoodMorningRunnable interrupted.");
}
}
}
class HelloRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Hello");
[Link](2000);
}
} catch (InterruptedException e) {
[Link]("HelloRunnable interrupted.");
}
}
}
class WelcomeRunnable implements Runnable {
public void run() {
try {
while (true) {
[Link]("Welcome");
[Link](3000);
}
} catch (InterruptedException e) {
[Link]("WelcomeRunnable interrupted.");
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Runnable goodMorningRunnable = new GoodMorningRunnable();
Runnable helloRunnable = new HelloRunnable();
Runnable welcomeRunnable = new WelcomeRunnable();
Thread goodMorningThread = new Thread(goodMorningRunnable);
Thread helloThread = new Thread(helloRunnable);
Thread welcomeThread = new Thread(welcomeRunnable);
[Link]();
[Link]();
[Link]();
}
}

7B)Write a java program illustrating Is Alive and Join() ?


Program:
class TaskThread extends Thread {
private String name;

public TaskThread(String name) {


[Link] = name;
}

public void run() {


try {
[Link](name + " is running.");
[Link]((int) ([Link]() * 5000));
[Link](name + " has completed.");
} catch (InterruptedException e) {
[Link](name + " was interrupted.");
}
}
}

public class ThreadMethodsExample {


public static void main(String[] args) {
TaskThread thread1 = new TaskThread("Thread 1");
TaskThread thread2 = new TaskThread("Thread 2");
TaskThread thread3 = new TaskThread("Thread 3");
[Link]();
[Link]();
[Link]();
try {
while ([Link]() || [Link]() || [Link]()) {
[Link]("Main thread checking if threads are alive...");
if ([Link]()) {
[Link]();
}
if ([Link]()) {
[Link]();
}
if ([Link]()) {
[Link]();
}
}
} catch (InterruptedException e) {
[Link]("Main thread was interrupted.");
}
[Link]("All threads have finished.");
}
}
7C)Write a program illustrating Daemon Threads?
Program:

class DaemonThread extends Thread {


public void run() {
try {
while (true) {
[Link]("Daemon thread is running...");
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Daemon thread was interrupted.");
}
}
}
class NonDaemonThread extends Thread {
public void run() {
try {
[Link]("Non-daemon thread started.");
[Link](5000);
[Link]("Non-daemon thread finished.");
} catch (InterruptedException e) {
[Link]("Non-daemon thread was interrupted.");
}
}
}

public class DaemonThreadExample {


public static void main(String[] args) {
DaemonThread daemonThread = new DaemonThread();
[Link](true);
NonDaemonThread nonDaemonThread = new NonDaemonThread();
[Link]();
[Link]();

try {
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread was interrupted.");
}

[Link]("Main thread finished.");


}
}

7D)Write a java program producer consumer problem?


Program:
import [Link];
import [Link];
class Buffer {
private static final int CAPACITY = 10;
private Queue<Integer> queue = new LinkedList<>();
public synchronized void produce(int item) throws InterruptedException {
while ([Link]() == CAPACITY) {
wait();
}
[Link](item);
[Link]("Produced: " + item);
notifyAll();
}
public synchronized int consume() throws InterruptedException {
while ([Link]()) {
wait();
}
int item = [Link]();
[Link]("Consumed: " + item);
notifyAll();
return item;
}
}
class Producer extends Thread {
private Buffer buffer;

public Producer(Buffer buffer) {


[Link] = buffer;
}

public void run() {


try {
for (int i = 0; i < 20; i++) {
[Link](i);
[Link](500);
}
} catch (InterruptedException e) {
[Link]("Producer interrupted.");
}
}
}
class Consumer extends Thread {
private Buffer buffer;

public Consumer(Buffer buffer) {


[Link] = buffer;
}

public void run() {


try {
for (int i = 0; i < 20; i++) {
[Link]();
[Link](1000);
}
} catch (InterruptedException e) {
[Link]("Consumer interrupted.");
}
}
}

public class ProducerConsumerExample {


public static void main(String[] args) {
Buffer buffer = new Buffer();

Producer producer = new Producer(buffer);


Consumer consumer = new Consumer(buffer);

[Link]();
[Link]();
}
}
Exercise:8
8A)Write a java Program that imports and use the user defined packages
8b) Without writing any code build a GUI that displays text in a Label and an
image in an ImageView (use javaFX)
System Requirents:
 Java installed on system
 Any IDE like netbeans or myeclipse installed on system
 Scene builder software installed and the path of Scene Builder is to be set in IDE

Use visual-programming techniques to drag-and-drop JavaFX components onto Scene Builder’s


content panel—the design area.
Next, use Scene Builder’s Inspector to configure options, such as the Labels’s text and font size, and
the ImageView’s image.
Finally, view the completed GUI using Scene Builder’s Show Preview in Window option.
Opening Scene Builder and Creating the File
[Link]
Open Scene Builder so that you can create the FXML file that defines the
GUI. The window initially appears fallows.
Untitled at the top of the window indicates that Scene Builder has created a new FXML file that you
have not yet saved. Select File > Save to display the Save As dialog, then select a location in which to
store the file, name the file [Link] and click the Save button.
Adding an Image to the Folder Containing
[Link]
The image which is use for this app ([Link]) is located in the images
subfolder examples folder.
To make it easy to find the image when it is ready to add it to the app, locate the images folder on the
file system, then copy [Link] into the folder where you saved [Link].
Creating a VBox Layout Container
For this app, place a Label and an ImageView in a VBox layout
container (package [Link]), which will be the scene
graph’s root node.
Layout containers help to arrange and size GUI
components. A VBox arranges its nodes vertically from top to bottom.
To add a VBox to Scene Builder’s content panel double-click VBox in the Library window’s
Containers section. (You also can drag-and-drop a VBox from the Containers section onto Scene
Builder’s content panel.)
Configuring the VBox Layout Container
Specifying the VBox’s Alignment
1. Select the VBox in Scene Builder’s content panel by clicking it.
Scene Builder displays many VBox properties in the Scene Builder
Inspector’s Properties section.
2. Click the Alignment property’s drop-down list and notice the
variety of potential alignment values you can use. Click CENTER to
set the Alignment.
Specifying the VBox’s Preferred Size
1. Select the VBox.
2. Expand the Inspector’s Layout section by clicking the right
arrow () next to Layout. The section expands and the right arrow changes
to a down arrow. Clicking the arrow again would collapse the section.
3. Click the Pref Width property’s text field, type 450 and press
Enter to change the preferred width.
4. Click the Pref Height property’s text field, type 300 and press
Enter to change the preferred height.
Adding and Configuring a Label
Adding a Label to the VBox
Expand the Scene Builder Library window’s Controls section by
clicking the right arrow () next to Controls, then drag-and-drop a Label from the Controls section
onto the VBox in Scene Builder’s content panel.
Adding and Configuring an ImageView
Adding an ImageView to the VBox
Drag and drop an ImageView from the Library window’s Controls
section to just below the Label, as shown

Setting the ImageView’s Image


Next you’ll set the image to display:
1. Select the ImageView, then in the Inspector’s Properties
section click the ellipsis (...) button to the right of the Image
property. By default, Scene Builder opens a dialog showing the folder
in which the FXML file is saved. This is where you placed the image
file [Link]
2. Select the image file, then click Open. Scene Builder displays the
image and resizes the ImageView to match the image’s aspect ratio
—that is, the ratio of the image’s width to its height
Changing the ImageView’s Size
We’d like to display the image at its original size. If we reset the
ImageView’s default Fit Width and Fit Height property values—
which Scene Builder set when you added the ImageView to the design—
Scene Builder will resize the ImageView to the image’s exact dimensions.

Previewing the Welcome GUI


You can preview what the design will look like in a running application’s
window. To do so, select Preview > Show Preview in Window,
which displays the window as follows
Exercise-9:
9A) Write a java program that connects to a database using JDBC?
Program:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class JDBCExample {


private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "password";
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
[Link]("[Link]");
connection = [Link](JDBC_URL, JDBC_USER,
JDBC_PASSWORD);
statement = [Link]();
String query = "SELECT * FROM mytable";
resultSet = [Link](query);
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
[Link]("ID: " + id + ", Name: " + name);
}
} catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: " + [Link]());
} catch (SQLException e) {
[Link]("Database error: " + [Link]());
} finally {
try {
if (resultSet != null) [Link]();
if (statement != null) [Link]();
if (connection != null) [Link]();
} catch (SQLException e) {
[Link]("Error closing resources: " + [Link]());
}
}
}
}

9B)Write a java program to connect to the database using JDBC and insert
values into it?
Program:
import [Link];
import [Link];
import [Link];
import [Link];

public class JDBCInsertExample {

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";


private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "password";

public static void main(String[] args) {


Connection connection = null;
PreparedStatement preparedStatement = null;
try {
[Link]("[Link]");

connection = [Link](JDBC_URL, JDBC_USER,


JDBC_PASSWORD);
String sql = "INSERT INTO mytable (name, age) VALUES (?, ?)";
preparedStatement = [Link](sql);

[Link](1, "John Doe");


[Link](2, 30);

int rowsInserted = [Link]();


if (rowsInserted > 0) {
[Link]("A new record was inserted successfully!");
}
} catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: " + [Link]());
} catch (SQLException e) {
[Link]("Database error: " + [Link]());
} finally {
try {
if (preparedStatement != null) [Link]();
if (connection != null) [Link]();
} catch (SQLException e) {
[Link]("Error closing resources: " + [Link]());
}
}
}
}
9C)Write a java program to connect to database using JDBC and delete values from it?
Program:
import [Link];
import [Link];
import [Link];
import [Link];

public class JDBCDeleteExample {


private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "password";

public static void main(String[] args) {


Connection connection = null;
PreparedStatement preparedStatement = null;

try {
[Link]("[Link]");

connection = [Link](JDBC_URL, JDBC_USER,


JDBC_PASSWORD);

String sql = "DELETE FROM mytable WHERE id = ?";

preparedStatement = [Link](sql);

int idToDelete = 1;
[Link](1, idToDelete);
int rowsDeleted = [Link]();
if (rowsDeleted > 0) {
[Link]("Record deleted successfully!");
} else {
[Link]("No record found with the specified ID.");
}
} catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: " + [Link]());
} catch (SQLException e) {
[Link]("Database error: " + [Link]());
} finally {
try {
if (preparedStatement != null) [Link]();
if (connection != null) [Link]();
} catch (SQLException e) {
[Link]("Error closing resources: " + [Link]());
}
}
}
}

You might also like