Java-b&c practical No. 1 Aim : Write a program to demonstrate command line parameter



Download 2.34 Mb.
Date28.05.2018
Size2.34 Mb.
#50892
JAVA-B&C

 

Practical No. 1

 

Aim : Write a program to demonstrate command line parameter.

 

public class Switch



{

public static void main(String key[])

{

int x=Integer.parseInt(key[0]);



switch(x){

case 1: System.out.println(“Monday”);

break;

case 2: System.out.println(“Tuesday”);



break;

case 3: System.out.println(“Wednesday”);

break;

case 4: System.out.println(“Thursday”);



break;

case 5: System.out.println(“Friday”);

break;

case 6: System.out.println(“Saturday”);



break;

case 7: System.out.println(“Sunday”);

break;

default :System.out.println(“Invalid Number of Day”);



}

}

}



 

 

 



 

Practical No. 2

 

 



Aim: Write a program to implement method overloading.

 

class Calculation



{

void sum(int a,int b)

{

System.out.println(a+b);



}

void sum(int a,int b,int c)

{

System.out.println(a+b+c);



}

}

class Overload



{

 

public static void main(String args[])



{

Calculation obj=new Calculation();

obj.sum(10,10,10);

obj.sum(20,20);

 

}

}



 

Output :

 

 



 

 

 



 

 

 



 

 

 



Practical No. 3

 

 



Aim : Write a program to use wrapper class.

 

class WrapperDemo



{

public static void main (String args[])

{

Integer intObj1 = new Integer (25);



Integer intObj2 = new Integer (“25″);

Integer intObj3= new Integer (35);

//compareTo demo

System.out.println(“Comparing using compareTo Obj1 and Obj2: ” + intObj1.compareTo(intObj2));

System.out.println(“Comparing using compareTo Obj1 and Obj3: ” + intObj1.compareTo(intObj3));

//Equals demo

System.out.println(“Comparing using equals Obj1 and Obj2: ” + intObj1.equals(intObj2));

System.out.println(“Comparing using equals Obj1 and Obj3: ” + intObj1.equals(intObj3));

Float f1 = new Float(“2.25f”);

Float f2 = new Float(“20.43f”);

Float f3 = new Float(2.25f);

System.out.println(“Comparing using compare f1 and f2: ” +Float.compare(f1,f2));

System.out.println(“Comparing using compare f1 and f3: ” +Float.compare(f1,f3));

//Addition of Integer with Float

Float f = intObj1.floatValue() + f1;

System.out.println(“Addition of intObj1 and f1: “+ intObj1 +”+” +f1+”=” +f );

}

}

 



Output :

 

 



Practical No. 4

 

 



Aim: Write a program to implement static methods to find the square of number and power function.

 

class ImpPower



{

static long Ipower(int num,int pow)

{

if(pow==0)



{

return 1;

}

else if(pow==1)



{

return num;

}

else


{

int m=num;

for(int i=1;i<=pow;i++)

{

num=num*m;



}

return num;

}

}

}



class Fourth

{

public static void main(String args[])



{

int m=3,p=4;

System.out.println(“3 raise to power 4 is : “+ImpPower.Ipower(m, p));

}

}



 

 

Output :

 

 

 



 

 

 



Practical No. 5

 

 



Aim : Write a program to sort an array using bubble sort method.

 

import java.util.Scanner;



 

class BubbleSort {

public static void main(String []args) {

int n, c, d, swap;

Scanner in = new Scanner(System.in);

System.out.println(“Input number of integers to sort”);

n = in.nextInt();

int array[] = new int[n];

System.out.println(“Enter ” + n + ” integers”);

for (c = 0; c < n; c++)

array[c] = in.nextInt();

 

for (c = 0; c < ( n – 1 ); c++) {



for (d = 0; d < n – c – 1; d++) {

if (array[d] > array[d+1]) /* For descending order use < */

{

swap       = array[d];



array[d]   = array[d+1];

array[d+1] = swap;

}

}

}



 

System.out.println(“Sorted list of numbers”);

 

for (c = 0; c < n; c++)



System.out.println(array[c]);

}

}



 

Output :

 

Practical No. 6

 

Aim : Write a program to compare two objects using object as a parameter

 

class BillingAddress



{

private String firstName;

private String lastName;

public BillingAddress(String firstName, String lastName)

{

this.firstName = firstName;



this.lastName = lastName;

}

public boolean equals(Object obj)



{

boolean isEqual = false;

if (this.getClass() == obj.getClass())

{

BillingAddress billingAddress = (BillingAddress) obj;



 

if ((billingAddress.firstName).equals(this.firstName) && (billingAddress.lastName).equals(this.lastName))

{

isEqual = true;



}

}

return isEqual;



}

}

