Final JAVA Practical of BCA SEM-5

Preview:

Citation preview

1.W.J.P.find the area of circle

import java.io.DataInputStream;class circle{

public static void main(String args [ ]){DataInputStream in = new DataInputStream(System.in);int y = 0;double area;

try{

System.out.print("Enter redius : ");y = Integer.parseInt(in.readLine());

}catch (Exception e){System.out.println("Error......!"); }

area = Math.PI*y*y;System.out.println("Area is " + area);}

}Output: Enter redius : 4

Area is 50.26

2.W.J.P. that will display Factorial of the given number.

import java.io.DataInputStream;class facto{

public static void main(String args [ ]){

DataInputStream in = new DataInputStream(System.in);int y = 0;double fact=1.0;try{

System.out.println("Enter the number ");y = Integer.parseInt(in.readLine());

}catch (Exception e){System.out.println("Error......!"); }

for(int i=1;i<=y;i++)fact *= i;

System.out.println("Factorial is " + fact);}

}

Output: Enter the number = 4Factorial is 24

1

3. W.J.P. that will display the sum of 1+1/2+1/3…..+1/n.

import java.io.DataInputStream;class disum{

public static void main(String args [ ]){

DataInputStream in = new DataInputStream(System.in);int y = 0;double sum=0.0;try{

System.out.println("Enter the number ");y = Integer.parseInt(in.readLine());

}catch (Exception e){System.out.println("Error......!"); }

for(int i=1;i<=y;i++)sum += 1.0/i;

System.out.println("Sum of the series is " + sum);}

}Output: Enter the number = 5

Sum of the series is 2.28

4. W.J.P. that will display 25 Prime nos.class prime{

public static void main(String[] ar){

int y=0,i=3,flag=0;System.out.print("Prime Numbers are 2");while(i<=25){

for(y=3;y<=((int)Math.sqrt(i))+1;y += 2){

if(i%y == 0){

flag=1;break;

}flag=0;

}if(flag==0)

System.out.print(" "+i);i +=2;

}}

}

Output : Prime Numbers are 2 3 5 7 11 13 17 19 23

2

5. W.J.P. that will accept command-line arguments and display the same.

class commandline{

public static void main(String a[]){

int i=0;while(true){

try{

System.out.println("The Arguments No "+i+" is "+a[i]);i++;

}catch(ArrayIndexOutOfBoundsException e){System.exit(0);}

}}

}

Output : The Arguments No 0 is goodThe Arguments No 1 is Morning

6. W.J.P. to sort the elements of an array in ascending order.

import java.io.*;

class arrayascending {

public static void main(String ar[]){ BufferedReader di = new BufferedReader(new

InputStreamReader(System.in));int x=0,no=0,temp=0,j=0,i=0;int a[] = new int[5];while(true){

try{

x=Integer.parseInt(di.readLine());a[i]=x;if(i == 4)

break;}

catch(IOException e){System.out.println(e.getMessage().toString()); }

catch(NumberFormatException e){System.out.println(e.getMessage().toString()); }catch(ArrayIndexOutOfBoundsException e){

3

System.out.println("Array Index is out of Bound"); return;}i++;

}no=0;for(i=0;i<4;i++){

for(j=i+1;j<5;j++){

if(a[i] > a[j]){

temp=a[i];a[i]=a[j];a[j]=temp;

}}

}System.out.println();while(no<5){

System.out.print(" "+a[no]);no++;

}}

}

Output : 5 3 4 1 2

1 2 3 4 5

7. W.J.P. which will read a Text and count all the occurrences of a particular word

import java.io.*;import java.util.*;

class CountCharacters { public static void main(String[] args) throws Exception

{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please enter string ");

System.out.println(); String str=br.readLine();

String st=str.replaceAll(" ", ""); char[]third =st.toCharArray();

for(int counter =0;counter<third.length;counter++) {

char ch= third[counter];

4

int count=0;

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

if (ch==third[i])count++;

}boolean flag=false;for(int j=counter-1;j>=0;j--){

if(ch==third[j])flag=true;

}if(!flag){

System.out.println("Character :"+ch+" occurs "+count+" times ");}

} }

}Output: Please enter string

Hello World

Character :H occurs 1 timesCharacter :e occurs 1 timesCharacter :l occurs 3 timesCharacter :o occurs 2 timesCharacter :W occurs 1 timesCharacter :r occurs 1 timesCharacter :d occurs 1 times

8. read a string and reverse it and then write in alphabetical order.

import java.io.*; import java.util.*;

