java programming lab
TRANSCRIPT
-
8/4/2019 Java Programming Lab
1/44
SONA COLLEGE OF TECHNLOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
JAVA PROGRAMMING LAB MANUAL
-
8/4/2019 Java Programming Lab
2/44
ABSTRACT CLASSES
PROGRAM
import java.io.*;
abstract class AreaMethods {
abstract void rect(int l,int b);
abstract void sqr(int a);
abstract void tri(int ba,int h);
}
class Area extends AreaMethods {
void rect(int l,int b) {
System.out.println("Area of the Rectangle : "+(l*b));
}
void sqr(int a) {
System.out.println("Area of the Square : "+(a*a));
}void tri(int ba,int h) {
System.out.println("Area of the Triangle : "+(0.5*ba*h));
}
}
class AbstractDemo {
public static void main(String args[]) throws Exception {
int l,b,a,ba,h;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the length of the Rectangle:");
l=Integer.parseInt(br.readLine());
System.out.println("Enter the breadth of the Rectangle:");
b=Integer.parseInt(br.readLine());
System.out.println("Enter the side of the Square:");
-
8/4/2019 Java Programming Lab
3/44
a=Integer.parseInt(br.readLine());
System.out.println("Enter the base of the Triangle:");
ba=Integer.parseInt(br.readLine());
System.out.println("Enter the height of the Triangle:");
h=Integer.parseInt(br.readLine());
Area obj=new Area();
obj.rect(l,b);
obj.sqr(a);
obj.tri(ba,h);
}
}
OUTPUT
Z:\cs2k944> javac AbstractDemo.java
Z:\cs2k944> java AbstractDemo
Enter the length of the Rectangle:
4
Enter the breadth of the Rectangle:
3
Enter the side of the Square:
4
Enter the base of the Triangle:
5
Enter the height of the Triangle:
6
Area of the Rectangle : 12
Area of the Square : 16
Area of the Triangle : 15.0
-
8/4/2019 Java Programming Lab
4/44
INHERITANCE
PROGRAM
abstract class Worker {
String name;
double rate;
Worker(String n, double r) {
name = n;
rate = r;
}
double getRate() {
return rate;
}
abstract double computePay(int hours);
}
class HourlyWorker extends Worker {
double pay;
HourlyWorker(String n, double r) {super(n, r);
}
double computePay(int hours)
{
if(hours 40)
pay = (getRate()*40) + (getRate() * (hours - 40) / 2);
return pay;
}
}
class SalariedWorker extends Worker {
SalariedWorker(String n, double r) {
-
8/4/2019 Java Programming Lab
5/44
super(n, r);
}
double computePay(int hours) {
return getRate() * 40;
}
}
class WorkerTester {
public static void main(String[] args) {
SalariedWorker s = new SalariedWorker("Sally", 40);
HourlyWorker h = new HourlyWorker("Harry", 40);
System.out.println(s.computePay(30));
System.out.println(h.computePay(30));
System.out.println(s.computePay(50));
System.out.println(h.computePay(50));
}
}
OUTPUT
Z:\cs2k940> javac WorkerTester.javaZ:\cs2k940> java WorkerTester
1600.0
1200.0
1600.0
1800.0
-
8/4/2019 Java Programming Lab
6/44
INTERFACES
PROGRAM
1. Write a java program using interface to find the GCD & LCM of two numbers.
import java.io.*;
interface GLInterface {
int getGCD(int a,int b);
int getLCM(int a,int b);
}
class GLClass implements GLInterface {
public int getGCD(int a,int b) {
if(b==0)
return a;
else
return getGCD(b,a%b);}
public int getLCM(int a,int b) {
return((a*b)/getGCD(a,b));
}
}
class GL {
public static void main(String args[]) throws Exception {
int a,b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
GLClass obj=new GLClass();
System.out.println("Enter the first number:");
a=Integer.parseInt(br.readLine());
System.out.println("Enter the second number:");
-
8/4/2019 Java Programming Lab
7/44
b=Integer.parseInt(br.readLine());
System.out.println("GCD = "+obj.getGCD(a,b));
System.out.println("LCM = "+obj.getLCM(a,b));
}
}
OUTPUT
Z:\cs2k944> javac GL.java
Z:\cs2k944> java GL
Enter the first number:
24Enter the second number:
12
GCD = 12
LCM = 24
2. Write the java program using interface to do the following
a) Binary to Decimalb) Decimal to Binaryc) Twos Complement of a Binary numberd) Addition of two Binary numbers
import java.io.*;
interface BinaryInterface {
int toDecimal(String binary);
String toBinary(int decimal);
String twosComplement(String binary);
String binaryAdd(String binary1,String binary2);
}
-
8/4/2019 Java Programming Lab
8/44
class BinaryClass implements BinaryInterface {
public int toDecimal(String binary) {
return(Integer.parseInt(binary,2));
}
public String toBinary(int decimal) {
return(Integer.toBinaryString(decimal));
}
public String binaryAdd(String binary1,String binary2) {
return(Integer.toBinaryString(Integer.parseInt(binary1,2)+Integer.parseInt(binary2,2)));
}
public String twosComplement(String binary) {
int i=Integer.parseInt(binary,2);
int j=~i+1;
return(Integer.toBinaryString(j));
}
}
class Binary {
public static void main(String args[]) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BinaryClass bc=new BinaryClass();
System.out.println("BINARY TO DECIMAL");
System.out.println("Enter the binary number:");
System.out.println("Binary-->Decimal = "+bc.toDecimal(br.readLine()));
System.out.println("DECIMAL TO BINARY");
System.out.println("Enter the decimal number:");
System.out.println("Decimal-->Binary = " + bc.toBinary (Integer.parseInt(br.readLine())));
System.out.println("TWO'S COMPLEMENT");
System.out.println("Enter the binary number:");
System.out.println("Two's Complement = "+bc.twosComplement(br.readLine()));
System.out.println("ADDITION OF TWO BINARY NUMBERS");
System.out.println("Enter two binary numbers:");
-
8/4/2019 Java Programming Lab
9/44
System.out.println("Addition Result = " + bc.binaryAdd (br.readLine() ,
br.readLine()));
}
}
OUTPUT
Z:\cs2k944> javac Binary.java
Z:\cs2k944> java Binary
BINARY TO DECIMAL
Enter the binary number:
0101
Binary-->Decimal = 5
DECIMAL TO BINARY
Enter the decimal number:
15
Decimal-->Binary = 1111
TWO'S COMPLEMENT
Enter the binary number:
0001
Two's Complement = 11111111111111111111111111111111ADDITION OF TWO BINARY NUMBERS
Enter two binary numbers:
0101
0010
Addition Result = 111
3. Write a java program using interface to implement Queue
import java.io.*;
interface QueueInterface {
void insert(int item);
void delete();
-
8/4/2019 Java Programming Lab
10/44
void display();
}
class QueueClass implements QueueInterface {
int size=5;
int que[];
int rear,front;
QueueClass() {
que=new int[size];
rear=0;
front=0;
}
public void insert(int x) {
if(rear>=size)
System.out.println("QUEUE IS FULL");
else {
que[rear]=x;
rear++;
System.out.println("Element Inserted");
}}
public void delete() {
if(front==rear)
System.out.println("QUEUE IS EMPTY");
else {
front++;
System.out.println("Element Deleted");
}
}
public void display() {
if(front==rear)
System.out.println("QUEUE IS EMPTY");
else {
-
8/4/2019 Java Programming Lab
11/44
System.out.println("Elements in the Queue are");
for(int i=front;i
-
8/4/2019 Java Programming Lab
12/44
System.exit(0);
default:
System.out.println("Wrong Choice!!!");
}
}while(true);
}
}
OUTPUT
Z:\cs2k944> javac Queue.java
Z:\cs2k944> java Queue
MENU
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue
4. Exit
Enter the choice:
1
Enter the element to be inserted:5
Element Inserted
MENU
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue
4. Exit
Enter the choice:
1
Enter the element to be inserted:
4
Element Inserted
MENU
-
8/4/2019 Java Programming Lab
13/44
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue
4. Exit
Enter the choice:
3
Elements in the Queue are
5 4
MENU
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue
4. Exit
Enter the choice:
2
Element Deleted
MENU
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue4. Exit
Enter the choice:
2
Element Deleted
MENU
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue
4. Exit
Enter the choice:
2
QUEUE IS EMPTY
-
8/4/2019 Java Programming Lab
14/44
MENU
1. Insert into the Queue
2. Delete from the Queue
3. Display Queue
4. Exit
Enter the choice:
4
-
8/4/2019 Java Programming Lab
15/44
EVENT HANDLING USING APPLETS
PROGRAM
1. Design an Applet program to perform MouseEvent.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
*/
public class MouseEventDemo extends Applet implements
MouseListener,MouseMotionListener {
String msg="";
public void init() {
setFont(new Font("Arial",Font.BOLD,18));
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e) {
msg="Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent e) {
msg="Mouse Entered";repaint();
}
public void mouseExited(MouseEvent e) {
msg="Mouse Exited";
repaint();
-
8/4/2019 Java Programming Lab
16/44
}
public void mousePressed(MouseEvent e) {
msg="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
msg="Mouse Released";
repaint();
}
public void mouseDragged(MouseEvent e) {
msg="Mouse Dragged";
repaint();
}
public void mouseMoved(MouseEvent e) {
msg="Mouse Moved";
repaint();
}
public void paint(Graphics g) {
g.drawString(msg,120,150);
}}
OUTPUT
Z:\cs2k944> javac MouseEventDemo.java
Z:\cs2k944> AppletViewer MouseEventDemo.java
-
8/4/2019 Java Programming Lab
17/44
2. Design an Applet program to perform Arithmetic Calculations.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
*/
public class Calculation extends Applet implements ActionListener {
TextField t1,t2;
Label l1,l2,l3,l4;
Button add,sub,mul,div,mod;
double res;
int res1;
public void init() {
setFont(new Font("Arial",Font.BOLD,20));
l1=new Label("Enter 1st Operand: ");
l2=new Label("Enter 2nd Operand: ");
t1=new TextField(25);t2=new TextField(25);
l3=new Label("Result: ");
l4=new Label(" ");
add=new Button("Addition");
sub=new Button("Subtraction");
mul=new Button("Multiplication");
div=new Button("Division");
mod=new Button("Modulus");
add(l1);
add(t1);
add(l2);
add(t2);
add(add);
-
8/4/2019 Java Programming Lab
18/44
add(sub);
add(mul);
add(div);
add(mod);
add(l3);
add(l4);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String x=ae.getActionCommand();
if(x.equals("Addition")) {
res=(Double.parseDouble(t1.getText()))+(Double.parseDouble(t2.getText()));
l4.setText(""+res);
}
if(x.equals("Subtraction")) {
res=(Double.parseDouble(t1.getText()))-(Double.parseDouble(t2.getText()));
l4.setText(""+res);
}
if(x.equals("Multiplication")) {
res=(Double.parseDouble(t1.getText()))*(Double.parseDouble(t2.getText()));
l4.setText(""+res);
}
if(x.equals("Division")) {
res=(Double.parseDouble(t1.getText()))/(Double.parseDouble(t2.getText()));
l4.setText(""+res);
}
-
8/4/2019 Java Programming Lab
19/44
if(x.equals("Modulus")) {
res1=(Integer.parseInt(t1.getText()))%(Integer.parseInt(t2.getText()));
l4.setText(""+res1);
}
}
}
OUTPUT
Z:\cs2k944> javac Calculation.java
Z:\cs2k944> AppletViewer Calculation.java
3. Design an Applet program to find Fibonacci Series and Factorial of a number.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
*/
public class Fibo_Fact extends Applet implements ActionListener {
Label l1;
-
8/4/2019 Java Programming Lab
20/44
TextField t1;
Button fact,fibo;
int fac,fibo1,fibo2,fibon,n;
String msg;
public void init() {
setFont(new Font("Arial",Font.BOLD,20));
msg="";
l1=new Label("Enter the number:");
t1=new TextField(10);
fact=new Button("Factorial");
fibo=new Button("Fibonacci");
add(l1);
add(t1);
add(fact);
add(fibo);
fact.addActionListener(this);
fibo.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {Object x=ae.getSource();
if(x==fact) {
msg="";
fac=1;
int n=Integer.parseInt(t1.getText());
for(int i=1;i
-
8/4/2019 Java Programming Lab
21/44
fibo1=0;
fibo2=1;
for(int i=0;i javac Fibo_Fact.java
Z:\cs2k944> AppletViewer Fibo_Fact.java
-
8/4/2019 Java Programming Lab
22/44
THREADS ( SINGLE AND MULTIPLE )
PROGRAM
1. Write a program WordCount that counts the words in one or more files. Start a
new thread for each file.
import java.io.*;
class FileThread implements Runnable {
String Filename;String name;
Thread t;FileThread(String tname) {
Filename=tname;name=tname;
t=new Thread(this,name);t.start();
}public void wordCount() {
try
{ StreamTokenizer input=new StreamTokenizer(newFileReader(Filename));
int tok=0;int count=0;
while((tok=input.nextToken())!= StreamTokenizer.TT_EOF)if(tok == StreamTokenizer.TT_WORD)
count++;System.out.println(Filename+": "+count);
}catch(IOException e) {}
}public void run() {
wordCount();}
}
class FileWordCounter {public static void main(String args[]) {
-
8/4/2019 Java Programming Lab
23/44
if(args.length ==0) {
System.out.println("Give the File Name in the Command Line...");
System.exit(0);}
else {
for(int i=0;i javac FileWordCounter.java
Z:\cs2k944> java FileWordCounter City.txt Subject.txt Project.txt
City.txt: 3
Subject.txt: 11
Project.txt: 11
-
8/4/2019 Java Programming Lab
24/44
2. Write a java program that creates three threads. First thread displays Good
Morning every one second, the second thread displays Hello every two seconds
and the third thread displays Welcome every three seconds.
class MultiThreadClass implements Runnable {String name;
Thread t;int sec;
MultiThreadClass(String threadname,int millisec) {
name = threadname;sec=millisec;
t = new Thread(this, name);t.start();
}
public void run() {try{
for(int i=5;i>0;i--){
System.out.println(name);Thread.sleep(sec);
}}
catch(InterruptedException e){}
}}
class MultiThreadDisplay
{public static void main(String args[]) throws Exception
{new MultiThreadClass("Good Morning",1000);
new MultiThreadClass("Hello",2000);new MultiThreadClass("Welcome",3000);
Thread.sleep(10000);}
}
-
8/4/2019 Java Programming Lab
25/44
OUTPUT
Z:\cs2k944> javac MultiThreadDisplay.java
Z:\cs2k944> java MultiThreadDisplay
Good Morning
Hello
Welcome
Good Morning
Hello
Good Morning
Welcome
Good Morning
Hello
Good Morning
Hello
Welcome
Hello
Welcome
Welcome
3. Write a java program that correctly implements producer consumer problem
using the concept of inter thread communication.
class Consumer implements Runnable {
Stock c;
Thread t;
Consumer(Stock c) {
this.c=c;
t=new Thread(this,"Consumer Thread");
t.start();
}
public void run() {
while(true) {
-
8/4/2019 Java Programming Lab
26/44
try
{
t.sleep(750);
}catch(InterruptedException e) {}
c.getStock((int) (Math.random()*20));
}
}
void stop() {
t.stop();
}
}
class Producer implements Runnable {
Stock s;
Thread t;
Producer(Stock s) {
this.s=s;
t=new Thread(this,"Producer Thread");
t.start();
}
public void run() {while(true) {
try
{
t.sleep(750);
}catch(InterruptedException e) {}
s.addStock((int)(Math.random()*20));
}
}
void stop() {
t.stop();
}
}
-
8/4/2019 Java Programming Lab
27/44
public class Stock {
int goods=0;
public synchronized void addStock(int i) {
if((goods+i)=j) {
goods-=j;
System.out.println("\nRequested Stock -> "+j);
System.out.println("STOCK TAKEN AWAY :"+j);
System.out.println("Present Stock :"+goods);
break;}
else {
System.out.println("\nRequested Stock -> "+j);
System.out.println("Stock Not Enough...");
System.out.println("Waiting For Stock To Come...");
try
{ wait();
}catch(InterruptedException e) {}
}
}
return goods;
}
-
8/4/2019 Java Programming Lab
28/44
public static void main(String args[]) {
Stock j=new Stock();
Producer p=new Producer(j);
Consumer c=new Consumer(j);
try
{
Thread.sleep(5000);
p.stop();
c.stop();
p.t.join();
c.t.join();
System.out.println("THREAD STOPPED");
}catch(InterruptedException e) {}
System.exit(0);
}
}
OUTPUT
Z:\cs2k944> javac Stock.java
Z:\cs2k944> java Stock
STOCK ADDED :17
Present Stock :17
Requested Stock -> 4
STOCK TAKEN AWAY :4
Present Stock :13
STOCK ADDED :7
Present Stock :20
Requested Stock -> 13
-
8/4/2019 Java Programming Lab
29/44
STOCK TAKEN AWAY :13
Present Stock :7
STOCK ADDED :12
Present Stock :19
Requested Stock -> 18
STOCK TAKEN AWAY :18
Present Stock :1
STOCK ADDED :14
Present Stock :15
Requested Stock -> 15
STOCK TAKEN AWAY :15
Present Stock :0
STOCK ADDED :18
Present Stock :18
Requested Stock -> 7
STOCK TAKEN AWAY :7
Present Stock :11
Stock cannot be added since it exceeds the limits
Requested Stock -> 7
STOCK TAKEN AWAY :7
Present Stock :4
THREAD STOPPED
-
8/4/2019 Java Programming Lab
30/44
SWINGS
PROGRAM
1. Write a program to plot the string HELLO, using only lines and circles. Do not
call drawstring, and do not use System.out. Make classes LetterH, LetterE, LetterL,
and LetterO.
import java.awt.*;
import javax.swing.*;
class LetterH extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.
VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8));
g2d.drawLine(10,10,10,50);
g2d.drawLine(10,27,40,27);
g2d.drawLine(40,10,40,50);
}}
class LetterE extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.
VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8));
g2d.drawLine(10,10,10,50);g2d.drawLine(10,10,40,10);
g2d.drawLine(10,27,40,27);
g2d.drawLine(10,50,40,50);
}
}
-
8/4/2019 Java Programming Lab
31/44
class LetterL extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.
VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8));
g2d.drawLine(10,10,10,50);
g2d.drawLine(10,50,40,50);
}
}
class LetterO extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.
VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8));
g2d.drawOval(10,10,40,40);
}
}
class Hello {
public static void main(String args[]) {
JFrame f=new JFrame("Hello Frame");
f.setLayout(new GridLayout(1,5));
f.add(new LetterH());
f.add(new LetterE());
f.add(new LetterL());
f.add(new LetterL());
f.add(new LetterO());
f.setVisible(true);
f.setSize(300,100);
f.setLocation(100,100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
-
8/4/2019 Java Programming Lab
32/44
OUTPUT
Z:\cs2k944> javac Hello.java
Z:\cs2k944> java Hello
2. Write a program that displays the Olympic rings. Color the rings in the Olympic
colors. Provide a class OlympicRing and a class OlympicRingsTest.
import java.awt.*;
import javax.swing.*;
class OlympicRings extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d=(Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(8));
g2d.setFont(new Font("Arial",Font.BOLD,30));
g2d.drawString("OLYMPIC RINGS",140,100);
g2d.setColor(Color.blue);
g2d.drawOval(100,200,100,100);
g2d.setColor(Color.black);
g2d.drawOval(208,200,100,100);g2d.setColor(Color.red);
g2d.drawOval(316,200,100,100);
g2d.setColor(Color.yellow);
g2d.drawOval(150,250,100,100);
g2d.setColor(Color.green);
-
8/4/2019 Java Programming Lab
33/44
g2d.drawOval(258,250,100,100);
}
}
class OlympicRingsTest {
public static void main(String args[]) {
JFrame f=new JFrame("Olympic Rings");
f.setVisible(true);
f.setSize(550,550);
f.setLocation(100,100);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new OlympicRings());
}
}
OUTPUT
Z:\cs2k944> javac OlympicRingsTest.java
Z:\cs2k944> java OlympicRingsTest
-
8/4/2019 Java Programming Lab
34/44
FILE HANDLING AND I/O HANDLING
PROGRAM
1. Write a program to read the content of a file.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try{
String strLine,filename;
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter the filename:");
filename=br.readLine();
FileInputStream fstream = new FileInputStream(filename);
BufferedReader inFile = new BufferedReader(new InputStreamReader(fstream));
System.out.println("File Contents:");
while ((strLine = inFile.readLine()) != null) {
System.out.println (strLine);
}
}
catch(Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Content.txt
Java Programming
C Programming
C++ Programming
-
8/4/2019 Java Programming Lab
35/44
OUTPUT
Z:\cs2k944> javac FileRead.java
Z:\cs2k944> java FileRead
Enter the filename:
Content.txt
File Contents:
Java Programming
C Programming
C++ Programming
2. Write a program to write a content to a file.
import java.io.*;
public class FileWrite {
public static void main(String[] args) {
try {
String k,filename;
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter the Filename:");
filename=br.readLine();
File outFile = new File(filename);
PrintStream out=new PrintStream(outFile);
System.out.println("Enter the content of the file :");
while(true) {
if((k=br.readLine()).equalsIgnoreCase("stop")) {
System.out.println("Content to a file is wrote
successfully");
break;
}
-
8/4/2019 Java Programming Lab
36/44
else
out.println(k);
}
} catch (IOException e){}
}
}
OUTPUT
Z:\cs2k944> javac FileWrite.java
Z:\cs2k944> java FileWrite
Enter the Filename:
Contents.txt
Enter the content of the file :
Software Engineering
Computer Networks
Theory of Computation
Stop
Content to a file is wrote successfully
Contents.txt
Software Engineering
Computer Networks
Theory Of Computation
3. Write a Program to search a number of occurrences of a particular
character in a file.
import java.io.*;
class CharSearch {
public static void main(String[] args) {
String filename;
char searchChar;
-
8/4/2019 Java Programming Lab
37/44
int count=0,fileChar;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("Enter the filename:");
filename=br.readLine();
FileInputStream in = new FileInputStream(filename);
System.out.println("Enter the Character to be searched:");
searchChar=(char)System.in.read();
while ((fileChar = in.read()) != -1) {
if((char)fileChar==searchChar)
count++;
}
if(count==0)System.out.println("The searched character is not present in the file");
else
System.out.println(searchChar+" exists "+count+" times in the file");
}
catch(Exception e) {}
}
}
Content.txt
Java Programming
C Programming
C++ Programming
OUTPUT
Z:\cs2k944> javac CharSearch.java
Z:\cs2k944> java CharSearch
Enter the filename:
Content.txt
Enter the Character to be searched:
m
m exists 6 times in the file
-
8/4/2019 Java Programming Lab
38/44
4. Write a Program to search a number of occurrences of a particular word in
a file.
import java.io.*;
class WordSearch {
public static void main(String[] args) {
String strLine,filename,word;
int count=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("Enter the filename:");
filename=br.readLine();
FileInputStream fstream = new FileInputStream(filename);
BufferedReader inFile = new BufferedReader(new InputStreamReader(fstream));
System.out.println("Enter the word to be searched:");
word=br.readLine();
while ((strLine = inFile.readLine()) != null) {
String[] strarr = strLine.split(" ");
for(String str:strarr) {
if(str.equalsIgnoreCase(word))count++;
}
}
if(count==0)
System.out.println("The searched word is not present in the file");
else
System.out.println(word+" exists "+count+" times in the file");
}
catch(Exception e)
{}
}
}
-
8/4/2019 Java Programming Lab
39/44
Content.txt
Java Programming
C Programming
C++ Programming
OUTPUT
Z:\cs2k944> javac WordSearch.java
Z:\cs2k944> java WordSearch
Enter the filename:
Content.txt
Enter the word to be searched:Programming
Programming exists 3 times in the file
-
8/4/2019 Java Programming Lab
40/44
DATABASE APPLICATIONS (JDBC )
PROGRAM
1. Write a program to establish JDBC connectivity between a java program and a
database.
import java.awt.*;import javax.swing.*;
import java.awt.event.*;import java.sql.*;
class BankDatabase extends JFrame implements ActionListener {JButton b1,b2;JLabel l1,l2,l3,l4;
private static Connection con=null;private static Statement st=null;
private static ResultSet rs=null;String acc,amt;
int bal,i;BankDatabase(String acc) {
try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:bank","","");st=con.createStatement();
this.acc=acc;bal=balance(st);
}catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage() , "ERRORMESSAGE", 1);
System.exit(0);}
l1=new JLabel("Account No. :");l2=new JLabel("Balance :");
l3=new JLabel(acc);l4=new JLabel(""+bal);
b1=new JButton("Deposit");b2=new JButton("Withdraw");
setLayout(null);l1.setBounds(50,20,100,20);
l2.setBounds(50,50,100,20);
-
8/4/2019 Java Programming Lab
41/44
l3.setBounds(180,20,150,20);l4.setBounds(180,50,150,20);
b1.setBounds(30,100,100,20);b2.setBounds(150,100,100,20);
add(l1);
add(l2);add(l3);add(l4);
add(b1);add(b2);
b1.addActionListener(this);b2.addActionListener(this);
setVisible(true);setTitle("Transaction");
setSize(300,200);setLocation(175,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
public void actionPerformed(ActionEvent ae) {if(ae.getSource()==b1) {
deposit(st);}
if(ae.getSource()==b2) {withdraw(st);
}}
public int balance(Statement st) {try {
rs=st.executeQuery("select balance from bank where accno='"+acc+"'");while(rs.next()) {
i++;bal=Integer.parseInt(rs.getString(1));
}if(i==0) {
JOptionPane.showMessageDialog(null,"Account No. does notExit","ERROR MESSAGE", 1);
System.exit(0);}
}catch(SQLException se) {
JOptionPane.showMessageDialog(null,se.getMessage(),"ERRORMESSAGE", 1);
System.exit(0);}
return bal;}
-
8/4/2019 Java Programming Lab
42/44
public void withdraw(Statement st) {
try {
amt = JOptionPane.showInputDialog(null, "Enter the Amount to withdraw: ", "Amount to withdraw", 1);
if(amt!=null) {
bal-=Integer.parseInt(amt);st.executeUpdate("update bank set balance='" +Integer.toString(bal) +"' where accno='"+acc +"'");
JOptionPane.showMessageDialog(null, "Transaction Successful!","Message",1);
l4.setText(""+bal);}
elseJOptionPane.showMessageDialog(null, "You pressed cancel
button", "Message", 1);}
catch(SQLException se) {JOptionPane.showMessageDialog(null,se.getMessage(),"ERROR
MESSAGE", 1);}
}public void deposit(Statement st) {
try {amt = JOptionPane.showInputDialog(null, "Enter the Amount to Deposit :
", "Amount to Deposit", 1);if(amt!=null) {
bal+=Integer.parseInt(amt);st.executeUpdate("update bank set
balance='"+Integer.toString(bal)+"' where accno='"+acc+"'");JOptionPane.showMessageDialog(null,"Transaction Successful!",
"Message",1);l4.setText(""+bal);
}else
JOptionPane.showMessageDialog(null, "You pressed cancelbutton", "Message", 1);
}catch(SQLException se) {
JOptionPane.showMessageDialog(null,se.getMessage(),"ERRORMESSAGE", 1);
}}
}
-
8/4/2019 Java Programming Lab
43/44
class Bank {
public static void main(String args[]) {
String str = JOptionPane.showInputDialog(null, "Enter the Account Number : ","Account Number", 1);
if(str != null) {
new BankDatabase(str);}else
JOptionPane.showMessageDialog(null, "You pressed cancel button","Message", 1);
}}
OUTPUT
Z:\cs2k944> javac Bank.java
Z:\cs2k944> java Bank
-
8/4/2019 Java Programming Lab
44/44