class Sixth            {



public static void main(String[] arg)          {

BillingAddress obj1 = new BillingAddress(“john”, “bates”);

BillingAddress obj2 = new BillingAddress(“Abc”, “Kumar”);

if (obj1.equals(obj2))

{

System.out.println(“Both the objects are equal”);



}

else


{

System.out.println(“Both the objects are not equal”);

}      }  }

 

Output :

 

Practical No. 7

 

Aim: Write a program to find the area of rectangle; circle and triangle using an abstract class (implement dynamic dispatch).

 

import java.util.Scanner;



abstract class A

{

abstract void area();



}

class Rectangle extends A

{

void area()



{

Scanner scan= new Scanner(System.in);

System.out.println(“Enter the lenght : “);

int Len=scan.nextInt();

System.out.println(“Enter the Breadth : “);

int bre=scan.nextInt();

System.out.println(“Enter the Height : “);

int high=scan.nextInt();

int a=Len*bre*high;

System.out.println(“Area of Rectangle : “+a);

}

}

 



class Triangle extends A

{

void area()



{

Scanner scan= new Scanner(System.in);

System.out.println(“Enter the Base : “);

int Base=scan.nextInt();

System.out.println(“Enter the Height : “);

int height=scan.nextInt();

double a=0.5*Base*height;

System.out.println(“Area of Triangle : “+a);

}

}

 



class Circle extends A

{

void area()



{

Scanner scan= new Scanner(System.in);

System.out.println(“Enter the Radius : “);

int rad=scan.nextInt();

double a=3.14*rad*rad;

System.out.println(“Area of Circle : “+a);

}

}

 



public class Dispatch

{

public static void main(String args[])



{

Rectangle b = new Rectangle();

Triangle c = new Triangle();

Circle d= new Circle();

A r;

 

r = b;



r.area();

 

r = c;



r.area();

 

r = d;



r.area();

}

}



 

Output :

 

 



 

 

 



 

 

 



 

 

 



Practical No. 8

 

 



Aim: Write a program to demonstrate single inheritance.

 

(Create a class box with data member width, height, depth  & member function volume to calculate volume  of  box with all the necessary constructor, derive a new class boxweight with data member weight which constructor  &  method to display with height & weight)

 

class Box



{

int width;

int height;

int depth;

Box(int w, int h,int d)

{

width=w;



height=h;

depth=d;


}

int volume()

{

return width*height*depth;



}

}

class boxweight extends Box



{

int weight;

boxweight(int w,int h,int d,int weigh)

{

super(w,h,d);



weight=weigh;

}

void display()



{

System.out.println(“Width : “+width);

System.out.println(“Height : “+height);

System.out.println(“Depth : “+depth);

System.out.println(“Weight : “+weight);

System.out.println(“Volume : “+volume());

}

}

class eight



{

public static void main(String args[])

{

boxweight b= new boxweight(4,5,6,7);



b.display();

}                              }

 

Output :

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No. 9

 

Aim :Write a program to demonstrate multiple inheritance using interface

(Create a class student with data member roll no & mark1,mark2,mark3 & create a interface sportswt with data member  wt, create another class result  derive from student & sportwt with member function to calculate total & to implement method of interface)

 

class Student



{

int rollNumber;

float marks1,marks2,marks3;

void getdata(int r,float m1,float m2,float m3)

{

rollNumber=r;



marks1=m1;

marks2=m2;

marks3=m3;

}

void putdata()



{

System.out.println(“Roll NUmber : “+rollNumber);

System.out.println(“Marks1 : “+marks1);

System.out.println(“Marks2 : “+marks2);

System.out.println(“Marks3 : “+marks3);

}

}



interface Sports

{

float wt=6.0F;



void putwt();

}

class Results extends Student implements Sports



{

float total;

public void putwt()

{

System.out.println(“Sports wt : “+wt);



}

void display()

{

total= marks1+marks2+marks3+wt;



putdata();

putwt();


System.out.println(“Total score : “+ total);

}

}



class ninth

{

public static void main(String args[])



{

Results student1= new Results();

student1.getdata(4,50,60,70);

student1.display();

}

}

 



Output :

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No. 10

 

Aim : Write a program to demonstrate package and access modifier.

(create class protection with 3 data member of  public, private, protected type. Create another class derive which is derived from protection & try to display all the member of protection class. Create another class in same package to use object of protection & display all the members of protection.)

 

SamplePackage:-



 

package packdemo;

 

public class samepackage



{

public void show1()

{

protection p=new protection(3,8,9);



System.out.println(“m= “+p.m);

//System.out.println(“n= “+p.n);

System.out.println(“o= “+p.o);

}

}



 

Derived Package:-

 

package packdemo;



 

public class derived extends protection

{

public derived(int m1,int n1,int o1)



{

super(m1,n1,o1);

}

public void show()



{

System.out.println(“m= “+m);

//System.out.println(“n= “+n);

System.out.println(“o= “+o);

}

}

 



Protection package:-

 

 



 

Packdemo:-

 

import packdemo.protection;



import packdemo.derived;

import packdemo.samepackage;

 

