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

Ashu

This practical file contains a comprehensive list of Java programming exercises submitted by Govind Sharma for the Core Java course (CSIT751). The topics cover basic to advanced concepts, including object creation, inheritance, exception handling, multithreading, JDBC, and GUI programming. Each entry includes a program description, page number, date, and signature, indicating a structured approach to learning Java.

Uploaded by

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

Ashu

This practical file contains a comprehensive list of Java programming exercises submitted by Govind Sharma for the Core Java course (CSIT751). The topics cover basic to advanced concepts, including object creation, inheritance, exception handling, multithreading, JDBC, and GUI programming. Each entry includes a program description, page number, date, and signature, indicating a structured approach to learning Java.

Uploaded by

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

Core Java

(CSIT751)

Practical File

Submitted by: - Submitted to: -


Govind Sharma Mr. Rajesh Kumar
A010145024166
MCA 1-D

1
S. no. Topics Page no Date Signature

1 WRITE A PROGRAM IN JAVA TO PRINT "HELLO WORLD". 8 16/08/24

2 WRITE A PROGRAM IN JAVA TO CREATE AN OBJECT 10 23/08/24

WRITE A PROGRAM IN JAVA TO CREATE AN OBJECT OF A CLASS AND ACCESS IN IN 23/08/24


3 ANOTHER CLASS. 12

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 TO CREATE OBJECT OF A CLASS WITH MULTIPLE 23/08/24


6 ATTRIBUTES 18

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

9 WRITE A PROGRAM IN JAVA USING INHERITANCE 25 28/08/24

WRITE A PROGRAM IN JAVA USING INHERITANCE AND "THIS" FUNCTION AND 29/08/24
10 CONSTRUCTOR 28

11 WRITE A PROGRAM IN JAVA USING PARAMETERIZED CONSTRUCTOR 31 30/08/24

12 WRITE A PROGRAM IN JAVA USING PARAMETERIZED CONSTRUCTOR 33 30/08/24

WRITE A PROGRAM IN JAVA CONSTRUCTING TWO DIFFERENT CONSTRUCTORS WITH 30/08/24


13 DIFFERENT PARAMETERS 35

WRITE A PROGRAM IN JAVA USING PARAMETERIZED CONSTRUCTOR, NON- 30/08/24


14 PARAMETERIZED CONSTRUCTOR AND INHERITANCE. 38

15 WRITE A PROGRAM IN JAVA TO SHOW THE OVERLOADING CONCEPT. 41 04/09/24

16 WRITE A PROGRAM IN JAVA SHOWING THE OVERRIDING CONCEPT 43 04/09/24

17 WRITE A PROGRAM IN JAVA FINDING OUT THE ARMSTRONG NUMBERS 46 04/09/24

18 WRITE A PROGRAM IN JAVA TO SHOW NULL POINTER EXCEPTION 50 05/09/24

19 WRITE A PROGRAM IN JAVA TO SHOW THE FILE NOT FOUND EXCEPTION 56 06/09/24

20 WRITE A PROGRAM IN JAVA SHOWING THE ARITHMETIC EXCEPTION 58 06/09/24

21 WRITE A PROGRAM IN JAVA WHICH THROWS THE IO EXCEPTION 60 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

24 WRITE A PROGRAM IN JAVA TO SHOW THE USAGE OF UNICODE IN COMMENTS 66 13/09/24

25 WRITE A PROGRAM IN JAVA TO PRINT DIFFERENT DATA TYPES IN STRING. 68 13/09/24

26 WRITE A PROGRAM IN JAVA USING INTEGER CALCULATIONS 70 13/09/24

27 WRITE A PROGRAM IN JAVA USING ONLY THE UNICODE 72 13/09/24

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

39 WRITE A PROGRAM IN JAVA USING SYSTEM.OUT.WRITE COMMAND 99 20/09/24

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

43 WRITE A PROGRAM IN JAVA TO CONCATENATE/COMBINE TWO STRINGS 104 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

46 WRITE A PROGRAM IN JAVA TO PRINT UPPERCASE STRING IN LOWERCASE 107 26/09/24

47 WRITE A PROGRAM IN JAVA TO PRINT LOWERCASE STRING IN UPPERCASE 108 27/09/24

WRITE A PROGRAM IN JAVA TO SORT STRING IN ALPHABETICAL ORDER/DICTIONARY 27/09/24


48 ORDER 109

49 WRITE A PROGRAM IN JAVA USING THE COMMAND LINE ARGUMENT 111 27/09/24

WRITE A PROGRAM IN JAVA USING AN ARRAY TO PASS A VARIABLE NUMBER OF 27/09/24


50 ARGUMENTS TO A METHOD 112

WRITE A PROGRAM IN JAVA USING AN ARRAY TO PASS A VARIABLE NUMBER OF 27/09/24


51 ARGUMENTS TO A METHOD REDUCING THE NUMBER OF LINES. 114

WRITE A PROGRAM IN JAVA USING AN ARRAY TO PASS A VARIABLE NUMBER OF 27/09/24


52 ARGUMENTS WITH STANDARD ARGUMENTS 116

53 WRITE A PROGRAM IN JAVA USING SPILT FEATURE OF STRING 118 27/09/24

54 WRITE A PROGRAM IN JAVA USING GET CHARS FEATURE OF STRING. 119 02/10/24

55 WRITE A PROGRAM IN JAVA USING EQUALS FUNCTION OF STRING 120 02/10/24

56 WRITE A PROGRAM IN JAVA TO ADD TWO NUMBERS INPUTTED BY THE USER 122 02/10/24

57 WRITE A PROGRAM IN JAVA TO PRINT THE TABLE OF 2 123 03/10/24

58 WRITE A PROGRAM IN JAVA TO PRINT THE GRADE VALUE USING IF CONDITION 124 03/10/24

59 WRITE A PROGRAM IN JAVA TO REVERSE A NUMBER ENTERED BY USER 125 04/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

63 WRITE A PROGRAM IN JAVA USING THE IMMUTABLE CLASS 132 09/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

65 WRITE A PROGRAM IN JAVA CHANGING THE THREAD NAME 134 11/10/24

4
WRITE A PROGRAM IN JAVA SCANNING INTEGER AND STRING VALUE WITH SAME 11/10/24
66 OBJECT NAME. 138

67 WRITE A PROGRAM IN JAVA USING THREAD AND INHERITANCE 140 11/10/24

68 WRITE A PROGRAM IN JAVA ADDING TWO NUMBERS IN COMMAND LINE 142 11/10/24

69 WRITE A PROGRAM IN JAVA EXPLAINING THE THREAD START 141 11/10/24

