jj_java_practical
jj_java_practical
Uttar Pradesh
Page | 1
INDEX
S.NO. PROGRAM PAGE DATE SIGN
NO.
1 WRITE A PROGRAM IN JAVA TO 9 16/08/2024
PRINT “HELLO WORLD”
2 WRITE A PROGRAM IN JAVA TO 11 23/08/2024
CREATE AN OBJECT
3 WRITE A PROGRAM IN JAVA TO 13 23/08/2024
CREATE AN OBJECT OF A CLASS AND
ACCESS IN IN ANOTHER CLASS
4 WRITE A PROGRAM IN JAVA TO 15 23/08/2024
CREATE AN OBJECT AND MODIFY ITS
ATTRIBUTES IN MAIN CLASS
5 WRITE A PROGRAM IN JAVA TO 17 23/08/2024
CREATE MULTIPLE OBJECTS OF ONE
CLASS AND CHANGE THE VALUE OF
ONLY ONE OBJECT
6 WRITE A PROGRAM IN JAVA TO 19 23/08/2024
CREATE OBJECT OF A CLASS WITH
MULTIPLE ATTRIBUTES
7 WRITE A PROGRAM IN JAVA 21 23/08/2024
CREATING A STATIC AND A PUBLIC
METHOD TO FIND OUT THE
DIFFERENCE.
8 WRITE A PROGRAM IN JAVA TO 23 28/08/2024
ACCESS PRIVATE DATA USING
SETTER AND GETTER FUNCTION
9 WRITE A PROGRAM IN JAVA TO 25 28/08/2024
SHOW INHERITANCE
10 WRITE A PROGRAM IN JAVA USING 27 29/08/2024
INHERITANCE AND “THIS” FUNCTION
AND CONSTRUCTOR
11 WRITE A PROGRAM IN JAVA USING 30 30/09/2024
PARAMETERIZED CONSTRUCTOR
12 WRITE A PROGRAM IN JAVA USING 32 30/09/2024
PARAMETERIZED CONSTRUCTOR
13 WRITE A PROGRAM IN JAVA 34 30/09/2024
CONSTRUCTING TWO DIFFERENT
CONSTRUCTORS WITH DIFFERENT
PARAMETERS.
14 WRITE A PROGRAM IN JAVA USING 36 30/09/2024
PARAMETERIZED CONSTRUCTOR,
NON-PARAMETERIZED
CONSTRUCTOR AND INHERITANCE.
15 WRITE A PROGRAM IN JAVA TO 38 04/09/2024
SHOW THE OVERLOADING CONCEPT
Page | 2
16 WRITE A PROGRAM IN JAVA 40 04/09/2024
SHOWING THE OVERRIDING
CONCEPT
17 WRITE A PROGRAM IN JAVA FINDING 42 04/09/2024
OUT THE ARMSTRONG NUMBERS
18 WRITE A PROGRAM IN JAVA TO 46 05/09/2024
SHOW NULL POINTER EXCEPTION
19 WRITE A PROGRAM IN JAVA TO 48 06/09/2024
SHOW THE FILE NOT FOUND
EXCEPTION
20 WRITE A PROGRAM IN JAVA 50 06/09/2024
SHOWING THE ARITHMETIC
EXCEPTION
21 WRITE A PROGRAM IN JAVA WHICH 52 06/09/2024
THROWS THE IO EXCEPTION
22 WRITE A PROGRAM IN JAVA USING 54 06/09/2024
TRY CATCH BLOCK TO SHOW THE
ARITHMETIC EXCEPTION
23 WRITE A PROGRAM IN JAVA USING 56 11/09/2024
THE TRY CATCH BLOCK TO SHOW
THE ARITHMETIC EXCEPTION.
24 WRITE A PROGRAM IN JAVA TO 58 13/09/2024
SHOW THE USAGE OF UNICODE IN
COMMENTS.
25 WRITE A PROGRAM IN JAVA TO 60 13/09/2024
PRINT DIFFERENT DATA TYPES IN
STRING.
26 WRITE A PROGRAM IN JAVA USING 62 13/09/2024
INTEGER CALCULATIONS.
27 WRITE A PROGRAM IN JAVA USING 64 13/09/2024
ONLY THE UNICODE.
28 WRITE A PROGRAM IN JAVA USING 66 18/09/2024
TRY, CATCH AND FINALLY IN WHICH
THE CATCH BLOCK DOES NOT
EXECUTE.
29 WRITE A PROGRAM IN JAVA IN 68 19/09/2024
WHICH TRY, CATCH AND FINALLY
BLOCKS ARE ALL EXECUTED.
30 WRITE A PROGRAM IN JAVA USING 70 20/09/2024
MULTIPLE EXCEPTIONS IN THE
CATCH BLOCK.
31 WRITE A PROGRAM IN JAVA USING 72 20/09/2024
MULTIPLE EXCEPTIONS AND THE
ARRAY INDEX OUT OF BOUND
EXCEPTION OCCURS.
32 WRITE A PROGRAM IN JAVA WITH 74 20/09/2024
MULTIPLE CATCH STATEMENTS AND
ARITHMETIC EXCEPTION IS
OCCURRED.
Page | 3
33 WRITE A PROGRAM IN JAVA WITH 76 20/09/2024
MULTIPLE CATCH STATEMENTS AND
NONE OF THEM MATCH SO THE
GENERAL EXCEPTION IS CAUGHT.
34 WRITE A PROGRAM IN JAVA TO READ 78 20/09/2024
A CHARACTER AND PRINT IT USING
A DO-WHILE LOOP.
35 WRITE A PROGRAM IN JAVA TO READ 80 20/09/2024
A LINE AND PRINT IT USING DO-
WHILE LOOP
36 WRITE A PROGRAM IN JAVA TO READ 82 20/09/2024
LINES AND PRINT IT ALL TOGETHER
USING FOR LOOP
37 WRITE A PROGRAM IN JAVA TO READ 84 20/09/2024
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
38 WRITE A PROGRAM IN JAVA TO READ 86 20/09/2024
LINES AND PRINT IT ALL TOGETHER
USING FOR LOOP WHICH GIVES NULL
POINTER EXCEPTION
39 WRITE A PROGRAM IN JAVA USING 88 20/09/2024
SYSTEM.OUT.WRITE COMMAND
40 WRITE A PROGRAM IN JAVA USING 90 20/09/2024
NESTED TRY CATCH BLOCK
41 WRITE A PROGRAM IN JAVA TO FIND 92 25/09/2024
OUT THE LENGTH OF STRING
42 WRITE A PROGRAM IN JAVA TO 94 25/09/2024
COMPARE TWO STRINGS AND PRINT
THE OUTPUT
43 WRITE A PROGRAM IN JAVA TO 96 25/09/2024
CONCATENATE/COMBINE TWO
STRINGS
44 WRITE A PROGRAM IN JAVA TO FIND 98 26/09/2024
OUT WHETHER THE STRING IS EMPTY
OR NOT
45 WRITE A PROGRAM IN JAVA USING 100 26/09/2024
THE TRIM FUNCTION OF STRINGS
46 WRITE A PROGRAM IN JAVA TO 102 26/09/2024
PRINT UPPERCASE STRING IN
LOWERCASE
47 WRITE A PROGRAM IN JAVA TO 104 27/09/2024
PRINT LOWERCASE STRING IN
UPPERCASE
48 WRITE A PROGRAM IN JAVA TO SORT 106 27/09/2024
STRING IN ALPHABETICAL
ORDER/DICTIONARY ORDER
Page | 4
49 WRITE A PROGRAM IN JAVA USING 108 27/09/2024
THE COMMAND LINE ARGUMENT
50 WRITE A PROGRAM IN JAVA USING 110 27/09/2024
AN ARRAY TO PASS A VARIABLE
NUMBER OF ARGUMENTS TO A
METHOD
51 WRITE A PROGRAM IN JAVA USING 112 27/09/2024
AN ARRAY TO PASS A VARIABLE
NUMBER OF ARGUMENTS TO A
METHOD REDUCING THE NUMBER OF
LINES
52 WRITE A PROGRAM IN JAVA USING 114 27/09/2024
AN ARRAY TO PASS A VARIABLE
NUMBER OF ARGUMENTS WITH
STANDARD ARGUMENTS
53 WRITE A PROGRAM IN JAVA USING 116 27/09/2024
SPLIT FEATURE OF STRING
54 WRITE A PROGRAM IN JAVA USING 118 2/10/2024
GET CHARS FEATURE OF STRING
55 WRITE A PROGRAM IN JAVA USING 120 2/10/2024
EQUALS FUNCTION OF STRING
56 WRITE A PROGRAM IN JAVA TO ADD 122 2/10/2024
TWO NUMBERS INPUTTED BY THE
USER
57 WRITE A PROGRAM IN JAVA TO 124 3/10/2024
PRINT THE TABLE OF 2
58 WRITE A PROGRAM IN JAVA TO 126 3/10/2024
PRINT THE GRADE VALUE USING IF
CONDITION
59 WRITE A PROGRAM IN JAVA TO 128 4/10/2024
REVERSE A NUMBER ENTERED BY
USER
60 WRITE A PROGRAM IN JAVA TO SORT 130 4/10/2024
AN ARRAY ENTERED BY USER USING
BUBBLE SORT
61 WRITE A PROGRAM IN JAVA TO 132 4/10/2024
REVERSE A NUMBER USING BUFFER
READER
62 WRITE A PROGRAM IN JAVA USING 134 4/10/2024
THE STRING BUFFER AND
CONCATENATE
63 WRITE A PROGRAM IN JAVA USING 136 9/10/2024
THE IMMUTABLE CLASS
64 WRITE A PROGRAM IN JAVA USING 138 10/10/2024
COMMAND LINE IN WHICH TWO
STRINGS ARE PASSED AND THREE
STRINGS ARE PRINTED
65 WRITE A PROGRAM IN JAVA 140 11/10/2024
CHANGING THE THREAD NAME
Page | 5
66 WRITE A PROGRAM IN JAVA 142 11/10/2024
SCANNING INTEGER AND STRING
VALUE WITH SAME OBJECT NAME
67 WRITE A PROGRAM IN JAVA USING 144 11/10/2024
THREAD AND INHERITANCE
68 WRITE A PROGRAM IN JAVA ADDING 146 11/10/2024
TWO NUMBERS IN COMMAND LINE
69 WRITE A PROGRAM IN JAVA 148 11/10/2024
EXPLAINING THE THREAD START
70 WRITE A PROGRAM IN JAVA 150 16/10/2024
EXPLAINING THE THREAD RUN
71 WRITE A PROGRAM IN JAVA FOR 152 17/10/2024
MULTITHREADING CONCEPT
72 WRITE A PROGRAM IN JAVA FOR 154 17/10/2024
MULTITHREADING CONCEPT USING
SLEEP FUNCTION
73 WRITE A PROGRAM IN JAVA USING 156 11/10/2024
THE DOUBLE RUN OF THREAD
CONCEPT
74 WRITE A PROGRAM IN JAVA USING 158 23/11/2024
THE DOUBLE START OF THREAD
CONCEPT
75 WRITE A PROGRAM IN JAVA USING 160 24/10/2024
JOIN METHODS TO WAIT FOR
THREADS TO FINISH
76 WRITE A PROGRAM IN JAVA 163 25/10/2024
PRINTING THE FIBONACCI SERIES
USING COMMAND LINE
77 WRITE A PROGRAM IN JAVA FOR 165 25/10/2024
MULTIPLE COMMAND LINE
ARGUMENTS
78 WRITE A PROGRAM IN JAVA FOR 167 25/10/2024
SYNCHRONIZING THREAD.
79 WRITE A PROGRAM IN JAVA USING 171 30/10/2024
PRINT WRITE FUNCTION.
80 WRITE A PROGRAM IN JAVA USING 173 30/10/2024
STATIC IMPORT.
81 WRITE A PROGRAM IN JAVA TO FIND 175 30/10/2024
THE HYPOTENUSE OF A TRIANGLE.
82 WRITE A PROGRAM IN JAVA TO FIND 177 31/10/2024
THE HYPOTENUSE USING STATIC
IMPORT
83 WRITE A PROGRAM IN JAVA TO COPY 179 31/10/2024
FILES USING COMMAND LINE
ARGUMENT
84 WRITE A PROGRAM IN JAVA TO 181 1/11/2024
MAKE FILE
85 WRITE A PROGRAM IN JAVA TO 183 1/11/2024
WRITE TO A FILE
Page | 6
86 WRITE A PROGRAM IN JAVA TO 185 1/11/2024
SHOW A SPECIFIED FILE.
87 WRITE A PROGRAM IN JAVA TO 187 1/11/2024
CONNECT IT TO MYSQL.
88 WRITE A PROGRAM IN JAVA TO 189 3/11/2024
INSERT VALUES TO A DATABASE IN
MYSQL
89 WRITE A PROGRAM IN JAVA TO 191 3/11/2024
INSERT ROW IN MYSQL DATABASE
USING PREPARED STATEMENT
90 WRITE A PROGRAM IN JAVA TO 193 6/11/2024
INSERT ROW IN MYSQL DATABASE
USING PREPARED STATEMENT
TAKING THE USER INPUT
91 WRITE A PROGRAM IN JAVA TO 195 7/11/2024
INSERT MANY ROWS IN MYSQL
DATABASE USING PREPARED
STATEMENT TAKING THE USER
INPUT
92 WRITE A PROGRAM IN JAVA FOR 197 8/11/2024
GRAPHIC DEMO IN APPLET.
93 WRITE A PROGRAM IN JAVA TO 199 9/11/2024
PRINT HAPPY DIWALI
94 WRITE A PROGRAM IN JAVA FOR 201 13/11/2024
BUTTON DEMO
95 WRITE A PROGRAM IN JAVA FOR 203 14/11/2024
CHOOSE BOX DEMO
96 WRITE A PROGRAM IN JAVA FOR 205 14/11/2024
DISPLAY MOUSE EVENT
97 WRITE A PROGRAM IN JAVA FOR 208 14/11/2024
CHOOSE LIST
98 WRITE A PROGRAM IN JAVA FOR 210 14/11/2024
KEYBOARD EVENT
99 WRITE A PROGRAM IN JAVA FOR 212 14/11/2024
VIRTUAL KEYBOARD AND EVENT
100 WRITE A PROGRAM IN JAVA FOR 215 14/11/2024
GRAPHIC MOUSE MOTION ADAPTER
101 WRITE A PROGRAM IN JAVA FOR 217 18/11/2024
GRAPHIC KEYBOARD ADAPTER
102 WRITE A PROGRAM IN JAVA FOR 219 18/11/2024
BORDER LAYOUT(N,E,W,S,C) USING
JBUTTON
103 WRITE A PROGRAM IN JAVA FOR 221 18/11/2024
GRIDLAYOUT (1-9) USING JBUTTON
104 WRITE A PROGRAM USING FRAME 223 18/11/2024
105 WRITE A PROGRAM TO 225 18/11/2024
DEMONSTRATE THE USE OF
TEXTFIELD IN JAVA
Page | 7
106 WRITE A PROGRAM FOR A SIMPLE 228 18/11/2024
SWING DEMO IN JAVA
107 WRITE A PROGRAM IN JAVA TO FIND 230 18/11/2024
IF 3 SUM EXISTS IN A GIVEN ARRAY.
108 WRITE A PROGRAM IN JAVA TO 233 18/11/2024
DEMONSTRATE STRING FUNCTIONS
IN JAVA.
109 WRITE A PROGRAM TO 235 18/11/2024
DEMONSTRATE THE SOLUTION TO
THE PRODUCER CONSUMER
PROBLEM USING
SYNCHRONIZATION.
110 WRITE A PROGRAM FOR BINARY TO 238 18/11/2024
DECIMAL CONVERSION IN JAVA
111 WRITE A PROGRAM TO CHECK IF A 240 18/11/2024
GIVEN IS NUMBER IS A PALINDROME
OR NOT.
112 WRITE A PROGRAM TO 242 18/11/2024
DEMONSTRATE THE USE OF
STRINGBUFFER
113 WRITE A PROGRAM IN TO CREATE A 244 18/11/2024
SIMPLE CALCULATOR USING SWING
WAP in JDBC to establish a connection
114 with the database
WAP in JDBC to establish a connection
115 with 3 databases simultaneously
116 WAP in JDBC to show different ways to
connect with a database
117 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
118 WAP in JDBC to insert 10 records in the
above table
119 WAP in JDBC to display all the records
of the above table
120 WAP in JDBC to create the table using
prepared Statement
121 WAP using prepared Statement to insert
records
122 WAP using prepared Statement to
display the records from the above table
123 WAP to insert 10 records using infinite
loop and display the records in the same
program
124 WAP to scroll the table using scrollable
resultSet using first, last, previous,
relative (both positive and negative) and
absolute
Page | 8
125 WAP to update the salary column of
employee table where it is incremented
by 50000
126 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
127 WAP to add 2 numbers using a
stored procedure
128 WAP to insert and image in a database
Page | 9
1. Write a program in java to print “Hello World”.
Code:
public class MyFirstProgram
{
public static void main(String[] args)
{
System.out.println ("Hello World");
}
}
Page | 10
Output:
Page | 11
2. Write a program in java to create an object
Code:
public class Object
{
int x=5;
public static void main(String[] args)
{
Object ob = new Object();
System.out.println(ob.x);
}
}
Page | 12
Output:
Page | 13
3. Write a program in java to create an object of a class and access in in
another class.
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);
}
}
Page | 14
Output:
Page | 15
4. Write a program in java to create an object and modify its attributes
in main class
Code:
public class ModifyAttributes
{
int x;
public static void main(String[] args)
{
ModifyAttributes ob= new ModifyAttributes();
ob.x=40;
System.out.println(ob.x);
}
}
Page | 16
Output:
Page | 17
5. Write a program in java to create multiple objects of one class and
change the value of only one object
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);
}
}
Page | 18
Output:
Page | 19
6. Write a program in java to create object of a class with multiple
attributes
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);
}
}
Page | 20
Output:
Page | 21
7. Write a program in java creating a static and a public method to find
out the difference.
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();
}
}
Page | 22
Output:
Page | 23
8. Write a program in java to access private data using setter and getter
function (Encapsulation)
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; }
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; }
}
Page | 24
Output:
Page | 25
9. Write a program in java using inheritance
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();
}
}
Page | 26
Output:
Page | 27
10.Write a program in java using inheritance and “this” function and
constructor
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);
}
}
class Car extends Vehicle
{
private String bodyStyle;
public Car(String make, String color, int year, String model, String bodyStyle)
{
super(make, color, year, model);
Page | 28
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();
}
}
Page | 29
Output:
Page | 30
11.Write a program in java using parameterized Constructor
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();
}
}
Page | 31
Output:
Page | 32
12.Write a program in java using parameterized constructor
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());
}
}
Page | 33
Output:
Page | 34
13.Write a program in java constructing two different constructors with
different parameters
Code:
class PCExample2
{
private int var;
public PCExample2()
{
this.var = 10;
}
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());
}
}
Page | 35
Output:
Page | 36
14.Write a program in java using parameterized constructor, non-
parameterized constructor and inheritance.
Code:
class Base{
Base() {
this(10);
System.out.println("Base class default constructor called");
}
Base(int x){ System.out.println("Base class parameterized constructor called"); }
}
class Derived extends Base
{
Derived() {
this(20);
System.out.println("Derived class default constructor called");
}
Derived(int x){
super();
System.out.println("Derived class parameterized constructor called");
}
}
class MainProgram{
public static void main(String args[]) {
Derived my_example = new Derived();
}
}
Page | 37
Output:
Page | 38
15.Write a program in java to show the overloading concept.
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));
}
}
Page | 39
Output:
Page | 40
16.Write a program in java showing the overriding concept
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
{
public static void main(String[] args)
{
Parent a;
a = new subclass1();
a.print();
a = new subclass2();
a.print();
}
}
Page | 41
Output:
Page | 42
17.Write a program in java finding out the Armstrong numbers
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++)
{
int temp, r, re=0;
temp = n;
Page | 43
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");
}
Page | 44
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;
}
}
}
Page | 45
Output:
Page | 46
18.Write a program in java to show Null Pointer Exception
Code:
public class NullPointerException
{
public static void main(String args[])
{
String myStr = null;
System.out.println(myStr.length());
}
}
Page | 47
Output:
Page | 48
19.Write a program in java to show the File Not Found Exception
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;
Page | 49
Output:
Page | 50
20.Write a program in java showing the Arithmetic Exception
Code:
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);
}
}
Page | 51
Output:
Page | 52
21.Write a program in java which throws the IO Exception
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;
Page | 53
Output:
Page | 54
22.Write a program in java using try catch block to show the arithmetic
Exception
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");
}
}
}
Page | 55
Output:
Page | 56
23.Write a program in java using the try catch block to show the
arithmetic exception
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.");
}
}
Page | 57
Output:
Page | 58
24.Write a program in java to show the usage of Unicode in comments
Code:
public class Test1
{
public static void main(String args[])
{
//\u000d System.out.println("hello");
}
}
Page | 59
Output:
Page | 60
25.Write a program in java to print different data types in string.
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);
}
}
Page | 61
Output:
Page | 62
26.Write a program in java using integer calculations
Code:
public class Test3
{
public static void main(String args[])
{
int s=10+ +11- -12+ +13- -14+ +15;
System.out.println(s);
}
}
Page | 63
Output:
Page | 64
27.Write a program in java using only the Unicode
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
Page | 65
Output:
Page | 66
28.Write a program in java using try, catch and finally in which the
catch block does not execute.
Code:
import java.io.*;
class FinallyDemo {
public static void main(String[] args)
{
try {
System.out.println("inside try block");
System.out.println(34 / 2);
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");
}
finally
{
System.out.println(
"finally : i execute always.");
}
}
}
Page | 67
Output:
Page | 68
29.Write a program in java in which try, catch and finally blocks are all
executed.
Code:
import java.io.*;
class FinallyDemo1 {
public static void main(String[] args)
{
try {System.out.println("inside try block");
System.out.println(34 / 0);
}
catch (ArithmeticException e) {
System.out.println(
"catch : exception handled.");
}
// Always execute
finally {
Page | 69
Output:
Page | 70
30.Write a program in java using multiple exceptions in the catch block
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");
}}
Page | 71
Output:
Page | 72
31.Write a program in java using multiple exceptions and the array
index out of bound exception occurs.
Code:
public class MultipleCatch2 {
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");
}
}
Page | 73
Output:
Page | 74
32.Write a program in java with multiple catch statements and
Arithmetic Exception is occurred.
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");
}
}
Page | 75
Output:
Page | 76
33.Write a program in java with multiple catch statements and none of
them match so the general exception is caught.
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");
}
}
Page | 77
Output:
Page | 78
34.Write a program in java to read a character and print it using a do-
while loop
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');
}
}
Page | 79
Output:
Page | 80
35.Write a program in java to read a line and print it using do-while
loop
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"));
}
}
Page | 81
Output:
Page | 82
36.Write a program in java to read lines and print it all together using
for loop
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]);
}
}
}
Page | 83
Output:
Page | 84
37.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
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]);
}
}
}
Page | 85
Output:
Page | 86
38.Write a program in java to read lines and print it all together using
for loop which gives null pointer exception
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]);
}
}
}
Page | 87
Output:
Page | 88
39.Write a program in java using system.out.write command
Code:
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Page | 89
Output:
Page | 90
40.Write a program in java using nested try catch block
Code:
class MultipleCatchE{
public static void main(String args[]){
try{
try{
System.out.println("Try Block1");
int num =15/0;
System.out.println(num);
}
catch(ArithmeticException e1){
System.out.println("Block1 Exception: e1");
}
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"); }
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");
}
}
Page | 91
Output:
Page | 92
41.Write a program in java to find out the length of string
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());
}
}
Page | 93
Output:
Page | 94
42.Write a program in java to compare two strings and print the output
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));
}
}
Page | 95
Output:
Page | 96
43.Write a program in java to concatenate/combine two strings
Code:
public class StringConcatenate
{
public static void main(String args[])
{
String s1 ="Hello ";
s1 = s1.concat("World!");
System.out.println(s1);
}
}
Page | 97
Output:
Page | 98
44.Write a program in java to find out whether the string is empty or
not
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());
}
}
Page | 99
Output:
Page | 100
45.Write a program in java using the trim function of strings
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?");
}
}
Page | 101
Output:
Page | 102
46.Write a program in java to print uppercase string in lowercase
Code:
public class StringLower
{
public static void main(String args[])
{
String s1="HELLO WORLD!";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
Page | 103
Output:
Page | 104
47.Write a program in java to print lowercase string in uppercase
Code:
public class StringUpper
{
public static void main(String args[])
{
String s1="hello user";
String s1upper = s1.toUpperCase();
System.out.println(s1upper);
}
}
Page | 105
Output:
Page | 106
48.Write a program in java to sort string in alphabetical order /
dictionary order
Code:
import java.util.Scanner;
public class StringSort {
public static void main(String[] args){
int count;
String temp;
Scanner scan = new Scanner(System.in);
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);
System.out.println("Enter the Strings one by one:");
for(int i = 0; i < count; i++){ str[i] = scan2.nextLine(); }
scan.close();
scan2.close();
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;
}
}
}
System.out.print("Strings in Sorted Order:");
for (int i = 0; i <= count - 1; i++){ System.out.print(str[i] + ", "); }
}
}
Page | 107
Output:
Page | 108
49.Write a program in java using the Command Line Argument
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]);
}
}
Page | 109
Output:
Page | 110
50.Write a program in java using an array to pass a variable number of
arguments to a method
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();
}
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
}
Page | 111
Output:
Page | 112
51.Write a program in java using an array to pass a variable number of
arguments to a method reducing the number of lines.
Code:
// Demonstrate variable-length arguments.
class VarArgs {
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();
}
Page | 113
Output:
Page | 114
52.Write a program in java using an array to pass a variable number of
arguments with standard arguments
Code:
// Use varargs with standard arguments.
class VarArgs2 {
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
Page | 115
Output:
Page | 116
53.Write a program in java using Spilt feature of String
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);
}
}
Page | 117
Output:
Page | 118
54.Write a program in java using get chars feature of string.
Code:
public class getCharsDemo {
}
}
Page | 119
Output:
Page | 120
55.Write a program in java using equals function of string
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 Ignore Case " +s4+ "->" + s1.equalsIgnoreCase(s4));
}
}
Page | 121
Output:
Page | 122
56.Write a program in java to add two numbers inputted by the user
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);
}
}
Page | 123
Output:
Page | 124
57.Write a program in java to print the table of 2
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);
}
}
}
Page | 125
Output:
Page | 126
58.Write a program in java to print the Grade value using if condition
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");
}
}
Page | 127
Output:
Page | 128
59.Write a program in java to reverse a number entered by user
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);
}
}
Page | 129
Output:
Page | 130
60.Write a program in java to sort an array entered by user using
bubble sort method.
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];
arr[i+1] = temp;
}
}
}
for (int i=0; i<n; i++)
{
System.out.print(arr[i] +" ");
}
}
}
Page | 131
Output:
Page | 132
61.Write a program in java to reverse a number using buffer reader
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));
Page | 133
Output:
Page | 134
62.Write a program in java using the String Buffer and concatenate
Code:
public class StringExample1 {
Page | 135
Output:
Page | 136
63.Write a program in java using the immutable class
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());
}
}
Page | 137
Output:
Page | 138
64.Write a program in java using Command Line in which two strings
are passed and three strings are printed
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]);
}
}
Page | 139
Output:
Page | 140
65.Write a program in java changing the thread name
Code:
class currentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
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");
}
}
}
Page | 141
Output:
Page | 142
66.Write a program in java scanning integer and string value with same
object name.
Code:
import java.util.*;
Page | 143
Output:
Page | 144
67.Write a program in java using thread and inheritance
Code:
class NewThread extends Thread {
NewThread() {
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the 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 {
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.");
}
}
Page | 145
Output:
Page | 146
68.Write a program in java adding two numbers in command line
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);
}
}
Page | 147
Output:
Page | 148
69.Write a program in java explaining the thread start
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();
}
}
Page | 149
Output:
Page | 150
70.Write a program in java explaining the thread run
Code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
class ThreadRun {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.run();
}
}
Page | 151
Output:
Page | 152
71.Write a program in java for multithreading concept
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();
}
}
Page | 153
Output:
Page | 154
72.Write a program in java for multithreading concept using sleep
function
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();
}
}
Page | 155
Output:
Page | 156
73.Write a program in java using the double run of thread concept
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();
}
}
Page | 157
Output:
Page | 158
74.Write a program in java using the double start of thread concept
Code:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
class DoubleStart {
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
t.start();
}
}
Page | 159
Output:
Page | 160
75.Write a program in java using join methods to wait for threads to
finish
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
}
class DemoJoin {
public static void main(String args[]) {
Page | 161
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();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
Page | 162
Output:
Page | 163
76.Write a program in java printing the Fibonacci series using
command line
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]+" ");
}
}
}
Page | 164
Output:
Page | 165
77.Write a program in java for multiple command line arguments.
Code:
public class Test {
public static void main(String[] args){
for(String s : args){
System.out.println(s);
}
}
}
Page | 166
Output:
Page | 167
78.Write a program in java for synchronizing thread
Code:
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;
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");
try {
ob1.t.join();ob2.t.join();ob3.t.join();
} catch(InterruptedException e) { System.out.println("Interrupted"); }
}}
Page | 168
Output:
Page | 169
Fixing the code:
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;
msg = s;
t = new Thread(this);
t.start();
}
public void run() { synchronized(target) { target.call(msg);} }
}
class Synch1 {
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");
try { ob1.t.join();ob2.t.join();ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}}}
Page | 170
Output:
Page | 171
79.Write a program in java using print write function
Code:
import java.io.*;
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
Page | 172
Output:
Page | 173
80.Write a program in java using static import
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");
}
}
Page | 174
Output:
Page | 175
81.Write a program in java to find the hypotenuse of a triangle
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);
}
}
Page | 176
Output:
Page | 177
82.Write a program in java to find the hypotenuse using static import
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);
}
}
Page | 178
Output:
Page | 179
83.Write a program in java to copy files using command line argument
Code:
import java.io.*;
class CopyFile {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin = null;
FileOutputStream fout = null;
if(args.length != 2) {
System.out.println("Usage: CopyFile from to");
return;
}
try {
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 {
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");}
}}}
Page | 180
My Original File
Page | 181
84.Write a program in java to make file
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);
}
}
}
Page | 182
Output:
Page | 183
85.Write a program in java to write to a file
Code:
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
Page | 184
Output:
Page | 185
86.Write a program in java to show a specified file
Code:
import java.io.*;
class ShowFile {
public static void main(String args[]){
int i;
FileInputStream fin;
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return;
}
try {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
}
try { fin.close(); }
catch(IOException e) { System.out.println("Error Closing File"); }
}
}
Page | 186
Output:
Page | 187
87.Write a program in java to connect it to MySQL
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/Abhinav"; //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();
}
}
}
Page | 188
Output:
Page | 189
88.Write a program in java to insert values to a database in MySQL
Code:
import java.sql.*;
class Mysqlinsert{
public static void main(String args[]){
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/Abhinav", "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);
System.out.println("Inserted records into the table...");
conn.close();
}catch(Exception e){ System.out.println(e);}}
}
Page | 190
Output:
Command Prompt
Page | 191
89.Write a program in java to insert row in MySQL database using
prepared statement
Code:
import java.sql.*;
class MysqlInsertPrep{
public static void main(String args[]){
try (Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/Abhinav", "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();
}catch(Exception e){ System.out.println(e);}
}
}
Page | 192
Output
Command Prompt:
Page | 193
90.Write a program in java to insert row in MySQL database using
prepared statement taking the user input
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/Abhinav", "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...");
conn.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Page | 194
Output:
Command Prompt
Page | 195
91.Write a program in java to insert many rows in MySQL database
using prepared statement taking the user input
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/Abhinav", "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();
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);}}}
Page | 196
Output:
Command Prompt
Page | 197
92.Write a program in java to graphic demo in applet
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>
*/
Page | 198
Output:
Page | 199
93.Write a program in java to print happy Diwali
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>
*/
Page | 200
Output:
Page | 201
94.Write a program in java for button demo
Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Page | 202
Output:
Page | 203
95.Write a program in java for choose box demo
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>
*/
Page | 204
Output:
Page | 205
96.Write a program in java to display mouse event
Code:
Page | 206
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
Page | 207
Output:
Page | 208
97.Write a program in java for choose list
Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
Page | 209
Output:
Page | 210
98.Write a program in java for keyboard event
Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Page | 211
Output:
Page | 212
99.Write a program in java for virtual keyboard and event
Code:
Page | 213
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Page | 214
Output:
Page | 215
100. Write a program in java for mouse motion adapter
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();
}
}
Page | 216
Output:
Page | 217
101. Write a program in java to make a keyboard adapter
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());
}
Page | 218
Output:
Page | 219
102. Write a program in java for Border Layout (north, west, east,
south, center) using jbutton
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();
}
}
Page | 220
Output:
Page | 221
103. Write a program in java for GridLayout using jbutton
Code:
import java.awt.*;
import javax.swing.*;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Page | 222
Output:
Page | 223
104. 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};
int ypoints[] = {450, 450, 650, 650, 450};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
g.drawString("This is a string", 120, 500);
}
Page | 224
Output:
Page | 225
105. Write a program to demonstrate the use of textfield in java
Code:
import java.awt.*;
import java.awt.event.*;
public TextFieldDemo() {
// Use a flow layout.
setLayout(new FlowLayout());
// Create controls.
Label namep = new Label("Name: ", Label.RIGHT);
name = new TextField(12);
Label passp = new Label("Password: ", Label.RIGHT);
pass = new TextField(8);
pass.setEchoChar('*');
Page | 227
Output:
Page | 228
106. 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();
}
});
}}
Page | 229
Output:
Page | 230
107. 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");
return false;
}
Page | 231
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);
}
}
Page | 232
Output:
Page | 233
108. 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));
System.out.println(s1.equalsIgnoreCase(s6));
}
}
Page | 234
Output:
Page | 235
109. 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 {
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);
}
Page | 236
}
}
class Consumer implements Runnable{
getput objQ;
Thread dhaga;
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();
}
}
Page | 237
Output:
Page | 238
110. Write a program for binary to decimal conversion in java
Code:
Page | 239
Output:
Page | 240
111. Write a program to check if a given is number is a palindrome
or not.
Code:
Page | 241
Output:
Page | 242
112. Write a program to demonstrate the use of StringBuffer
Code:
Page | 243
Output:
Page | 244
113. Write a program in to create a simple calculator using swing
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public Calculator() {
// Set up the frame
JFrame frame = new JFrame("Simple Calculator");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// 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
Page | 245
formPanel.add(resultLabel);
formPanel.add(resultField);
// Operation Buttons
addButton = new JButton("Add");
subtractButton = new JButton("Subtract");
multiplyButton = new JButton("Multiply");
divideButton = new JButton("Divide");
clearButton = new JButton("Clear");
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.");
Page | 246
return;
}
result = num1 / num2;
}
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
showError("Please enter valid numbers.");
}
}
Page | 247
Output:
Page | 248
Page | 249
114. WAP in JDBC to establish a connection with the database.
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());
}
}
}
OUTPUT
Page | 250
Page | 251
115. WAP in JDBC to establish a connection with 3 databases
simultaneously.
import java.sql.*;
try {
Connection con1 = DriverManager.getConnection(url1, username, password);
System.out.println(" connection done with database 1");
Connection con2 = DriverManager.getConnection(url2, username, password);
System.out.println("connection done with database 2");
Connection con3 = DriverManager.getConnection(url3, username, password);
System.out.println("connection done with database 3");
con1.close();
System.out.println("connection closed with database 1");
con2.close();
System.out.println("connection closed with database 2");
con3.close();
System.out.println("connection closed with database 3");
} catch (SQLException e) {
System.out.println("cant " + e.getMessage());
}
}
}
Page | 252
OUTPUT
Page | 253
116. WAP in JDBC to show different ways to connect with a database
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();
dataSource.setURL(url);
dataSource.setUser(username);
dataSource.setPassword(pass);
Page | 254
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());
}
}
}
OUTPUT
Page | 255
Page | 256
117. 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.
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());
}
}
}
Page | 257
OUTPUT
SQL
Page | 258
118. WAP in JDBC to insert 10 records in the above table.
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");
Page | 259
}
OUTPUT
SQL
Page | 260
119. WAP in JDBC to display all the records of the above table.
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());
}
}
}
Page | 261
OUTPUT
Page | 262
120. WAP in JDBC to create the table using prepared Statement.
import java.sql.*;
import java.sql.PreparedStatement;
public class myPreparedStatement {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/employeee";
Page | 263
OUTPUT
SQL
Page | 264
121. WAP using prepared Statement to insert records.
import java.sql.*;
import java.sql.PreparedStatement;
public class InsertUsingPrepared {
public static void main (String[] args) {
Page | 265
stmt.setString(2, "New Delhi");
stmt.setInt(3, 85000);
stmt.setDate(4, Date.valueOf("2004-03-10"));
stmt.executeUpdate();
Page | 266
OUTPUT
SQL
Page | 267
122. WAP using prepared Statement to display the records from the
above table.
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());
}
}
}
Page | 268
OUTPUT
Page | 269
123. WAP to insert 10 records using infinite loop and display the
records in the same program.
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();
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);
Page | 270
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());
}
}
}
Page | 271
OUTPUT
Page | 272
SQL
Page | 273
124. WAP to scroll the table using scrollable resultSet using first, last,
previous, relative (both positive and negative) and absolute.
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();
}
}
Page | 274
OUTPUT
Page | 275
125. WAP to update the salary column of employee table where it is
incremented by 50000
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());
}
}
}
Page | 276
OUTPUT
SQL
Page | 277
126. 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.
import java.sql.*;
class JDBCPrg13 {
public static void main(String[] args) {
String createProcedureSQL =
"CREATE PROCEDURE InsertEmployeeBirthday(IN emp_id INT, IN
birthday DATE) " +
"BEGIN " +
" INSERT INTO birthday VALUES (emp_id, birthday); " +
" SELECT e.emp_id, b.birthday " +
" FROM employee e " +
" JOIN birthday b ON e.emp_id = b.id; " +
"END";
int Id = 2;
String birthday = "2000-03-10";
if(cstmt.execute()) {
ResultSet rs= cstmt.getResultSet();
System.out.println("Employee birthday inserted successfully.");
while(rs.next())
System.out.println("Emp_id: " + rs.getInt(1) + " Birthday: " +
rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Page | 278
OUTPUT
Page | 279
127. WAP to add 2 numbers using a stored procedure.
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();
}
}
}
Page | 280
OUTPUT
Page | 281
128. WAP in JDBC to insert an Image in database
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;
try {
Connection con = DriverManager.getConnection(url, "root", "meha1811");
System.out.println("Database connection established.");
Page | 282
OUTPUT
SQL
Page | 283