class packdemomain



{

public static void main(String[] args)

{

derived d=new derived(2,4,6);



d.show();

samepackage s=new samepackage();

s.show1();

}

}



 

 

Output :

 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

Practical No. 11

 

Aim:  Write a program that will read a text and count all the occurrences of particular word.

 

import java.util.*;



class TextSearch

{

public static void main(String as[]) throws Exception



{

Scanner scan=new Scanner(System.in);

int i=0,count=0;

String text=””,s=””;

System.out.println(“Enter Text:(press ENTER  to stop)\n”);

s=scan.nextLine();

while(s.length()!=0)

{

text+=s;



s=scan.nextLine();

}

System.out.println(“Enter search word:”);



s=scan.nextLine();

while(true)

{

i=text.indexOf(s,i);



if(i==-1)

break;


System.out.println(“Word found at position:”+(i+1));

count++;


i+=s.length();

}

System.out.println(“Number of occurrences of given word:”+count);



}

}

 



Output :

 

 



Practical No. 12

 

 



Aim : Write a program that will read a string and rewrite it in alphabetical order (STRING AS GINRST).

 

import java.util.*;



class twelve

{

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



{

Scanner scan = new Scanner(System.in);

System.out.println(“Enter a string:”);

String s = scan.nextLine();

char input[] = s.toCharArray();

for(int i = input.length-2; i>=0; i–)

{

for(int j=0; j<=i; j++)



{

if(input[j] > input[j+1])

{

char temp = input[j];



input[j] = input[j+1];

input[j+1] = temp;

}

}

}



System.out.println(“In sorted Order: ” + new String(input));}}

 

 



Output :

 

 



 

 

 



 

 

Practical No.  13

 

 

Aim Write a program to count the number of vowel and consonant in the given string



import java.io.Console;

 

public class Vowels {



 

public static final char[] CONSONANTS = {

‘b’, ‘c’, ‘d’, ‘f’, ‘g’, ‘h’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’};

 

public static final char SPACE = ‘ ‘;



static char[] getConsonants() {

return CONSONANTS;

}

static boolean isConsonant(char c) {



boolean isConsonant = false;

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

if (getConsonants()[i] == c) {

isConsonant = true;

break;

}

}



return isConsonant;

}

static boolean isSpace(char c) {



return SPACE == c;

}

public static void main(String[] args) {



int spaces     = 0;

int consonants = 0;

int vowelcount = 0;

 

Console console = System.console();



console.format(“Enter a String:”);

 

String text = console.readLine();;



 

for (int index = 0; index < text.length(); index++) {

char letter = text.charAt(index);

if (!isSpace(letter)) {

if (isConsonant(letter)) {

consonants++;

} else {

vowelcount++;

}

 

} else {



spaces++;

}

}



 

System.out.println (“Vowels:” + vowelcount  + “\nConsonants :” + consonants + “\nSpaces : ” + spaces);

}

}

 



Output :

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No. 14

 

 

Aim: Write a program to check where given string is palindrome or not.



 

import java.util.*;

class Palindrome

{

public static void main(String args[])



{

String original, reverse=””;

Scanner in = new Scanner(System.in);

System.out.println(“Enter a string to check if it is a palindrome”);

original = in.nextLine();

int length = original.length();

for ( int i = length – 1 ; i >= 0 ; i– )

reverse = reverse + original.charAt(i);

if (original.equals(reverse))

System.out.println(“Entered string is a palindrome.”);

else

System.out.println(“Entered string is not a palindrome.”);



}

}

 



 

Output :

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No. 15

 

Aim: Write a program to demonstrate multiple catch statement.

 

class Error4



