Java Lab 1 To 9
Java Lab 1 To 9
Aim: To write a JAVA program to display default value of all primitive data type of JAVA .
Description:
Primitive datatypes are predefined by the language and named by a keyword in Java.
Primitive types are the Java data types used for data manipulation, for example, int, char, float,
double, boolean, etc. The following are the some data types and their sizes:
class defaultdemo
static byte b;
static short s;
static int i;
static long l;
static float f;
static double d;
static char c;
System.out.println("Byte :"+b);
System.out.println("Short :"+s);
System.out.println("Int :"+i);
System.out.println("Long :"+l);
System.out.println("Float :"+f);
System.out.println("Double :"+d);
System.out.println("Char :"+c);
System.out.println("Boolean :"+bl);
}
OUTPUT:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Boolean :false
Result:
Hence, to display default value of all primitive data type of JAVA is executed
successfully.
EXP :1 b
Aim: To write a java program that display the roots of a quadratic equation ax2+bx=0. Calculate
the discriminate D and basing on value of D, describe the nature of root.
Description:
The roots of a function are the x-intercepts. By definition, the y-coordinate of points lying
on the x-axis is zero. Therefore, to find the roots of a quadratic function, we set f (x) = 0, and
solve the equation, ax2 + bx + c = 0.
ax^2 + bx + c = 0
where a, b, c are real numbers and cannot be zero ie, there value must be from {-∞ to -1} and {1
to ∞}
Program:
import java.util.*;
class quadraticdemo
int a, b, c;
System.out.print("Enter a:");
a = s.nextInt();
System.out.print("Enter b:");
b = s.nextInt();
System.out.print("Enter c:");
c = s.nextInt();
D = b * b - 4 * a * c; if(D > 0)
r1 = ( - b + Math.sqrt(D))/(2*a);
r2 = (-b - Math.sqrt(D))/(2*a);
else if(D == 0)
r1 = (-b+Math.sqrt(D))/(2*a);
System.out.println("Root:"+r1);
else
OUTPUT:
Enter b:3
Enter c:1
Result:
Hence, java program that display the roots of a quadratic equation ax2+bx=0, Calculated the
discriminate D and basing on value of D, described the nature of root is completed successfully.
EXPPERIMENT 2
A) Binary Search
Aim: To write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
Description:
Binary Search mechanism is a searching mechanism used in a sorted array by repeatedly
dividing the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity to O(log N). Binary search is a search
mechanism used to find the position of a target value within a sorted array. It works by
repeatedly dividing the search interval in half until the target value is found or the interval is
empty. The search interval is halved by comparing the target element with the middle value of
the search space. To apply Binary Search algorithm:
The data structure must be sorted.
Access to any element of the data structure should take constant time.
Program:
import java.util.Scanner;
class binarysearchdemo
{
public static void main(String args[])
{
int n, i, num,first, last, middle;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements in sorted order:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
System.out.println("Enter the search value:");
num = s.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num )
first = middle + 1;
else if ( a[middle] == num )
{
System.out.println("number found");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println( " Number is not found");
}
}
Output:
Enter total number of elements: 5
Enter elements:
24689
Enter the search value: 8
number found
Result:
Hence, JAVA program to search for an element in a given list of elements using binary
search mechanism is executed successfully.
B) Bubble Sort
Aim: To write a JAVA program to sort for an element in a given list of elements using bubble
sort.
Description:
Bubble sort works on the repeatedly swapping of adjacent elements until they are not in
the intended order. It is not suitable for large data sets. The average and worst-case complexity of
Bubble sort is O(n2), where n is a number of items.
Return Value : The method returns the string after deleting the substring formed by the range
mentioned in the parameters.
Program:
class stringbufferdemo
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("Some Content");
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.deleteCharAt(0);
System.out.println(sb3);
}
}
Output:
World
Some Content
ello World
Result:
Hence, JAVA program using StringBuffer to delete, remove character is executed
successfully.
Experiments:3(a)
Class Mechanism
class A
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display();
}
}
Output:
10
20
2. no return type and with parameter-list:
class A
{
void display(int l,int b)
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display(10,20);
}
}
Output:
10
20
3. return type and without parameter-list
class A
{
int l=10,b=20;
int area()
{
return l*b;
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);
}
}
Output:
The area is:200
4. return type and with parameter-list:
class A
{
int area(int l,int b)
{
return l*b;
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area(10,20);
System.out.println(“The area is:”+r);
}
}
Output:
The area is:200
Result:
Method Overloading
Program:
class A
{
int l=10,b=20; int area()
{
return l*b;
}
int area(int l,int b)
{
return l*b;
}
}
class overmethoddemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);
int r2=a1.area(5,20);
System.out.println("The area is: "+r2);
}
}
Output:
The area is: 200
The area is: 100
Result:
Experiments:3(c)
Constructor
Program:
(i) A constructor with no parameters:
class A
{
int l,b;
A()
{ l=10; b=20;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(); int r=a1.area();
System.out.println("The area is: "+r);
}
}
Output:
The area is:200
Result:
Constructor Overloading
Program:
class A
{
int l,b;
A()
{ l=10; b=20;
}
A(int u,int v)
{
l=u; b=v;
}
int area()
{
return l*b;
}
}
class overconstructdemo
{
public static void main(String args[])
{
A a1=new A(); int r1=a1.area();
System.out.println("The area is: "+r1); A a2=new A(30,40);
int r2=a2.area(); System.out.println("The area is: "+r2);
}
}
Output:
The area is: 200 The area is: 1200
Result:
Description:
Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that we can create new classes that are built
upon existing classes. When we inherit from an existing class, we can reuse
methods and fields of the parent class. Moreover, we can add new methods and
fields in your current class also. The ’extends’ keyword is used for inheritance in
Java. Using the ‘extends’ keyword indicates you are derived from an existing
class.
In single inheritance, a sub-class is derived from only one super class. It inherits
the properties and behavior of a single-parent class
Program:
class A
{
A()
{
System.out.println("Inside A's Constructor");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}
}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}
}
Output:
Inside A's Constructor
Result:
Program:
class A
{
A()
{
System.out.println("Inside A's Constructor");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}
}
class C extends B
{
C()
{
System.out.println("Inside C's Constructor");
}
}
class multidemo
{
public static void main(String args[])
{
C c1=new C();
}
}
Output:
Inside A's Constructor
Result:
Abstract Class
Aim: To write a java program for abstract class to find areas of different shapes.
Description:
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery. Abstraction
lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
Result:
Hence, a java program for abstract class to find areas of different shapes is
executed successfully.
Experiment:5(a)
Description:
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
The most common use of the super keyword is to eliminate the confusion between
super classes and subclasses that have methods with the same name.
This scenario occurs when a derived class and base class have the same data
members. In that case, there is a possibility of ambiguity
This is used when we want to call the parent class method. So whenever a
parent and child class have the same-named methods then to resolve
ambiguity we use the super keyword.
The super keyword can also be used to access the parent class constructor.
One more important thing is that ‘super’ can call both parametric as well as
non-parametric constructors depending on the situation.
Program:
(i) Using super to call super class constructor (Without parameters)
class A
{
int l,b;
A()
{
l=10;
b=20;
}
}
class B extends A
{
int h;
B()
{
super();
h=30;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B();
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}
Output:
The vol. is:6000
(ii) Using super to call super class constructor (With parameters)
class A
{
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
}
class B extends A
{
int h;
B(int u,int v,int w)
{
super(u,v);
h=w;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B(30,20,30);
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}
Output:
The vol. is:18000
Result:
Thus, a JAVA program of given example for “super” keyword is executed
successfully.
Experiment:5(b)
Implementing Interface
Aim: To write a JAVA program to implement Interface.
Description:
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
Syntax:
interface <interface_name>{
Program:
(i) First form of interface implementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("B's method");
}
}
class C extends B
{
public void callme()
{
System.out.println("C's method");
}
}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.callme();
}
}
Output:
B's method
C's method
Result:
Thus, a JAVA program to implement Interface is completed successfully.
Experiment: 5(c)
Runtime Polymorphism
Aim: To write a JAVA program that implements Runtime polymorphism.
Description:
Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example,
SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.
Program:
class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
A ref;
ref=c1;
ref.display();
ref=b1;
ref.display();
ref=a1;
ref.display();
}
}
Output:
Inside C class
Inside B class
Inside A class
Result:
Thus, a JAVA program that implements Runtime polymorphism is executed
successfully.
Experiment 6(A)
Aim:
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be
caught and handled by the program. When an exception occurs within a method, it creates an object.
This object is called the exception object. It contains information about the exception, such as the name
and description of the exception and the state of the program when the exception occurred.
Error: An Error indicates a serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Java provides five keywords that are used to handle the exception. The following table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Program:
class trydemo
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}
Output:
java.lang.ArithmeticException: / by zero
class throwdemo
{
public static void main(String args[])
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.NullPointerException: demo
class finallydemo
{
public static void main(String args[])
{
try
{
int a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
class finallydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("This is inside finally block");
}
}
}
Output:
2
This is inside finally block
Result :
Hence , a JAVA program that describes exception handling mechanism is successfully completed
successfully.
Experiment 6(B)
Aim:
Description:
Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown from a particular
code section. A try block can have multiple catch blocks to handle multiple exceptions.
Syntax:
try {
// Protected code
// Catch block
// Catch block
// Catch block
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must
come before catch for Exception.
Flowchart of Multi-catch Block:
Program:
class multitrydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
int d[]={0,1};
System.out.println(d[10]);
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}
Output:
java.lang.ArrayIndexOutOfBoundsException:
Result:
Hence, to write a JAVA program Illustrating Multiple catch clauses is successfully executed.
Experiment 6(C)
Aim:
Description:
Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type RuntimeException.
Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
Built-in Exceptions in Java are categorized into two categories Checked Exceptions and Unchecked
Exceptions.
Checked Exceptions: The checked exceptions are handled by the programmer during writing
the code, they can be handled using the try-catch block. These exceptions are checked at
compile-time.
Unchecked Exceptions: The unchecked exceptions are not handled by the programmer. These
exceptions are thrown on run-time. Some of the unchecked exceptions are
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.
Types of Exceptions in Java Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
4.FileNotFoundException : This Exception is raised when a file is not accessible or does not open.
5. NumberFormatException : This exception is raised when a method could not convert a string into
a numeric format.
6. ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array has been accessed with
an illegal index. The index is either negative or greater than or equal to the size of the array.
7.ClassNotFoundException : This Exception is raised when we try to access a class whose definition
is not found.
Program:
{
try
{
int a = 10, b = 0; int c = a/b;
System.out.println (c);
}
catch(ArithmeticException e)
{
System.out.println (e);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
{
String a = "This is like chipping "; char c = a.charAt(24); System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println(e);
}
}
}
try
{
int num = Integer.parseInt ("akki") ; System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.NumberFormatException: For input string: "akki"
Result:
Hence, to write a JAVA program for creation of Java Built-in Exceptions is executed successfully.
Experiment 6(D)
AIM:
Description:
In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception. Basically, Java
custom exceptions are used to customize the exception according to user need.
Using the custom exception, we can have your own exception and message. Here, we have passed a
string to the constructor of superclass i.e. Exception class that can be obtained using getMessage()
method on the object we have created.
Custom exceptions provide several benefits over using only the predefined exceptions.
Improve code readability: Custom exceptions can convey specific error conditions that are relevant to
the application domain. This improves the expressiveness and readability of the code.
Enhance error reporting: Custom exceptions can contain extra details that are unique to the error,
such as error codes, pertinent information, and contextual information. Better error reporting and
debugging are the results of this.
Separate business logic from exception handling: Developers may do just that by generating custom
exceptions, separating the application's business logic from the code that handles exceptions. The result
is cleaner, easier-to-maintain code.
Handle special cases: Using custom exceptions, developers can manage error scenarios unique to a
certain application and not covered by the standard exceptions.
Program:
Result:
Hence, to write a JAVA program for creation of User Defined Exception is completed successfully.
Experiment 7(a):
Aim:
Threads can be used to perform complicated tasks in the background without interrupting
the main program.
It can be created by extending the Thread class and overriding its run() method
We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.
Program:
Output:
good morninghello
good morninggood
morningwelcome
hello
good morning
good morning
hello
good morning
welcome good
morninghello
good morninggood
morningwelcome
hello
good morninghello
welcome hello
welcome
hello
hello
welcomehello
welcome
welcome
welcome
welcome
(ii) Creating multiple threads using Runnable interface
class A implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
Thread.sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B implements Runnable
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
Thread.sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C implements Runnable
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class runnabledemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
Thread t1=new Thread(a1);
Thread t2=new Thread(b1);
Thread t3=new Thread(c1);
t1.start();
t2.start();
t3.start();
}
}
Output:
good morning
good morning
hello
good morning
welcome good
morning hello
good morning good
morning welcome
hello
goodmorning
goodmorning
hello
good morning
welcome
good morning
hello
welcome hello
hello
welcome hello
welcome hello
hello
welcome
welcome
welcome
welcome
Result:
Hence, a JAVA program that creates threads by extending Thread class. First thread
display “Good Morning “every 1 sec, the second thread displays “Hello “every 2
seconds and the third display “Welcome” every 3 seconds, (Repeat the same by
implementing Runnable) is executed successfully.
Experiment 7(B):
is Alive and join ()
Aim:
To write a JAVA program illustrating is Alive and join ()
Description:
Thread class in java provides numerous methods that are very essential in order to
understand the working of threads as the thread stages are triggered by them. Java multi-
threading provides two ways to find with the help of isAlive() and join() method.
One thread gets to know when another thread has ended. Let us do depict stages of the
lifecycle of the thread via the below image which helps us to connect dots to understand
these methods’ workings.
isAlive() method works internally very closely in parallel to the lifecycle stages of a
thread. It tests if this thread is alive. A thread is alive if it has been started and has not yet
died. There is a transitional period from when a thread is running to when a thread is not
running.
After the run() method returns, there is a short period of time before the thread stops.
If we want to know if the start method of the thread class has been called or if the thread
has been terminated, we must use the isAlive() method. This method is used to find out if
a thread has actually been started and has yet not terminated.
Program:
class A extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class isalivedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
a1.start();
b1.start();
c1.start();
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
try
{
a1.join();
b1.join();
c1.join();
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(a1.isAlive());
System.out.println(b1.isAlive());
System.out.println(c1.isAlive());
}
}
Output:
true good morning
true hello
true welcome
good morning hello
good morning hello
hello welcome
good morning hello
welcome welcome
good morning hello
hello hello
good morning welcome
good morning welcome
welcome welcome
hello welcome
good morning false
good morning false
hello false
good morning
welcome
Result:
Hence, a JAVA program illustrating is Alive and join () is successfully completed.
Experiment 7(C):
Daemon Threads
Aim:
To write a JAVA Program illustrating Daemon Threads.
Description:
In Java, daemon threads are low-priority threads that run in the background to perform
tasks such as garbage collection or provide services to user threads. The life of a daemon
thread depends on the mercy of user threads, meaning that when all user threads finish
their execution, the Java Virtual Machine (JVM) automatically terminates the daemon
thread.
To put it simply, daemon threads serve user threads by handling background tasks and
have no role other than supporting the main execution.
Some examples of daemon threads in Java include garbage collection (gc) and finalizer.
These threads work silently in the background, performing tasks that support the main
execution without interfering with the user’s operations.
Program:
class A extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
System.out.println("daemon thread work");
else
System.out.println("user thread work");
}
}
class daemondemo
{
public static void main(String[] args)
{
A a1=new A();
A a2=new A();
A a3=new A();
a1.setDaemon(true);
a1.start();
a2.start();
a3.start();
}
}
Output:
daemon thread work
user thread work
user thread work
Result:
Hence, a JAVA Program illustrating Daemon Threads is successfully completed.
Experiment 7(D)
Aim:
Description:
Access: The producer and consumer cannot access the buffer at the same time.
Waiting: If the buffer is empty, the consumer must wait for the producer to add an
item. If the buffer is full, the producer must wait for the consumer to remove an item.
Program:
class A
{
int n;
boolean b=false;
synchronized int get()
{
if(!b)
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n);
b=false;
notify();
return n;
}
synchronized void put(int n)
{
if(b) try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
this.n=n;
b=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
A a1;
Thread t1;
producer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}
class consumer implements Runnable
{
A a1;
Thread t1;
consumer(A a1)
{
this.a1=a1;
t1=new Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class interdemo
{
public static void main(String args[])
{
A a1=new A();
producer p1=new producer(a1);
consumer c1=new consumer(a1);
}
}
Output:
Put:1
Got:1
Put:2
Got:2
Put:3
Got:3
Put:4
Got:4
Put:5
Got:5
Put:6
Got:6
Put:7
Got:7
Put:8
Got:8
Put:9
Got:9
Put:10
Got:10
Result:
AIM: To create a Java program that imports and utilizes user-defined packages for organized
code structure.
Description:
A package is a directory (or folder) that organizes related classes, interfaces, and subpackages
in Java.
Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
(i) Creating a package:
To create a package, you choose a name for the package and put a package statement with
that name at the top of every source file that contains the types (classes, interfaces,
enumerations, and annotation types) that you want to include in the package.
The package statement (for example, package graphics;) must be the first line in the source
file. There can be only one package statement in each source file, and it applies to all types in
the file.
Steps:
1. First declare the name of the package using package keyword
Example: package mypack;
2. Type the following SOURCE-CODE under this package statement. In package : class
,data, methods all are public
package mypack;
public class box
{
public int l=10,b=20;
public void display()
{
System.out.println(l);
System.out.println(b);
}
}
Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.
Steps:
1. packages can be accessed by using the import statement
General form: import pack1[.pack2].(classname/*);
Example: import java.io.*;
Here pack1 is name of top level package and pack2 is name of sub package
2. Type the following SOURCE-CODE under the current working directory and save the
SOURCE-CODE with a file name.java.
import mypack.box;
class packagedemo
{
public static void main(String args[])
{
box b1=new box();
b1.display();
}
}
3. Now compile the above SOURCE-CODE in the current working directory
javac packagedemo.java
4. Execute the above SOURCE-CODE in current working directory
java packagedemo
OUT-PUT:
10
20
Result:
The program successfully imported a user-defined package and displayed the message
b) Without writing any code, build a GUI that display text in label and image in an
image view.
AIM:
To create a JavaFX GUI that displays text in a label and an image in an image view.
Description:
A simple graphical user interface (GUI) using JavaFX, a powerful framework for creating
desktop applications in Java. The main goal is to display a welcoming message in a label and
show an image below it, providing a basic understanding of GUI components and layout
management in JavaFX.
Source Code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
// Create a Label
Label label = new Label("Welcome to JavaFX!");
// Create an ImageView
Image image = new Image("image.png"); // Adjust the path if necessary
ImageView imageView = new ImageView(image);
Welcome to JavaFX!
[ Image Here ]
Result:
The program successfully displayed a welcome message in a label and an image in the image
view.
c) Build a tip Calculator app using several javafx components and learn how to
respond to user interactions with the GUI.
AIM:
To create a JavaFX tip calculator app that responds to user interactions for calculating tip
amounts based on bill and tip percentage inputs.
Description:
The Tip Calculator application is designed to provide users with a straightforward tool for
calculating the tip amount based on a specified bill and tip percentage. Built using JavaFX,
this application utilizes a graphical user interface (GUI) that enhances user experience
through interactive components.
SOURCE CODE:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
@Override
public void start(Stage primaryStage) {
// Create UI components
Label billLabel = new Label("Bill Amount:");
TextField billField = new TextField();
Output:
User Inputs:
o
Bill Amount: 50
o
Tip Percentage: 15
Tip Amount: $7.50
Result:
The Tip Calculator app successfully calculates and displays the tip amount based on user
input for the bill and tip percentage.
Exercise-9
A) Write a java program that connects to a database using JDBC program
AIM: To Write a java program that connects to a database using JDBC program
DESCRIPTION:
This Java program demonstrates how to establish a connection to a PostgreSQL database
using JDBC (Java Database Connectivity). The code imports essential packages like
java.sql.Connection and java.sql.DriverManager, which are part of the JDBC API. These
classes enable the program to interact with a database.
1. Database Connectivity: In this program, the main objective is to connect to a
PostgreSQL database. The Connection object is declared, which represents the active
connection to the database.
2. Loading the PostgreSQL Driver: The line Class.forName("org.postgresql.Driver")
loads the PostgreSQL JDBC driver dynamically, which is required to communicate
with the database. This ensures the driver class is registered before attempting the
connection.
3. Establishing the Connection: The DriverManager.getConnection() method is
invoked with three arguments: the JDBC URL
(jdbc:postgresql://localhost:5432/testdb), the username (postgres), and the password
(123). This method tries to connect to a PostgreSQL database named testdb running
locally on port 5432.
4. Error Handling: A try-catch block handles any exceptions that may occur during the
connection process. If an error occurs, the exception is printed, and the program exits.
5. Success Confirmation: If the connection is successful, the message "Opened
database successfully" is printed to the console, confirming the connection.
Source code:
import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC
{
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb",
"postgres", "123");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
OUTPUT:
Opened database successfully
RESULT:
Java program that connects to a database using JDBC program has been done successfully.
B) Write a java program to connect to database using JDBC & insert values into table
AIM: To write a java program to connect to database using JDBC & insert values into table
DESCRIPTION:
This Java program demonstrates how to insert data into an Oracle database using JDBC
(Java Database Connectivity). The program defines four string variables (id, pwd, fullname,
email) that hold the data to be inserted into a database table.
1. Database Driver Setup: The Class.forName("oracle.jdbc.driver.OracleDriver")
statement loads the Oracle JDBC driver, which is necessary for the Java application to
interact with the Oracle database. This ensures the driver is available before
establishing the connection.
2. Establishing the Connection: The DriverManager.getConnection() method is used to
establish a connection to the Oracle database. The method takes three arguments: the
JDBC URL (in this case, jdbc:oracle:thin:@localhost:1521:orcl), the username
(login1), and the password (pwd1). These details must match the database server
settings.
3. Creating and Executing SQL Statement: A Statement object is created using
con.createStatement(). Then, an SQL INSERT query is constructed, which includes
the data values defined earlier. The query is dynamically generated using the values
for id, pwd, fullname, and email.
4. Executing the Insert: The stmt.executeUpdate() method executes the INSERT query.
If the query is successful (i.e., data is inserted), it returns a value greater than 0, and
the program prints "Successfully Inserted". Otherwise, it prints "Insert Failed".
5. Error Handling and Closing Resources: A try-catch block handles any exceptions,
such as driver issues or connection failures. The connection is closed once the
operation is complete to release resources.
SOURCE CODE:
import java.sql.*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "MRCET";
String email = "[email protected]";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Inserting data in database
String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
Successfully Inserted
After successful execution, the userid table in the Oracle database will contain a new
row with the following values:
RESULT:
Java program to connect to database using JDBC & insert values into table has been done
successfully.
C) Write a java program to connect to a database using JDBC and delete values from
table.
AIM: To write a java program to connect to a database using JDBC and delete values from
table.
DESCRIPTION:
This Java program demonstrates how to delete data from an Oracle database using
JDBC (Java Database Connectivity). The program focuses on deleting a specific user record
from the database based on matching id and pwd (password) fields.
Key Components of the Code:
1. Database Driver Setup: The line Class.forName("oracle.jdbc.driver.OracleDriver")
dynamically loads the Oracle JDBC driver, which is essential for enabling
communication between the Java program and the Oracle database.
2. Establishing the Connection: The program establishes a connection to the Oracle
database using the DriverManager.getConnection() method. It connects to the Oracle
instance running on localhost:1521, database identifier orcl, with the username login1
and password pwd1. These credentials must be correct for the connection to succeed.
3. Creating and Executing SQL Statement: A Statement object is created using
con.createStatement(), and the DELETE query is dynamically built. The query
attempts to delete a record from the userid table where both the id and pwd fields
match the values id2 and pwd2, respectively.
4. Executing the Deletion: The stmt.executeUpdate(q1) method executes the DELETE
query. If the query deletes a record, the value of x will be greater than 0, and the
program will print "One User Successfully Deleted". If no records match the criteria,
the message "ERROR OCCURED :(" is printed.
5. Error Handling and Closing Resources: The program uses a try-catch block to
handle any exceptions, such as invalid credentials or SQL syntax errors. After
execution, the connection is closed to free resources.
SOURCE CODE:
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" +
id + "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
ERROR OCCURED :(
RESULT:
Java program to connect to a database using JDBC and delete values from table has been
done successfully.