Ashu
Ashu
(CSIT751)
Practical File
1
S. no. Topics Page no Date Signature
WRITE A PROGRAM IN JAVA TO CREATE AN OBJECT AND MODIFY ITS ATTRIBUTES IN 23/08/24
4 MAIN CLASS 14
WRITE A PROGRAM IN JAVA TO CREATE MULTIPLE OBJECTS OF ONE CLASS AND 23/08/24
5 CHANGE THE VALUE OF ONLY ONE OBJECT 16
WRITE A PROGRAM IN JAVA CREATING A STATIC AND A PUBLIC METHOD TO FIND 23/08/24
7 OUT THE DIFFERENCE. 20
WRITE A PROGRAM IN JAVA TO ACCESS PRIVATE DATA USING SETTER AND GETTER 28/08/24
8 FUNCTION (ENCAPSULATION) 22
WRITE A PROGRAM IN JAVA USING INHERITANCE AND "THIS" FUNCTION AND 29/08/24
10 CONSTRUCTOR 28
19 WRITE A PROGRAM IN JAVA TO SHOW THE FILE NOT FOUND EXCEPTION 56 06/09/24
2
WRITE A PROGRAM IN JAVA USING TRY CATCH BLOCK TO SHOW THE ARITHMETIC 06/09/24
22 EXCEPTION 62
WRITE A PROGRAM IN JAVA USING THE TRY CATCH BLOCK TO SHOW THE 11/09/24
23 ARITHMETIC EXCEPTION 64
WRITE A PROGRAM IN JAVA USING TRY, CATCH AND FINALLY IN WHICH THE CATCH 18/09/24
28 BLOCK DOES NOT EXECUTE. 74
WRITE A PROGRAM IN JAVA IN WHICH TRY, CATCH AND FINALLY BLOCKS ARE ALL 19/09/24
29 EXECUTED. 77
30 WRITE A PROGRAM IN JAVA USING MULTIPLE EXCEPTIONS IN THE CATCH BLOCK 80 20/09/24
WRITE A PROGRAM IN JAVA USING MULTIPLE EXCEPTIONS AND THE ARRAY INDEX 20/09/24
31 OUT OF BOUND EXCEPTION OCCURS. 82
WRITE A PROGRAM IN JAVA WITH MULTIPLE CATCH STATEMENTS AND ARITHMETIC 20/09/24
32 EXCEPTION IS OCCURRED. 85
WRITE A PROGRAM IN JAVA WITH MULTIPLE CATCH STATEMENTS AND NONE OF 20/09/24
33 THEM MATCH SO THE GENERAL EXCEPTION IS CAUGHT 87
WRITE A PROGRAM IN JAVA TO READ A CHARACTER AND PRINT IT USING A DO- 20/09/24
34 WHILE LOOP 89
35 WRITE A PROGRAM IN JAVA TO READ A LINE AND PRINT IT USING DO-WHILE LOOP 93 20/09/24
WRITE A PROGRAM IN JAVA TO READ LINES AND PRINT IT ALL TOGETHER USING FOR 20/09/24
36 LOOP 95
WRITE A PROGRAM IN JAVA TO READ LINES AND PRINT IT ALL TOGETHER USING FOR 20/09/24
LOOP WHICH GIVES ONLY SOME OF THE OUTPUT AND STOPS WITHOUT USING THE
37 STOP COMMAND AFTER 10 LINES 96
WRITE A PROGRAM IN JAVA TO READ LINES AND PRINT IT ALL TOGETHER USING FOR 20/09/24
38 LOOP WHICH GIVES NULL POINTER EXCEPTION 97
40 WRITE A PROGRAM IN JAVA USING NESTED TRY CATCH BLOCK 100 20/09/24
41 WRITE A PROGRAM IN JAVA TO FIND OUT THE LENGTH OF STRING 102 25/09/24
3
42 WRITE A PROGRAM IN JAVA TO COMPARE TWO STRINGS AND PRINT THE OUTPUT 103 25/09/24
44 WRITE A PROGRAM IN JAVA TO FIND OUT WHETHER THE STRING IS EMPTY OR NOT 105 26/09/24
45 WRITE A PROGRAM IN JAVA USING THE TRIM FUNCTION OF STRINGS 106 26/09/24
49 WRITE A PROGRAM IN JAVA USING THE COMMAND LINE ARGUMENT 111 27/09/24
54 WRITE A PROGRAM IN JAVA USING GET CHARS FEATURE OF STRING. 119 02/10/24
56 WRITE A PROGRAM IN JAVA TO ADD TWO NUMBERS INPUTTED BY THE USER 122 02/10/24
58 WRITE A PROGRAM IN JAVA TO PRINT THE GRADE VALUE USING IF CONDITION 124 03/10/24
WRITE A PROGRAM IN JAVA TO SORT AN ARRAY ENTERED BY USER USING BUBBLE 04/10/24
60 SORT METHOD. 126
61 WRITE A PROGRAM IN JAVA TO REVERSE A NUMBER USING BUFFER READER 128 04/10/24
62 WRITE A PROGRAM IN JAVA USING THE STRING BUFFER AND CONCATENATE 130 04/10/24
WRITE A PROGRAM IN JAVA USING COMMAND LINE IN WHICH TWO STRINGS ARE 10/10/24
64 PASSED AND THREE STRINGS ARE PRINTED 133
4
WRITE A PROGRAM IN JAVA SCANNING INTEGER AND STRING VALUE WITH SAME 11/10/24
66 OBJECT NAME. 138
68 WRITE A PROGRAM IN JAVA ADDING TWO NUMBERS IN COMMAND LINE 142 11/10/24
73 WRITE A PROGRAM IN JAVA USING THE DOUBLE RUN OF THREAD CONCEPT 147 17/10/24
74 WRITE A PROGRAM IN JAVA USING THE DOUBLE START OF THREAD CONCEPT 149 23/10/24
WRITE A PROGRAM IN JAVA USING JOIN METHODS TO WAIT FOR THREADS TO 24/10/24
75 FINISH 150
WRITE A PROGRAM IN JAVA PRINTING THE FIBONACCI SERIES USING COMMAND 24/10/24
76 LINE 153
77 WRITE A PROGRAM IN JAVA FOR MULTIPLE COMMAND LINE ARGUMENTS. 155 25/10/24
82 WRITE A PROGRAM IN JAVA TO FIND THE HYPOTENUSE USING STATIC IMPORT 164 31/10/24
83 WRITE A PROGRAM IN JAVA TO COPY FILES USING COMMAND LINE ARGUMENT 165 31/10/24
WRITE A PROGRAM IN JAVA TO INSERT ROW IN MYSQL DATABASE USING PREPARED 03/11/24
89 STATEMENT 174
5
WRITE A PROGRAM IN JAVA TO INSERT ROW IN MYSQL DATABASE USING PREPARED 06/11/24
90 STATEMENT TAKING THE USER INPUT 175
WRITE A PROGRAM IN JAVA TO INSERT MANY ROWS IN MYSQL DATABASE USING 06/11/24
91 PREPARED STATEMENT TAKING THE USER INPUT 176
92 WRITE A PROGRAM IN JDBC TO ESTABLISH A CONNECTION WITH THE DATABASE. 182 06/11/24
96 WRITE A PROGRAM IN JDBC TO INSERT 10 RECORDS IN THE ABOVE TABLE 191 06/11/24
97 WRITE A PROGRAM IN JDBC TO DISPLAY ALL THE RECORDS OF THE ABOVE TABLE 194 06/11/24
98 WRITE A PROGRAM IN JDBC TO CREATE THE TABLE USING PREPARED STATEMENT 196 06/11/24
WRITE A PROGRAM USING PREPARED STATEMENT TO DISPLAY THE RECORDS FROM 06/11/24
202
100 THE ABOVE TABLE
WRITE A PROGRAM TO INSERT 10 RECORDS USING INFINITE LOOP AND DISPLAY THE 07/11/24
205
101 RECORDS IN THE SAME PROGRAM
WRITE A PROGRAM TO SCROLL THE TABLE USING SCROLLABLE RESULTSET USING 07/11/24
209
102 FIRST, LAST, PREVIOUS, RELATIVE (BOTH POSITIVE AND NEGATIVE) AND ABSOLUTE
WRITE A PROGRAM TO UPDATE THE SALARY COLUMN OF EMPLOYEE TABLE WHERE 07/11/24
212
103 IT IS INCREMENTED BY 50000
WRITE A PROGRAM TO CREATE A STORED PROCEDURE THAT INSERTS THE BIRTHDAY 07/11/24
OF AN EMPLOYEE THROUGH THEIR ID WHERE THEY WILL DISPLAY BIRTHDAY IN THE 214
104 BIRTHDAY TABLE AND ID IN THE EMPLOYEE TABLE
105 WRITE A PROGRAM TO ADD 2 NUMBERS USING A STORED PROCEDURE 217 07/11/24
107 WRITE A PROGRAM IN JAVA FOR GRAPHIC DEMO IN APPLET 223 08/11/24
6
110 WRITE A PROGRAM IN JAVA FOR CHOOSE BOX DEMO 227 14/11/24
111 WRITE A PROGRAM IN JAVA FOR DISPLAY MOUSE EVENT 231 14/11/24
114 WRITE A PROGRAM IN JAVA FOR VIRTUAL KEYBOARD AND EVENT 244 14/11/24
115 WRITE A PROGRAM IN JAVA FOR GRAPHIC MOUSE MOTION ADAPTER 248 14/11/24
116 WRITE A PROGRAM IN JAVA FOR GRAPHIC KEYBOARD ADAPTER 249 18/11/24
117 WRITE A PROGRAM IN JAVA FOR BOARDER LAYOUT(N,E,W,S,C)USING JBUTTON 271 18/11/24
118 WRITE A PROGRAM IN JAVA FOR GRIDLAYOUT(1-9) USING JBUTTON 276 18/11/24
120 WRITE A PROGRAM IN JAVA TO DEMONSTRATE THE USE OF TEXTFIELD IN JAVA 283 18/11/24
121 WRITE A PROGRAM IN JAVA FOR A SIMPLE SWING DEMO IN JAVA 287 20/11/24
122 WRITE A PROGRAM IN JAVA TO FIND IF 3 SUM EXISTS IN A GIVEN ARRAY 290 20/11/24
123 WRITE A PROGRAM IN JAVA TO DEMONSTRATE STRING FUNCTIONS IN JAVA 292 20/11/24
125 WRITE A PROGRAM IN JAVA FOR BINARY TO DECIMAL CONVERSION IN JAVA 297 20/11/24
127 WRITE A PROGRAM IN JAVA TO DEMONSTRATE THE USE OF STRINGBUFFER 306 20/11/24
128 WRITE A PROGRAM IN JAVA TO CREATE A SIMPLE CALCULATOR USING SWING 310 20/11/24
7
Practical 1 (14/08/2024)
8
Output:
9
Practical 2 (15/08/2024)
10
Output:
11
Practical 3 (16/08/2024)
12
Output:
13
Practical 4 (16/08/2024)
14
Output:
15
Practical 5 (16/08/2024)
16
Output:
17
Practical 6 (21/08/2024)
18
Output:
19
Practical 7 (22/08/2024)
20
Output:
21
Practical 8 (23/08/2024)
22
public int getEmpAge()
{
return empAge;
}
public void setEmpAge(int empAge)
{
this.empAge=empAge;
}
public String getEmpName()
{
return empName;
}
public void setEmpName(String empName)
{
this.empName=empName;
}
}
23
Output:
24
Practical 9 (23/08/2024)
25
Output:
26
Practical 10 (28/08/2024)
public Vehicle (String make, String color, int year, String model)
{
this.make = make;
this.color =color;
this.year = year;
this.model = model;
}
27
class Car extends Vehicle
{
private String bodyStyle;
public Car(String make, String color, int year, String model, String bodyStyle)
{
super(make, color, year, model);
this.bodyStyle = bodyStyle;
}
public void carDetails()
{
printDetails();
System.out.println("Body Style: " + bodyStyle);
}
}
class Inherit
{
public static void main(String[] args)
{
Car elantraSedan = new Car("Hyundai", "Red", 2019, "Elantra", "Sedan");
elantraSedan.carDetails();
}
}
28
Output:
29
Practical 11 (29/09/2024)
30
Output:
31
Practical 12 (30/09/2024)
32
Output:
33
Practical 13 (30/09/2024)
34
}
}
35
Output:
36
Practical 14 (30/09/2024)
37
Derived(int x)
{
super();
System.out.println("Derived class parameterized constructor called");
}
}
class MainProgram
{
// main
public static void main(String args[])
{
// initializes the instance of example class
Derived my_example = new Derived();
}
}
38
Output:
39
Practical 15 (04/09/2024)
40
Output:
41
Practical 16 (04/09/2024)
42
public static void main(String[] args)
{
Parent a;
a = new subclass1();
a.print();
a = new subclass2();
a.print();
}
}
43
Output:
44
Practical 17 (04/09/2024)
45
{
int temp, r, re=0;
temp = n;
int d= String.valueOf(n).length();
while(temp !=0)
{
r = temp %10;
re += Math.pow(r,d);
temp /=10;
}
if(re == n)
{
System.out.print (n + ", ");
c++;
}
}
System.out.println (".");
if(c == 0)
System.out.println ("None");
}
46
Scanner in = new Scanner (System.in);
System.out.println ("Enter 1 to check a particular number for
Armstrong.");
System.out.println("Enter 2 to check for Armstrong numbers within a
range.");
System.out.println("Enter 3 to exit.");
i = in.nextInt();
if (i == 1)
{
System.out.print ("Enter number to be checked:");
int d = in.nextInt();
ob.num(d);
}
else
if (i == 2)
{
System.out.print ("Enter starting number of range:");
int e = in.nextInt();
System.out.print ("Enter end number of range");
int f = in.nextInt();
ob.series(e,f);
}
else
break;
}
}
}
47
Output:
48
Practical 18 (05/09/2024)
49
Output:
50
Program Code (Fixing the error):
public class NullPointerException
{
public static void main(String args[])
{
String myStr = "Ananya";
System.out.println(myStr.length());
}
}
51
Output:
52
Practical 19 (06/09/2024)
53
Output:
Note: This Exception can be fixed after saving this file on your pc.
54
Practical 20 (06/09/2024)
55
Output:
56
Program Code (Fixing the error):
class AirthmeticException
{
public static void main(String args[])
{
int num1=40;
int num2=20;
//divide both numbers and print the result
int result=num1/num2;
System.out.println(result);
}
}
57
Output:
58
Practical 21 (06/09/2024)
59
Output:
60
Practical 22 (06/09/2024)
Write a program in java using try catch block to show the arithmetic
Exception
Program Code:
class UsingTryCatch
{
public static void main(String args[])
{
try
{
//define two numbers
int num1 = 100, num2 = 0;
int result = num1 / num2; // divide by zero
//print the result
System.out.println("Result = " + result);
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException:Division by Zero");
}
}
}
61
Output:
62
Practical 23 (11/09/2024)
Write a program in java using the try catch block to show the
arithmetic exception
Program Code:
class TryCatch
{
public static void main(String args[])
{
int val1, val2;
try
{
System.out.println("Try Block:: Start");
val1 = 0;
val2 = 25/ val1;
System.out.println(val2);
System.out.println("Try Block:: End");
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException :: Divide by Zero!!");
}
System.out.println("Outside try-catch:: Rest of the code.");
}
}
63
Output:
64
Practical 24 (13/09/2024)
65
Output:
66
Practical 25 (13/09/2024)
67
Output:
68
Practical 26 (13/09/2024)
69
Output:
70
Practical 27 (13/09/2024)
71
Output:
72
Practical 28 (18/09/2024)
Write a program in java using try, catch and finally in which the
catch block does not execute.
Program Code:
import java.io.*;
class FinallyDemo {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
}
// Always execute
finally {
System.out.println(
"finally : i execute always.");
}
}
}
73
Output:
74
Practical 29 (19/09/2024)
Write a program in java in which try, catch and finally blocks are all
executed.
Program Code:
import java.io.*;
class FinallyDemo1 {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
75
Output:
76
Practical 30 (20/09/2024)
77
Output:
78
Practical 31(20/09/2024)
79
Output:
80
Practical 32 (20/09/2024)
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
81
Output:
82
Practical 33 (20/09/2024)
Write a program in java with multiple catch statements and none of
them match so the general exception is caught.
Program Code:
public class MultipleCatch4 {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
83
Output:
84
Practical 34 (20/09/2024)
85
Output:
86
Practical 35 (20/09/2024)
Write a program in java to read a line and print it using do-while loop
Program Code:
import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}
87
Output:
88
Practical 36 (20/09/2024)
Write a program in java to read lines and print it all together using for
loop
Program Code:
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
}
89
Output:
90
Practical 37 (20/09/2024)
Write a program in java to read lines and print it all together using for
loop which gives only some of the output and stops without using
the stop command after 10 lines
Program Code:
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<10; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<5; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
}
91
Output:
92
Practical 38 (20/09/2024)
Write a program in java to read lines and print it all together using for
loop which gives null pointer exception
Program Code:
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<3; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<5; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
}
}
93
}
Output:
94
Practical 39 (20/09/2024)
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Output:
95
Practical 40 (20/09/2024)
96
catch(ArithmeticException e3){
System.out.println("Main Block Arithmetic Exception");
}
catch(ArrayIndexOutOfBoundsException e4){
System.out.println("Main Block ArrayIndexOutOfBoundsException");
}
catch(Exception e5){
System.out.println("Main Block General Exception");
}
System.out.println("Code after Nested Try Block");
}
}
97
Output:
98
Practical 41 (25/09/2024)
99
Practical 42 (25/09/2024)
Write a program in java to compare two strings and print the output
Program Code:
public class StringCompare
{
public static void main(String args[])
{
String s1="Hello";
String s2="Hello";
String s3="Hello ";
String s4="Hello World";
System.out.println("Returns 1 if comparison is false. Returns 0 if comparison
is true");
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}
}
100
Output:
101
Practical 43 (25/09/2024)
102
Output:
103
Practical 44 (26/09/2024)
Write a program in java to find out whether the string is empty or not
Program Code:
public class StringIsEmpty
{
public static void main(String args[])
{
String s1 ="";
String s2 ="Hello";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}
}
104
Output:
105
Practical 45 (26/09/2024)
106
Output:
107
Practical 46 (26/09/2024)
108
Output:
109
Practical 47 (27/09/2024)
110
Output:
111
Practical 48 (27/09/2024)
112
scan.close();
scan2.close();
113
Output:
114
Practical 49 (27/09/2024)
115
Output:
116
Practical 50 (27/09/2024)
System.out.println();
}
public static void main(String args[])
{
// Notice how an array must be created to
// hold the arguments.
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = { };
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
117
Output:
118
Practical 51 (27/09/2024)
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
119
Output:
120
Practical 52 (27/09/2024)
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
121
Output:
122
Practical 53 (27/09/2024)
123
Output:
124
Practical 54 (2/10/2024)
}
}
125
Output:
126
Practical 55 (2/10/2024)
System.out.println (s1 + " equals Ignore Case " +s4+ "->" + s1.equalsIgnoreCase(s4));
}
}
127
Output:
128
Practical 56 (2/10/2024)
}
}
129
Output:
130
Practical 57 (3/10/2024)
131
Output:
132
Practical 58 (3/10/2024)
133
Output:
134
Practical 59 (4/10/2024)
135
Output:
136
Practical 60 (4/10/2024)
137
arr[i+1] = temp;
}
}
}
for (int i=0; i<n; i++)
{
System.out.print(arr[i] +" ");
}
}
}
138
Output:
139
Practical 61 (4/10/2024)
140
}
}
Output:
141
Practical 62 (4/10/2024)
142
StrBufConcat(str2);
System.out.println("The final String is - " + str2);
143
Output:
144
Practical 63 (9/10/2024)
}
}
145
Output:
146
Practical 64 (10/10/2024)
147
Output:
148
Practical 65 (11/10/2024)
149
Output:
150
Practical 66 (11/10/2024)
Write a program in java scanning integer and string value with same
object name.
Program Code:
import java.util.*;
151
Output:
152
Practical 67 (11/10/2024)
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
class ExtendThread {
153
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
154
Output:
155
Practical 68 (11/10/2024)
156
Output:
157
Practical 69 (11/10/2024)
158
Output:
159
Practical 70 (16/10/2024)
class ThreadRun {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
}
}
160
Output:
161
Practical 71 (17/10/2024)
162
Output:
163
Practical 72 (17/10/2024)
164
Output:
165
Practical 73 (11/10/2024)
class DoubleRun {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
t.run();
}
}
166
Output:
167
Practical 74 (23/11/2024)
class DoubleStart {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
t.start();
}
}
168
Output:
169
Fixing the code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
class DoubleStart {
public static void main(String[] args)
{
MyThread t = new MyThread();
MyThread t1 = new MyThread();
t.start();
t1.start();
}
}
Output:
170
Practical 75 (24/10/2024)
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
171
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
172
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
173
Output:
174
Practical 76 (25/10/2024)
175
Output:
176
Practical 77 (25/10/2024)
for(String s : args){
System.out.println(s);
}
}
}
177
Output:
178
Practical 78 (25/10/2024)
179
msg = s;
t = new Thread(this);
t.start();
}
180
Output:
181
Fixing the code:
// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
182
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
class Synch1 {
public static void main(String args[]) {
183
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
184
Output:
185
Practical 79 (30/10/2024)
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
186
Output:
187
Practical 80 (30/10/2024)
188
Output:
189
Practical 81 (30/10/2024)
190
Output:
191
Practical 82 (31/10/2024)
192
Output:
193
Practical 83 (31/10/2024)
194
try {
if(fin != null) fin.close();
} catch(IOException e2) {
System.out.println("Error Closing Input File");
}
try {
if(fout != null) fout.close();
} catch(IOException e2) {
System.out.println("Error Closing Output File");
}
}
}
}
195
My Original File
196
197
Practical 84 (1/11/2024)
198
Output:
199
Practical 85 (1/11/2024)
200
Output:
201
Practical 86 (1/11/2024)
202
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
}
// Close the file.
try {
fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
203
Output:
204
Practical 87 (1/11/2024)
try {
String url1 = "jdbc:mysql://localhost/Ananya"; //should be changed depending your pc and
files
String user = "root";
String password = "mylife5@"; //should be the password of your MySQL
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
205
Output:
206
Practical 88 (3/11/2024)
if (conn != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}
Statement stmt=conn.createStatement();
String sql = "INSERT INTO Registrationnew " +
"VALUES (200, 'Adrit', 'Adi', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registrationnew " +
"VALUES (201, 'Arjun', 'Bash', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registrationnew " +
"VALUES (202, 'Bekham', 'David', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registrationnew " +
"VALUES(203, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
207
System.out.println("Inserted records into the table...");
conn.close();
}
catch(Exception e){ System.out.println(e);}
}
}
208
Output:
Command Prompt
209
Practical 89 (3/11/2024)
if (conn != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}
int i=pstmt.executeUpdate();
System.out.println(i+" records inserted");
conn.close();
210
}catch(Exception e){ System.out.println(e);}
}
}
211
Output
Command Prompt:
212
Practical 90 (6/11/2024)
if (conn != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}
String sql="insert into mytable1(Name,City) values(?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your name:");
String Name=br.readLine();
System.out.println("Enter city:");
String City=br.readLine();
pstmt.setString(1,Name);
pstmt.setString(2,City);
pstmt.executeUpdate();
System.out.println("Inserted...");
213
conn.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Output:
Command Prompt
214
Practical 91 (6/11/2024)
if (conn != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}
String sql="insert into mytable1(Name,City) values(?,?)";
PreparedStatement pstmt=conn.prepareStatement(sql);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do{
System.out.println("Enter your name:");
String Name=br.readLine();
System.out.println("Enter city:");
String City=br.readLine();
pstmt.setString(1,Name);
pstmt.setString(2,City);
pstmt.executeUpdate();
215
System.out.println("Records Inserted...");
System.out.println("Do you want to continue: y/n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);
conn.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Output:
Command Prompt
216
Note: One previous row was present in the table.
217
Practical 92 (6/11/2024)
218
OUTPUT
219
Practical 93 (6/11/2024)
WAP in JDBC to establish a connection with 3 databases
simultaneously.
Program Code:
import java.sql.*;
try {
Connection con1 = DriverManager.getConnection(url1, username, password);
System.out.println(" connection done with database 1");
Connection con2 = DriverManager.getConnection(url2, username, password);
System.out.println("connection done with database 2");
Connection con3 = DriverManager.getConnection(url3, username, password);
System.out.println("connection done with database 3");
con1.close();
System.out.println("connection closed with database 1");
con2.close();
System.out.println("connection closed with database 2");
con3.close();
System.out.println("connection closed with database 3");
} catch (SQLException e) {
System.out.println("cant " + e.getMessage());
}
}
}
220
OUTPUT
221
Practical 94 (6/11/2024)
WAP in JDBC to show different ways to connect with a database
Program Code:
import java.sql.*;
import com.mysql.cj.jdbc.MysqlDataSource;
public class WaystoConnect {
static String url = "jdbc:mysql://localhost:3306/employeee";
static String username = "root";
static String pass = "meha1811";
public static void main (String[] args) {
UsingdataSource();
UsingDriverManager();
}
//using driver manager class
public static void UsingDriverManager() {
try {
Connection con = DriverManager.getConnection(url, username, pass);
System.out.println("Connection is established using DriverManager");
con.close();
System.out.println("Connection Closed..");
} catch (SQLException e) {
System.out.println("Connection did't make " + e.getMessage());
}
}
//Using a DataSource object
public static void UsingdataSource() {
MysqlDataSource dataSource = new MysqlDataSource();
222
dataSource.setURL(url);
dataSource.setUser(username);
dataSource.setPassword(pass);
try {
Connection con = dataSource.getConnection();
System.out.println("Connection is established using DataSource");
con.close();
System.out.println("Connection Closed..");
} catch (SQLException e) {
System.out.println("Connection did't make " + e.getMessage());
}
}
}
223
OUTPUT
224
Practical 95 (6/11/2024)
225
OUTPUT
SQL
226
Practical 96 (6/11/2024)
WAP in JDBC to insert 10 records in the above table.
Program Code:
import java.sql.*;
public class insertTable {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String insert = "INSERT INTO employee (name, city, salary, date_of_joining)
VALUES”+
"('Meha', 'Noida', 120000, '2002-09-10')," +
"('Anirudh', 'Noida', 115000, '2002-10-10')," +
"('Isha', 'New Delhi', 12000, '2004-10-12')," +
"('Arsheya', 'Noida', 90000, '2002-04-10')," +
"('Shubham', 'New Delhi', 85000, '2004-03-10')," +
"('Agamini', 'New Delhi', 85000, '2005-04-10')," +
"('Ashok', 'Noida', 95000, '2005-04-10')," +
"('Prabjot', 'Noida', 110000, '2005-05-08')," +
"('Daksh', 'New Delhi', 75000, '2006-01-11')," +
"('Kashish', 'Noida', 80000, '2006-12-11')";
try{
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database Connection Established");
227
} catch (SQLException e){
System.out.println(e.getMessage());
}
}
}
228
OUTPUT
SQL
229
Practical 97 (6/11/2024)
WAP in JDBC to display all the records of the above table.
Program Code:
import java.sql.*;
public class DisplayTable {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String query = "SELECT * FROM Employee";
try{
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database Connection Established");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.printf("%-5s %-10s %-15s %-10s %-15s%n", "empID", "name",
"city", "salary", "dateOfJoining");
while(rs.next()){
String name = rs.getString("name");
int empid = rs.getInt("emp_ID");
String city = rs.getString("city");
int salary = rs.getInt("salary");
java.sql.Date dateOfJoining = rs.getDate("date_of_joining");
System.out.printf("%-5d %-10s %-15s %-10d %-15s%n", empid, name, city,
salary, dateOfJoining);}
con.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
230
OUTPUT
231
Practical 98 (6/11/2024)
WAP in JDBC to create the table using prepared Statement.
Program Code:
import java.sql.*;
import java.sql.PreparedStatement;
public class myPreparedStatement {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
232
}
}
233
OUTPUT
SQL
234
Practical 99 (6/11/2024)
235
stmt.setDate(4, Date.valueOf("2002-10-10"));
stmt.executeUpdate();
236
OUTPUT
SQL
237
Practical 100 (6/11/2024)
WAP using prepared Statement to display the records from the
above table.
Program Code:
import java.sql.*;
import java.sql.PreparedStatement;
public class DisplayUsingPrepared {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String query = "SELECT * FROM employe";
try {
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database Connection Established");
PreparedStatement pstmt = con.prepareStatement(query);
System.out.printf("%-6s | %-13s | %-9s | %-7s | %s%n",
"emp_ID", "employee_name", "city", "salary", "date_of_joining");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int empID = rs.getInt("emp_ID");
String name = rs.getString("employee_name");
String city = rs.getString("city");
int salary = rs.getInt("salary");
Date dateOfJoining = rs.getDate("date_of_joining");
System.out.printf("%-6d | %-13s | %-9s | %-7d | %s%n",
empID, name, city, salary, dateOfJoining);}
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
238
}
}
239
OUTPUT
240
Practical 101 (7/11/2024)
WAP to insert 10 records using infinite loop and display the records
in the same program.
Program Code:
import java.sql.*;
import java.util.Scanner;
import java.sql.PreparedStatement;
public class PopulateTableUsingLoop {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String populateTable = "Insert into employe (employee_name, city, salary,
date_of_joining) " +
"values (?, ?, ?, ?)";
try {
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database Connection Established");
Scanner sc = new Scanner(System.in);
PreparedStatement stmt = con.prepareStatement(populateTable);
int i = 0;
while (i < 10) {
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.print("Enter City: ");
String city = sc.nextLine();
System.out.print("Enter Salary: ");
int salary = sc.nextInt();
241
System.out.print("Enter date of Joining (YY-MM-DD): ");
String date = sc.next();
stmt.setString(1, name);
stmt.setString(2, city);
stmt.setInt(3, salary);
stmt.setDate(4, Date.valueOf(date));
stmt.executeUpdate();
i++;
sc.nextLine();
System.out.print("Do you want to insert more? yes or no: ");
String stillGoing = sc.nextLine();
if (stillGoing.equalsIgnoreCase("no")) {
break;
}
}
con.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
242
OUTPUT
243
SQL
244
Practical 102 (7/11/2024)
WAP to scroll the table using scrollable resultSet using first, last,
previous, relative (both positive and negative) and absolute.
Program Code:
import java.sql.*;
public class JDBCPrg11 {
public static void main(String args[]) {
try(Connection con=
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employeee", "root",
"meha1811")) {
if(con!=null)
System.out.println("Connected to database ");
else
System.out.println("Invalid username or password");
String sql= "Select * from employe";
Statement st= con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs= st.executeQuery(sql);
rs.first();
readEmpInfo("first", rs);
rs.relative(3);
readEmpInfo("relative(3)", rs);
rs.previous();
readEmpInfo("previous", rs);
rs.absolute(4);
readEmpInfo("absolute(4)", rs);
rs.last();
readEmpInfo("last", rs);
rs.relative(-2);
readEmpInfo("relative(-2)", rs);
} catch(SQLException e) {
e.printStackTrace();
}
}
245
String name= rs.getString("employee_name");
String city= rs.getString("city");
float salary= rs.getFloat("salary");
String doj= rs.getString("date_of_joining");
String employeInfo= "%-15s:%d--%s--%s--%f--%s\n";
System.out.format(employeInfo, position, empid, name, city, salary, doj);
}
}
246
OUTPUT
247
Practical 103 (7/11/2024)
WAP to update the salary column of employee table where it is
incremented by 50000.
Program Code:
import java.sql.*;
public class IncrementSalary {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String increment = "UPDATE employe SET salary = salary + 50000";
try{
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database Connection established");
Statement stmt = con.createStatement();
int updateSalary = stmt.executeUpdate(increment);
System.out.println("Salaries updated successfully for " + updateSalary + "
employees.");
con.close();
}catch (SQLException e){
System.out.println(e.getMessage());
}
}
}
248
OUTPUT
SQL
249
Practical 104 (7/11/2024)
WAP to create a stored procedure that inserts the birthday of an
employee through their id where they will display birthday in the
birthday table and Id in the employee table.
Program Code:
import java.sql.*;
class JDBCPrg13 {
public static void main(String[] args) {
String createProcedureSQL =
"CREATE PROCEDURE InsertEmployeeBirthday(IN emp_id INT, IN birthday
DATE) " +
"BEGIN " +
" INSERT INTO birthday VALUES (emp_id, birthday); " +
" SELECT e.emp_id, b.birthday " +
" FROM employee e " +
" JOIN birthday b ON e.emp_id = b.id; " +
"END";
int Id = 2;
String birthday = "2000-03-10";
if(cstmt.execute()) {
ResultSet rs= cstmt.getResultSet();
System.out.println("Employee birthday inserted successfully.");
while(rs.next())
System.out.println("Emp_id: " + rs.getInt(1) + " Birthday: " + rs.getString(2));
}
250
} catch (SQLException e) {
e.printStackTrace();
}
}
}
251
OUTPUT
252
Practical 105 (7/11/2024)
WAP to add 2 numbers using a stored procedure.
Program Code:
import java.sql.*;
class JDBCPrg14 {
public static void main(String[] args) {
String createProcedureSQL =
"CREATE PROCEDURE AddTwoNumbers(IN num1 INT, IN num2 INT, OUT
result INT) " +
"BEGIN " +
" SET result = num1 + num2; " + "END";
int num1 = 52;
int num2 = 140;
try (Connection con =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/employeee", "root",
"meha1811")){
Statement stmt = con.createStatement();
stmt.execute(createProcedureSQL);
System.out.println("Stored procedure created");
String callProcedure = "{CALL AddTwoNumbers(?, ?, ?)}";
CallableStatement cstmt = con.prepareCall(callProcedure);
cstmt.setInt(1, num1);
cstmt.setInt(2, num2);
cstmt.registerOutParameter(3, Types.INTEGER);
cstmt.execute();
int sum = cstmt.getInt(3);
System.out.println(num1 + " + " + num2 + "= " + sum);
} catch (SQLException e) {
e.printStackTrace();
}
253
}
}
OUTPUT
254
255
Practical 106 (7/11/2024)
try {
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database connection established.");
256
}
}
257
OUTPUT
SQL
258
https://meet.google.com/nee-oqwd-gvfPractical 107 (8/11/2024)
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo1 extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
/*
<html>
<body>
<applet code="GraphicsDemo1.class" width="300" height="300">
</applet>
</body>
</html>
*/ \
259
Output:
260
Practical 108 (9/11/2024)
Program Code:
import java.awt.*;
import java.applet.*;
public class GraphicsExample2 extends Applet
{
public void init()
{
setBackground(Color.black);
setForeground(Color.white);
}
public void paint(Graphics g)
{
g.drawString("Happy Diwali",40,50);
g.drawRect(40,70,100,40);
g.fillRect(40,120,100,40);
g.drawOval(40,170,30,60);
g.fillOval(90,170,30,60);
g.drawLine(40,240,140,240);
g.drawArc(40,260,60,100,60,60);
int x[]={200,250,280,290,200};
int y[]={100,200,300,400,500};
g.drawPolygon(x,y,5);
}
}
/*
<html>
<body>
<applet code="GraphicsExample2.class" width="500" height="500">
</applet>
</body>
</html>
*/
261
Output:
262
Practical 109 (13/11/2024)
Program Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
263
Output:
264
Practical 110 (14/11/2024)
Program Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Checkboxdemo extends Applet
{
public void init()
{
Checkbox c1=new Checkbox("singing");
Checkbox c2=new Checkbox("cycling");
Checkbox c3=new Checkbox("swimming");
Checkbox c4=new Checkbox("para jumping");
add(c1);
add(c2);
add(c3);
add(c4);
}
public void paint(Graphics g)
{
g.drawString("Checkbox DEMO",100,100);
}
}
/*
<html>
<body>
<applet code = "Checkboxdemo.class" width ="500" height ="500">
</applet>
</body>
</html>
*/
265
Output:
266
Practical 111 (14/11/2024)
Program Code:
267
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
268
repaint();
}
269
Output:
270
Practical 112 (14/11/2024)
Program Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
271
}
}
/*
<html>
<body>
<applet code = "ChoiceList.class" width ="600" height ="600">
</applet>
</body>
</html>
*/
272
Output:
273
Practical 113 (14/11/2024)
Program Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
274
{
g.drawString(msg,X,Y);
}
}
/*
<html>
<applet code="KeyeventsExample.class" width=600 height=600>
</applet>
</html>
*/
275
Output:
276
Practical 114 (14/11/2024)
Program Code:
277
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
278
Output:
279
Practical 115 (14/11/2024)
Program Code:
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (500, 500);
f.setLayout(null);
f.setVisible(true);
}
// overriding the mouseDragged() method
public void mouseDragged(MouseEvent me) {
// creating the Graphics object and fetching them from the Frame object using getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor(Color.BLUE);
// setting the shape of graphics object
g.fillOval(me.getX(), me.getY(), 50, 50);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
280
Output:
281
Practical 116 (18/11/2024)
Program Code:
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
282
Output:
283
Practical 117 (18/11/2024)
Program Code:
// import statement
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample
{
JFrame jframe;
// constructor
BorderLayoutExample()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout class using
// the parameterized constructor where the horizontal gap is 20
// and vertical gap is 15. The gap will be evident when buttons are placed
// in the frame
jframe.setLayout(new BorderLayout(20, 15));
jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);
jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);
jframe.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new BorderLayoutExample();
}
}
284
Output:
285
Practical 118 (18/11/2024)
Program Code:
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample()
286
Output:
287
Practical 119 (18/11/2024)
import java.awt.event.*;
import java.awt.*;
public GraphicsDemo() {
addWindowListener(new WindowAdapter() {
System.exit(0);
});
288
int ypoints[] = {450, 450, 650, 650, 450};
int num = 5;
appwin.setTitle("Graphics Demo");
appwin.setVisible(true);
289
Output:
290
Practical 120 (18/11/2024)
Write a program to demonstrate the use of textfield in java
Code:
import java.awt.*;
import java.awt.event.*;
public TextFieldDemo() {
// Use a flow layout.
setLayout(new FlowLayout());
// Create controls.
Label namep = new Label("Name: ", Label.RIGHT);
name = new TextField(12);
Label passp = new Label("Password: ", Label.RIGHT);
pass = new TextField(8);
pass.setEchoChar('*');
291
name.addActionListener(this);
pass.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
292
Output:
293
Practical 121 (19/11/2024)
Write a program for a simple swing demo in java
Code
import javax.swing.*;
class SwingDemo {
SwingDemo () {
// Create a new JFrame container.
JFrame jfrm = new JFrame("A Simple Swing Application");
// Give the frame an initial size.
jfrm.setSize(275, 100);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a text-based label.
JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater (new Runnable() {
public void run() {
new SwingDemo();
}
});
}}
294
Output :
295
Practical 122 (19/11/2024)
Write a program in java to find if 3 sum exists in a given array.
Code :
import java.util.Arrays;
public class threesum {
public boolean getNums(int nums[],int target){
int len=nums.length;
Arrays.sort(nums);
for (int i = 0; i < len-2; i++) {
int start=i+1;
int end=len-1;
while (start<end) {
int sum=nums[i]+nums[start]+nums[end];
if (sum==target) {
System.out.println(nums[i]+","+nums[start]+","+nums[end]);
return true;
}
if (sum>target) {
end--;
}
if (sum<target) {
start++;
}
}
}
System.out.println("No Triplet");
296
return false;
}
public static void main(String[] args) {
int a[]={4,3,5,6,29,10,7,8};
int target=23;
threesum obj=new threesum();
obj.getNums(a,target);
}
}
297
Output:
298
Practical 123 (19/11/2024)
Write a program in java to demonstrate string functions in java.
Code:
public class stringKaExample {
public static void main(String[] args) {
String s1="Hello";
String s2="Helps";
System.out.println(s1.compareTo(s2));
System.out.println(s1.concat(s2));
s1=s1.trim();
System.out.println(s1);
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
String s3="jkhsjadbkhfansdaufhaj";
String s4="My Name Is Abhinav";
int end=10,start=5;
char buff[]=new char[end-start];
s3.getChars(start, end, buff, 0);
System.out.println(buff);
char s5[]=s4.toCharArray();
String s6="HELLO";
System.out.println(s5[5]);
System.out.println(s1.equals(s6));
299
System.out.println(s1.equalsIgnoreCase(s6));
}
}
300
Output:
301
Practical 124 (20/11/2024)
Write a program to demonstrate the solution to the producer consumer problem using
synchronization.
Code:
class getput{
int number;
boolean flag=false;
synchronized void put(int n){
while(flag==true){
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
}
number=n;
flag=true;
System.out.println("Put: "+n);
notify();
}
synchronized void get(){
while (flag==false) {
try {
302
wait();
} catch (Exception e) {
System.out.println(e);
}
}
flag=false;
System.out.println("Get: "+number);
notify();
}
}
class Producer implements Runnable{
getput objQ;
Thread dhaga;
Producer(getput obj){
objQ=obj;
dhaga=new Thread(this);
}
public void run(){
for (int i = 0; i < 10; i++) {
objQ.put(i);
}
}
}
class Consumer implements Runnable{
getput objQ;
Thread dhaga;
303
Consumer(getput obj){
objQ=obj;
dhaga=new Thread(this);
}
public void run(){
for (int i = 0; i < 10; i++) {
objQ.get();
}
}
}
public class prodConsumer {
public static void main(String[] args) {
getput obj=new getput();
Producer p=new Producer(obj);
Consumer c=new Consumer(obj);
p.dhaga.start();
c.dhaga.start();
}
}
304
Output:
305
Practical 125 (20/11/2024)
Write a program for binary to decimal conversion in java
Code:
306
Output:
307
Practical 126 (21/11/2024)
Write a program to check if a given is number is a palindrome or not.
Code:
308
Output:
309
Practical 127 (20/11/2024)
Write a program to demonstrate the use of StringBuffer
Code:
310
Output:
311
Practical 128 (20/11/2024)
1. Write a program in to create a simple calculator using swing
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public Calculator() {
// Set up the frame
JFrame frame = new JFrame("Simple Calculator");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
312
// Create the form panel
JPanel formPanel = new JPanel(new GridLayout(5, 2, 10, 10));
formPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
// Number 1 Input
JLabel num1Label = new JLabel("Number 1:");
num1Field = new JTextField();
formPanel.add(num1Label);
formPanel.add(num1Field);
// Number 2 Input
JLabel num2Label = new JLabel("Number 2:");
num2Field = new JTextField();
formPanel.add(num2Label);
formPanel.add(num2Field);
// Result Display
JLabel resultLabel = new JLabel("Result:");
resultField = new JTextField();
resultField.setEditable(false); // Result field is read-only
formPanel.add(resultLabel);
formPanel.add(resultField);
// Operation Buttons
addButton = new JButton("Add");
subtractButton = new JButton("Subtract");
multiplyButton = new JButton("Multiply");
divideButton = new JButton("Divide");
313
clearButton = new JButton("Clear");
314
double num2 = Double.parseDouble(num2Field.getText().trim());
double result = 0;
switch (operation) {
case "Add" -> result = num1 + num2;
case "Subtract" -> result = num1 - num2;
case "Multiply" -> result = num1 * num2;
case "Divide" -> {
if (num2 == 0) {
showError("Cannot divide by zero.");
return;
}
result = num1 / num2;
}
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
showError("Please enter valid numbers.");
}
}
315
num1Field.setText("");
num2Field.setText("");
resultField.setText("");
}
316
Output:
317
318
319
320