{

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 :

 

 



 

 

 



 

Practical No. 16

 

 



Aim:  Write a program to create own exception and Create a student class if marks is greater than 100 to use this exception.

 

import java.lang.Exception;



import java.util.*;

class MyException extends Exception

{

MyException(String message)



{

super(message);

}

}

class Student



{

public static void main(String args[])

{

Scanner scan= new Scanner(System.in);



System.out.println(“Enter the marks : “);

int mrks1=scan.nextInt();

try          {

if(mrks1>100)

{

throw new MyException(“Marks are out of Bound”);



}

}

catch(MyException e)    {



System.out.println(“Caught my exception : “);

System.out.println(e.getMessage());

}

finally


{

System.out.println(“I am always here”);

}

}

}



 

Output :

 

Practical No. 17

 

 

Aim: Write a program to implement multithreading for multiplication table, Prime Number and Fibonacci Series.



 

class tm extends Thread

{

public void run()



{

System.out.println(“This is a multiplication table.”);

}

}

class tp extends Thread



{

public void run()

{

int count=0;



System.out.println(“Prime Numbers : “);

for(int i=2;i<30;i++)

{

count=0;


for(int j=2;j

{

if(i%j==0)



{

count++;


}

}

if(count==0)



{

System.out.print(i+”\t”);

}

}

System.out.println();



}

}

class tf extends Thread



{

public void run()

{

int a=-1,b=1,c=0;



System.out.println(“Fibonacci Series.”);

for( c=0;c<=21;c++)

{

c=a+b;


System.out.print(c+”\t”);

a=b;


b=c;

}

System.out.println();



}

}

class Threading



{

public static void main(String args[])

{

tf tf1=new tf();



tp tp1=new tp();

tm tm1= new tm();

//tf1.setPriority(Thread.MAX_PRIORITY);

tf1.start();

tp1.start();

tm1.start();

}

}

 



Output :

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No. 18

 

 

Aim: Write a program to Demonstrate Thread Priority



 

class thrun implements Runnable

{

Thread t;



boolean runn = true;

 

thrun(String st,int p)



{

t = new Thread(this,st);

t.setPriority(p);

t.start();

}

publicvoid run()



{

System.out.println(“Thread name : ” + t.getName());

System.out.println(“Thread Priority : ” + t.getPriority());

}

}



 

class priority

{

publicstaticvoid main(String args[])



{

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

thrun t1 = new thrun(“Thread1″,Thread.NORM_PRIORITY + 2);

thrun t2 = new thrun(“Thread2″,Thread.NORM_PRIORITY – 2);

System.out.println(“Main Thread : ” + Thread.currentThread());

System.out.println(“Main Thread Priority : ” + Thread.currentThread().getPriority());

}

}

 



 

Output :

 

Main Thread : Thread[main,10,main]



Main Thread Priority : 10

Thread name : Thread2

Thread name : Thread1

Thread Priority : 7

Thread Priority : 3

 

 



 

 

Practical No. 19

 

Aim : Write an applet program to draw shape like Indian flag, Ashok chakra.

 

import java.awt.*;



import java.applet.*;

import javax.swing.*;

/*

*/

public class lifecycleApplet extends JApplet

{

public void init()                {



System.out.println(“This is init”);

}

public void start()             {



System.out.println(“Applet started”);

}

public void paint(Graphics g)



{

g.drawString(“Vande Mathram”,20,30);

g.drawRect(166,49,336,79);

g.setColor(Color.orange);

for(int i=0;i<20;i++)         {

g.drawLine(166,48+i,500,48+i);

}

g.setColor(Color.blue);



g.drawOval(310,70,30,30);

g.fillOval(310,70,30,30);

g.setColor(Color.black);

g.drawLine(166,68,500,68);

g.drawLine(166,100,500,100);

g.setColor(Color.green);

for(int i=0;i<20;i++)         {

g.drawLine(166,105+i,500,105+i);

}

g.setColor(Color.black);



g.drawLine(166,49,166,549);

g.drawRect(136,549,166,589);

//System.out.println(“Applet just painted”);

}

public void stop()



{

System.out.println(“Applet stoped”);

}

public void destroy()



{

System.out.println(“Applet destroyed”);

}

}

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

Practical No. 20

 

 



Aim: Write an applet program to perform addition, subtraction, multiplication and division of two numbers.

 

import javax.swing.*;



import java.awt.*;

import java.awt.event.*;

 

/**/



public class calculator extends JApplet implements ActionListener

{

private JLabel l1,l2,l3;



private JTextField t1,t2,t3;

private JButton b1,b2,b3,b4;

public void init()

{

Container c=getContentPane();



c.setLayout(new GridLayout(5,2));

l1=new JLabel(“First No. :”);

l2=new JLabel(“Second No. :”);

l3=new JLabel(“Result :”);

t1=new JTextField(10);

t2=new JTextField(10);

t3=new JTextField(10);

b1=new JButton(“Add”);

b2=new JButton(“Sub”);

b3=new JButton(“Mul”);

b4=new JButton(“Div”);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

c.add(l1);

c.add(t1);

c.add(l2);

c.add(t2);

c.add(l3);

c.add(t3);

c.add(b1);

c.add(b2);

c.add(b3);

c.add(b4);

}

public void actionPerformed(ActionEvent ae)



{

int a,b,c;

a=Integer.parseInt(t1.getText());

b=Integer.parseInt(t2.getText());

if(ae.getSource()==b1)

{

c=a+b;



t3.setText(“”+c);

}

if(ae.getSource()==b2)



{

c=a-b;


t3.setText(“”+c);

}

if(ae.getSource()==b3)



{

c=a*b;


t3.setText(“”+c);

}

if(ae.getSource()==b4)



{

c=a/b;


t3.setText(“”+c);

}

}



}

 

 



 

 

 



 

 

 



 

 

 



 

 

 



Practical No. 21

 

Aim :  Write program using swing to create scientific calculator.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

 

class Calculator extends JFrame {



private final Font BIGGER_FONT = new Font(“monspaced”,Font.PLAIN, 20);

private JTextField textfield;

private boolean number = true;

private String equalOp = “=”;

private CalculatorOp op = new CalculatorOp();

public Calculator() {

textfield = new JTextField(“”, 12);

textfield.setHorizontalAlignment(JTextField.RIGHT);

textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();

String buttonOrder = “1234567890 “;

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));

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

String key = buttonOrder.substring(i, i+1);

if (key.equals(” “)) {

buttonPanel.add(new JLabel(“”));

} else {


JButton button = new JButton(key);

button.addActionListener(numberListener);

button.setFont(BIGGER_FONT);

buttonPanel.add(button);

}

}

ActionListener operatorListener = new OperatorListener();



JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 4, 4));