70 WRITE A PROGRAM IN JAVA EXPLAINING THE THREAD RUN 142 16/10/24

71 WRITE A PROGRAM IN JAVA FOR MULTITHREADING CONCEPT 143 17/10/24

WRITE A PROGRAM IN JAVA FOR MULTITHREADING CONCEPT USING SLEEP 17/10/24


72 FUNCTION 146

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

78 WRITE A PROGRAM IN JAVA FOR SYNCHRONIZING THREAD 156 25/10/24

79 WRITE A PROGRAM IN JAVA USING PRINT WRITE FUNCTION 161 30/10/24

80 WRITE A PROGRAM IN JAVA USING STATIC IMPORT 162 30/10/24

81 WRITE A PROGRAM IN JAVA TO FIND THE HYPOTENUSE OF A TRIANGLE 163 30/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

84 WRITE A PROGRAM IN JAVA TO MAKE FILE 168 01/11/24

85 WRITE A PROGRAM IN JAVA TO WRITE TO A FILE 169 01/11/24

86 WRITE A PROGRAM IN JAVA TO SHOW A SPECIFIED FILE 170 01/11/24

87 WRITE A PROGRAM IN JAVA TO CONNECT IT TO MYSQL 172 01/11/24

88 WRITE A PROGRAM IN JAVA TO INSERT VALUES TO A DATABASE IN MYSQL 173 03/11/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

WRITE A PROGRAM IN JDBC TO ESTABLISH A CONNECTION WITH 3 DATABASES 06/11/24


183
93 SIMULTANEOUSLY

WRITE A PROGRAM IN JDBC TO SHOW DIFFERENT WAYS TO CONNECT WITH A 06/11/24


186
94 DATABASE

WRITE A PROGRAM IN JDBC TO CREATE AN EMPLOYEE TABLE WITH EMPLOYEE_ID 06/11/24


AS PRIMARY KEY WITH AUTO_INCREMENT, EMPLOYEE_NAME, CITY, SALARY AND 186
95 DATE OF JOINING

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

99 WRITE A PROGRAM USING PREPARED STATEMENT TO INSERT RECORDS 199 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

106 WRITE A PROGRAM TO INSERT AND IMAGE IN A DATABASE 222 07/11/24

107 WRITE A PROGRAM IN JAVA FOR GRAPHIC DEMO IN APPLET 223 08/11/24

108 WRITE A PROGRAM IN JAVA TO PRINT HAPPY DIWALI 224 09/11/24

109 WRITE A PROGRAM IN JAVA FOR BUTTON DEMO 225 13/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

112 WRITE A PROGRAM IN JAVA FOR CHOOSE LIST 235 14/11/24

113 WRITE A PROGRAM IN JAVA FOR KEYBOARD EVENT 238 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

119 WRITE A PROGRAM IN JAVA USING FRAME 279 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

WRITE A PROGRAM IN JAVA TO DEMONSTRATE THE SOLUTION TO THE PRODUCER 20/11/24


124 CONSUMER PROBLEM USING SYNCHRONIZATION. 295

125 WRITE A PROGRAM IN JAVA FOR BINARY TO DECIMAL CONVERSION IN JAVA 297 20/11/24

WRITE A PROGRAM IN JAVA TO CHECK IF A GIVEN IS NUMBER IS A PALINDROME OR 20/11/24


126 NOT 302

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)

Write a program in java to print “Hello World”.


Program Code:
public class MyFirstProgram
{
public static void main(String[] args)
{
System.out.println ("Hello World");
}
}

8
Output:

9
Practical 2 (15/08/2024)

Write a program in java to create an object


Program Code:
public class Object
{
int x=5;
public static void main(String[] args)
{
Object ob = new Object();
System.out.println(ob.x);
}
}

10
Output:

11
Practical 3 (16/08/2024)

Write a program in java to create an object of a class and access in


in another class.
Program Code:
-----------------//First file:
public class MultipleClass
{
int x=5;
}
-------------------------//Second file:
class MultipleClassRun
{
public static void main(String[] args)
{
MultipleClass ob = new MultipleClass();
System.out.println(ob.x);
}
}

12
Output:

13
Practical 4 (16/08/2024)

Write a program in java to create an object and modify its attributes


in main class
Program Code:
public class ModifyAttributes
{
int x;
public static void main(String[] args)
{
ModifyAttributes ob= new ModifyAttributes();
ob.x=40;
System.out.println(ob.x);
}
}

14
Output:

15
Practical 5 (16/08/2024)

Write a program in java to create multiple objects of one class and


change the value of only one object
Program Code:
public class MultipleObjects
{
int x =5;
public static void main(String[] args)
{
MultipleObjects ob1 = new MultipleObjects();
MultipleObjects ob2 = new MultipleObjects();
ob2.x = 25;
System.out.println(ob1.x);
System.out.println(ob2.x);
}
}

16
Output:

17
Practical 6 (21/08/2024)

Write a program in java to create object of a class with multiple


attributes
Program Code:
public class MultipleAttributes
{
String fname= "John";
String lname = "Doe";
int age = 24;
public static void main(String[] args)
{
MultipleAttributes ob = new MultipleAttributes();
System.out.println("Name: " +ob.fname+ " "+ob.lname);
System.out.println("Age: "+ob.age);
}
}

18
Output:

19
Practical 7 (22/08/2024)

Write a program in java creating a static and a public method to find