class ReverseAlphabetical { String reverse(String str) { String rStr = new StringBuffer(str).reverse().toString(); return rStr; }

String alphaOrder(String str)

5

{ char[] charArray = str.toCharArray(); Arrays.sort(charArray); String aString = new String(charArray); return aString ; }

public static void main(String[] args) throws IOException { System.out.print("Enter the String : "); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); String inputString = br.readLine(); System.out.println("String before reverse : " + inputString); ReverseAlphabetical obj = new ReverseAlphabetical(); String reverseString = obj.reverse(inputString); String alphaString = obj.alphaOrder(inputString); System.out.println("String after reverse : " + reverseString); System.out.println("String in alphabetical order : " + alphaString); }}

Output : Enter the String : STRINGString before reverse : STRINGString after reverse : GNIRTSString in alphabetical order : GINRST

6

19. W.J.P. which create threads using the thread class.

class A extends Thread{

public void run(){

for(int i=1;i<=5;i++){

System.out.println("\t From ThreadA : i = "+i);}

System.out.println("Exit from A");}

}

class B extends Thread{

public void run(){

for(int j=1;j<=5;j++){

System.out.println("\t From ThreadB : j = "+j);}

System.out.println("Exit from B");}

}

class C extends Thread{

public void run(){

for(int k=1;k<=5;k++){

System.out.println("\t From ThreadC : k = "+k);}

System.out.println("Exit from C");}

}

class threadclass{

public static void main(String args[]){

new A().start();new B().start();new C().start();

}}

Output: From ThreadA : i = 1 From ThreadB : j = 1

From ThreadB : j = 2

7

From ThreadB : j = 3From ThreadB : j = 4From ThreadA : i = 2From ThreadB : j = 5

Exit from BFrom ThreadA : i = 3From ThreadC : k = 1From ThreadA : i = 4From ThreadC : k = 2From ThreadC : k = 3From ThreadC : k = 4From ThreadC : k = 5

Exit from CFrom ThreadA : i = 5

Exit from A

20. W.J.P. which shows the use of yield(),stop() and sleep() methods.

class A extends Thread{

public void run(){

for(int i=1;i<=5;i++){

if(i==1) yield();System.out.println("\t From ThreadA : i = "+i);

}System.out.println("Exit from A");}

}

class B extends Thread{

public void run(){

for(int j=1;j<=5;j++){

if(j==3) stop();System.out.println("\t From ThreadB : j = "+j);

}System.out.println("Exit from B");}

}

class C extends Thread{

public void run(){

for(int k=1;k<=5;k++)

8

{System.out.println("\t From ThreadC : k = "+k);if(k==1)try{

sleep(1000);}catch(Exception e) {}

}System.out.println("Exit from C");}

}

class threadmethod{

public static void main(String args[]){

A a=new A();B b=new B();C c=new C();System.out.println("Start thread A");a.start();System.out.println("Start thread B");b.start();System.out.println("Start thread C");c.start();

}}

Output :Start thread AStart thread BStart thread C

From ThreadB : j = 1 From ThreadA : i = 1 From ThreadA : i = 2 From ThreadA : i = 3 From ThreadA : i = 4 From ThreadA : i = 5Exit from A From ThreadC : k = 1 From ThreadB : j = 2 From ThreadC : k = 2 From ThreadC : k = 3 From ThreadC : k = 4 From ThreadC : k = 5Exit from C

9

21.W.J.P. which shows the priority in threads

class A extends Thread{

public void run(){

System.out.println("Thread A started");for(int i=1;i<=4;i++){

System.out.println("\t From ThreadA : i = "+i);}

System.out.println("Exit from A");}

}

class B extends Thread{

public void run(){

System.out.println("Thread B started");for(int j=1;j<=4;j++){

System.out.println("\t From ThreadB : j = "+j);}

System.out.println("Exit from B");}

}

class C extends Thread{

public void run(){

System.out.println("Thread C started");for(int k=1;k<=4;k++){

System.out.println("\t From ThreadC : k = "+k);}

System.out.println("Exit from C");}

}

class threadpriority{

public static void main(String args[]){

A threadA=new A();B threadB=new B();C threadC=new C();

10

threadC.setPriority(Thread.MAX_PRIORITY);threadB.setPriority(threadA.getPriority()+1);threadA.setPriority(Thread.MIN_PRIORITY);

System.out.println("Start thread A");threadA.start();System.out.println("Start thread B");threadB.start();System.out.println("Start thread C");threadC.start();

System.out.println("End of main thread");}

}Output :Start thread A

Start thread BThread A startedStart thread C

From ThreadA : i = 1Thread C startedThread B started

From ThreadC : k = 1From ThreadC : k = 2From ThreadC : k = 3

From ThreadC : k = 4Exit from C From ThreadA : i = 2End of main thread From ThreadA : i = 3 From ThreadB : j = 1 From ThreadA : i = 4 From ThreadB : j = 2Exit from A From ThreadB : j = 3 From ThreadB : j = 4Exit from B

