Java Lab Manual 2022-23
Java Lab Manual 2022-23
Java Lab Manual 2022-23
JAVA PROGRAMMING
LAB MANUAL
Subject Code: KG21CS407
Regulation: KG21
II B. TECH II SEMESTER
MISSION:
To offer undergraduate and post-graduate programs which are supported through industry
relevant curriculum and innovative teaching and learning processes that would help students succeed in
their professional careers.
To provide faculty and students with an ecosystem that fosters innovation, research,
entrepreneurship, and international exposure through strategic partnerships with government
organizations and collaboration with industries.
To provide holistic learning environment to students which will contribute to their personal and
professional growth and enable them to become leaders in their respective fields.
To contribute to the development of the region by using our technological expertise to work with
nearby communities and support them in their social and economic development.
\
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION:
To be recognized as a department of excellence by stimulating a learning environment in
which students and faculty will thrive and grow to achieve their professional, institutional and
societal goals.
MISSION:
To provide high quality technical education to students that will enable life-long learning and
build expertise in advanced technologies in Computer Science and Engineering.
To encourage professional development of students that will inculcate ethical values and
leadership skills through entrepreneurship while working with the community to address societal
issues.
PO II: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
PO V: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
PO VI: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
PO VII: Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge of and
need for sustainable development.
PO VIII: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO IX: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO XI: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in
a team, to manage projects and in multidisciplinary environments.
PO XII: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PROGRAM SPECIFIC OUTCOMES
PSO1: The Computer Science and Engineering graduates are able to analyze, design, develop,
test and apply management principles, mathematical foundations in the development of intelligent
systems with computational solutions, make them to expert in designing the secure application
and hardware prototype
PSO2: The graduating student will be analyze the contemporary research issues in different areas
of computer science & engineering and explore research gaps, analyze and carry out research in
the specialized/emerging areas.
PSO3: Develop their skills to solve problems in the broad area of programming concepts and
appraise environmental and social issues with ethics and manage different projects in multi-
disciplinary field to conducive in cultivating skills for successful career, entrepreneurship and
higher studies.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
1. To write programs using abstract classes for solving real world problemsusing java collection
framework.
Course Outcomes: Upon completion of this course, the students will beable to
CO2: Write Java application programs using OOP principles and properprogram structuring.
CO4: Write java programs for solving real world problems using javacollection framework.
Note:
1. Use LINUX and MySQL for the Lab Experiments. Though not mandatory,encourage the use
of Eclipse platform.
2. The list suggests the minimum program set. Hence, the concerned staffis requested to add
more problems to the list as needed.
List of Experiments:
1. Installation of Java software, study of any integrated development environment, Use Eclipse or
Net-bean platform and acquaint with the various menus. Create a test project, add a test class and
run it. See how you ca use auto suggestions, auto fill. Try code formatter and code refactoring like
renaming variables, methods an classes. Try debug step by step with java program to find prime
numbers between 1to n.
2. Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read
in a, b, c an use the quadratic formula
4. Write Java program on use of inheritance, preventing inheritance usingfinal, abstract classes.
5. Write a Java program to create an abstract class named Shape that contains two integers and
an empt method named print Area (). Provide three classes named Rectangle, Triangle, and
Circle such that each one o the classes extends the class Shape. Each one of the classes contains
only the method print Area () that prints th area of the given shape.
8. Write a Java program of currency converter (Dollar to INR, EURO to INR, Yen) using
Interfaces.
10. Write a Java program that creates a user interface to perform integer divisions. The user
enters tw numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is
displayed in the Result fiel when the Divide button is clicked. If Num1 or Num2 were not an
integer, the program would throw a Numbe Format Exception. If Num2 were Zero, the program
would throw an Arithmetic Exception. Display the exceptio in a message dialog box.
11. 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 ofthe number and prints. If the value is odd, the third thread will print thevalue of cube of
the number.
12. Write a Java program that correctly implements the producer – consumer problem using the
concept of inter thread communication.
13. Write a java program to split a given text file into n parts. Name each part as the name of the
original file followed by .part where n is the sequence number of the part file.
14. Write a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, orwritable, the type of file and the length of the
file in bytes.
15. Write a java program that connects to a database using JDBC and does add, delete, modify
and retrieve operations.
16. Write a java program that simulates a traffic light. The program lets theuser 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 selected color. Initially, there is
no message shown.
17. 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.
19. 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 exception likedivided by zero.
21. Develop an applet in Java that receives an integer in one text field, andcomputes its factorial
Value and returns it in another text field, when the button named “Compute” is clicked.
Reference Books:
4. Cay S. Horstmann and G Cornell, “Core Java, Volume 1”, Pearson, 9thedition.
1. Installation of Java software, study of any Integrated development
environment, Use Eclipse or Netbean platform and acquaint with the
various menus. Create a test project, add a test class and run it. See
how you can use auto suggestions, auto fill. Try code formatter and
code refactoring like renaming variables, methods and classes. Try
debug step by step with java program to find prime numbers between 1
to n.
AIM: Try debug step by step with java program to find prime numbers
between 1 ton.
SOURCE CODE:
Import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System. in); int i =0;
int num =0;
//Empty String
String primeNumbers = ""; System.out.println("Enter the value of n:"); int n
= scanner.nextInt();
scanner.close();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
1
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String primeNumbers = primeNumbers
+ i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
OUTPUT:
Enter the value of n:
150
Prime numbers from 1 to n are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89
97 101 103 107 109 113 127 131 137 139 149
2
2. 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
AIM: 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.
SOURCE CODE
import static java.lang.Math.*;
public class QuadraticEquationExample2
{
//defining a static method that finds the roots of the quadratic equation
static void calculateRoots(int a, int b, int c)
{
//comparing the value of a with 0, if a is 0 then the equation is not quadratic
if (a == 0)
{
System.out.println("The value of a cannot be 0.");
return;
}
//calculating discriminant (d)
int d = b * b - 4 * a * c;
double sqrtval = sqrt(abs(d));
if (d > 0)
{
System.out.println("The roots of the equation are real and different. \n");
System.out.println((double)(-b + sqrtval) / (2 * a) + "\n"+ (double)(-b -
sqrtval) / (2 * a));
}
else if (d == 0)
{
System.out.println("The roots of the equation are real and same. \n");
3
System.out.println(-(double)b / (2 * a) + "\n"+ -(double)b / (2 * a));
}
// executes if d < 0
else
{
System.out.println("The roots of the equation are complex and different. \n")
;System.out.println(-(double)b / (2 * a) + " + i"+ sqrtval + "\n"+ -
(double)b / (2 * a)+ " i" + sqrtval);
} }
//main method
public static void main(String args[])
{
//Output 1
int a = 1, b = 5, c = 2;
//calling function
calculateRoots(a, b, c);
//Output 2: int a=1, b=1, c=1
//Output 3: int a=1, b=-2, c=1
}
}
Output 1:
Output 2:
Output 3:
4
3. Write a Java program to multiply two given matrices
AIM: To multiply two given matrices
SOURCE CODE:
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
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
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
} }}
5
Output:
666
12 12 12
18 18 18
4. Write Java program on use of inheritance, preventing inheritance
usingfinal, abstract classes
AIM: Java program on use of inheritance, preventing inheritance using
final, abstract classes
SOURCE CODE:
Use of Inheritance:
class Employee{ float salary=40000;
}
class Programmer extends Employee{ int bonus=10000;
public static void main(String args[]){ Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
OUTPUT: Programmer salary is: 40000.0Bonus of programmer is: 10000
Preventing inheritance:
final class Bike{}
class Honda1 extends Bike{ void run(){
System.out.println("running safely with 100kmph");}
public static void main(String args[]){ Honda1 honda= new Honda1();
honda.run();
}
}
Output: running safely with 100kmph
Abstract Classes:
abstract class Shape{ abstract void draw();
6
}
class Rectangle extends Shape{ void draw(){
System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{ void draw(){
System.out.println("drawing circle");}
}
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through
method, e.g., getShape() method
s.draw();
}
Output: drawing circle
7
5. Write a Java program to create an abstract class named Shape
that contains two integers and an empty method named print Area
(). Provide three classes named Rectangle, Triangle, and Circle such
that each one of the classes extends the class Shape. Each one of the
classes contains only the method print Area () that prints the area of
the given shape.
SOURCE CODE:
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
8
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);
}
}
Output:
Area of rectangle is :10.0
Area of circle is :78.5
Area of triangle is :5.0
9
6. Write a java program to implement method overloading and
constructors overloading.
SOURCE CODE:
11
7. Write a java program to implement method overriding.
AIM: To implement method overriding.
SOURCE CODE:
12
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
13
8. Write a Java program of currency converter (Dollar to INR, EURO
to INR, Yen) using Interfaces
AIM: a java application to implement currency converter (Dollar to INR,
EURO to INR, Yen) using Interfaces.
SOURCE CODE:
16
Converter.java
import ConversionDemo.CurrencyConverter; import
ConversionDemo.DistanceConverter; import ConversionDemo.TimeConverter;
import java.util.Scanner;
class Converter
{
public static void main(String[] args) throws NoClassDefFoundError
{
double CurrentExchange; int
choice,choice1,choice2,choice3; double inr;
double km; double hr; char ans='y'; do
{
System.out.println("\n Main Menu"); System.out.println("1.Currency Converter
\n2.Distance
Converter \n3. Time Converter");
System.out.println("Enter your choice: "); Scanner input = new Scanner(System.in);
choice = input.nextInt(); switch(choice)//outer Switch
{
case 1:System.out.println("\tCurrency Conversion");
do
{System.out.println("Menu For Currency Conversion"); System.out.println("1. Dollar
to INR"); System.out.println("2. INR to Dollar"); System.out.println("3. Euro to INR");
System.out.println("4. INR to Euro"); System.out.println("5. Yen to INR");
System.out.println("6. INR to Yen");
System.out.println("Enter your choice: "); choice1 = input.nextInt();
System.out.println("Please enter the current exchange rate: "); CurrentExchange =
input.nextDouble(); CurrencyConverter cc=new CurrencyConverter(CurrentExchange);
switch(choice1)//inner switch
{
case 1:
System.out.print("Enter Dollars
:"); double dollar=input.nextDouble();
System.out.println (dollar+" dollars are converted to
"+cc.DollarToINR(dollar)+" Rs.");
break; case 2:
System.out.print("Enter INR
:"); inr=input.nextDouble();
System.out.println(inr+" Rs. are converted to
17
"+cc.INRToDollar(inr)+" Dollars");
break; case 3:
System.out.print("Enter Euro
:"); double euro=input.nextDouble();
System.out.println(euro+" Euros are converted to
"+cc.EuroToINR(euro)+" Rs.");
break; case 4:
System.out.print("Enter INR
:"); inr=input.nextDouble();
System.out.println(inr+" Rs. are converted to
"+cc.INRToEuro(inr)+" Euros");
break; case 5:
System.out.print("Enter Yen
:"); double yen=input.nextDouble();
System.out.println(yen+" Yens are converted to"+cc.YenToINR(yen)+" Rs.");
break; case 6:
System.out.print("Enter INR
:"); inr=input.nextDouble();
System.out.println(inr+" Rs. are converted to
"+cc.INRToYen(inr)+" Yens");
break;
}
System.out.println("Do You want to go to Currency Conversion Menu?(y/n)
"); ans = input.next().charAt(0);
}while(ans==' y'); break;
case 2:System.out.println("\tDistance Conversion"); do
{
System.out.println("Menu For Distance Conversion"); System.out.println("1. Meter to
Km"); System.out.println("2. Km to Meter"); System.out.println("3. Miles to Km");
System.out.println("4. Km to Miles");
System.out.println("Enter your choice: "); choice2 = input.nextInt(); DistanceConverter
dc=new DistanceConverter(); switch(choice2)
{
case 1:
System.out.print("Enter meters to convert to Km:"); double meter=input.nextDouble();
System.out.println(meter+" Meters are converted to
"+dc.MeterToKM(meter)+" Km.");
break; case 2:
18
System.out.print("Enter Km to convert to meters:"); km=input.nextDouble();
System.out.println(km+" Km. are converted meters"+dc.KMToMeter(km)+" Meters");
break; case 3:
System.out.print("Enter Miles to convert to Km:"); double miles=input.nextDouble();
System.out.println(miles+" Miles are converted to
"+dc.MileToKM(miles)+" Km.");
break; case 4:
System.out.print("Enter Km to convert to miles:"); km=input.nextDouble();
System.out.println(km+"Km.areconverted miles"+dc.KMToMile(km)+" Miles");
break;
}
System.out.println("Do You want to go to Distance Conversion Menu?(y/n)
"); ans = input.next().charAt(0);
}while(ans==' y'); break;
case 3:System.out.println("\tTime Conversion"); do
{
System.out.println("Menu For Time Conversion"); System.out.println("1. Hour to
Minutes"); System.out.println("2. Minutes to Hour"); System.out.println("3. Hour to
Seconds"); System.out.println("4. Seconds to Hour"); System.out.println("Enter your
choice: ");
choice3 = input.nextInt();
TimeConverter tc=new TimeConverter(); switch(choice3)
{
case 1:
System.out.print("Enter hours to convert to Minutes:"); hr=input.nextDouble();
System.out.println(hr+" Hours are converted to"+tc.HrToMin(hr)+" min.");
break; case 2:
System.out.print("Enter Minutes to convert to hours:");
double minutes=input.nextDouble();
System.out.println(minutes+" Minutes. are converted
hours"+tc.MinToHour(minutes)+" Hours");
break; case 3:
System.out.print("Enter Hours to convert to Seconds:"); hr=input.nextDouble();
System.out.println(hr+" Hours are converted to"+tc.HrToSec(hr)+" Seconds.");
break;
case 4:
System.out.print("Enter Seconds to convert to hours:");
double seconds=input.nextDouble();
19
System.out.println(seconds+" Seconds. are converted hours"+tc.SecToHour(seconds)+"
Hours");
break;
}
System.out.println("Do You want to go to Time Conversion Menu?(y/n) ");
ans = input.next().charAt(0);
}while(ans==' y'); break;
}//end of outer switch
System.out.println("Do you want to go back to Main Menu?(y/n)");
ans=input.next().charAt(0);
}while(ans=='y');
}//end of main
}//end of class
Step 3 :
Open the Command prompt and issue following commands
Output
D:\>cd ConversionDemo D:\ConversionDemo>javac CurrencyConverter.java
D:\ConversionDemo>javac DistanceConverter.java D:\ConversionDemo>javac
TimeConverter.java D:\ConversionDemo>cd.. D:\>javac
Converter.java D:\>java Converter Main Menu 1.Currency Converter 2.Distance
Converter
3. Time
Converter Enter your choice: 1
Currency Conversion Menu For Currency Conversion
1. Dollar to INR
2. INR to Dollar
3. Euro to INR
4. INR to Euro
5. Yen to INR
6. INR to Yen Enter your choice:
1
21
9. Write a Java program to implement user defined exception handling.
AIM: Java program to implement user defined Exception handling. Source code:
SOURCE CODE:
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
Output: hi this is my catch block Output string=custom
23
10. Write a Java program that creates a user interface to perform integer
divisions. The user enters two numbers in the text fields, Num1 and Num2.
The division of Num1 and Num 2 is displayed in the Result field when the
Divide button is clicked. If Num1 or Num2 were not an integer, the program
would throw a Number Format Exception. If Num2 were Zero, the program
would throw an Arithmetic Exception. Display the exception in a message
dialog box.
AIM: a Java program that creates a user interface to perform integer division. The
user enters two numbers in the text fields, Num1 and Num2. The division of Num1
and Num2 is displayed in the Result field when the Divide button is clicked. If Num1
and Num2 were not integers, the program would throw a Number Format Exception. If
Num2 were zero, the program would throw an Arithmetic Exception Display the
exception in a message dialogbox.
SOURCE CODE:
{
e=this;
24
t1=new TextField(10); t2=new TextField(10); t3=new TextField(10); L1=new
Label("enter num1"); L2=new Label("enter num2"); L3=new Label("Result is");
add(L4);
add(L1);
add(t1);
add(L2);
add(t2);
add(L3);
add(t3);
add(b); b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
try
catch(ArithmeticException a)
{
JOptionPane.showMessageDialog(null,"Divide by zero");
}
25
catch(NumberFormatException b)
JOptionPane.showMessageDialog(null,"NumberFormateException");
}
}
}
OUTPUT:
GOOD MORNING
26
11. 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 thevalue of cube of the number
AIM: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 thevalue of cube of the number.
SOURCE CODE:
import java.util.*;// class for Even Numberclass EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a *
a);
} } // class for Odd Numberclass OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a *
a);
}}// class to generate random numberclass RandomNumGenerator extends Thread {
27
public void run() {
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++) {
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else {
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
// thread wait for 1 second
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
} }// Driver classpublic class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start(); }}
Output:
28
12. Write a Java program that correctly implements the producer – consumer
problem using the concept of inter thread communication.
AIM: a Java program that correctly implements producer consumer problem using the
concept of inter thread communication.
SOURCE CODE:
class Q
{
int n; booleanvalueSet=false;synchronizedint get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
29
}
System.out.println("Got:"+n); valueSet=false;
notify();return n;
}
{
if(valueSet)try
{
wait();
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n; valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
inti=0; while(true)
{
30
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
31
}
public void run()
{
while(true)
{
q.get();
}
}}
classProdCons
{
public static void main(String[] args)
{
Q q=new Q(); new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
Output:
Put:1 Got:1 Put:2 Got:2 Put:3 Got:3 Put:4 Got:4 Put:5 Got:5
Put:6 Got:6 Put:7 Got:7 Put:8 Got:8 Put:9 Got:9 Put:10 Got:10 Put:11 Got:11 Put:12
Got:12 Put:13 Got:13 Put:14 Got:14
32
13. Write a java program to split a given text file into n parts. Name each part
as the name of the original file followed by .part where n is the sequence
number of the part file.
AIM: a java program to split a given text file into n parts. Name each part as the name
of the original file followed by .part where n is the sequence number of the part file.
SOURCE CODE:
34
if(f.canWrite())
System.out.println("The file " +file_name+ " is writeable"); else
System.out.println("The file " +file_name+ " is not writeable");
System.out.println("The file type is: "
+file_name.substring(file_name.indexOf('.')+1));
System.out.println("The Length of the file:" +f.length());
}
}
}
35
15. Write a java program that connects to a database using JDBC and does
add, delete, modify and retrieve operations
AIM: Java program that connects to a database using JDBC and does add, delete,
modify and retrieve operations.
SOURCE CODE:
36
//Implementing Insert Statement
import java.sql.*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "geeks for geeks";
String email = "[email protected]";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output-
Successfully Registered
37
//Implementing Update Statement
import java.sql.*;
public class update1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String newPwd = "newpwd";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Updating database
String q1 = "UPDATE userid set pwd = '" + newPwd +
"' WHERE id = '" +id+ "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Password Successfully Updated");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output-
Password Successfully Updated
38
//Implementing Delete Statement
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output-
One User Successfully Deleted
39
//Implementing Select Statement
import java.sql.*;
public class select
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
String q1 = "select * from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
ResultSet rs = stmt.executeQuery(q1);
if (rs.next())
{
System.out.println("User-Id : " + rs.getString(1));
System.out.println("Full Name :" + rs.getString(3));
System.out.println("E-mail :" + rs.getString(4));
}
else
{
System.out.println("No such user id is already registered");
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
40
}
Output-
User-Id: id1
Full Name: Dataflair
16. 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 selected color. Initially, there is no message
shown.
AIM: Develop a Java application 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 ǁo rǁ GO ǁshould appear above
the buttons in selected color.Initially, there is no message show.
SOURCE CODE:
import java.awt.event.*;
* </applet>
* */
redLight.addItemListener(this);
41
yellowLight.addItemListener(this);
greenLight.addItemListener(this);
add(redLight);
add(yellowLight);
add(greenLight);
add(msg);
redLight.setForeground(Color.RED);
msg.setForeground(Color.RED);
msg.setText("STOP");
else{
greenLight.setForeground(Color.GREEN);
msg.setForeground(Color.GREEN); msg.setText("GO");
}}}
42
OUTPUT:
43
17. 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.
AIM: Develop a Java application that handles all mouse events and shows the event
name at the center of the window when a mouse event is fired. Use adapterclasses.
SOURCE CODE:
45
18. Write a java program to demonstrate the key event handlers
AIM: Develop a Java application to demonstrate the key event handlers.
SOURCE CODE:
import java.awt.*; import java.awt.event.*; import java.applet.*; import java.applet.*;
import java.awt.event.*; import java.awt.*;
public class Test extends Applet implements KeyListener
{
String msg=""; public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
46
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar(); repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
HTML code:
<applet code="Test" width=300, height=100>
</applet>
Output:
47
19. 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 exception likedivided by zero
AIM: 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 exception likedivided by zero
SOURCE CODE:
Import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200>
</applet>
public class Calculator extends JApplet
{
public void init()
{
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}
class CalculatorPanel extends JPanel implements ActionListener
{
JButton n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45);
static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,
secVal=0,res;
private static void assign(String no)
{
if((result.getText()).equals("0")
) result.setText(no);
else if(lastCommand=="=")
{
result.setText(no); lastCommand=null;
}
48
else
result.setText(result.getText()+no);
}
public CalculatorPanel()
{
setLayout(new BorderLayout())
; result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));
n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);
n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6); n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);
n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
49
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTE R);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1"); else if(ae.getSource()==n2) assign("2");
else
if(ae.getSource()==n3) assign("3"); else if(ae.getSource()==n4) assign("4");
else
if(ae.getSource()==n5) assign("5"); else if(ae.getSource()==n6) assign("6");
else
if(ae.getSource()==n7) assign("7"); else if(ae.getSource()==n8) assign("8");
else
50
if(ae.getSource()==n9) assign("9"); else if(ae.getSource()==n0) assign("0");
else
if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText ()); lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText()); lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText()); if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*")) res=preRes*secVal;
else if(lastCommand.equals("- ")) res=preRes-secVal;
else if(lastCommand.equals("+")) res=preRes+secVal;
result.setText(" "+res); lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText()); lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText()); lastCommand="+";
result.setText("0");
}
51
}
}
OUTPUT:
52
20. Develop an applet in Java that displays a simple message
import java.awt.*;
import java.applet.*;
/*
<applet code="Demo" width=300 height=200>
</applet>
*/
public class Demo extends Applet {
public void paint(Graphics g) {
g.drawString("Welcome to Goeduhub Technologies", 20, 20);
}
}
Output
53
21. Develop an applet in Java that receives an integer in one text field,
and computes its factorial Value and returns it in another text field,
when the button named “Compute” is clicked.
AIM: An applet in Java that receives an integer in one text field, and
computes its factorial Value and returns it in another text field, when the
button named “Compute” is clicked.
SOURCE CODE:
54
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n) {
if(n==0)
return 1;
else
return n*factorial(n-1);
}}
Output:
55