out the difference.
Program Code:
public class Method
{
static void myStaticMethod()
{
System.out.println("My Static Method. Can be called without creating
objects.");
}
public void myPublicMethod()
{
System.out.println("My Public Method. Must be called by creating objects.");
}
public static void main(String[] args)
{
Method ob = new Method();
ob.myPublicMethod();
myStaticMethod();
}
}

20
Output:

21
Practical 8 (23/08/2024)

Write a program in java to access private data using setter and


getter function (Encapsulation)
Program Code:
public class Encapsulation
{
private int empId;
private String empName;
private int empAge;
public static void main(String[] args)
{
Encapsulation emp = new Encapsulation();
emp.setEmpName("Ashok");
emp.setEmpAge(21);
emp.setEmpID(123456);
System.out.println("Employee name is: "+emp.getEmpName());
System.out.println("Employee age is: "+emp.getEmpAge());
System.out.println("Employee ID is: "+emp.getEmpID());
}
public int getEmpID()
{
return empId;
}
public void setEmpID(int empId)
{
this.empId = empId;
}

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)

Write a program in java using inheritance


Program Code:
class Faculty {
String designation ="Professor";
String collegeName ="AIIT";
void does()
{
System.out.println ("Teaching");
}
}
public class JavaFaculty extends Faculty
{
String mainSubject ="Java";
void hacking()
{
System.out.println ("Hacking is my hobby");
}
public static void main(String[] args)
{
JavaFaculty ob = new JavaFaculty();
System.out.println (ob.collegeName);
System.out.println(ob.designation);
System.out.println(ob.mainSubject);
ob.does();
ob.hacking();

25
Output:

26
Practical 10 (28/08/2024)

Write a program in java using inheritance and “this” function and


constructor
Program Code:
class Vehicle
{
private String make;
private String color;
private int year;
private String model;

public Vehicle (String make, String color, int year, String model)
{
this.make = make;
this.color =color;
this.year = year;
this.model = model;
}

public void printDetails()


{
System.out.println("Manufacturer: " +make);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
System.out.println("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)

Write a program in java using parameterized Constructor


Program Code:
public class Employee
{
int empId;
String empName;

Employee(int id, String name)


{
this.empId = id;
this.empName = name;
}
void info ()
{
System.out.println("Id:"+empId+" Name: "+empName);
}
public static void main(String args[])
{
Employee obj1 = new Employee(112233, "Chirag");
Employee obj2 = new Employee(992244,"Narendra");
obj1.info();
obj2.info();
}
}

30
Output:

31
Practical 12 (30/09/2024)

Write a program in java using parameterized constructor


Program Code:
class PCExample3
{
private int var;
public PCExample3(int num)
{
var=num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
PCExample3 myobj = new PCExample3(54);
System.out.println("value of var is: "+myobj.getValue());
}
}

32
Output:

33
Practical 13 (30/09/2024)

Write a program in java constructing two different constructors with


different parameters
Program Code:
class PCExample2
{
private int var;
//default constructor
public PCExample2()
{
this.var = 10;
}
//parameterized constructor
public PCExample2(int num)
{
this.var = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
PCExample2 obj = new PCExample2();
PCExample2 obj2 = new PCExample2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());

34
}
}

35
Output:

36
Practical 14 (30/09/2024)

Write a program in java using parameterized constructor, non-


parameterized constructor and inheritance.
Program Code:
class Base
{
// default constructor
Base()
{
this(10);
System.out.println("Base class default constructor called");
}
// parameterized constructor
Base(int x)
{
System.out.println("Base class parameterized constructor called");
}
}
class Derived extends Base
{
// default constructor
Derived()
{
this(20);
System.out.println("Derived class default constructor called");
}
// parameterized constructor

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)

Write a program in java to show the overloading concept.


Program Code:
class Multiply
{
static int Mul(int a, int b)
{
return a*b;
}
static int Mul(int a, int b, int c)
{
return a*b*c;
}
}
public class Overload
{
public static void main(String args[])
{
System.out.println (Multiply.Mul(5,6));
System.out.println (Multiply.Mul(5,6,4));
}
}

40
Output:

41
Practical 16 (04/09/2024)

Write a program in java showing the overriding concept


Program Code:
class Parent
{
void print()
{
System.out.println("Parent Class");
}
}
class subclass1 extends Parent
{
void print()
{
System.out.println ("Subclass1");
}
}
class subclass2 extends Parent
{
void print()
{
System.out.println("Subclass2");
}
}
public class overriding
{

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)

Write a program in java finding out the Armstrong numbers


Program Code:
import java.util.*;
public class Armstrong
{
void num(int n)
{
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.println (n + " is an Armstrong number.");
else
System.out.println (n + " is not an Armstrong number.");
}
void series(int start, int end)
{
int c=0;
System.out.println("The Armstrong numbers are:");
for(int n=start; n<=end; n++)

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");
}

public static void main(String[] args)


{
Armstrong ob = new Armstrong();
int i=1;
while (i !=3)
{

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)

Write a program in java to show Null Pointer Exception


Program Code (While showing the error):
public class NullPointerException
{
public static void main(String args[])
{
String myStr = null;
System.out.println(myStr.length());
}
}

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)

Write a program in java to show the File Not Found Exception


Program Code:
import java.io.*;
class FileNotFoundException {
public static void main(String args[])
{
FileInputStream fis = null;
//Open a file
fis = new FileInputStream("C:/myfile.txt");
int k;

//read contents of the file


while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
//close the file
fis.close();
}
}

53
Output:

Note: This Exception can be fixed after saving this file on your pc.

54
Practical 20 (06/09/2024)

Write a program in java showing the Arithmetic Exception


Program Code (Showing the error):
class AirthmeticException
{
public static void main(String args[])
{
int num1=10;
int num2=0;
//divide both numbers and print the result
int result=num1/num2;
System.out.println(result);
}
}

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)

Write a program in java which throws the IO Exception


Program Code:
import java.io.*;
class ThrowsIOException {
public static void main(String args[]) throws IOException
{
FileInputStream fis = null;
//Open a file
fis = new FileInputStream("C:/myfile.txt");
int k;

//read contents of the file


while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
//close the file
fis.close();
}
}

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)

Write a program in java to show the usage of Unicode in comments


Program Code:
public class Test1
{
public static void main(String args[])
{
//\u000d System.out.println("hello");
}
}

65
Output:

66
Practical 25 (13/09/2024)

Write a program in java to print different data types in string.


Program Code:
public class Test2
{
public static void main(String args[])
{
String s="one"+1+2+"two"+"three"+3+4+"four"+"five"+5;
System.out.println(s);
}
}

67
Output:

68
Practical 26 (13/09/2024)

Write a program in java using integer calculations


Program Code:
public class Test3
{
public static void main(String args[])
{
int s=10+ +11- -12+ +13- -14+ +15;
System.out.println(s);
}
}

69
Output:

70
Practical 27 (13/09/2024)

Write a program in java using only the Unicode


Program Code:
\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020
\u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079
\u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020
\u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063
\u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028
\u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020
\u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b
\u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020
\u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b
\u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d

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");

// Not throw any exception


System.out.println(34 / 2);
}
// Not execute in this case
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");

}
// 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");

// Throw an Arithmetic exception


System.out.println(34 / 0);
}

// catch an Arithmetic exception


catch (ArithmeticException e) {
System.out.println(
"catch : exception handled.");
}
// Always execute
finally {

System.out.println("finally : i execute always.");


}
}

75
Output:

76
Practical 30 (20/09/2024)

Write a program in java using multiple exceptions in the catch block


Program Code:
public class MultipleCatch1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
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");
}}

77
Output:

78
Practical 31(20/09/2024)

Write a program in java using multiple exceptions and the array