22.W.J.P. which use runnable interface.

class X implements Runnable{

public void run(){

for(int i=1;i<=10;i++){

System.out.println("threadX:"+i);}System.out.println("end of ThreadX");

}}

11

class runnableinterface{

public static void main(String rgs[]){

X runnable=new X();Thread threadx=new Thread(runnable);threadx.start();System.out.println("End of main Thread");

}}

Output :End of main ThreadthreadX: 1threadX: 2threadX: 3threadX: 4threadX: 5threadX: 6threadX: 7threadX: 8threadX: 9threadX: 10

end of ThreadX

23.W.J.P. which use try and catch for exception handling

class trycatch{

public static void main(String args[]){

int a=10;int b=5;int c=5;int x,y;try{

x=a/(b-c); // here is the exception}catch(ArithmeticException e){

System.out.println("Division by zero");}y=a/(b+c);System.out.println("Y = "+y);

}}

Output: Division by zeroY = 1

12

24.W.J.P. which use multiple catch blocks

class multiplecatch{

public static void main(String args[]){

int a[]={5,10};int b=5;

try{

int X=a[2]/b-a[1];}catch(ArithmeticException e){

System.out.println("Division by zero");}catch(ArrayIndexOutOfBoundsException e){

System.out.println("Array index error");}catch(ArrayStoreException e){

System.out.println("Wrong data type");}

int y=a[1]/a[0];System.out.println("Y = "+y);

}}

Output : Array index error Y = 2

25. W.J.P. which shows throwing our own exception

import java.lang.Exception;

class myexception extends Exception{

myexception(String message){

super(message);}

}

class ownexception{

public static void main(String args[]){

int x=5,y=1000;

13

try{

float z=(float) x / (float) y;if(z<0.01){

throw new myexception("number is too small");}

}

catch(myexception e){

System.out.println("caught my exception");System.out.println(e.getMessage());

}finally{

System.out.println("I M always here");}

}}

Output: caught my exception number is too small I M always here

26. make an applet that create two bottons named “red”and “Blue” when a buttons is pressed the background color of the circle is set to the color named by the button’s label.

* Java program coding

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

public class appletredblue extends Applet implements ActionListener{

Button red,blue;Label l;int x=0,y=0;public void init(){GridBagLayout gridbag = new GridBagLayout();

GridBagConstraints c = new GridBagConstraints();

c.weighty = 1.0; c.weightx = 1.0;

red = new Button("Red");c.gridwidth = GridBagConstraints.RELATIVE;

14

gridbag.setConstraints(red, c); add(red);

red.addActionListener(this);

blue = new Button("Blue");c.gridwidth = GridBagConstraints.REMAINDER;

gridbag.setConstraints(blue, c); add(blue); blue.addActionListener(this);

setSize(300,300);setLayout(gridbag);

}public void start(){}

public void stop(){}public void actionPerformed(ActionEvent e){

if(e.getSource() == red){

setBackground(Color.red);}if(e.getSource()== blue){

setBackground(Color.blue);}

}

}

• HTML Program coding

<html><head><title>wel come to java applets</title></head><body><center><APPLET code=appletredblue.class width=400 height=200> </APPLET></center></body></html>

Output :

15

27. Write java applet that creates some text fields and text areas to demonstrate features of each

* Java program coding

import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.Applet;import java.net.*;

public class WriteFile extends Applet{ Button write = new Button("WriteToFile"); Label label1 = new Label("Enter the file name:"); TextField text = new TextField(20); Label label2 = new Label("Write your text:"); TextArea area = new TextArea(10,20); public void init(){ add(label1); label1.setBackground(Color.lightGray); add(text); add(label2); label2.setBackground(Color.lightGray); add(area); add(write,BorderLayout.CENTER); write.addActionListener(new ActionListener (){ public void actionPerformed(ActionEvent e){ new WriteText(); } }); } public class WriteText { WriteText(){ try { String str = text.getText(); if(str.equals("")){ JOptionPane.showMessageDialog(null,"Please enter the file name!"); text.requestFocus(); } else{ File f = new File(str); if(f.exists()){ BufferedWriter out = new BufferedWriter(new FileWriter(f,true)); if(area.getText().equals("")){ JOptionPane.showMessageDialog(null,"Please enter your text!"); area.requestFocus(); }

16

else{ out.write(area.getText()); if(f.canWrite()){ JOptionPane.showMessageDialog(null,"Text is written in "+str); text.setText(""); area.setText(""); text.requestFocus(); } else{ JOptionPane.showMessageDialog(null,"Text isn't written in "+str); } out.close(); } } else{ JOptionPane.showMessageDialog(null,"File not found!"); text.setText(""); text.requestFocus(); } } } catch(Exception x){ x.printStackTrace(); } } }}