String[] opOrder = {“+”, “-”, “*”, “/”,”=”,”C”,”sin”,”cos”,”log”};

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

JButton button = new JButton(opOrder[i]);

button.addActionListener(operatorListener);

button.setFont(BIGGER_FONT);

panel.add(button);

}

JPanel pan = new JPanel();



pan.setLayout(new BorderLayout(4, 4));

pan.add(textfield, BorderLayout.NORTH );

pan.add(buttonPanel , BorderLayout.CENTER);

pan.add(panel , BorderLayout.EAST);

this.setContentPane(pan);

this.pack();

this.setTitle(“Calculator”);

this.setResizable(false);

}

private void action() {



number = true;

textfield.setText(“”);

equalOp = “=”;

op.setTotal(“”);

}

class OperatorListener implements ActionListener {



public void actionPerformed(ActionEvent e) {

String displayText = textfield.getText();

if (e.getActionCommand().equals(“sin”))

{

textfield.setText(“” + Math.sin(Double.valueOf(displayText).doubleValue()));



}else

if (e.getActionCommand().equals(“cos”))

{

textfield.setText(“” + Math.cos(Double.valueOf(displayText).doubleValue()));



}

else


if (e.getActionCommand().equals(“log”))

{

textfield.setText(“” + Math.log(Double.valueOf(displayText).doubleValue()));



}

else if (e.getActionCommand().equals(“C”))

{

textfield.setText(“”);



}

 

else



{

if (number)

{

action();



textfield.setText(“”);

}

else



{

number = true;

if (equalOp.equals(“=”))

{

op.setTotal(displayText);



}else

if (equalOp.equals(“+”))

{

op.add(displayText);



}

else if (equalOp.equals(“-”))

{

op.subtract(displayText);



}

else if (equalOp.equals(“*”))

{

op.multiply(displayText);



}

else if (equalOp.equals(“/”))

{

op.divide(displayText);



}

textfield.setText(“” + op.getTotalString());

equalOp = e.getActionCommand();

}

}



}

}

class NumberListener implements ActionListener {



public void actionPerformed(ActionEvent event) {

String digit = event.getActionCommand();

if (number) {

textfield.setText(digit);

number = false;

} else {


textfield.setText(textfield.getText() + digit);

}

}



}

public class CalculatorOp {

private int total;

public CalculatorOp() {

total = 0;

}

public String getTotalString() {



return “”+total;

}

public void setTotal(String n) {



total = convertToNumber(n);

}

public void add(String n) {



total += convertToNumber(n);

}

public void subtract(String n) {



total -= convertToNumber(n);

}

public void multiply(String n) {



total *= convertToNumber(n);

}

public void divide(String n) {



total /= convertToNumber(n);

}

private int convertToNumber(String n) {



return Integer.parseInt(n);

}

}



}