index out of bound exception occurs.
Program Code:
public class MultipleCatch2 {
public static void main(String[] args) {
try{
int a[]=new int[5];
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");
}
}
//In this example, try block contains two exceptions.
//But at a time only one exception occurs
//and its corresponding catch block is executed

79
Output:

80
Practical 32 (20/09/2024)

Write a program in java with multiple catch statements and


Arithmetic Exception is occurred.
Program Code:
public class MultipleCatch3 {
public static void main(String[] args) {

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 {

public static void main(String[] args) {

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)

Write a program in java to read a character and print it using a do-


while loop
Program Code:
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

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)

Write a program in java using system.out.write command


Program Code:
class WriteDemo {
public static void main(String args[]) {
int b;

b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Output:

95
Practical 40 (20/09/2024)

Write a program in java using nested try catch block


Program Code:
class MultipleCatchE{
public static void main(String args[]){
//Main try block
try{
//try block1
try{
System.out.println("Try Block1");
int num =15/0;
System.out.println(num);
}
catch(ArithmeticException e1){
System.out.println("Block1 Exception: e1");
}
//try block2
try{
System.out.println("Try Block2");
int num =100/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Block2 Exception: e2");
}
System.out.println("General statement after Block1 and Block2");
}

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)

Write a program in java to find out the length of string


Program Code:
public class StringLength
{
public static void main(String args[])
{
String s1 ="Hello";
String s2 ="Whatsup";
System.out.println ("String Length for first string is:"+s1.length());
System.out.println ("String Length for second string is:"+s2.length());
}
}
Output:

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)

Write a program in java to concatenate/combine two strings


Program Code:
public class StringConcatenate
{
public static void main(String args[])
{
String s1 ="Hello ";
s1 = s1.concat("World!");
System.out.println(s1);
}
}

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)

Write a program in java using the trim function of strings


Program Code:
public class StringTrim
{
public static void main(String args[])
{
String s1=" hello ";
System.out.println ("Without Trim");
System.out.println(s1+"How are you?");
System.out.println ("After Trim");
System.out.println (s1.trim()+"How are you?");
}
}

106
Output:

107
Practical 46 (26/09/2024)

Write a program in java to print uppercase string in lowercase


Program Code:
public class StringLower
{
public static void main(String args[])
{
String s1="HELLO WORLD!";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}

108
Output:

109
Practical 47 (27/09/2024)

Write a program in java to print lowercase string in uppercase


Program Code:
public class StringUpper
{
public static void main(String args[])
{
String s1="hello user";
String s1upper = s1.toUpperCase();
System.out.println(s1upper);
}
}

110
Output:

111
Practical 48 (27/09/2024)

Write a program in java to sort string in alphabetical order/dictionary


order
Program Code:
import java.util.Scanner;
public class StringSort
{
public static void main(String[] args)
{
int count;
String temp;
Scanner scan = new Scanner(System.in);

//User will be asked to enter the count of strings


System.out.print("Enter number of strings you would like to enter:");
count = scan.nextInt();

String str[] = new String[count];


Scanner scan2 = new Scanner(System.in);

//User is entering the strings and they are stored in an array


System.out.println("Enter the Strings one by one:");
for(int i = 0; i < count; i++)
{
str[i] = scan2.nextLine();
}

112
scan.close();
scan2.close();

//Sorting the strings


for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (str[i].compareTo(str[j])>0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
//Displaying the strings after sorting them based on alphabetical order
System.out.print("Strings in Sorted Order:");
for (int i = 0; i <= count - 1; i++)
{
System.out.print(str[i] + ", ");
}
}
}

113
Output:

114
Practical 49 (27/09/2024)

Write a program in java using the Command Line Argument


Program Code:
// Display all command line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}

115
Output:

The circled part is for passing the arguments.

116
Practical 50 (27/09/2024)

Write a program in java using an array to pass a variable number of


arguments to a method
Program Code:
// Use an array to pass a variable number of
// arguments to a method.
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");

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)

Write a program in java using an array to pass a variable number of


arguments to a method reducing the number of lines.
Program Code:
// Demonstrate variable-length arguments.
class VarArgs {

// vaTest() now uses a vararg.


static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");

for(int x : v)
System.out.print(x + " ");

System.out.println();
}

public static void main(String args[])


{
// Notice how vaTest() can be called with a
// variable number of arguments.
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
}

119
Output:

120
Practical 52 (27/09/2024)

Write a program in java using an array to pass a variable number of


arguments with standard arguments
Program Code:
// Use varargs with standard arguments.
class VarArgs2 {

// Here, msg is a normal parameter and v is a


// varargs parameter.
static void vaTest(String msg, int ... v) {
System.out.print(msg + v.length +
" Contents: ");

for(int x : v)
System.out.print(x + " ");

System.out.println();
}

public static void main(String args[])


{
vaTest("One vararg: ", 10);
vaTest("Three varargs: ", 1, 2, 3);
vaTest("No varargs: ");
}
}

121
Output:

122
Practical 53 (27/09/2024)

Write a program in java using Spilt feature of String


Program Code:
public class SplitDemo
{
public static void main(String args[])
{
String str ="JavaForMCAStudents";
String[] arrOfStr = str.split("For");
for (String a : arrOfStr)
System.out.println(a);
}
}

123
Output:

124
Practical 54 (2/10/2024)

Write a program in java using get chars feature of string.


Program Code:
public class getCharsDemo {

public static void main(String args[])


{
String s="This is a demo of getChars method.";
int start = 9;
int end = 18;
char buf[] = new char[end - start];

s.getChars(start, end, buf, 0);


System.out.println(buf);

}
}

125
Output:

126
Practical 55 (2/10/2024)

Write a program in java using equals function of string


Program Code:
class EqualsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println (s1 + " equals " +s2+ "->" + s1.equals(s2));

System.out.println (s1 + " equals " +s3+ "->" + s1.equals(s3));

System.out.println (s1 + " equals " +s4+ "->" + s1.equals(s4));

System.out.println (s1 + " equals Ignore Case " +s4+ "->" + s1.equalsIgnoreCase(s4));
}
}

127
Output:

128
Practical 56 (2/10/2024)

Write a program in java to add two numbers inputted by the user


Program Code:
import java.util.Scanner;
public class Add
{
public static void main(String args[])
{
int x,y,c;
System.out.println("Enter two numbers");
Scanner ob= new Scanner(System.in);
x=ob.nextInt();
y=ob.nextInt();
c=x+y;
System.out.println("Addition of two entered users= "+c);

}
}

129
Output:

130
Practical 57 (3/10/2024)

Write a program in java to print the table of 2


Program Code:
public class table
{
public static void main(String args[])
{
int mul;
for (int x=0; x<10;x++)
{
mul=2*(x+1);
System.out.println("2 x " +(x+1)+ "= " +mul);
}
}
}

131
Output:

132
Practical 58 (3/10/2024)

Write a program in java to print the Grade value using if condition


Program Code:
import java.util.Scanner;
public class marks
{
public static void main(String args[])
{
int marks;
System.out.println("Enter marks");
Scanner ob=new Scanner(System.in);
marks=ob.nextInt();
if (marks>75)
System.out.println("Distinction");
else
if (marks>60)
System.out.println("1st Division");
else
if (marks>45)
System.out.println("2nd Division");
else
if (marks>30)
System.out.println("3rd Division");
else
System.out.println("Default");
}
}

133
Output:

134
Practical 59 (4/10/2024)

Write a program in java to reverse a number entered by user


Program Code:
import java.util.Scanner;
public class reverse
{
public static void main(String args[])
{
int num,temp=0,r=0;
System.out.println("Enter number");
Scanner ob=new Scanner(System.in);
num=ob.nextInt();
while(num !=0)
{
temp=num%10;
r=r*10+temp;
num=num/10;
}
System.out.println(r);
}
}

135
Output:

136
Practical 60 (4/10/2024)

Write a program in java to sort an array entered by user using


bubble sort method.
Program Code:
import java.util.Scanner;
public class bubblesort
{
public static void main(String args[])
{
int[] arr=new int [10];
int n;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the length of array");
n=ob.nextInt();
System.out.println ("Enter the elements of the array");
for (int x=0; x<n; x++)
{
arr[x]=ob.nextInt();
}
for (int x=0; x<10-1; x++)
{
for (int i=0; i<n-x-1; i++)
{
if (arr[i]>arr[i+1])
{
int temp = arr[i];
arr[i] = arr[i+1];

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)

Write a program in java to reverse a number using buffer reader


Program Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferReaderReverse
{
public static void main(String[] args) throws IOException
{
System.out.println("Enter the number: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String number = reader.readLine();


String rev_number = "";
String digit = "";
int num_len = number.length();

for(int i=0; i<number.length(); i++)


{
digit = number.substring(num_len - 1, num_len);
rev_number = rev_number + digit;
num_len--;
}

System.out.println("Reversed number: " + rev_number);

140
}

}
Output:

141
Practical 62 (4/10/2024)

Write a program in java using the String Buffer and concatenate


Program Code:
public class StringExample1 {

public static void StrConcat(String str1)


{
str1 = str1 + "Amity";
}

public static void StrBufConcat(StringBuffer str2)


{
str2.append("Amity");
}

public static void StrBuildConcat(StringBuilder str3)


{
str3.append("Amity");
}

public static void main(String[] args)


{
String str1 = "Hello!";
StrConcat(str1);
System.out.println("The final String is - " + str1);

StringBuffer str2 = new StringBuffer("Hello!");

142
StrBufConcat(str2);
System.out.println("The final String is - " + str2);

StringBuilder str3 = new StringBuilder("Hello!");


StrBuildConcat(str3);
System.out.println("The final String is -" + str3);
}
}

143
Output:

144
Practical 63 (9/10/2024)

Write a program in java using the immutable class


Program Code:
public class ExampleImmutable {
private final String coursename;
ExampleImmutable(final String coursename) {
this.coursename = coursename;
}
public final String getName() {
return coursename;
}
public static void main(String[] args) {
ExampleImmutable obj = new ExampleImmutable("Machine Learning");
System.out.println(obj.getName());

}
}

145
Output:

146
Practical 64 (10/10/2024)

Write a program in java using Command Line in which two strings


are passed and three strings are printed
Program Code:
public class CommandLineString
{
public static void main (String args[])
{
System.out.print(args[0] + " University ");
System.out.print(args[1]);
System.out.print(args[2]);
}
}

147
Output:

148
Practical 65 (11/10/2024)

Write a program in java changing the thread name


Program Code:
class currentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();

System.out.println("Current thread: " + t);

// change the name of the thread


t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}

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.*;

public class solution {

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);
System.out.print ("Enter Integer value");
int i = scan.nextInt();
System.out.print ("Enter double value");
double d = scan.nextDouble();
scan.nextLine();
System.out.print ("Enter string");
String s = scan.nextLine();

System.out.println("String: " + s);


System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}

151
Output:

152
Practical 67 (11/10/2024)

Write a program in java using thread and inheritance


Program Code:
class NewThread extends Thread {

NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child 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)

Write a program in java adding two numbers in command line


Program Code:
public class CommandLineNumber
{
public static void main (String args[])
{
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int a= i+j;
System.out.print("Addition of entered numbers: "+a);
}
}

156
Output:

157
Practical 69 (11/10/2024)

Write a program in java explaining the thread start


Program Code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
System.out.println("run() method called");
}
}
class ThreadStart {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
}
}

158
Output:

159
Practical 70 (16/10/2024)

Write a program in java explaining the thread run


Program Code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());

System.out.println("run() method called");


}
}

