Professional Documents
Culture Documents
Abheet Kumar 19Bcs002
Abheet Kumar 19Bcs002
Abheet Kumar 19Bcs002
1.Write program to print the kth digit from last. e.g. input 23617 and k=4 output 3.
3. Write program to print the second digit. e.g. input 23516 the output is
4. Write program to find sum of all digits. Input 23617 output 2+3+6+1+7=19.
5. Write program, which will find sum of product to consecutive digits. e.g. when
the input is 23145 the output is 2x3 + 3x1 + 1x4 + 4x5 = 33.
6. Write program, which reads two number (assume that both have same number
of digits). The program outputs the sum of product of corresponding digits. Input
327 and 539 output 3x5+2x3+7x9=84.
7. Write program to print positional values of digits. Input 21463 output 3, 60, 400,
1000 and 20000.
8. Write program to find sum of even digits. Input 23617 output 2+6=8.
9. Write program to find number of digits. Input 423 output 3. Input 21151 output
5.
10. Write program to find number of even digits. In above case 2 and 1
respectively.
11. Write program to print the last even digit. e.g. input 23613 output 6.
[Hint:while (x%2 ¹ 0) x=x/10] 42. Program to print the digit immediately before
the last even digit. In above case 3.
12. Write program to print the digit immediately after the last even digit. In above
case 1.
13. Write program to print the last digit, which is multiple of 3. e.g. input 23617
output 6.
14. Write program to print the second last even digit. e.g. input 23863 output 8 (do
not use ‘if’). Input 325145761 output 4. [Hint: use two loops]
15. Read a number. Do half of number after last odd digit. Input 3 times. Input
61389426 output 184167639 (61389213*3). Input 87 output 261. Input 78 output
222 (74*3).
16. Write program, which finds the sum of numbers formed by consecutive digits.
Input 2415 output 24+41+15=80.
18.Write a Java program that prints all real solutions to the quadratic equation ax2
+bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminate b2 -
4ac is negative, display a message stating that there are no real solutions.
19.The Fibonacci sequence is defined by the following rule. The first 2 values in
the sequence are 1, 1. Every subsequent value is the sum of the 2 values preceding
it. Write a Java program that uses both recursive and non-recursive functions to
print the nth value of the Fibonacci sequence.
26.Write a Java program to practice using String class and its methods.
27.Write a Java program to practice using String Buffer class and its methods.
28.You are given a String at runtime. Capitalize all the characters at all odd
indexes in the string.
29.You are given a String at runtime. You are required to fetch the remaining
String after the occurrence of a certain sequence / character.
30.You are given a String at run time. Count the occurrence of a given word /
sequence in that String.
31.You are given a String at run-time. Delete all duplicate words from the String
(ignore the case) and return the modified String.
32.You are given a String at runtime. Find total vowels in the given String and also
display the count of each vowel in the String.
33.You are given a String at runtime. Replace all the characters at the even index
by the character present al all the next even index. Replace the character at the last
even index by “1”.
36.Write a java program to find the details of the students eligible to enroll for the
examination ( Students, Department combinedly give the eligibility criteria for the
enrollement class) using interfaces
38.Write a java program to create an abstract class named Shape that contains two
integers and an empty method named printArea(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contain only the method printArea( ) that prints the
area of the given shape.
39.WAP for class TV with attributes name of company , Screen Size using
keyword inheritance . Create a colour TV class & B&W TV class.
41.Write a Java program to implement the concept of importing classes from user
defined package and creating packages.
44.Write a Java program to implement the concept of importing classes from user
defined package and creating packages.
48.Write a java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and if the value is
even, second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of cube of the number.
58.Write programs for using Graphics class - to display basic shapes and fill them -
draw different items using basic shapes - set background and foreground color.
59.Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divide by zero.
60. Develop an Applet that receives an integer in one text field & compute its
factorial value & returns it in another text filed when the button “Compute” is
clicked.
61.Write a Java program that handles all mouse events and shows the event name
at the center of the window when a mouse event is fired. (Use adapter classes).
66.Write a java program to design the page authenticating user name and password
by using SWING.
68.Write a java program that implements a simple client server application. The
client sends data to server. The server receives the data uses it to produce a result
and then sends the result back to the client then the client displays the result on the
console.
69.Write a java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green with radio buttons. On selecting a
button, an appropriate message with “stop” or “ready” or “go” should appear above
the buttons in a selected color. Initially there is no message shown.
70.Write a java program that connects to a database using JDBC and does add,
deletes, modify and retrieve operations?
SOLUTIONS
1. Write program to print the kth digit from last. e.g. input 23617 and k=4
output 3.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int m=0;
System.out.println("enter the no");
int x = sc.nextInt();
int y = sc.nextInt();
for(int i=0; i<y; i++)
{
m=x%10;
x=x/10;
}
System.out.println(y+"th digit from last is ="+m);
}
}
3. Write program to print the second digit. e.g. input 23516 the output is 3.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0,z=0;
while(x>99)
{
x=x/10;
y=x%10;
}
System.out.println("Second digit is ="+y);
}
}
}
}
5. Write program, which will find sum of product to consecutive digits. e.g.
when the input
is 23145 the output is 2x3 + 3x1 + 1x4 + 4x5 = 33.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0,z=0;
while(x>0)
{
y= (x%10);
x=x/10;
y=y*(x%10);
z=z+y;
}
System.out.println("Sum of conjugative digits of given number is = "+z);
}
}
6. Write program, which reads two number (assume that both have same
number of digits).
The program outputs the sum of product of corresponding digits. Input 327
and 539
output 3x5+2x3+7x9=84.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
int m=0,n=0,o=0;
while(x>0 && y>00)
{
m=x%10;
n=y%10;
o=o+(m*n);
x=x/10;
y=y/10;
}
System.out.println("sum of product of corresponding digits= "+o);
}
}
7. Write program to print positional values of digits. Input 21463 output 3,
60, 400, 1000
and 20000.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int m=0,n=1;
System.out.print("Positional Values of the give number are :-");
while(x>0)
{
m=x%10;
m=m*n;
System.out.print(m +",");
n=n*10;
x=x/10;
}
}
}
8. Write program to find sum of even digits. Input 23617 output 2+6=8.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int m=0,n=0;
while(x>0)
{
m=x%10;
if(m%2==0)
{
n=n+m;
x=x/10;
}
x=x/10;
}
System.out.println("Sum of even digits of given number :-"+n);
}
}
9. Write program to find number of digits. Input 423 output 3. Input 21151
output 5.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int m=0,n=0;
while(x>0)
{
x=x/10;
n++;
}
System.out.println("Number of digits in given number are :- " + n);
}
}
10. Write program to find number of even digits. In above case 2 and 1
respectively.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int m=0,n=0;
while(x>0)
{
m=x%10;
if(m%2==0)
{
n++;
}
x=x/10;
}
System.out.println("Number of even digits in given number are :- " + n);
}
}
11. Write program to print the last even digit. e.g. input 23613 output 6.
[Hint:while (x%2 ¹ 0) x=x/10]
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int m=0,n=0;
while(x>0)
{
m=x%10;
if(m%2==0)
{
System.out.println("Last even digit in given number is :- " + m);
break;
}
x=x/10;
}
}
}
12. Program to print the digit immediately before the last even digit. In
above case 3.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int m=0,n=0;
while(x>0)
{
m=x%10;
if(m%2==0)
{
x=x/10;
m=x%10;
System.out.println("Digit immediately before the last even digit is :- " +
m);
break;
}
x=x/10;
}
}
}
13. Write program to print the digit immediately after the last even digit. In
above case 1.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0;
int m=0,n=0;
while(x>0)
{
if(x%2==0)
{
System.out.println("The digit immediately after the last even digit="+y);
break;
}
y=x%10;
x=x/10;
}
}
}
14. Write program to print the last digit, which is multiple of 3. e.g. input
23617 output 6.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0;
int m=0,n=0;
while(x>0)
{
if(x%2==0)
{
System.out.println("The digit immediately after the last even digit="+y);
break;
}
y=x%10;
x=x/10;
}
}
}
while(true)
{
while(x%2==0 && x>0)
{
x=x/10;
}
}
15. Write program to print the second last even digit. e.g. input 23863
output 8 (do not use
‘if’). Input 325145761 output 4. [Hint: use two loops]
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0;
int m=0,n=0;
while(true)
{
while(x%2==0 && x>0)
{
x=x/10;
}
}
}
}
16. Read a number. Do half of number after last odd digit. Input 3 times.
Input 61389426
output 184167639 (61389213*3). Input 87 output 261. Input 78 output 222
(74*3).
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0;
int z=0,count=0;
while(x>0)
{
y=x%10;
if(y%2!=0)
{
break;
}
x=x/10;
z=(int)(z+y*Math.pow(10,count));
count++;
}
z=z/2;
x=(int)(x*Math.pow(10,count));
x=(x+z)*3;
System.out.println(x);
}
}
17. Write program, which finds the sum of numbers formed by consecutive
digits. Input 2415
output 24+41+15=80.
sol.
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y =0;
int z=0,m=0,sum=0;
while (x>9)
{
y=x%10;
x=x/10;
z=x%10;
m=z*10;
sum=sum+y+m;
}
System.out.println("sum of numbers formed by consecutiv digits="+sum);
}
}
}
}
19. The Fibonacci sequence is defined by the following rule. The first 2 values in the sequence are 1, 1.
Every subsequent value is the sum of the 2 values preceding it. Write a Java program that uses both
recursive and non-recursive functions to print the nth value of the Fibonacci sequence.
import java.util.*;
class Function
{
void nrcf(int a,int b,int c,int n)
{
for(int i=1;i<=n-2;i++)
{
c=a+b;
a=b;
b=c;
}
a=b=1;
System.out.println("nth value in the series using non recursive function is : "+c);
}
void rcf(int a,int b,int c,int n)
{
if(n-2>0)
{
c=a+b;
a=b;
b=c;
rcf(a,b,c,n-1);
return;
}
System.out.println("\nnth value in the series using recursive function is : "+c);
}
}
class Fibonacci
{
public static void main(String args[])
{
Function f=new Function();
int n,a=1,b=1,c=0;
Scanner scr=new Scanner(System.in);
System.out.println("\nEnter n value: ");
n=scr.nextInt();
f.nrcf(a,b,c,n);
f.rcf(a,b,c,n);
}
}
{
public static void main(String[] args)
double x = 28;
double y = 4;
// return a power of 2
}
23.Demonstrate the use of BigInteger and BigDecimal classes to perform
operations on very large integers and decimals
import java.math.BigDecimal;
BigDecimal bd1 =
new BigDecimal("124567890.0987654321");
BigDecimal bd2 =
new BigDecimal("987654321.123456789");
bd1 = bd1.add(bd2);
bd1 = bd1.multiply(bd2);
bd1 = bd1.divide(bd2);
bd1 = bd1.pow(2);
bd1 = bd1.negate();
}
24.Write a Java Program to implement inheritance and demonstrate use of method
overriding.
class Bank{
class Test2{
class Student
try
rollno=Integer.parseInt(dis.readLine());
name=dis.readLine();
catch(Exception e){ }
}
void putrollno()
System.out.println("Roll No ="+rollno);
System.out.println("Name ="+name);
void getmarks()
try
m1=Integer.parseInt(dis.readLine());
m2=Integer.parseInt(dis.readLine());
m3=Integer.parseInt(dis.readLine());
catch(Exception e) { }
void putmarks()
System.out.println("m1="+m1);
System.out.println("m2="+m2);
System.out.println("m3="+m3);
void compute_display()
total=m1+m2+m3;
class MultilevelDemo
r.getrollno();
r.getmarks();
r.putrollno();
r.putmarks();
r.compute_display();
}
26.Write a Java program to practice using String class and its methods.
import java.lang.String;
}
}
27.Write a Java program to practice using String Buffer class and its methods.
public class StringBufferInsert {
public static void main(String[] args) {
StringBuffer stringName = new StringBuffer(" Welcome");
System.out.println(stringName);
stringName.insert(8, " to ");
System.out.println(stringName);
stringName.insert(12, "TechVidvan ");
System.out.println(stringName);
stringName.insert(22, " Tutorial ");
System.out.println(stringName);
stringName.insert(31, " of ");
System.out.println(stringName);
stringName.insert(35, "Java");
System.out.println(stringName);
}
}
28.You are given a String at runtime. Capitalize all the characters at all odd
indexes in the string.
import java.util.*;
class A {
String s)
if (i % 2 == 1)
new_string += s.charAt(i).toUpperCase();
else
new_string += s.charAt(i);
return new_string;
// Driver Code
public static void main(String[] args)
str = removeOddIndexCharacters(str);
System.out.print(str);
29.You are given a String at runtime. You are required to fetch the remaining
String after the occurrence of a certain sequence / character.
public class ABC
{
int occ = 0, i;
if (count == 0) {
System.out.println(str);
return;
}
occ++;
break;
}
System.out.println(str.substring(i + 1));
else
System.out.println("Empty string");
}
{
}
30.You are given a String at run time. Count the occurrence of a given word /
sequence in that String.
// of occurrence of a word in
import java.io.*;
class GFG {
int count = 0;
if (word.equals(a[i]))
count++;
return count;
// Driver code
System.out.println(countOccurrences(str, word));
}
31.You are given a String at run-time. Delete all duplicate words from the String
(ignore the case) and return the modified String.
// order
import java.util.*;
class GFG {
// excluding '\0'
s.add(x);
for (char x : s)
System.out.print(x);
}
// Driver code
int n = str.length;
removeDuplicate(str, n);
32.You are given a String at runtime. Find total vowels in the given String and also
display the count of each vowel in the String.
//Declare a string
str = str.toLowerCase();
vCount++;
cCount++;
class WrapperTest
//compareTo() method
//Equals() method
36.Write a java program to find the details of the students eligible to enroll for the
examination ( Students, Department combinedly give the eligibility criteria for the
enrollement class) using interfaces
import java.lang.*;
import java.util.*;
class Student
{
int studentId;
Scanner s=new Scanner(System.in);
String studentName,Class;
int getStudentId()
{
return studen
tId;
}
String getStudentName()
{
return studentName;
}
String getStudentClass()
{
return Class;
}
}
interface Department
{
int studentId1=0;
int attendance1=0;
double getAttendence();
}
class Exam extends Student implements Department
{
double attendLecture,totalLecture;
int studentId= studentId1;
double attendance = attendance1;
public double getAttendence()
{
return this.attendance;
}
boolean eligible()
//function to check student eligibility
{
if(this.attendance>75)
{
return true;
}
else
return false;}
void calculateAttendence()
{this.attendance=(this.attend
Lecture/this.totalLecture)*100;
}
void setValue()
//function to set info of students
{
System.out.println("Enter Student Id :");
super.studentI
d=s.nextInt();
s.nextLine();
System.out.println("Enter Student Name :");
super.studentName=s.nextLine();
System.out.println("Enter Student Class :");
super.Class=s.nextLine();
System.out.println("Enter attendLecture");
this.attendLecture=s.ne
xtInt();
System.out.println("Enter totalLecture");
this.totalLecture=s.nextInt();
}
}
class ex21
{
public static void main(String []args)
System.out.println("Name:
Mann
Patel");
System.out.println("ID:
18dcs074
");
Exam E=new Exam();
E.setValue();
E.calculateAttendence();
System.out.println("Student Id : "+E.getStudentId());
System.out.println("Student Name : "+E.getStudentName());
System.out.println("Student Class : "+E.getStudentClass());
System.out.println("Student a
ttendance : "+E.getAttendence());
System.out.println("You are eligible or not for Exam :
"+E.eligible());
}
}
.
interface area
int length,breadth,area;
System.out.print("Enter length:");
length=s.nextInt();
System.out.print("Enter breadth:");
breadth=s.nextInt();
area=length*breadth;
System.out.print("Area:"+area);
}
public static void main(String[] args)
obj.dimensions();
obj.area();
38.Write a java program to create an abstract class named Shape that contains two
integers and an empty method named printArea(). Provide three classes named
Rectangle, Triangle and Circle such that each one of the classes extends the class
Shape. Each one of the classes contain only the method printArea( ) that prints the
area of the given shape.
import java.util.*;
import java.util.Scanner;
int length;
int width;
void getValue()
{
length=s.nextInt();
width=s.nextInt();
void getValue()
length=s.nextInt();
width=s.nextInt();
{ void getValue()
width=s.nextInt();}
void PrintArea()
class ex19
{ System.out.println("Name:Mann Patel");
System.out.println("ID:18dcs074");
r.getValue();
r.PrintArea();
t.getValue();
t.PrintArea();
c.getValue();
c.PrintArea();}}
39.WAP for class TV with attributes name of company , Screen Size using
keyword inheritance . Create a colour TV class & B&W TV class.
import java.io.*;
import java.util.*;
class Cosmic
String name;
int id;
this.name = name;
this.id = id;
@Override
return true;
return false;
@Override
// hashCode() method.
return this.id;
// Driver code
class ABH
// same state
map.put(g1, "CSE");
map.put(g2, "IT");
System.out.println(map.get(geek).toString());
41.Write a Java program to implement the concept of importing classes from user
defined package and creating packages.
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
}//end of j loop
System.out.println();//new line
}}
obj[0].display();
obj[1].display();
obj[2].display();
obj[3].display();
obj[4].display();
class Product
int pro_Id;
String pro_name;
pro_Id = pid;
pro_name = n;
System.out.println();
import java.util.*;
v2.add(100);
v2.add(100);
v2.add(100);
// main method
{
// creating an object of the class MyThread2
th1.start();
System.out.println(str);
// Main method
// creating an object of the Thread class using the constructor Thread(String name)
t.start();
System.out.println(str);
48.Write a java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and if the value is
even, second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of cube of the number.
import java.util.Random;
if((randomInteger%2) == 0) {
sThread.start();
}
else {
cThread.start();
try {
Thread.sleep(1000);
System.out.println(ex);
int number;
SquareThread(int randomNumbern) {
number = randomNumbern;
}
public void run() {
int number;
CubeThread(int randomNumber) {
number = randomNumber;
rnThread.start();
}
class Table{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
Table t;
MyThread1(Table t){
this.t=t;
t.printTable(5);
Table t;
MyThread2(Table t){
this.t=t;
t.printTable(100);
class TestSynchronization1{
t2.start();
package customArrayList;
// Create instance variables name, id, and rollNo of data type String, int, and int
respectively.
String name;
int id;
int rollNo;
// Create three parameters constructor with parameters name, id, and rollNo.
this.name = name;
this.rollNo = rollNo;
this.id = id;
}
package customArrayList;
import java.util.ArrayList;
ArrayList<Student> studentData()
// Create three objects of the class Student and pass arguments to the constructor.
// Now add Student objects in the ArrayList using reference variable studentlist.
studentlist.add(s1);
studentlist.add(s2);
studentlist.add(s3);
// Return object reference variable 'studentlist' of the array list to the method
'studentValue'.
return studentlist;
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
names.add("Jane");
names.add("Thomas");
names.add("Robin");
names.add("David");
names.add("Becky");
System.out.println(names);
names.set(1, "Tom");
System.out.println(names);
System.out.format("There are %d elements in the collection%n",
names.size());
names.remove(1);
names.size());
System.out.println(names.get(3));
System.out.println("************");
Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
nums.add(5);
nums.add(10);
nums.add(13);
nums.add(12);
nums.add(15);
nums.add(23);
System.out.println(nums);
nums.removeFirst();
nums.removeLast();
nums.addFirst(17);
nums.addLast(77);
System.out.println(nums);
domains.put("de", "Germany");
domains.put("sk", "Slovakia");
domains.put("ru", "Russia");
domains.put("hu", "Hungary");
domains.put("pl", "Poland");
System.out.println(domains.get("pl"));
System.out.println(keys);
class Main {
try {
int divideByZero = 5 / 0;
catch (ArithmeticException e) {
finally {
System.out.println("This is the finally block");
Same as above
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}
class Example1{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
// I'm throwing the custom exception using throw
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
55.Write a program using Applet For configuring Applets by passing
parameters.
import java.applet.*;
import java.awt.Graphics;
</applet> */
String p,c;
p=getParameter("place");
c=getParameter("college");
g.drawString(c,80,20);
g.drawString(p,100,40);
import java.awt.*;
import java.awt.event.*;
//Driver function
//Create a frame
frame.setBackground(Color.white);
frame.setSize(500,500);
frame.setLayout(null);
output=new JTextField();
output.setBounds(0,0,500,50);
frame.add(output);
input=new JTextField();
input.setBounds(0,400,500,50);
frame.add(input);
exit.setBounds(220,200,60,30);
frame.add(exit);
input.addKeyListener(obj);
exit.addActionListener(obj);
frame.setVisible(true);
@Override
frame.dispose();
@Override
output.setText("");
if(Character.isLetter(e.getKeyChar()))
keyTyped(e);
if(Character.isDigit(e.getKeyChar()))
keyTyped(e);
@Override
output.setText("");
if(Character.isLetter(e.getKeyChar()))
keyTyped(e);
if(Character.isDigit(e.getKeyChar()))
keyTyped(e);
@Override
output.setText("");
import java.awt.*;
import java.awt.event.*;
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
l.setText("Mouse Exited");
l.setText("Mouse Pressed");
l.setText("Mouse Released");
new MouseListenerExample();
58.Write programs for using Graphics class - to display basic shapes and fill them -
draw different items using basic shapes - set background and foreground color.
import java.applet.*;
import java.awt.*;
setForefround(Color.red);
setBackGround(Color.blue);
//drawing squares
g.drawLine(10,10,100,10);
g.drawLine(10,10,10,10);
g.drawLine(10,100,100,100);
g.drawLine(100,100,100,10);
// Drawing triangle
g.drawLine(10,120,100,120);
g.drawLine(10,120,50,200);
g.drawLine(50,200,100,120);
//drawing Rectangle
g.drawRect(120,10,220,120);
g.fillRect(120,120,220,120);
g.drawOval(10,220,100,220);
g.setColor(Cplor.yellow);
g.fillOval(120,250,250,250);
//draw a polygon
int x[]={400,500,400,500);
int y[]={240,240,340,340};
g.drawPolygon(x,y,4);
59.Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divide by zero.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
implements ActionListener
int p,q,result;
TextField t1;
Button add,sub,mul,div,clear,mod,EQ;
char OP;
t1=new TextField(10);
setLayout(gl);
for(int i=0;i<10;i++)
b[i]=new Button(""+i);
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
add(b[i]);
add(add);
add(sub);
add(mul);
14
add(div);
add(mod);
add(clear);
add(EQ);
for
(int i=0;i<10;i++)
b[i].addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add")) {
p=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
else if(str.equals("sub")) {
p=Integer.parseInt(t1.getText());
OP='
-';
t1.setText("");
else if(str.equals("mul")) {
p=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
else if(str.equals("div")) {
p=Integer.parseInt(t1.getText());
OP='/';
15
t1.setText("");
}
else if(str.equals("mod")) {
p=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
if(str.equals("EQ")) {
q=Integer.parseInt(t1.getText());
if(OP=='+')
result=p+q;
else if(OP=='
-')
result=p
-q;
else if(OP=='*')
result=p*q;
else if(OP=='/')
result=p/q;
else if(OP=='%')
result=p%q;
t1.setText(""+result);
if(str.equals("clear")) {
t1.setText("");
60. Develop an Applet that receives an integer in one text field & compute its
factorial value & returns it in another text filed when the button “Compute” is
clicked.
import java.awt.*;
import java.awt.event.*;
TextField t1,t2;
Label l1,l2,l3;
Button b1;
int fact=1,n,i;
factorial e;
e=this;
t1=new TextField(10);
t2=new TextField(10);
l3=new Label("result");
b1=new Button("compute");
add(l1);add(l2);add(l3);add(t1);add(t2);add(b1);
b1.addActionListener(this);
String str=t1.getText();
n=Integer.parseInt(str);
for(i=n;i>1;i--)
fact=fact*i;
String msg=""+fact;
t2.setText(msg);
fact=1;
61.Write a Java program that handles all mouse events and shows the event name
at the center of the window when a mouse event is fired. (Use adapter classes).
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
</applet>*/
int mx=0;
int my=0;
String msg="";
addMouseListener(this);
addMouseMotionListener(this);
mx=20;
my=40;
msg="Mouse Clicked";
repaint();
mx=30;
my=60;
msg="Mouse Pressed";
repaint();
}
mx=30;
my=60;
msg="Mouse Released";
repaint();
mx=40;
my=80;
msg="Mouse Entered";
repaint();
mx=40;
my=80;
msg="Mouse Exited";
repaint();
mx=me.getX();
my=me.getY();
repaint(); }
mx=me.getX();
my=me.getY();
repaint();
g.drawString(msg,60,40);
/*
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
l1.setBounds(50,60,100,120);
l1.add("DSU");
l1.add("PIC");
l1.add("OOP");
l1.add("CGR");
l1.add("DTE");
l1.add("Microprocessor");
l1.add("CN");
l1.add("DBMS");
l1.add("SEN");
l1.add("JAVA");
add(l1);
setLayout(null);
}
public void paint(Graphics g)
repaint();
import javax.swing.*;
JFrame f;
TableExample(){
f=new JFrame();
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
jt.setBounds(30,40,200,300);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
new TableExample();
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
// default constructor
calculator()
{
s0 = s1 = s2 = "";
// main function
// create a frame
f = new JFrame("calculator");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassNa
me());
catch (Exception e) {
System.err.println(e.getMessage());
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
// create . button
be = new JButton(".");
// create a panel
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
p.setBackground(Color.blue);
f.add(p);
f.setSize(200, 220);
f.show();
String s = e.getActionCommand();
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
l.setText(s0 + s1 + s2);
s0 = s1 = s2 = "";
l.setText(s0 + s1 + s2);
double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
s1 = s2 = "";
else {
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
s1 = s;
s2 = "";
l.setText(s0 + s1 + s2);
66.Write a java program to design the page authenticating user name and password
by using SWING.
//import required classes and packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Exception;
JButton b1;
JPanel newPanel;
//calling constructor
CreateLoginForm()
add(newPanel, BorderLayout.CENTER);
page.getContentPane().add(wel_label);
else{
class LoginFormDemo
try
catch(Exception e)
//handle exception
JOptionPane.showMessageDialog(null, e.getMessage());
NewPage.java
import javax.swing.*;
import java.awt.*;
//create NewPage class to create a new page on which user will navigate
//constructor
NewPage()
setDefaultCloseOperation(javax.swing.
WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Welcome");
setSize(400, 200);
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
int i=0,temp=0;
char a;
float stk[];
int top;
TextField t;
Button dot,mod,b,one,two,three,four,five,six,seven,eight,nine,
zero,add,sub,mul,div,eq,sine,sqrt,cbrt;
GridBagConstraints gc;
Week9()
super("My Calculator");
stk=new float[20];
top=-1;
t=new TextField("");
b=new Button("Reset");
dot=new Button("...");
setSize(250,250);
setLocation(500,200);
setLayout(new GridBagLayout());
addcomp(one,1,1,1,1);
addcomp(two,1,2,1,1);
addcomp(three,1,3,1,1);
addcomp(four,1,4,1,1);
addcomp(five,2,1,1,1);
addcomp(six,2,2,1,1);
addcomp(seven,2,3,1,1);
addcomp(eight,2,4,1,1);
addcomp(nine,3,1,1,1);
addcomp(zero,3,2,1,1);
addcomp(mul,3,3,1,1);
addcomp(div,3,4,1,1);
addcomp(add,4,1,1,1);
addcomp(sub,4,2,1,1);
addcomp(eq,4,3,1,1);
addcomp(mod,4,4,1,1);
addcomp(dot,5,1,1,1);
addcomp(sine,5,2,1,1);
addcomp(sqrt,5,3,1,1);
addcomp(cbrt,5,4,1,1);
addcomp(new Label(""),7,1,4,1);
addcomp(t,8,1,4,1);
addcomp(new Label(""),9,1,4,1);
addcomp(b,10,2,2,1);
setVisible(true);
one.addActionListener(this);
two.addActionListener(this);
three.addActionListener(this);
four.addActionListener(this);
five.addActionListener(this);
six.addActionListener(this);
seven.addActionListener(this);
eight.addActionListener(this);
nine.addActionListener(this);
zero.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
eq.addActionListener(this);
mod.addActionListener(this);
dot.addActionListener(this);
sine.addActionListener(this);
sqrt.addActionListener(this);
cbrt.addActionListener(this);
b.addActionListener(this);
gc.gridx=c;
gc.gridy=r;
gc.gridwidth=w;
gc.gridheight=h;
gc.fill=gc.BOTH;
add(cc,gc);
if(ae.getSource()==b)
t.setText("");
}
if(ae.getSource()==one)
if(temp==1)
func();
t.setText(t.getText()+"1");
if(ae.getSource()==two)
if(temp==1)
func();
t.setText(t.getText()+"2");
if(ae.getSource()==three)
if(temp==1)
func();
t.setText(t.getText()+"3");
if(ae.getSource()==four)
if(temp==1)
func();
t.setText(t.getText()+"4");
}
if(ae.getSource()==five)
if(temp==1)
func();
t.setText(t.getText()+"5");
if(ae.getSource()==six)
if(temp==1)
func();
t.setText(t.getText()+"6");
if(ae.getSource()==seven)
if(temp==1)
func();
t.setText(t.getText()+"7");
if(ae.getSource()==eight)
if(temp==1)
func();
t.setText(t.getText()+"8");
if(ae.getSource()==nine)
t.setText(t.getText()+"9");
if(temp==1)
func();
if(ae.getSource()==zero)
t.setText(t.getText()+"0");
if(temp==1)
func();
if(ae.getSource()==add||ae.getSource()==sub||ae.getSource()==mul||
ae.getSource()==div||ae.getSource()==mod||ae.getSource()==sqrt||
ae.getSource()==cbrt||ae.getSource()==sine)
String s;
s=t.getText();
float num1=0,num2=0,num3=0;
float n=Float.parseFloat(s);
push(n);
if(ae.getSource()==add)
a='+';
if(ae.getSource()==sub)
a='-';
if(ae.getSource()==mul)
a='*';
if(ae.getSource()==div)
a='/';
if(ae.getSource()==mod)
a='%';
t.setText("");
if(ae.getSource()==sqrt)
double num=pop();
t.setText(Double.toString(Math.sqrt(num)));
if(ae.getSource()==cbrt)
double num=pop();
t.setText(Double.toString(Math.cbrt(num)));
if(ae.getSource()==sine)
{
double num=pop();
t.setText(Double.toString(Math.sin(num)));
if(ae.getSource()==eq)
float num1=0,num2=0,num3=0,temp1;
String s=t.getText();
float n=Float.parseFloat(s);
push(n);
num1=pop();
num2=pop();
switch(a)
if(i==1)
{
t.setText(Float.toString(num3));
i=0;
else
t.setText(Integer.toString((int)num3));
temp=1;
if(ae.getSource()==dot)
i=1;
t.setText(t.getText()+".");
top++;
stk[top]=a;
float num=stk[top];
top--;
return(num);
}
t.setText("");
temp=0;
new Week9();
68.Write a java program that implements a simple client server application. The
client sends data to server. The server receives the data uses it to produce a result
and then sends the result back to the client then the client displays the result on the
console.
import java.io.*;
import java.net.*;
class Server
try
Socket s=ss.accept();
BufferedReader br;
PrintStream ps;
String str;
br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Received radius");
double r=Double.parseDouble(str);
double area=3.14*r*r;
ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(area));
br.close();
ps.close();
s.close();
ss.close();
catch(Exception e)
{
System.out.println(e);
//Client Program
import java.io.*;
import java.net.*;
class Client
{
Socket s=new Socket(InetAddress.getLocalHost(),1064);
BufferedReader br;
PrintStream ps;
String str;
ps=new PrintStream(s.getOutputStream());
ps.println(br.readLine());
br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Area of the circle is : "+str);
br.close();
ps.close();
69.Write a java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green with radio buttons. On selecting a
button, an appropriate message with “stop” or “ready” or “go” should appear above
the buttons in a selected color. Initially there is no message shown.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
String msg="";
Checkbox stop,ready,go;
CheckboxGroup cbg;
public void init()
add(stop);
add(ready);
add(go);
stop.addItemListener(this);
ready.addItemListener(this);
go.addItemListener(this);
repaint();
{
msg=cbg.getSelectedCheckbox().getLabel();
g.drawOval(165,40,50,50);
g.drawOval(165,100,50,50);
g.drawOval(165,160,50,50);
if(msg.equals("Stop"))
g.setColor(Color.red);
g.fillOval(165,40,50,50);
else if(msg.equals("Ready"))
g.setColor(Color.yellow);
g.fillOval(165,100,50,50);
else
g.setColor(Color.green);
g.fillOval(165,160,50,50);
}
}
70.Write a java program that connects to a database using JDBC and does add,
deletes, modify and retrieve operations?
ConnectionUtil.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtil
{
public static Connection getConnection() throws SQLException
{
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Connection");
connection = DriverManager.getConnection("jdbc:mysql://192.168.216.250:3306/vijju","root",
"root");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
System.out.println("message for connection open"+connection);
return connection;
}
}
StudentDetails.java
public class StudentDetails
{
private long st_id;
private String st_name;
private long st_mobile;
public StudentDetails(long st_id,String st_name,long st_mobile)
{
this.st_id = st_id;
this.st_name = st_name;
this.st_mobile = st_mobile;
}
public long getSt_id()
{
return st_id;
}
public void setSt_id(long st_id)
{
this.st_id = st_id;
}
public String getSt_name()
{
return st_name;
}
public void setSt_name(String st_name)
{
this.st_name = st_name;
}
public long getSt_mobile()
{
return st_mobile;
}
public void setSt_mobile(long st_mobile)
{
this.st_mobile = st_mobile;
}
}
Prog6.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Prog6
{
String createTableQuery = "create table test.student_details (st_namevarchar(50), st_mobile
numeric(10), st_id numeric(10))";
public static void main(String[] args)
{ Connection conn = null;
try
{
conn = ConnectionUtil.getConnection();
Prog6 prog6 = new Prog6();
System.out.println("Student_details table data before inserting:");
prog6.retrieveData(conn);
{
String query = "update student_details set st_mobile=? wherest_id=?";
try {
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setLong(1, st_mobile);
pstmt.setLong(2, st_id);
int row = pstmt.executeUpdate();
//System.out.println(row);
} catch (SQLException e)
{ e.printStackTrace();
}
}
private void deleteARow(Connection conn, long st_id)
{
String query = "delete from student_details where st_id=?" ;
try
{
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setLong(1, st_id);
int row = pstmt.executeUpdate();
//System.out.println(row);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void insertData(Connection conn, StudentDetails details)
{
String query = "insert into test.student_details values (?,?,?)";
try
{
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1,details.getSt_name());
pstmt.setLong(2, details.getSt_mobile());
pstmt.setLong(3, details.getSt_id());
int row = pstmt.executeUpdate();
//System.out.println(row);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
private void retrieveData(Connection conn)
{
try {
String query = "select * from test.student_details";
PreparedStatement pstmt = conn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
System.out.println("ST_ID\tST_NAME\t\tST_MOBILE");
while(rs.next())
{
System.out.println(rs.getString("st_id")+"\t"+rs.getString("st_name")+"\t\
t"+rs.getString( "st_mobile"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}