• HTML Coading *

<HTML><HEAD><TITLE> Write file example </TITLE><applet code="WriteFile.class", width="200",height="300"></applet></HEAD></HTML>

Output :

17

28. Create an applet with three text Fields and two buttons add and subtract. User will entertwo values in the Text Fields. When the button add is pressed, the addition of the twovalues should be displayed in the third Text Fields. Same the Subtract button shouldperform the subtraction operation.

* Java Coading *

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

public class sumsub extends Applet implements ActionListener{

Button addbtn,subbtn;TextField txt1,txt2,result;Label l;int x=0,y=0;public void init(){

GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints();

c.fill = GridBagConstraints.BOTH;c.weightx = 0.5;c.weighty = 0.5; txt1 = new TextField();c.gridwidth = GridBagConstraints.RELATIVE;gridbag.setConstraints(txt1, c);

add(txt1);

txt2 = new TextField();c.gridwidth = GridBagConstraints.REMAINDER;gridbag.setConstraints(txt2, c);

add(txt2); addbtn = new Button("Add");

c.gridwidth = GridBagConstraints.RELATIVE;gridbag.setConstraints(addbtn, c);

add(addbtn); addbtn.addActionListener(this);

subbtn = new Button("Subtract");c.gridwidth = GridBagConstraints.REMAINDER;gridbag.setConstraints(subbtn, c);

add(subbtn); subbtn.addActionListener(this); l = new Label(" Result");

c.gridwidth = GridBagConstraints.RELATIVE;

18

gridbag.setConstraints(l, c); add(l);

result = new TextField();c.gridwidth = GridBagConstraints.RELATIVE;gridbag.setConstraints(result, c);

add(result);

setSize(200,120);setLayout(gridbag);

}public void start(){}

public void stop(){}public void actionPerformed(ActionEvent e){

if(e.getSource() == addbtn){

x=Integer.parseInt(txt1.getText());y=Integer.parseInt(txt2.getText());x=x+y;result.setText(Integer.valueOf(x).toString());

}if(e.getSource()== subbtn){

x=Integer.parseInt(txt1.getText());y=Integer.parseInt(txt2.getText());x=x-y;result.setText(Integer.valueOf(x).toString());

}}

}

* HTML Coading *

<html><head><title>wel come to java applets</title></head><body><center><APPLET code= sumsub.class width=400 height=200> </APPLET></center></body></html>

Output :

19

29. Create an applet to display the scrolling text. The text should move from right to left. Whenit reaches to start of the applet border, it should stop moving and restart from the left. Whenthe applet is deactivated, it should stop moving. It should restart moving from the previouslocation when again activated.

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

public class scrollingtext extends Applet implements Runnable{ int X=290,Y=200,flag=1; String msg ="Lovely Scrolling Text"; Thread t1; public void init() { t1 = new Thread(this); t1.start(); } public void start(){} public void stop(){}

public void paint(Graphics g){

if(flag==0)X++;

elseX--;

if(X==0)flag=0;

if(X==290)flag=1;

msg ="Lovely Scrolling Text";g.drawString(msg,X,Y);

}public void run(){

try{

while(true){

repaint();t1.sleep(50);

}}catch(Exception e){}

}

}

20

* HTML code *

<html><head><title>wel come to java applets</title></head><body><center><APPLET code= scrollingtext.class width=400 height=200> </APPLET></center></body></html>

Output :

21

30. Write a program to create three scrollbar and a label. The background color of the lableshould be changed according to the values of the scrollbars (The combination of the values RGB).

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

public class scrol extends Applet implements AdjustmentListener {

Scrollbar R,G,B;Label l1;public void init(){

l1 = new Label("");add(l1);R = new Scrollbar(Scrollbar.HORIZONTAL,0, 10, 0, 255);add(R);G = new Scrollbar(Scrollbar.HORIZONTAL,0, 10, 0, 255);add(G);B = new Scrollbar(Scrollbar.HORIZONTAL,0, 10, 0, 255);add(B);

l1.setVisible(true);

setSize(200,200);setLayout(new GridLayout(4,4));R.addAdjustmentListener(this);G.addAdjustmentListener(this);B.addAdjustmentListener(this);

}public void start(){}

public void stop(){}public void adjustmentValueChanged(AdjustmentEvent ae){

l1.setBackground(new Color(R.getValue(),G.getValue(),B.getValue()));

}

}

* HTML Coading *

22

<html><head><title>wel come to java applets</title></head><body><center><APPLET code= scrol.class width=400 height=200> </APPLET></center></body></html>

Output :

23