class ThreadRun {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
}
}

160
Output:

161
Practical 71 (17/10/2024)

Write a program in java for multithreading concept


Program Code:
class MultiThreadingConcept extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println(i);
}
}
public static void main(String args[]){
MultiThreadingConcept mtc=new MultiThreadingConcept();
mtc.start();
}
}

162
Output:

163
Practical 72 (17/10/2024)

Write a program in java for multithreading concept using sleep


function
Program Code:
class MultiThreadingConcept1 extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println(i);
try{Thread.sleep(10000);}
catch(InterruptedException e){}
}
}
public static void main(String args[]){
MultiThreadingConcept1 mtc=new MultiThreadingConcept1();
MultiThreadingConcept1 mtc1=new MultiThreadingConcept1();
mtc.start();
mtc1.start();
}
}

164
Output:

165
Practical 73 (11/10/2024)

Write a program in java using the double run of thread concept


Program Code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
System.out.println("run() method called");
}
}

class DoubleRun {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
t.run();
}
}

166
Output:

167
Practical 74 (23/11/2024)

Write a program in java using the double start of thread concept


Program Code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());

System.out.println("run() method called");


}
}

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());

System.out.println("run() method called");


}
}

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)

Write a program in java using join methods to wait for threads to


finish
Program Code:

// Using join() to wait for threads to finish.


class NewThread implements Runnable {
String name; // name of thread
Thread t;

NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}

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");
}

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());

System.out.println("Main thread exiting.");


}
}

173
Output:

174
Practical 76 (25/10/2024)