class SwingCalculator {

public static void main(String[] args) {

JFrame frame = new Calculator();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

 



 

  


 

 

 



 

 

 



 

 

 



 

 

 



 

Practical No. 22

 

Aim :  Create an applet program for Banner; banner text (Your Roll No.) should



be passed as parameter. This applet creates a thread that scrolls the message contained in message right to left across the applet’s window & also uses status.

 

import java.awt.*;



import javax.swing.*;

import java.util.*;

 

/*


*/

public class Bannerdemo extends JApplet implements Runnable



{

Thread t;

String s,tmp,rno;

int i;


public Bannerdemo()

{

tmp=” “;



i=0;

s=” “;


//rno=getParameter(“rno”);

}

public void init()



{

tmp=” “;


i=0;

s=” “;


rno=getParameter(“rno”);

//rno=new String(“MCA17″);

}

public void run()



{

 

for(;;)



{

try{


if(i==100)

i=0;


repaint();

Thread.sleep(250);

tmp=tmp+”   “;

s=tmp;


i=i+2;

rno=rno.substring(1,rno.length()).concat(rno.substring(0,1));

}catch(Exception e) {}

}

}



public void start()

{

t=new Thread(this);



t.start();

}

public void paint(Graphics g)



{

setBackground(new Color(255,255,255-(i+i)));

g.clearRect(0,0,1000,1000);

g.drawString(“MCA17″+s,300-i,10);

g.drawString(rno,300-i,50);

}

}



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No.  23

 

Aim: Write a program using swing to create a registration form.

 

import java.awt.*;



import javax.swing.*;

import java.awt.event.*;

public class biodata extends JFrame implements ActionListener {

JLabel l1,l2,l3,l4,l5,l6,l7;

JTextField t1,t2;

JTextArea ta1;

JCheckBox c1,c2,c3;

JTable tb1;

JButton b1,b2;

JRadioButton r1,r2;

JScrollPane sp1,sp2;

JComboBox cb1,cb2,cb3;

int i;

GridBagLayout gbl=new GridBagLayout();



GridBagConstraints gbc=new GridBagConstraints();

Container con;

public biodata(){

l1=new JLabel(“Name :-”);

l2=new JLabel(“Address :-”);

l3=new JLabel(“Telephone No. :-”);

l4=new JLabel(“Gender :-”);

l5=new JLabel(“Date Of Birth :-”);

l6=new JLabel(“Language known :-”);

l7=new JLabel(“Education Qualification :-”);

t1=new JTextField(20);

t2=new JTextField(20);

ta1=new JTextArea(30,20);

//JRadioButton

r1=new JRadioButton(“Male”);

r2=new JRadioButton(“Female”);

//JCheckBox

c1=new JCheckBox(“English”);

c2=new JCheckBox(“Marathi”);

c3=new JCheckBox(“Hindi”);

//JComboBox

cb1=new JComboBox();

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

cb1.addItem(“”+i);}

cb2=new JComboBox();

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

cb2.addItem(“”+i);}

cb3=new JComboBox();

for(int i=1990;i<=2020;i++){

cb3.addItem(“”+i);}

b1=new JButton(“ok”);

b1.addActionListener(this);

b2=new JButton(“Cancel”);

b2.addActionListener(this);

sp1=new JScrollPane(ta1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

tb1=new JTable();

Object rowdata[][]={{“S.S.C.”,”2008″,”70%”,”I”},{“H.S.C”,”2010″,”64%”,”I”},{“B.S.C(cs)”,”2013″,”80%”,”I”}};

Object Coldata[]={“Board”,”Year of Passing”,”Percentage”,”Class”};

tb1=new JTable(rowdata,Coldata);

sp2=new JScrollPane(tb1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

ButtonGroup gp=new ButtonGroup();

gp.add(r1);gp.add(r2);

con=getContentPane();

con.setLayout(gbl);

gbc.fill=GridBagConstraints.HORIZONTAL;

gbc.weightx=1.0;gbc.weighty=1.0;

//name

gbc.gridx=0;gbc.gridy=0;



con.add(l1,gbc);

gbc.gridx=1;gbc.gridy=0;

con.add(t1,gbc);

//ADDRESS

gbc.gridx=0;gbc.gridy=1;

con.add(l2,gbc);

gbc.gridx=1;gbc.gridy=1;

gbc.fill=GridBagConstraints.RELATIVE;

gbc.fill=GridBagConstraints.BOTH;

con.add(sp1,gbc);

//Telephone

gbc.gridx=0;gbc.gridy=2;

con.add(l3,gbc);

gbc.gridx=1;gbc.gridy=2;

gbc.fill=GridBagConstraints.HORIZONTAL;

con.add(t2,gbc);

//Date Of Birth

gbc.gridx=0;gbc.gridy=3;

con.add(l5,gbc);

gbc.gridx=1;gbc.gridy=3;

con.add(cb1,gbc);

gbc.gridx=2;gbc.gridy=3;

con.add(cb2,gbc);

gbc.gridx=3;gbc.gridy=3;

con.add(cb3,gbc);

//Gender


gbc.gridx=0; gbc.gridy=4;

con.add(l4,gbc);

gbc.gridx=1;gbc.gridy=4;

con.add(r1,gbc);

gbc.gridx=2;gbc.gridy=4;

con.add(r2,gbc);

//Languages Known

gbc.gridx=0;gbc.gridy=5;

con.add(l6,gbc);

gbc.gridx=1;gbc.gridy=5;

con.add(c1,gbc);

gbc.gridx=2;gbc.gridy=5;

con.add(c2,gbc);

gbc.gridx=3;gbc.gridy=5;

con.add(c3,gbc);

//Education Qualification

gbc.gridx=0;gbc.gridy=6;

con.add(l7,gbc);

gbc.gridx=1;gbc.gridy=6;

gbc.gridwidth=2;gbc.gridheight=2;

gbc.fill=GridBagConstraints.BOTH;

con.add(sp2,gbc);

gbc.fill=GridBagConstraints.RELATIVE;

// CMD Buttons

gbc.gridx=1; gbc.gridy=7;

con.add(b1,gbc);

gbc.gridx=2;gbc.gridy=7;

con.add(b2,gbc);

setSize(500,700);

show();


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}

public void actionPerformed(ActionEvent ae){

String a,b,c;

a=t1.getText();

b=t2.getText();

c=ta1.getText();

if (ae.getSource()==b1){

if(a.equals(“”)||b.equals(“”)||c.equals(“”)){

JOptionPane.showMessageDialog(this,”Please enter the All the TextBox !!”);}

else


if((r1.isSelected()==false)&&(r2.isSelected()==false)){

JOptionPane.showMessageDialog(this,”Please Select the Gender !!”); }

else

if((c1.isSelected()==false)&&(c2.isSelected()==false)&&(c3.isSelected()==false)){



JOptionPane.showMessageDialog(this,”Please Select the Language Known !!”);}

elseif(ae.getSource()==b1){

JOptionPane.showMessageDialog(this,”BIODATA UPDATED !!”);}

}

if (ae.getSource()==b2){



System.exit(0);}

}

public static void main(String []args){



new biodata();

}}

 



 

 

Practical No. 24

 

Aim: Write a program on JDBC to store telephone directory and implement all operations.

 

import java.awt.*;



import javax.swing.*;

import java.sql.*;

import java.awt.event.*;

import java.util.Vector;

 

public class friend extends JFrame implements ActionListener{



JLabel lname,lDOB,lAddress,lPhno;

JTextField txtname,txtdob,txtadd,txtphno;

JButton btnadd,btnshow;

Connection dbcon;

Statement st;

String str=””;

ResultSet rs;

 

public friend(){



Container con=getContentPane();

con.setLayout(null);

con.setBackground(Color.GREEN);

 

lname=new JLabel(“Friend_Name :-”);



lname.setFont(new Font(“Georgia”,Font.PLAIN,12));

lname.setBounds(20,40,100,25);

add(lname);

 

lDOB=new JLabel(“DOB :-”);



lDOB.setFont(new Font(“Georgia”,Font.PLAIN,12));

lDOB.setBounds(20,80,100,25);

add(lDOB);

 

lAddress=new JLabel(“Address :-”);



lAddress.setFont(new Font(“Georgia”,Font.PLAIN,12));

lAddress.setBounds(20,120,100,25);

add(lAddress);

 

lPhno=new JLabel(“Phno :-”);



lPhno.setFont(new Font(“Georgia”,Font.PLAIN,12));

lPhno.setBounds(20,160,100,25);

add(lPhno);

 

txtname=new JTextField(20);



txtname.setBounds(150,40,200,25);

add(txtname);

 

txtdob=new JTextField(20);



txtdob.setBounds(150,80,200,25);

add(txtdob);

 

txtadd=new JTextField(20);



txtadd.setBounds(150,120,200,25);

add(txtadd);

 

txtphno=new JTextField(20);



txtphno.setBounds(150,160,200,25);

add(txtphno);

 

btnadd=new JButton(“SAVE”);



btnadd.addActionListener(this);

btnadd.setBounds(150,200,80,30);

add(btnadd);

btnshow=new JButton(“SHOW”);

btnshow.addActionListener(this);

btnshow.setBounds(250,200,80,30);

add(btnshow);

 

setVisible(true);



setSize(500,500);

}

 



public void actionPerformed(ActionEvent ae){

if(ae.getSource()==btnadd){

String a=txtname.getText();

String b=txtdob.getText();

String c=txtadd.getText();

String d=txtphno.getText();

try{

//JOptionPane.showMessageDialog(this, “Record Saved”);



Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

dbcon=DriverManager.getConnection(“jdbc:odbc:Friend”);

st=dbcon.createStatement();

JOptionPane.showMessageDialog(this, “Record Saved”);

String sql=”insert into Dosti1(Name,Dob,Address,Phno)values(‘”+a+”‘,’”+b+”‘,’”+c+”‘,’”+d+”‘)”;

st.executeQuery(sql);

JOptionPane.showMessageDialog(this, “Record Saved”);

 

}catch(Exception ex){}



}

if(ae.getSource()==btnshow){

Show as=new Show();

}

}



public static void main(String []args){

new friend();

}

 

class Show extends JDialog{



String mysql;

JTable jt1;

JScrollPane jsp;

int v,h;


Statement st;

ResultSet rs;

Connection dbcon;

 

JFrame JFParentFrame;



 

public Show(){

 

Container con=getContentPane();



con.setLayout(new FlowLayout());

 

try



{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

dbcon=DriverManager.getConnection(“jdbc:odbc:Friend”);

st =dbcon.createStatement();

mysql=”select * from Dosti1″;

rs=st.executeQuery(mysql);

Vector ch=new Vector();

ch.add(“Name”);

ch.add(“Dob”);

ch.add(“Address”);

ch.add(“Phno”);

 

Vector data =new Vector();



while(rs.next())

{

Vector row=new Vector();



row.addElement(rs.getString(“Name”));

row.addElement(rs.getString(“Dob”));

row.addElement(rs.getString(“Address”));

row.addElement(rs.getString(“Phno”));

 

data.addElement(row);



}

jt1=new JTable(data,ch);

}

catch(Exception e){System.out.println(e);



}

v=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;

h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

 

jsp=new JScrollPane(jt1,v,h);



 

con.add(jsp);

setSize(500,500);

setResizable(false);

show();

}    }


}

 

 



 

 

 



 

 

 



Practical No. 25

 

Aim: Write a program on JDBC to store product information and select the product name and display its bill .

 

import java.sql.Connection;



import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

 

public class ResultSetDemo extends JFrame implements ActionListener,ItemListener



{

JButton btnShow;

JLabel lbl,lblQ,lblR,lblT;

JTextField tx1;

JComboBox product;

Connection conn,conn1;

Statement st,st1;

String pr;

int r=0;

public static void main(String[] args)

{

ResultSetDemo r=new ResultSetDemo();



}

 

ResultSetDemo()



{

Container c=getContentPane();

c.setLayout(new FlowLayout());

setVisible(true);

setSize(200,200);

 

btnShow = new JButton(“Add”);



lbl = new JLabel(“Rate : “);

lblQ = new JLabel(“Quantity”);

lblR = new JLabel();

lblT = new JLabel();

product=new JComboBox();

tx1=new JTextField(20);

//tx2=new JTextField(20);

 

c.add(product);



c.add(lblQ);

c.add(tx1);

c.add(lbl);

c.add(lblR);

c.add(btnShow);

c.add(lblT);

 

btnShow.addActionListener(this);



product.addItemListener(this);

try


{

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

conn = DriverManager.getConnection(“jdbc:odbc:Phone”);

st = conn.createStatement();

ResultSet rs = st.executeQuery(“select * from Cust”);

String msg=””;

ResultSet rs1 = st.executeQuery(“select * from Products”);

String item;

while(rs1.next())

{

item=rs1.getString(“NameP”);



product.addItem(item);

}

lbl.setText(msg);



rs.close();

st.close();

conn.close();

}

catch (Exception e)



{

}

 



}

public void itemStateChanged(ItemEvent e)

{

pr=product.getSelectedItem().toString();



String q=”select rate from Products where NameP = ‘”+pr+”‘”;

try


{

conn1 = DriverManager.getConnection(“jdbc:odbc:Phone”);

st1 = conn.createStatement();

ResultSet rs2 = st1.executeQuery(q);

rs2.next();

r=rs2.getInt(“rate”);

}

catch (Exception e11)



{

}

lblR.setText(” “+r);



}

public void actionPerformed(ActionEvent ae)

{

int total=0;



int q=Integer.parseInt(tx1.getText());

total=r*q;

lblT.setText(” “+total);

}

}



 

 

 



 

 

 



 

 

 



 

 

 



 

 

Practical No. : 26

 

Aim: Write a program to implement  object serialization  and deserialization.

 

Employee.java

class Employee implements java.io.Serializable

{

public String name;



public String address;

public transient int SSN;

public int number;

 

public void mailCheck()



{           System.out.println(“Mailing a check to ” + name + ” ” + address);   }

}

 



//SerializeDemo.java

import java.io.*;

class SerializeDemo

{

public static void main(String[] args)



{

Employee e = new Employee();

e.name = “Santosh Goilkar”;

e.address = “Chembur”;

e.SSN = 10;

e.number = 1010;

try

{

FileOutputStream fileOut = new FileOutputStream(“employee.ser”);



ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(e);

out.close();

fileOut.close();

System.out.println(“serealized”);

}

catch (IOException i) {  i.printStackTrace();}



}

}

 



 

// DeserializeDemo.java

import java.io.*;

class DeserializeDemo

{

public static void main(String[] args)



{

Employee e = null;

try

{

FileInputStream fileIn = new FileInputStream(“employee.ser”);



ObjectInputStream in = new ObjectInputStream(fileIn);

e = (Employee) in.readObject();

in.close();

fileIn.close();

}

catch (IOException i)



{      i.printStackTrace();

return;


} catch (ClassNotFoundException c)

{      System.out.println(“Employee class not found”);

c.printStackTrace();

return;


}

System.out.println(“Name: ” + e.name);

System.out.println(“Address: ” + e.address);

System.out.println(“SSN: ” + e.SSN);

System.out.println(“Number: ” + e.number);

}

}



/*

Output:


H:\sem 4\Java\done>javac Employee.java

H:\sem 4\Java\done>javac SerializeDemo.java

H:\sem 4\Java\done>java SerializeDemo

serealized

H:\sem 4\Java\done>javac DeserializeDemo.java

H:\sem 4\Java\done>java DeserializeDemo

Name: Santosh Goilkar

Address: Chembur

SSN: 10

Number: 1010



*/

 

 



 

Practical No. 27

 

Aim:  Write a Servlet program for Currency Converter.

 

Form1.jsp

 

To change this template, choose Tools | Templates



and open the template in the editor.

–>















From Currenct :

Amount :



To Currency: 







Download 2.34 Mb.

Share with your friends:




The database is protected by copyright ©ininet.org 2024
send message

    Main page