Write a program in java printing the Fibonacci series using


command line
Program Code:
public class CommandLineFibonacci
{ public static void main (String args[])
{
int n = Integer.parseInt (args[0]);
int f[] = new int[n+2];
f[0]= 0; f[1]=1;
int i;
for (i=2; i<=n; i++)
{
f[i] = f[i-1] + f[i-2];
}
for (i=0; i<=n; i++)
{
System.out.print (f[i]+" ");
}
}
}

175
Output:

176
Practical 77 (25/10/2024)

Write a program in java for multiple command line arguments.


Program Code:

public class Test {


public static void main(String[] args){

for(String s : args){
System.out.println(s);
}
}
}

177
Output:

178
Practical 78 (25/10/2024)

Write a program in java for synchronizing thread


Program Code:
// This program is not synchronized.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}

class Caller implements Runnable {


String msg;
Callme target;
Thread t;

public Caller(Callme targ, String s) {


target = targ;

179
msg = s;
t = new Thread(this);
t.start();
}

public void run() {


target.call(msg);
}
}
class Sync {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}

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("]");
}
}

class Caller implements Runnable {


String msg;
Callme target;
Thread t;

182
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}

// synchronize calls to call()


public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}

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");

// wait for threads to end


try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}

184
Output:

185
Practical 79 (30/10/2024)

Write a program in java using print write function


Program Code:
import java.io.*;

public class PrintWrite {


public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);

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)

Write a program in java using static import


Program Code:
import static java.lang.System.*;
class StaticImport{
public static void main(String args[]){
out.println("Hello");//Now no need of System.out
out.println("Java");
}
}

188
Output:

189
Practical 81 (30/10/2024)

Write a program in java to find the hypotenuse of a triangle


Program Code:
class Hypot {
public static void main(String args[]) {
double side1, side2;
double hypot;
side1 = 3.0;
side2 = 4.0;
// Notice how sqrt() and pow() must be qualified by
// their class name, which is Math.
hypot = Math.sqrt(Math.pow(side1, 2) +
Math.pow(side2, 2));
System.out.println("Given sides of lengths " +
side1 + " and " + side2 +
" the hypotenuse is " +
hypot);
}
}

190
Output:

191
Practical 82 (31/10/2024)

Write a program in java to find the hypotenuse using static import


Program Code:
import static java.lang.System.*;
class StaticHypot {
public static void main(String args[]) {
double side1, side2;
double hypot;
side1 = 3.0;
side2 = 4.0;
// Notice how sqrt() and pow() must be qualified by
// their class name, which is Math.
hypot = Math.sqrt(Math.pow(side1, 2) +
Math.pow(side2, 2));
out.println("Given sides of lengths " +
side1 + " and " + side2 +
" the hypotenuse is " +
hypot);
}
}

192
Output:

193
Practical 83 (31/10/2024)

Write a program in java to copy files using command line argument


Program Code:
import java.io.*;
class CopyFile {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin = null;
FileOutputStream fout = null;
// First, confirm that both files has been specified.
if(args.length != 2) {
System.out.println("Usage: CopyFile from to");
return;
}
// Copy a File.
try {
// Attempt to open the files.
fin = new FileInputStream(args[0]);
fout = new FileOutputStream(args[1]);
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("I/O Error: " + e);
} finally {

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

My copied file before running

Running the Program

The Copied file after running

196
197
Practical 84 (1/11/2024)

Write a program in java to make file


Program Code:
import java.io.*;
public class MakeFile {
public static void main(String args[])
{
try {
// Get the file
File f = new File("D:\\ NewFile.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("NewFile.txt File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
}
}

198
Output:

199
Practical 85 (1/11/2024)

Write a program in java to write to a file


Program Code:
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors

public class WritetoFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("D:\\ NewFile.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

200
Output:

201
Practical 86 (1/11/2024)

Write a program in java to show a specified file


Program Code:
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
FileInputStream fin;
// First, confirm that a file name has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// Attempt to open the file.
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return;
}
// At this point, the file is open and can be read.
// The following reads characters until EOF is encountered.
try {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);

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)

Write a program in java to connect it to MySQL


Program Code:
import java.sql.*;
public class JDBCExample2 {
public static void main(String[] args) {
// creates Connection objects
Connection conn1 = null;

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)

Write a program in java to insert values to a database in MySQL


Program Code:
import java.sql.*;
class Mysqlinsert{
public static void main(String args[]){
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/Ananya", "root", "mylife5@")) {

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

MySQL Command Line Client

209
Practical 89 (3/11/2024)

Write a program in java to insert row in MySQL database using


prepared statement
Program Code:
import java.sql.*;
class MysqlInsertPrep{
public static void main(String args[]){
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/ananya", "root", "mylife5@")) {

if (conn != null) {
System.out.println("Connected to the database!");
} else {
System.out.println("Failed to make connection!");
}

PreparedStatement pstmt=conn.prepareStatement("insert into mytable values(?,?,?)");


pstmt.setInt(1,21); //1 specifies the first parameter in the query
pstmt.setString(2,"Mike");
pstmt.setString(3,"Tokyo");

int i=pstmt.executeUpdate();
System.out.println(i+" records inserted");

conn.close();

210
}catch(Exception e){ System.out.println(e);}

}
}

211
Output
Command Prompt:

MySQL Command Line Client:

212
Practical 90 (6/11/2024)

Write a program in java to insert row in MySQL database using


prepared statement taking the user input
Program Code:
import java.sql.*;
import java.io.*;
class MysqlInsertPrepared{
public static void main(String args[]){
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/Ananya", "root", "mylife5@")) {

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

MySQL Command Line Client

214
Practical 91 (6/11/2024)

Write a program in java to insert many rows in MySQL database


using prepared statement taking the user input
Program Code:
import java.sql.*;
import java.io.*;
class MysqlInsertManyPrepared{
public static void main(String args[]){
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/Ananya", "root", "mylife5@")) {

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

MySQL Command Line Client

216
Note: One previous row was present in the table.

217
Practical 92 (6/11/2024)

WAP in JDBC to establish a connection with the database.


Program Code:
import java.sql.*;
public class jdbc {
public static void main(String[] args) {
String url= "jdbc:mysql://localhost:3306/employeee";
String username="root";
String password="meha1811";
try{
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("connection established");
con.close();
System.out.println("Connection closed");
} catch(SQLException e){
System.out.println("can't make connection : "+ e.getMessage());
}
}
}

218
OUTPUT

219
Practical 93 (6/11/2024)
WAP in JDBC to establish a connection with 3 databases
simultaneously.
Program Code:
import java.sql.*;

public class connectionwith3databases {

public static void main(String[] args) {


String url1= "jdbc:mysql://127.0.0.1:3306/employeee";
String url2= "jdbc:mysql://127.0.0.1:3306/employee";
String url3= "jdbc:mysql://127.0.0.1:3306/student";
String username ="root";
String password="meha1811";

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)

WAP in JDBC to create an Employee table with employee_id as


primary key with auto_increment, employee_name, city, salary and
date of joining.
Program Code:
import java.sql.*;
public class CreateTable {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String createtable = "CREATE TABLE EMPLOYEE (" +
"emp_ID int AUTO_INCREMENT," +
"name varchar(20)," +
"city varchar(20)," +
"salary int," +
"date_of_joining DATE," +
"PRIMARY KEY (emp_ID))";
try {
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database Connection is Established");
Statement statement = con.createStatement();
statement.executeUpdate(createtable);
System.out.println("Table is Created Successfully");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

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");

Statement statement = con.createStatement();


statement.executeUpdate(insert);
System.out.println("Values inserted into table Successfully");
con.close();

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";

String createtable = "CREATE TABLE EMPLOYE (" +


"emp_ID int AUTO_INCREMENT," +
"employee_name VARCHAR(50)," +
"city VARCHAR(20)," +
"salary INT," +
"date_of_joining DATE," +
"PRIMARY KEY (emp_ID))";
try{
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database connection establishment");

PreparedStatement stmt = con.prepareStatement(createtable);


stmt.executeUpdate();
System.out.println("EMPLOYE table created successfully");
con.close();

}catch (SQLException e){


System.out.println(e.getMessage());
}

232
}
}

233
OUTPUT

SQL

234
Practical 99 (6/11/2024)

WAP using prepared Statement to insert records.


Program Code:
import java.sql.*;
import java.sql.PreparedStatement;
public class InsertUsingPrepared {
public static void main (String[] args) {

String url = "jdbc:mysql://localhost:3306/employeee";


String populate = "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");

PreparedStatement stmt = con.prepareStatement(populate);


// Insert first row
stmt.setString(1, "Meha");
stmt.setString(2, "Noida");
stmt.setInt(3, 120000);
stmt.setDate(4, Date.valueOf("2002-09-10"));
stmt.executeUpdate();

// Insert second row


stmt.setString(1, "Anirudh");
stmt.setString(2, "Noida");
stmt.setInt(3, 115000);

235
stmt.setDate(4, Date.valueOf("2002-10-10"));
stmt.executeUpdate();

// Insert third row


stmt.setString(1, "Daksh");
stmt.setString(2, "New Delhi");
stmt.setInt(3, 85000);
stmt.setDate(4, Date.valueOf("2004-03-10"));
stmt.executeUpdate();

System.out.println("Values inserted into table successfully");


con.close();
}catch (SQLException e){
System.out.println(e.getMessage());
}
}
}

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();
}
}

private static void readEmpInfo(String position, ResultSet rs) throws SQLException


{
int empid= rs.getInt("emp_Id");

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";

try (Connection con =


DriverManager.getConnection("jdbc:mysql://localhost:3306/employeee", "root",
"meha1811")) {
Statement stmt = con.createStatement();
stmt.execute(createProcedureSQL);
System.out.println("Stored procedure created");

String callProcedure = "{CALL InsertEmployeeBirthday(?, ?)}";


CallableStatement cstmt = con.prepareCall(callProcedure);
cstmt.setInt(1, Id);
cstmt.setString(2, birthday);

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)

WAP in JDBC to insert an Image in database


Program Code:
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.io.File;

public class InsertImage {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
String insertSQL = "INSERT INTO person (first_name, last_name, photo) VALUES
(?, ?, ?)";
String filePath = "E:/MEHA/photo.png";

try {
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database connection established.");

PreparedStatement pstmt = con.prepareStatement(insertSQL);


pstmt.setString(1, "Meha");
pstmt.setString(2, "Jain");

try (FileInputStream fileImage = new FileInputStream(new File(filePath))) {


pstmt.setBlob(3, fileImage);
int rowsAffected = pstmt.executeUpdate();
System.out.println(rowsAffected + " record inserted successfully.");
} catch (IOException e) {
System.out.println("Error reading the photo file: " + e.getMessage());
}
con.close();
} catch (SQLException e) {
System.out.println("SQL Error: " + e.getMessage());
}

256
}
}

257
OUTPUT

SQL

258
https://meet.google.com/nee-oqwd-gvfPractical 107 (8/11/2024)

Write a program in java to graphic demo in applet


Program Code:
package com.company;

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)

Write a program in java to print happy Diwali

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)

Write a program in java for button demo

Program Code:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class ButtonDemo extends Applet implements ActionListener


{
public void init()
{
Button b1 = new Button("Red");
Button b2 = new Button("Blue");
Button b3 = new Button("Green");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString("Button Demo",100,100);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Red"))
setBackground(Color.red);
else if(str.equals("Blue"))
setBackground(Color.blue);
else
setBackground(Color.green);
}
}
/*
<html>
<body>
<applet code = "ButtonDemo.class" width ="500" height ="500">
</applet>
</body>
</html>
*/

263
Output:

264
Practical 110 (14/11/2024)

Write a program in java for choose box demo

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)

Write a program in java to display mouse event

Program Code:

// Demonstrate the mouse event handlers.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/

public class MouseEvents extends Applet


implements MouseListener, MouseMotionListener {

String msg = "";


int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {

267
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

// Handle mouse exited.


public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}

// Handle button pressed.


public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}

// Handle mouse dragged.


public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);

268
repaint();
}

// Handle mouse moved.


public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}

// Display msg in applet window at current X,Y location.


public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

269
Output:

270
Practical 112 (14/11/2024)

Write a program in java for choose list

Program Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class ChoiceList extends Applet implements ItemListener,ActionListener


{
Choice c;
List l;
String cmsg,lmsg;
public void init()
{
c=new Choice();
l=new List();
c.add("java");
c.add("python");
c.add("Android");
c.add("IOS");
l.add("java");
l.add("python");
l.add("Android");
l.add("IOS");
add(c);
add(l);
c.addItemListener(this);
l.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
cmsg=c.getSelectedItem();
lmsg=l.getSelectedItem();
g.drawString(cmsg,300,400);
g.drawString(lmsg,300,500);

271
}
}
/*
<html>
<body>
<applet code = "ChoiceList.class" width ="600" height ="600">
</applet>
</body>
</html>
*/

272
Output:

273
Practical 113 (14/11/2024)

Write a program in java for keyboard event

Program Code:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class KeyeventsExample extends Applet implements KeyListener


{
int X=150,Y=150;
String msg="Key Events";

public void init()


{
setBackground(Color.black);
setForeground(Color.white);
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
msg="Key Pressed";
setBackground(Color.pink);
showStatus(" Key Pressed");
repaint();
}
public void keyReleased(KeyEvent ke)
{
msg="Key Released";
setBackground(Color.red);
showStatus("Key Released");
repaint();
}
public void keyTyped(KeyEvent ke)
{
msg="Key Typed";
msg+=ke.getKeyChar();
setBackground(Color.blue);
showStatus("Key Typed");
repaint();
}
public void paint(Graphics g)

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)

Write a program in java for virtual keyboard and event

Program Code:

// Demonstrate some virutal key codes.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/

public class KeyEvents extends Applet


implements KeyListener {

String msg = "";


int X = 10, Y = 20; // output coordinates

public void init() {


addKeyListener(this);
}

public void keyPressed(KeyEvent ke) {


showStatus("Key Down");

int key = ke.getKeyCode();


switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:

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();
}

public void keyReleased(KeyEvent ke) {


showStatus("Key Up");
}

public void keyTyped(KeyEvent ke) {


msg += ke.getKeyChar();
repaint();
}

// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

278
Output:

279
Practical 115 (14/11/2024)

Write a program in java for mouse motion adapter

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)

Write a program in java to make a keyboard adapter

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());
}

public static void main(String[] args) {


new KeyAdapterExample();
}
}

282
Output:

283
Practical 117 (18/11/2024)

Write a program in java for Border Layout (north,west,east,south,center) using jbutton

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)

Write a program in java for GridLayout using jbutton

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");

// adding buttons to the frame


// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);

// setting the grid layout using the parameterless constructor


frameObj.setLayout(new GridLayout());

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)

1. Write a program using frame


Code:

import java.awt.event.*;

import java.awt.*;

public class GraphicsDemo extends Frame {

public GraphicsDemo() {

// Anonymous inner class to handle window close events.

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

System.exit(0);

});

public void paint(Graphics g) {

g.drawLine(20, 40, 100, 90);

g.drawLine(20, 90, 100, 40);

g.drawLine(40, 45, 250, 80);

g.drawRect(20, 150, 60, 50);

g.fillRect(110, 150, 60, 50);

g.drawRoundRect(200, 150, 60, 50, 15, 15);

g.fillRoundRect(290, 150, 60, 50, 30, 40);

g.drawOval(20, 250, 50, 50);

g.fillOval(100, 250, 75, 50);

g.drawOval(200, 260, 100, 40);

g.drawArc(20, 350, 70, 70, 0, 180);

g.fillArc(70, 350, 70, 70, 0, 75);

int xpoints[] = {20, 200, 20, 200, 20};

288
int ypoints[] = {450, 450, 650, 650, 450};

int num = 5;

g.drawPolygon(xpoints, ypoints, num);

g.drawString("This is a string", 120, 500);

public static void main(String[] args) {

GraphicsDemo appwin = new GraphicsDemo();

appwin.setSize(new Dimension(400, 600));

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 class TextFieldDemo extends Frame implements ActionListener {


TextField name, pass;

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('*');

// Add the controls to the frame.


add(namep);
add(name);
add(passp);
add(pass);

// Add action event handlers.

291
name.addActionListener(this);
pass.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

public void actionPerformed(ActionEvent ae) {


repaint();
}

public void paint(Graphics g) {


g.drawString("Name: " + name.getText(), 20, 100);
g.drawString("Selected text in name: " + name.getSelectedText(), 20, 120);
g.drawString("Password: " + pass.getText(), 20, 140);
}

public static void main(String[] args) {


TextFieldDemo appwin = new TextFieldDemo();

appwin.setSize(new Dimension(380, 180));


appwin.setTitle("TextFieldDemo");
appwin.setVisible(true);
}
}

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:

public class binarytodecimal {


public static void main(String[] args) {
int bin=100110101,pow=0,deci=0,rem;
System.out.println("Binary: "+bin);
while (bin!=0) {
rem=bin%10;
deci+=rem*Math.pow(2,pow++);
bin/=10;
}
System.out.println("Decimal: "+deci);
}
}

306
Output:

307
Practical 126 (21/11/2024)
Write a program to check if a given is number is a palindrome or not.

Code:

public class palin {


public static boolean palindrome(int x){
int temp=x,sum=0;
while(temp!=0){
sum=sum*10+temp%10;
temp/=10;
}
return x==sum?true:false;
}
public static void main(String[] args) {
System.out.println(palindrome(12321));
}
}

308
Output:

309
Practical 127 (20/11/2024)
Write a program to demonstrate the use of StringBuffer

Code:

public class stringmanipal {


public static void main(String[] args) {
String name=new String("Jai Shree Ram");
System.out.println(name.charAt(5))
System.out.println(s.capacity());
System.out.println(s.append(name));
}
}

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 class Calculator {


private JTextField num1Field, num2Field, resultField;
private JButton addButton, subtractButton, multiplyButton, divideButton, clearButton;

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());

// Heading at the top


JLabel headingLabel = new JLabel("edSlash Coding Hub Calculator",
JLabel.CENTER);
headingLabel.setFont(new Font("Arial", Font.BOLD, 22));
headingLabel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));
frame.add(headingLabel, BorderLayout.NORTH);

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");

JPanel buttonPanel = new JPanel(new GridLayout(1, 5, 5, 5));


buttonPanel.add(addButton);
buttonPanel.add(subtractButton);
buttonPanel.add(multiplyButton);
buttonPanel.add(divideButton);
buttonPanel.add(clearButton);

// Add components to the frame


frame.add(formPanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);

// Add Action Listeners using Lambdas


ActionListener listener = e -> handleOperation(e.getActionCommand());
addButton.addActionListener(listener);
subtractButton.addActionListener(listener);
multiplyButton.addActionListener(listener);
divideButton.addActionListener(listener);
clearButton.addActionListener(e -> clearFields());

// Make the frame visible


frame.setVisible(true);
}

private void handleOperation(String operation) {


try {
double num1 = Double.parseDouble(num1Field.getText().trim());

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.");
}
}

private void showError(String message) {


JOptionPane.showMessageDialog(null, message, "Input Error",
JOptionPane.ERROR_MESSAGE);
}

private void clearFields() {

315
num1Field.setText("");
num2Field.setText("");
resultField.setText("");
}

public static void main(String[] args) {


SwingUtilities.invokeLater(Calculator::new);
}
}

316
Output:

317
318
319
320

You might also like