233
JAVA MCA-III Page 1 A Helpful Hand Indus Institute of Technology & Engineering MCA Department ALL THE BEST

Java - A Helpful Hand

Embed Size (px)

Citation preview

Page 1: Java - A Helpful Hand

JAVA

MCA-III Page 1

A Helpful Hand

Indus Institute of Technology & Engineering

MCA Department

ALL THE BEST

Page 2: Java - A Helpful Hand

JAVA

MCA-III Page 2

Final programs (25) list which has to be

written in Lab observation book

Week 1:

1. Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0.

Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a

message stating that there are no real solutions.

2. The Fibonacci sequence is defined by the following rule. The fist two values in the sequence

are 1 and 1. Every subsequent value is the run of the two values preceding it. Write a Java

program that uses both recursive and non recursive functions to print the nth value in the

Fibonacci sequence.

Week 2:

3. Write a Java program that prompts the user for an integer and then prints out all prime

numbers up to that. Integer.

4. Write a Java program to multiply two given matrices.

5. Write a Java Program that reads a line of integers, and then displays each integers, and the

sum of all the integers (use string tokenizer class)

Week 3:

6. Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM

is a palindrome.

7. Write a Java program for sorting a given list of names in ascending order.

8. Write a java program to make frequency count of words in a given text.

Week 4:

9. Write a Java program that reads on file name from the user then displays information about

whether the file exists, whether the file is readable, whether the file is writable, the type of file

and the length of the file in bytes.

10. Write a Java program that reads a file and displays a file and displays the file on the screen,

with a line number before each line.

11. Write a Java program that displays the number of characters, lines and words in a text file.

Week 5:

Page 3: Java - A Helpful Hand

JAVA

MCA-III Page 3

12. Write a Java program that:

a) Implements stack ADT.

Week 6:

13. Write an applet that displays a simple message.

14. Develop an applet that displays 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.

Week 7:

15. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons

for the digits and for the + - X % operations. Add a text field to display the result.

Week 8:

16. Write a Java program for handling mouse events.

NOTE: write keyboard events in addition to

Written mouse events (already written)

Week 9:

17. Write a Java program for creating multiple 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.

18. Write a Java program that correctly implements producer consumer problem using the

concept of inter thread communication.

Week 11:

19. Write a Java program that implements a simple client/server application. The client sends

data to a server. The server receives the data, uses it to produce a result, and then sends the result

back to the client. The client displays the result on the console. For ex: The data sent from the

client is the radius of a circle, and the result produced by the server is the area of the circle.

Page 4: Java - A Helpful Hand

JAVA

MCA-III Page 4

Week 12:

20. Write a Java program that allows the user to draw lines, rectangles and Ovals

21. Write a java Program to display the table using JTable Component.

22.Write a Swing program using JTable

23. Write a Swing Program using JTabbed.

24. Write a Swing Program using JTree.

25.Write a java program to display TextBox, Radio Buttons, CheckBox.

Page 5: Java - A Helpful Hand

JAVA

MCA-III Page 5

OBJECT ORIENTED PROGRAMMING:

OOP Concepts:

The object oriented paradigm is built on the foundation laid by the

structured programming concepts. The fundamental change in OOP

is that a program is designed around the data being operated upon

rather upon the operations themselves. Data and its functions are

encapsulated into a single entity.OOP facilitates creating reusable

code that can eventually save a lot of work. A feature called

polymorphism permits to create multiple definitions for operators and

functions. Another feature called inheritance permits to derive new

classes from old ones. OOP introduces many new ideas and involves

Page 6: Java - A Helpful Hand

JAVA

MCA-III Page 6

a different approach to programming than the procedural

programming.

Benefits of object oriented programming:

Data security is enforced.

Inheritance saves time.

User defined data types can be easily constructed.

Inheritance emphasizes inventions of new data types.

Large complexity in the software development cn be easily

managed.

Basic C++ Knowledge:

C++ began its life in Bell Labs, where Bjarne Stroustrup developed the

language in the early 1980s. C++ is a powerful and flexible

programming language. Thus, with minor exceptions, C++ is a

superset of the C Programming language.

The principal enhancement being the object –oriented concept of

a class.

A Class is a user defined type that encapsulates many important

mechanisms. Classes enable programmers to break an application

up into small, manageable pieces, or objects.

Basic concepts of Object oriented programming:

Page 7: Java - A Helpful Hand

JAVA

MCA-III Page 7

Object:

Objects are the basic run time entities in an object-oriented

system.

thy may represent a person, a place, a bank account, a

table of data or any item that the program has to handle.

Class:

The entire set of data and code of an object can be made of

a user defined data type with the help of a class.

I fact, Objects are variables of the type class.

Once a class has been defined, we can create any number of

objects belonging to that class

A class is thus a collection of objects of similar type.

for example: mango, apple, and orange are members of the

class fruit.

ex: fruit mango; will create an object mango belonging

to the class fruit.

Data Abstraction and Encapsulation:

The wrapping up of data and functions in to a single unit is

known as encapsulation.

Data encapsulation is the most striking feature of a class.

The data is not accessible to the outside world, and only those

functions which are wrapped in the class can access.

Page 8: Java - A Helpful Hand

JAVA

MCA-III Page 8

This insulation of the data from direct access by the program is

called data hiding.

Abstraction :

Abstraction referes to the act of representing essential features

without including the background details or explanations.

since the classes use the concept of data abstraction ,thy are

known as abstraction data type(ADT).

Inheritance :

Inheritance is the process by which objects of one class

acquire the properties of objects of another class. Inheritance

supports the concept of hierarchical classification.

Page 9: Java - A Helpful Hand

JAVA

MCA-III Page 9

for example:

The bird 'robin ' is a part of the class 'flying bird' which is agian a

part of the class 'bird'. The concept of inheritance provide the idea

of reusability.

POLYMORPHISM:

Polymorphism is another important oop concept. Polymorphism

means the ability to take more than one form. an operation may

Bird

Attributes

Flying

bird

Attributes

:

Non flying

bird

Attributes:

Robin

Attributes

Swallow

Attributes

Penguin

Attributes

Kiwi

Attributes

Page 10: Java - A Helpful Hand

JAVA

MCA-III Page 10

exhibit different instances. The behavior depends upon the types of

data used in the operation.

The process of making an operator to exhibit different behaviors

in different instance is known as operator overloading.

Polymorphism plays an important role in allowing objects having

different internal structures to share the same external interface.

Polymorphism is extensively used if implementing inheritance.

The Object-Oriented Approach

The fundamental idea behind object-oriented languages is to

combine into a single program entity both data and the functions

that operate on that data. Such an entity is called an object.

An object's functions, called member functions in C++ (because

they belong to a particular class of objects), typically provide the

only way to access its data. If you want to read a data item in an

object, you call a member function in the object. It will read the item

and return the value to you. You can't access the data directly. The

data is hidden, so it is safe from accidental alteration. Data and its

Shape

Circle Object

Box Object

Triangle Object

Page 11: Java - A Helpful Hand

JAVA

MCA-III Page 11

functions are said to be encapsulated into a single entity.

Encapsulation and data hiding are key terms in the description of

object-oriented languages.

Page 12: Java - A Helpful Hand

JAVA

MCA-III Page 12

Java History:

Java is a general-purpose; object oriented programming language

developed by Sun Microsystems of USA in 1991. Originally called “oak” by James

Gosling, one of the inventors if the language. This goal had a strong impact on the

development team to make the language simple, portable, highly reliable and

powerful language.

Java also adds some new features. While C++ is a superset of C. Java

is neither a superset nor a subset of C or C++.

C++

C

Java

Page 13: Java - A Helpful Hand

JAVA

MCA-III Page 13

Process of building and running java application programs:

The way these tools are applied to build and run application programs is create a

program. We need create a source code file using a text editor. The source code is

then compiled using the java compiler javac and executed using the java interpreter

java. The java debugger jdb is used to find errors. A complied java program can be

converted into a source code.

Text Editor

Java Source

Code Javado

c

HTML

files

Javac

Java Class

File Javah

Header

Files

Java (only file

name)

Jdb

(database)

Java

progra

m

Page 14: Java - A Helpful Hand

JAVA

MCA-III Page 14

SOLUTIONS

Program Statement :

Write a Java program that prints all real solutions to the quadratic

equation ax2+bx+c = 0. Read in a, b, c and use the quadratic

formula. If the discriminant

b2-4ac is negative, display a message stating that there are no real

solutions.

Program :

import java.io.*;

class Quadratic

{

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

{

double x1,x2,disc,a,b,c;

InputStreamReader obj=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(obj);

Page 15: Java - A Helpful Hand

JAVA

MCA-III Page 15

System.out.println("enter a,b,c values");

a=Double.parseDouble(br.readLine());

b=Double.parseDouble(br.readLine());

c=Double.parseDouble(br.readLine());

disc=(b*b)-(4*a*c);

if(disc==0)

{

System.out.println("roots are real and equal ");

x1=x2=-b/(2*a);

System.out.println("roots are "+x1+","+x2);

}

else if(disc>0)

{

System.out.println("roots are real and unequal");

x1=(-b+Math.sqrt(disc))/(2*a);

x2=(-b+Math.sqrt(disc))/(2*a);

Page 16: Java - A Helpful Hand

JAVA

MCA-III Page 16

System.out.println("roots are "+x1+","+x2);

}

else

{

System.out.println("roots are imaginary");

}

}

}

Input & Output :

Page 17: Java - A Helpful Hand

JAVA

MCA-III Page 17

Program Statement :

The Fibonacci sequence is defined by the following rule. The first 2

values in the sequence are 1, 1. Every subsequent value is the sum of

the 2 values preceding it. Write a Java program that uses both

recursive and non-recursive functions to print the nth value of the

Fibonacci sequence.

Program :

/*Non Recursive Solution*/

import java.util.Scanner;

class Fib {

public static void main(String args[ ]) {

Scanner input=new Scanner(System.in);

int i,a=1,b=1,c=0,t;

System.out.println("Enter value of t:");

t=input.nextInt();

System.out.print(a);

System.out.print(" "+b);

for(i=0;i<t-2;i++) {

c=a+b;

a=b;

Page 18: Java - A Helpful Hand

JAVA

MCA-III Page 18

b=c;

System.out.print(" "+c);

}

System.out.println();

System.out.print(t+"th value of the series is: "+c);

}

}

Input & Output :

Page 19: Java - A Helpful Hand

JAVA

MCA-III Page 19

Page 20: Java - A Helpful Hand

JAVA

MCA-III Page 20

/* Recursive Solution*/

import java.io.*;

import java.lang.*;

class Demo {

int fib(int n) {

if(n==1)

return (1);

else if(n==2)

return (1);

else

return (fib(n-1)+fib(n-2));

}

}

class RecFibDemo {

public static void main(String args[])throws IOException {

Page 21: Java - A Helpful Hand

JAVA

MCA-III Page 21

InputStreamReader obj=new

InputStreamReader(System.in);

BufferedReader br=new BufferedReader(obj);

System.out.println("enter last number");

int n=Integer.parseInt(br.readLine());

Demo ob=new Demo();

System.out.println("fibonacci series is as follows");

int res=0;

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

res=ob.fib(i);

System.out.println(" "+res);

}

System.out.println();

System.out.println(n+"th value of the series is "+res);

}

}

Input & Output :

Page 22: Java - A Helpful Hand

JAVA

MCA-III Page 22

Page 23: Java - A Helpful Hand

JAVA

MCA-III Page 23

Program Statement :

WAJP that prompts the user for an integer and then prints out all the

prime numbers up to that Integer.

Program :

Import java.util.*

class Test {

void check(int num) {

System.out.println ("Prime numbers up to "+num+" are:");

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

for (int j=2;j<i;j++) {

Page 24: Java - A Helpful Hand

JAVA

MCA-III Page 24

if(i%j==0)

break;

else if((i%j!=0)&&(j==i-1))

System.out.print(“ “+i);

}

}

} //end of class Test

class Prime {

public static void main(String args[ ]) {

Test obj1=new Test();

Scanner input=new Scanner(System.in);

System.out.println("Enter the value of n:");

int n=input.nextInt();

obj1.check(n);

}

}

Page 25: Java - A Helpful Hand

JAVA

MCA-III Page 25

Input & Output :

Page 26: Java - A Helpful Hand

JAVA

MCA-III Page 26

Program Statement :

WAJP that checks whether a given string is a palindrome or not. Ex:

MADAM is a palindrome.

Program :

import java.io.*;

Page 27: Java - A Helpful Hand

JAVA

MCA-III Page 27

class Palind {

public static void main(String args[ ])throws IOException {

BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Enter the string to check for palindrome:");

String s1=br.readLine();

StringBuffer sb=new StringBuffer();

sb.append(s1);

sb.reverse();

String s2=sb.toString();

if(s1.equals(s2))

System.out.println("palindrome");

else

System.out.println("not palindrome");

}

}

Page 28: Java - A Helpful Hand

JAVA

MCA-III Page 28

Input &

Output

Page 29: Java - A Helpful Hand

JAVA

MCA-III Page 29

Program Statement :

WAJP for sorting a given list of names in ascending order.

Program :

import java.io.*;

class Test {

int len,i,j;

String arr[ ];

Page 30: Java - A Helpful Hand

JAVA

MCA-III Page 30

Test(int n) {

len=n;

arr=new String[n];

}

String[ ] getArray()throws IOException {

BufferedReader br=new BufferedReader (new

InputStreamReader(System.in));

System.out.println ("Enter the strings U want to sort----");

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

arr[i]=br.readLine();

return arr;

}

String[ ] check()throws ArrayIndexOutOfBoundsException {

for (i=0;i<len-1;i++) {

for(int j=i+1;j<len;j++) {

if ((arr[i].compareTo(arr[j]))>0) {

String s1=arr[i];

arr[i]=arr[j];

arr[j]=s1;

}

Page 31: Java - A Helpful Hand

JAVA

MCA-III Page 31

}

}

return arr;

}

void display()throws ArrayIndexOutOfBoundsException {

System.out.println ("Sorted list is---");

for (i=0;i<len;i++)

System.out.println(arr[i]);

}

} //end of the Test class

class Ascend {

public static void main(String args[ ])throws IOException {

Test obj1=new Test(4);

obj1.getArray();

obj1.check();

obj1.display();

}

}

Input & Output :

Page 32: Java - A Helpful Hand

JAVA

MCA-III Page 32

Page 33: Java - A Helpful Hand

JAVA

MCA-III Page 33

Program Statement :

WAJP to multiply two given matrices.

Program :

import java.util.*;

class Test {

int r1,c1,r2,c2;

Test(int r1,int c1,int r2,int c2) {

this.r1=r1;

this.c1=c1;

this.r2=r2;

this.c2=c2;

}

int[ ][ ] getArray(int r,int c) {

int arr[][]=new int[r][c];

System.out.println("Enter the elements for "+r+"X"+c+"

Matrix:");

Scanner input=new Scanner(System.in);

Page 34: Java - A Helpful Hand

JAVA

MCA-III Page 34

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

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

arr[i][j]=input.nextInt();

return arr;

}

int[ ][ ] findMul(int a[ ][ ],int b[ ][ ]) {

int c[][]=new int[r1][c2];

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

for (int j=0;j<c2;j++) {

c[i][j]=0;

for (int k=0;k<r2;k++)

c[i][j]=c[i][j]+a[i][k]*b[k][j];

}

return c;

}

void putArray(int res[ ][ ]) {

System.out.println ("The resultant "+r1+"X"+c2+" Matrix is:");

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

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

System.out.print(res[i][j]+" ");

Page 35: Java - A Helpful Hand

JAVA

MCA-III Page 35

System.out.println();

}

}

} //end of Test class

class MatrixMul {

public static void main(String args[ ])throws IOException {

Test obj1=new Test(2,3,3,2);

Test obj2=new Test(2,3,3,2);

int x[ ][ ],y[ ][ ],z[ ][ ];

System.out.println("MATRIX-1:");

x=obj1.getArray(2,3); //to get the matrix from user

System.out.println("MATRIX-2:");

y=obj2.getArray(3,2);

z=obj1.findMul(x,y); //to perform the multiplication

obj1.putArray(z); // to display the resultant matrix

}

}

Page 36: Java - A Helpful Hand

JAVA

MCA-III Page 36

Input & Output :

Page 37: Java - A Helpful Hand

JAVA

MCA-III Page 37

Page 38: Java - A Helpful Hand

JAVA

MCA-III Page 38

Program Statement :

WAJP that reads a line of integers and then displays each integer

and the sum of all integers. (use StringTokenizer class)

Program :

// Using StringTokenizer class

import java.lang.*;

import java.util.*;

class tokendemo {

public static void main(String args[ ]) {

String s="10,20,30,40,50";

int sum=0;

Page 39: Java - A Helpful Hand

JAVA

MCA-III Page 39

StringTokenizer a=new StringTokenizer(s,",",false);

System.out.println("integers are ");

while(a.hasMoreTokens()) {

int b=Integer.parseInt(a.nextToken());

sum=sum+b;

System.out.println(" "+b);

}

System.out.println("sum of integers is "+sum);

}

}

// Alternate solution using command line arguments

class Arguments {

public static void main(String args[ ]) {

int sum=0;

int n=args.length;

System.out.println("length is "+n);

int arr[]=new int[n];

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

arr[i]=Integer.parseInt(args[i]);

Page 40: Java - A Helpful Hand

JAVA

MCA-III Page 40

System.out.println("The enterd values are:");

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

System.out.println(arr[i]);

System.out.println("sum of enterd integers is:");

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

sum=sum+arr[i];

System.out.println(sum);

}

}

Input & Output :

Page 41: Java - A Helpful Hand

JAVA

MCA-III Page 41

Page 42: Java - A Helpful Hand

JAVA

MCA-III Page 42

Program Statement :

WAJP that reads on file name from the user, then displays

information about whether the file exists, whether the file is readable,

wheteher the file is writable, the type of file and the length of the file

in bytes.

Program :

import java.io.File;

class FileDemo {

static void p(String s) {

System.out.println(s);

}

public static void main(String args[ ]) {

File f1 = new File(args[0]);

p("File Name: " + f1.getName());

p("Path: " + f1.getPath());

p("Abs Path: " + f1.getAbsolutePath());

p("Parent: " + f1.getParent());

p(f1.exists() ? "exists" : "does not exist");

p(f1.canWrite() ? "is writeable" : "is not writeable");

p(f1.canRead() ? "is readable" : "is not readable");

p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));

p(f1.isFile() ? "is normal file" : "might be a named pipe");

p(f1.isAbsolute() ? "is absolute" : "is not absolute");

p("File last modified: " + f1.lastModified());

p("File size: " + f1.length() + " Bytes");

}

}

Page 43: Java - A Helpful Hand

JAVA

MCA-III Page 43

Input & Output :

:

Page 44: Java - A Helpful Hand

JAVA

MCA-III Page 44

Program Statement :

WAJP that reads a file and displays the file on the screen, with a line

number before each line.

Program :

import java.io.*;

class LineNum{

public static void main(String args[]){

String thisline;

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

{

try{

LineNumberReader br=new LineNumberReader(new

FileReader(args[i]));

while((thisline=br.readLine())!=null)

{

System.out.println(br.getLineNumber()+"."+thisline);

}

}catch(IOException e){

System.out.println("error:"+e);

Page 45: Java - A Helpful Hand

JAVA

MCA-III Page 45

}

}

}

}

Input & Output :

Page 46: Java - A Helpful Hand

JAVA

MCA-III Page 46

Page 47: Java - A Helpful Hand

JAVA

MCA-III Page 47

Program Statement :

WAJP that displays the number of characters, lines and words in a

text file.

Program :

import java.io.*;

public class FileStat {

public static void main(String args[ ])throws IOException {

long nl=0,nw=0,nc=0;

String line;

BufferedReader br=new BufferedReader(new

FileReader(args[0]));

while ((line=br.readLine())!=null) {

nl++;

nc=nc+line.length();

int i=0;

boolean pspace=true;

while (i<line.length()) {

char c=line.charAt(i++);

boolean cspace=Character.isWhitespace(c);

if (pspace&&!cspace)

Page 48: Java - A Helpful Hand

JAVA

MCA-III Page 48

nw++;

pspace=cspace;

}

}

System.out.println("Number of Characters"+nc);

System.out.println("Number of Characters"+nw);

System.out.println("Number of Characters"+nl);

}}

// Alternate solution using StringTokenizer

import java.io.*;

import java.util.*;

public class FileStat {

public static void main(String args[ ])throws IOException {

long nl=0,nw=0,nc=0;

String line;

BufferedReader br=new BufferedReader(new

FileReader(args[0]));

while ((line=br.readLine())!=null) {

nl++;

nc=nc+line.length();

StringTokenizer st = new StringTokenizer(line);

Page 49: Java - A Helpful Hand

JAVA

MCA-III Page 49

nw += st.countTokens();

}

System.out.println("Number of Characters"+nc);

System.out.println("Number of Characters"+nw);

System.out.println("Number of Characters"+nl);

}}

Input & Output :

Page 50: Java - A Helpful Hand

JAVA

MCA-III Page 50

Program Statement :

WAJP that:

(a) Implements a Stack ADT

(b) Converts Infix expression to Postfix expression

(c) Evaluates a Postfix expression

Program :

import java.io.*;

interface stack

{

void push(int item);

int pop();

}

class Stackimpl

{

private int stck[];

private int top;

Page 51: Java - A Helpful Hand

JAVA

MCA-III Page 51

Stackimpl(int size)

{

stck=new int[size];

top=-1;

}

void push(int item)

{

if(top==stck.length-1)

System.out.println("stack is full insertion is not

possible");

else

stck[++top]=item;

}

int pop()

{

if(top==-1)

{

Page 52: Java - A Helpful Hand

JAVA

MCA-III Page 52

System.out.println("stack is empty deletion is not

possible");

return 0;

}

else

return stck[top--];

}

}

class Stackdemo

{

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

{

int a[];

BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));

System.out.println("enter the size of the array");

int n=Integer.parseInt(br.readLine());

Page 53: Java - A Helpful Hand

JAVA

MCA-III Page 53

Stackimpl obj1=new Stackimpl(n);

a=new int[n];

System.out.println("enter numbers into the stack");

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

a[i]=Integer.parseInt(br.readLine());

System.out.println("numbers are inserted");

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

obj1.push(a[i]);

System.out.println("The following numbers are poped

out.");

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

System.out.println(" "+obj1.pop());

}

}

Page 54: Java - A Helpful Hand

JAVA

MCA-III Page 54

Input & Output :

Page 55: Java - A Helpful Hand

JAVA

MCA-III Page 55

Program Statement :

Write an Applet that displays a simple message.

Program :

import java.awt.*;

import java.applet.*;

/*

<applet code = “HelloJava” width = 200 height = 60 >

</applet>

*/

public class HelloJava extends Applet {

public void paint(Graphics g) {

g.drawString(“Hello Java”, 10, 100);

}

}

Input & Output :

Page 56: Java - A Helpful Hand

JAVA

MCA-III Page 56

Page 57: Java - A Helpful Hand

JAVA

MCA-III Page 57

Program Statement :

Write an Applet that computes the payment of a loan based on the

amount of the loan, the interest rate and the number of months. It

takes one parameter from the browser: Monthly rate; if true, the

interest rate is per month, otherwise the interest rate is annual.

Program :

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code = "LoanPayment" width=500 height=300 >

<param name = monthlyRate value=true>

</applet>

*/

public class LoanPayment extends Applet implements ActionListener

{

TextField amt_t, rate_t, period_t;

Button compute = new Button("Compute");

boolean monthlyRate;

Page 58: Java - A Helpful Hand

JAVA

MCA-III Page 58

public void init() {

Label amt_l = new Label("Amount: ");

Label rate_l = new Label("Rate: ", Label.CENTER);

Label period_l = new Label("Period: ", Label.RIGHT);

amt_t = new TextField(10);

rate_t = new TextField(10);

period_t = new TextField(10);

add(amt_l);

add(amt_t);

add(rate_l);

add(rate_t);

add(period_l);

add(period_t);

add(compute);

amt_t.setText("0");

rate_t.setText("0");

period_t.setText("0");

Page 59: Java - A Helpful Hand

JAVA

MCA-III Page 59

monthlyRate =

Boolean.valueOf(getParameter("monthlyRate"));

amt_t.addActionListener(this);

rate_t.addActionListener(this);

period_t.addActionListener(this);

compute.addActionListener(this);

}

public void paint(Graphics g) {

double amt=0, rate=0, period=0, payment=0;

String amt_s, rate_s, period_s, payment_s;

g.drawString("Input the Loan Amt, Rate and Period in

each box and press Compute", 50,100);

try {

amt_s = amt_t.getText();

amt = Double.parseDouble(amt_s);

rate_s = rate_t.getText();

rate = Double.parseDouble(rate_s);

period_s = period_t.getText();

Page 60: Java - A Helpful Hand

JAVA

MCA-III Page 60

period = Double.parseDouble(period_s);

}

catch (Exception e) { }

if (monthlyRate)

payment = amt * period * rate * 12 / 100;

else

payment = amt * period * rate / 100;

payment_s = String.valueOf(payment);

g.drawString("The LOAN PAYMENT amount is: ", 50, 150);

g.drawString(payment_s, 250, 150);

}

public void actionPerformed(ActionEvent ae) {

repaint();

}

}

Input & Output :

Page 61: Java - A Helpful Hand

JAVA

MCA-III Page 61

Page 62: Java - A Helpful Hand

JAVA

MCA-III Page 62

Program Statement :

WAJP that works as a simple calculator. Use a grid layout to arrange

buttons for the digits and for the + - x / % operations. Add atext field

to display the result.

Program :

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);

Page 63: Java - A Helpful Hand

JAVA

MCA-III Page 63

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;

}

else

result.setText(result.getText()+no);

}

public CalculatorPanel() {

setLayout(new BorderLayout());

result.setEditable(false);

result.setSize(300,200);

add(result,BorderLayout.NORTH);

Page 64: Java - A Helpful Hand

JAVA

MCA-III Page 64

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);

Page 65: Java - A Helpful Hand

JAVA

MCA-III Page 65

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);

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);

Page 66: Java - A Helpful Hand

JAVA

MCA-III Page 66

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.CENTER);

}

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");

Page 67: Java - A Helpful Hand

JAVA

MCA-III Page 67

else 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());

Page 68: Java - A Helpful Hand

JAVA

MCA-III Page 68

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");

Page 69: Java - A Helpful Hand

JAVA

MCA-III Page 69

}

}

}

Input & Output :

Page 70: Java - A Helpful Hand

JAVA

MCA-III Page 70

Program Statement :

WAJP for handling mouse events.

Program :

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MouseEvents" width=300 height=100>

</applet>

*/

public class MouseEvents extends Applet

implements MouseListener, MouseMotionListener {

String msg = "";

int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {

addMouseListener(this);

addMouseMotionListener(this);

}

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse clicked.";

repaint();

}

// Handle mouse entered.

Page 71: Java - A Helpful Hand

JAVA

MCA-III Page 71

public void mouseEntered(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse entered.";

repaint();

}

// Handle mouse exited.

public void mouseExited(MouseEvent me) {

// save coordinates

mouseX = 0;

mouseY = 10;

msg = "Mouse exited.";

repaint();

}

// Handle button pressed.

public void mousePressed(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Down";

repaint();

}

// Handle button released.

public void mouseReleased(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

msg = "Up";

repaint();

}

// Handle mouse dragged.

public void mouseDragged(MouseEvent me) {

// save coordinates

mouseX = me.getX();

mouseY = me.getY();

Page 72: Java - A Helpful Hand

JAVA

MCA-III Page 72

msg = "*";

showStatus("Dragging mouse at " + mouseX + ", " + mouseY);

repaint();

}

// Handle mouse moved.

public void mouseMoved(MouseEvent me) {

// show status

showStatus("Moving mouse at " + me.getX() + ", " + me.getY());

}

// Display msg in applet window at current X,Y location.

public void paint(Graphics g) {

g.drawString(msg, mouseX, mouseY);

}

}

Input & Output :

Page 73: Java - A Helpful Hand

JAVA

MCA-III Page 73

Program Statement :

WAJP for creating multiple threads.

Program :

class NewThread implements Runnable {

String name; // name of thread

Thread t;

NewThread(String threadname) {

name = threadname;

Page 74: Java - A Helpful Hand

JAVA

MCA-III Page 74

t = new Thread(this, name);

System.out.println("New thread: " + t);

t.start(); // Start the thread

}

// This is the entry point for thread.

public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println(name + ": " + i);

Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println(name + "Interrupted");

}

System.out.println(name + " exiting.");

}

}

class MultiThreadDemo {

public static void main(String args[]) {

new NewThread("One"); // start threads

new NewThread("Two");

new NewThread("Three");

try {

// wait for other threads to end

Thread.sleep(10000);

} catch (InterruptedException e) {

System.out.println("Main thread Interrupted");

}

System.out.println("Main thread exiting.");

}

}

Page 75: Java - A Helpful Hand

JAVA

MCA-III Page 75

Input & Output :

Page 76: Java - A Helpful Hand

JAVA

MCA-III Page 76

Page 77: Java - A Helpful Hand

JAVA

MCA-III Page 77

Program Statement :

WAJP that correctly implements Producer-Consumer problem using

the concept of Inter Thread Communication.

Program :

class Q {

int n;

boolean valueSet = false;

synchronized int get() {

if (!valueSet)

try {

wait();

} catch (InterruptedException e) { }

System.out.println(“Got: “ + n);

valueSet = false;

notify();

return n;

}

Page 78: Java - A Helpful Hand

JAVA

MCA-III Page 78

synchronized void put(int n) {

if (valueSet)

try {

wait();

} catch (InterruptedException e) { }

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();

}

Page 79: Java - A Helpful Hand

JAVA

MCA-III Page 79

public void run() {

int i = 0;

while(true) {

q.put(i++);

}

}

}

class Consumer implements Runnable {

Q q;

Consumer(Q q) {

this.q = q;

new Thread(this, “Consumer”).start();

}

public void run() {

while(true) {

q.get();

}

}

Page 80: Java - A Helpful Hand

JAVA

MCA-III Page 80

}

class PC {

public static void main (String args[ ]) {

Q q = new Q();

new Producer(q);

new Consumer(q);

System.out.println(“Press Ctrl-C to stop”);

}

}

Input & Output :

Page 81: Java - A Helpful Hand

JAVA

MCA-III Page 81

Page 82: Java - A Helpful Hand

JAVA

MCA-III Page 82

Program Statement :

WAJP that lets users create Pie charts. Design your own user

interface (with Swings & AWT).

Program :

import java.awt.*;

import java.applet.*;

/*<applet code=PiChart.class width=600 height=600></applet>*/

public class PiChart extends Applet {

public void paint(Graphics g) {

setBackground(Color.green);

g.drawString("PI CHART",200,40);

g.setColor(Color.blue);

g.fillOval(50,50,150,150);

g.setColor(Color.white);

g.drawString("40%",130,160);

g.setColor(Color.magenta);

Page 83: Java - A Helpful Hand

JAVA

MCA-III Page 83

g.fillArc(50,50,150,150,0,90);

g.setColor(Color.white);

g.drawString("25%",140,100);

g.setColor(Color.yellow);

g.fillArc(50,50,150,150,90,120);

g.setColor(Color.black);

g.drawString("35%",90,100);

g.setColor(Color.yellow);

g.fillOval(250,50,150,150);

g.setColor(Color.black);

g.drawString("15%",350,150);

g.setColor(Color.magenta);

g.fillArc(250,50,150,150,0,30);

g.setColor(Color.black);

g.drawString("5%",360,120);

g.setColor(Color.blue);

g.fillArc(250,50,150,150,30,120);

g.setColor(Color.white);

g.drawString("30%",330,100);

g.setColor(Color.black);

g.fillArc(250,50,150,150,120,180);

Page 84: Java - A Helpful Hand

JAVA

MCA-III Page 84

g.setColor(Color.white);

g.drawString("50%",280,160);

}

}

Input & Output :

Page 85: Java - A Helpful Hand

JAVA

MCA-III Page 85

Page 86: Java - A Helpful Hand

JAVA

MCA-III Page 86

Program Statement :

WAJP that allows user to draw lines, rectangles and ovals.

Program :

import javax.swing.*;

import java.awt.Graphics;

public class choice extends JApplet

{

int i,ch;

public void init()

{

String input;

input=JOptionPane.showInputDialog("enter your

choice(1-lines,2-rectangles,3-ovals)");

ch=Integer.parseInt(input);

}

public void paint(Graphics g)

{

switch(ch)

{

case 1:{

Page 87: Java - A Helpful Hand

JAVA

MCA-III Page 87

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

{

g.drawLine(10,10,250,10*i);

}

break;

}

case 2:{

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

{

g.drawRect(10*i,10*i,50+10*i,50+10*i);

}

break;

}

case 3:{

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

{

g.drawOval(10*i,10*i,50+10*i,50+10*i);

}

break;

}}}}

Page 88: Java - A Helpful Hand

JAVA

MCA-III Page 88

Input & Output :

Page 89: Java - A Helpful Hand

JAVA

MCA-III Page 89

Page 90: Java - A Helpful Hand

JAVA

MCA-III Page 90

Program Statement :

WAJP that implements a simple client/server application. The client

sends data to a server. The server receives the data, uses it to

produce a result and then sends the result back to the client. The

client displays the result on the console. For ex: The data sent from

the client is the radius of a circle and the result produced by the

server is the area of the circle.

Program :

// Server Program

import java.io.*;

import java.net.*;

import java.util.*;

public class Server {

public void static main (String args [ ] ) {

try {

// create a server socket

ServerSocket s = new ServerSocket(8000);

// start listening for connections on srver socket

Page 91: Java - A Helpful Hand

JAVA

MCA-III Page 91

Socket connectToClient = s.accept();

// create a buffered reader stream to get data from

client

BufferedReader isFromClient = new

BufferedReader(new InputStreamReader

(connectToClient.getInputStream()));

// create a buffer reader to send result to client

PrintWriter osToClient = new

PrintWriter(connectToClient.getOutputStream(), true);

// continuously read from client, process, send back

while (true) {

// read a line and create string tokenizer

StringTokenizer st = new

StringTokenizer(isFromClient.readLine());

//convert string to double

double radius = new

Double(st.nextToken()).doubleValue();

// display radius on console

Page 92: Java - A Helpful Hand

JAVA

MCA-III Page 92

System.out.println(“Radius received from client:

“ + radius);

// comput area

double area = radius * radius *Math.PI;

// send result to client

osToClient.println(area);

// print result on console

System.out.println(“Area found: “ +area);

}

} catch (IOException e) {

System.err.println(e);

}

}

}

// Client Program

import java.io.*;

Page 93: Java - A Helpful Hand

JAVA

MCA-III Page 93

import java.net.*;

import java.util.*;

public class Client {

public void static main (String args [ ] ) {

try {

// create a socket to connect to server

Socket connectToServer = new Socket(“local host”,

8000);

// create a buffered input stream to get result from

server

BufferedReader isFromServer = new

BufferedReader(new InputStreamReader

(connectToServer.getInputStream()));

// create a buffer output stream to send data to

server

PrintWriter osToServer = new

PrintWriter(connectToClient.getOutputStream(), true);

// continuously send radius and get area

while (true) {

Scanner input=new Scanner(System.in);

Page 94: Java - A Helpful Hand

JAVA

MCA-III Page 94

System.out.print(“Please enter a radius: “);

double radius =input.nextDouble();

// display radius on console

osToServer.println(radius);

// get area from server

StringTokenizer st = new

StringTokenizer(isFromServer.readLine());

// convert string to double

Double area = new

Double(st.nextToken()).doubleValue();

// print result on console

System.out.println(“Area received from the

server is: “ +area);

}

} catch (IOException e) {

System.err.println(e);

}

}

}

Page 95: Java - A Helpful Hand

JAVA

MCA-III Page 95

Input & Output :

Page 96: Java - A Helpful Hand

JAVA

MCA-III Page 96

Page 97: Java - A Helpful Hand

JAVA

MCA-III Page 97

Program Statement :

WAJP that illustrates how runtime polymorphism is achieved.

Program :

class Figure {

double dim1;

double dim2;

Figure(double a, double b) {

dim1 = a;

dim2 = b;

}

double area() {

System.out.println("Area for Figure is undefined.");

return 0;

}

}

class Rectangle extends Figure {

Rectangle(double a, double b) {

super(a, b);

}

// override area for rectangle

double area() {

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;

}

}

class Triangle extends Figure {

Triangle(double a, double b) {

Page 98: Java - A Helpful Hand

JAVA

MCA-III Page 98

super(a, b);

}

// override area for right triangle

double area() {

System.out.println("Inside Area for Triangle.");

return dim1 * dim2 / 2;

}

}

class FindAreas {

public static void main(String args[]) {

Figure f = new Figure(10, 10);

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

Figure figref;

figref = r;

System.out.println("Area is " + figref.area());

figref = t;

System.out.println("Area is " + figref.area());

figref = f;

System.out.println("Area is " + figref.area());

}

}

Page 99: Java - A Helpful Hand

JAVA

MCA-III Page 99

Input & Output :

Page 100: Java - A Helpful Hand

JAVA

MCA-III Page 100

Program Statement :

WAJP to generate a set of random numbers. Find its sum and

average. The program should also display ‘*’ based on the random

numbers generated.

Program :

import java.util.*;

class RandNum {

public static void main(String ax[ ]) {

int a[ ]=new int[5];

int sum=0;

Random r=new Random();

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

a[i]=r.nextInt(10);

System.out.print(a[i]);

for(int y=0;y<a[i];y++)

System.out.print(" *");

System.out.println("");

}

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

sum=sum+a[i];

Page 101: Java - A Helpful Hand

JAVA

MCA-III Page 101

System.out.println("Sum="+sum);

System.out.println("Avg="+(double)sum/a.length);

}

}

Input & Output :

Page 102: Java - A Helpful Hand

JAVA

MCA-III Page 102

Page 103: Java - A Helpful Hand

JAVA

MCA-III Page 103

Program Statement :

WAJP to create an abstract class named Shape, that contains an

empty method named numberOfSides(). Provide three classes

named Trapezoid, Triangle and Hexagon, such that each one of

the classes contains only the method numberOfSides(), that

contains the number of sides in the given geometrical figure.

Program :

abstract class Shape

{

abstract void numberOfSides();

}

class Trapezoid extends Shape{

Page 104: Java - A Helpful Hand

JAVA

MCA-III Page 104

void numberOfSides() {

System.out.println(" Trapezoidal has four sides");

}

}

class Triangle extends Shape {

void numberOfSides()

{

System.out.println("Triangle has three sides");

}

}

class Hexagon extends Shape {

void numberOfSides()

{

System.out.println("Hexagon has six sides");

}

}

class ShapeDemo {

public static void main(String args[ ]) {

Trapezoid t=new Trapezoid();

Triangle r=new Triangle();

Hexagon h=new Hexagon();

Shape s;

Page 105: Java - A Helpful Hand

JAVA

MCA-III Page 105

s=t;

s.numberOfSides();

s=r;

s.numberOfSides();

s=h;

s.numberOfSides();

}

}

Input & Output :

Page 106: Java - A Helpful Hand

JAVA

MCA-III Page 106

Program Statement :

WAJP to implement a Queue, using user defined Exception Handling

(also make use of throw, throws).

Program :

import java.util.Scanner;

class ExcQueue extends Exception {

ExcQueue(String s) {

super(s);

}

}

class Queue {

int front,rear;

int q[ ]=new int[10];

Queue() {

rear=-1;

front=-1;

Page 107: Java - A Helpful Hand

JAVA

MCA-III Page 107

}

void enqueue(int n) throws ExcQueue {

if (rear==9)

throw new ExcQueue("Queue is full");

rear++;

q[rear]=n;

if (front==-1)

front=0;

}

int dequeue() throws ExcQueue {

if (front==-1)

throw new ExcQueue("Queue is empty");

int temp=q[front];

if (front==rear)

front=rear=-1;

else

front++;

return(temp);

}

}

Page 108: Java - A Helpful Hand

JAVA

MCA-III Page 108

class UseQueue {

public static void main(String args[ ]) {

Queue a=new Queue();

try {

a.enqueue(5);

a.enqueue(20);

} catch (ExcQueue e) {

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

}

try {

System.out.println(a.dequeue());

System.out.println(a.dequeue());

System.out.println(a.dequeue());

} catch(ExcQueue e) {

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

}

}

}

Input & Output :

Page 109: Java - A Helpful Hand

JAVA

MCA-III Page 109

Page 110: Java - A Helpful Hand

JAVA

MCA-III Page 110

Program Statement :

WAJP that creates 3 threads by extending Thread class. First thread

displays “Good Morning” every 1 sec, the second thread displays

“Hello” every 2 seconds and the third displays “Welcome” every 3

seconds. (Repeat the same by implementing Runnable)

Program :

// Using Thread class

class One extends Thread {

public void run() {

for ( ; ; ) {

try{

sleep(1000);

}catch(InterruptedException e){}

System.out.println("Good Morning");

}

}

}

class Two extends Thread {

public void run() {

Page 111: Java - A Helpful Hand

JAVA

MCA-III Page 111

for ( ; ; ) {

try{

sleep(2000);

}catch(InterruptedException e){}

System.out.println("Hello");

}

}

}

class Three extends Thread {

public void run() {

for ( ; ; ) {

try{

sleep(3000);

}catch(InterruptedException e){}

System.out.println("Welcome");

}

}

}

class MyThread {

public static void main(String args[ ]) {

Page 112: Java - A Helpful Hand

JAVA

MCA-III Page 112

Thread t = new Thread();

One obj1=new One();

Two obj2=new Two();

Three obj3=new Three();

Thread t1=new Thread(obj1);

Thread t2=new Thread(obj2);

Thread t3=new Thread(obj3);

t1.start();

try{

t.sleep(1000);

}catch(InterruptedException e){}

t2.start();

try{

t.sleep(2000);

}catch(InterruptedException e){}

t3.start();

try{

t.sleep(3000);

}catch(InterruptedException e){}

}

Page 113: Java - A Helpful Hand

JAVA

MCA-III Page 113

}

// Using Runnable interface

class One implements Runnable {

One( ) {

new Thread(this, "One").start();

try{

Thread.sleep(1000);

}catch(InterruptedException e){}

}

public void run() {

for ( ; ; ) {

try{

Thread.sleep(1000);

}catch(InterruptedException e){}

System.out.println("Good Morning");

}

}

}

Page 114: Java - A Helpful Hand

JAVA

MCA-III Page 114

class Two implements Runnable {

Two( ) {

new Thread(this, "Two").start();

try{

Thread.sleep(2000);

}catch(InterruptedException e){}

}

public void run() {

for ( ; ; ) {

try{

Thread.sleep(2000);

}catch(InterruptedException e){}

System.out.println("Hello");

}

}

}

class Three implements Runnable {

Three( ) {

Page 115: Java - A Helpful Hand

JAVA

MCA-III Page 115

new Thread(this, "Three").start();

try{

Thread.sleep(3000);

}catch(InterruptedException e){}

}

public void run() {

for ( ; ; ) {

try{

Thread.sleep(3000);

}catch(InterruptedException e){}

System.out.println("Welcome");

}

}

}

class MyThread {

public static void main(String args[ ]) {

One obj1=new One();

Two obj2=new Two();

Three obj3=new Three();

}

Page 116: Java - A Helpful Hand

JAVA

MCA-III Page 116

}

Input & Output :

Page 117: Java - A Helpful Hand

JAVA

MCA-III Page 117

Program Statement :

WAJP that will compute the following series:

(a) 1 + 1/2 + 1/3+ …….+ 1/n

(b) 1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2n

(c) ex = 1 + x/1! + x2/2! + x3/3! + … …

Program :

// (a) 1 + 1/2 + 1/3+ …….+ 1/n

import java.util.Scanner;

class Series1 {

public static void main(String arg[ ]) {

int n;

double sum=0,i;

Scanner input= new Scanner(System.in);

System.out.println("enter value of n:");

n=input.nextInt();

for(i=1;i<=n;i++)

sum=sum+(double)(1/i);

System.out.println("Result:"+sum);

Page 118: Java - A Helpful Hand

JAVA

MCA-III Page 118

}

}

Input & Output :

// (b)1 + 1/2 + 1/ 22 + 1/ 23 + … … + 1/ 2n

import java.util.Scanner;

class Series2 {

public static void main(String arg[ ]) {

int n;

double sum=0,i;

Scanner input= new Scanner(System.in);

System.out.println("enter value of n:");

n=input.nextInt();

Page 119: Java - A Helpful Hand

JAVA

MCA-III Page 119

for(i=1;i<=n;i++)

sum=sum+(double)(1/Math.pow(2,i-1));

System.out.println("Result:"+sum);

}

}

Input & Output :

Page 120: Java - A Helpful Hand

JAVA

MCA-III Page 120

// (c) ex = 1 + x/1! + x2/2! + x3/3! + … …

import java.util.*;

class Series3{

public static void main(String arg[ ]) {

int n,x;

double sum=0,i,d=1;

Scanner input= new Scanner(System.in);

System.out.println("enter value of n:");

n=input.nextInt();

System.out.println("enter value of x:");

x=input.nextInt();

for (i=1;i<=n;i++) {

sum=sum+(double)((Math.pow(x,i-1)/d));

d=d*i;

}

System.out.println("Result :"+sum);

}

}

Page 121: Java - A Helpful Hand

JAVA

MCA-III Page 121

Input & Output :

Page 122: Java - A Helpful Hand

JAVA

MCA-III Page 122

Program Statement :

WAJP to do the following:

(a) To output the question “Who is the inventor of Java?”

(b) To accept an answer

(c) To printout “GOOD” and then stop if the answer is correct

(d) To output the message “TRY AGAIN”, if the answer is

wrong

(e) To display the correct answer, when the answer is wrong

even at the third attempt

Program :

import java.io.*;

class Ask {

public static void main(String a[ ])throws Exception {

String str1,str2;

int count=0;

str1="James Gosling";

BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Who is the inventor of Java ?");

while(count!=3) {

Page 123: Java - A Helpful Hand

JAVA

MCA-III Page 123

str2=br.readLine();

if(str1.equalsIgnoreCase(str2)) {

System.out.println("!!! GOOD !!!");

break;

}

else {

if(count<2)

System.out.println("TRY AGAIN !");

count++;

}

}

if(count==3)

System.out.println("Correct Answer is : "+str1);

}

}

Input & Output :

Page 124: Java - A Helpful Hand

JAVA

MCA-III Page 124

:

Page 125: Java - A Helpful Hand

JAVA

MCA-III Page 125

Program Statement :

WAJP to transpose a matrix using ‘arraycopy’ command.

Program :

class TransMatrix {

public static void main(string args[ ]) {

int i,j,k=0;

int rows,cols,r,c;

int a[ ][ ]={{1,2,3,4},{5,6,7,8}};

rows=a.length;

cols=a[0].length;

int b[ ][ ]=new int[rows*cols];

int s[ ]=new int[rows*cols];

int d[ ]=new int[rows*cols];

for (i=0;i<rows;i++)

for (j=0;j<cols;j++,k++)

s[k]=a[i][j];

i=j=k=r=c=0;

Page 126: Java - A Helpful Hand

JAVA

MCA-III Page 126

while(r<rows) {

while(c<cols) {

System.arraycopy(s,i,d,i,l);

b[j++][k]=d[i++];

c++;

}

j=c=0;

k++;

t++;

}

System.out.println("a matrix:");

for (i=0;i<rows;i++) {

for(j=0;j<cols;j++)

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

System.out.println();

}

System.out.println("\nb matrix:");

for(i=0;i<cols;i++) {

for(j=0;j<rows;j++)

System.out.print(" "+b[i][j]);

Page 127: Java - A Helpful Hand

JAVA

MCA-III Page 127

System.out.println();

}

}

}

Input & Output :

INPUT :

OUTPUT :

Page 128: Java - A Helpful Hand

JAVA

MCA-III Page 128

Program Statement :

Create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster

etc. In the base class provide methods that are common to all

Rodents and override these in the derived classes to perform

different behaviors, depending on the specific type of Rodent.

Create an array of Rodent, fill it with different specific types of

Rodents and call your base class methods.

Program :

import java.util.Random;

class Rodent{

void place() {}

void tail() {}

void eat() {}

public static Rodent randRodent(){

Random rr=new Random();

switch (rr.nextInt(4)) {

case 0: return new Mouse();

case 1: return new Gerbil ();

case 2: return new Hamster ();

Page 129: Java - A Helpful Hand

JAVA

MCA-III Page 129

case 3: return new Beaver ();

}

return new Rodent();

}

}

class Mouse extends Rodent {

void place() {

System.out.println(“Mice are found all over the

world”);

}

void tail() {

System.out.println(“Mice have long and hairless

tail”);

}

void eat() {

System.out.println(“Mice eat cardboards,

papers, clothes”);

}

}

class Gerbil extends Rodent {

void place() {

Page 130: Java - A Helpful Hand

JAVA

MCA-III Page 130

System.out.println(“Gerbils are found in arid

parts of Africa and Asia”);

}

void tail() {

System.out.println(“Gerbils have long tail”);

}

void eat() {

System.out.println(“Gerbils eat seeds, roots,

insects, parts of plants”);

}

}

class Hamster extends Rodent {

void place() {

System.out.println(“Hamsters are found in

Western Europe to China – Dry regions only”);

}

void tail() {

System.out.println(“Hamsters have short tail”);

}

void eat() {

System.out.println(“Hamsters eat cereals”);

}

Page 131: Java - A Helpful Hand

JAVA

MCA-III Page 131

}

class Beaver extends Rodent {

void place() {

System.out.println(“Beavers are found in

Northern Europe and North America”);

}

void tail() {

System.out.println(“Beavers have broad tail”);

}

void eat() {

System.out.println(“Beavers eat bark”);

}

}

public class Rodents{

public static void main(String args[ ]) {

Rodent r[] = new Rodent[6];

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

r[i] = Rodent.randRodent();

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

Page 132: Java - A Helpful Hand

JAVA

MCA-III Page 132

r[i].place();

r[i].tail();

r[i].eat();

}

}

}

Page 133: Java - A Helpful Hand

JAVA

MCA-III Page 133

Input & Output :

Page 134: Java - A Helpful Hand

JAVA

MCA-III Page 134

Program Statement :

WAJP to print a chessboard pattern.

Program :

import java.awt.*;

import java.applet.*;

public class ChessBoard extends Applet {

/* This applet draws a red-and-black checkerboard.

It is assumed that the size of the applet is 160

by 160 pixels.

*/

/* <applet code="ChessBoard.class" width=200 height=160>

</applet> */

public void paint(Graphics g) {

int row; // Row number, from 0 to 7

int col; // Column number, from 0 to 7

int x,y; // Top-left corner of square

Page 135: Java - A Helpful Hand

JAVA

MCA-III Page 135

for ( row = 0; row < 8; row++ ) {

for ( col = 0; col < 8; col++) {

x = col * 40;

y = row * 40;

if ( (row % 2) == (col % 2) )

g.setColor(Color.white);

else

g.setColor(Color.black);

g.fillRect(x, y, 40, 40);

}

} // end for row

} // end paint()

} // end class

Input & Output :

Page 136: Java - A Helpful Hand

JAVA

MCA-III Page 136

Page 137: Java - A Helpful Hand

JAVA

MCA-III Page 137

SOME OTHER PROGRAMS

APPLET PROGRAMS

1. // Demonstrate BorderLayout.

import java.awt.*;

import java.applet.*;

import java.util.*;

/*

<applet code="BorderLayoutDemo" width=400 height=200>

</applet>

*/

public class BorderLayoutDemo extends Applet {

public void init() {

setLayout(new BorderLayout());

add(new Button("This is across the top."),

BorderLayout.NORTH);

add(new Label("The footer message might go here."),

BorderLayout.SOUTH);

add(new Button("Right"), BorderLayout.EAST);

add(new Button("Left"), BorderLayout.WEST);

Page 138: Java - A Helpful Hand

JAVA

MCA-III Page 138

String msg = "The reasonable man adapts " +

"himself to the world;\n" +

"the unreasonable one persists in " +

"trying to adapt the world to himself.\n" +

"Therefore all progress depends " +

"on the unreasonable man.\n\n" +

" - George Bernard Shaw\n\n";

add(new TextArea(msg), BorderLayout.CENTER);

}

}

2. // Demonstrate Buttons

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="ButtonDemo" width=250 height=150>

</applet>

*/

Page 139: Java - A Helpful Hand

JAVA

MCA-III Page 139

public class ButtonDemo extends Applet implements ActionListener {

String msg = "";

Button yes, no, maybe;

TextField f1;

public void init() {

yes = new Button("Yes");

no = new Button("No");

maybe = new Button("Undecided");

f1=new TextField(19);

add(yes);

add(no);

add(maybe);

add(f1);

yes.addActionListener(this);

no.addActionListener(this);

maybe.addActionListener(this);

}

public void actionPerformed(ActionEvent ae) {

String str = ae.getActionCommand();

Page 140: Java - A Helpful Hand

JAVA

MCA-III Page 140

if(str.equals("Yes")) {

msg = "You pressed Yes.";

f1.setText(str);

}

else if(str.equals("No")) {

msg = "You pressed No.";

}

else {

msg = "You pressed Undecided.";

}

repaint();

}

public void paint(Graphics g) {

g.drawString(msg, 6, 100);

}

}

3. // Demonstrate Buttons

Page 141: Java - A Helpful Hand

JAVA

MCA-III Page 141

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="ButtonDemo" width=250 height=150>

</applet>

*/

public class ButtonDemo1 extends Frame implements

ActionListener {

static String msg = "";

static Button yes, no, maybe;

public void ButtonDemo1() {

yes = new Button("Yes");

no = new Button("No");

maybe = new Button("Undecided");

add(no);

add(maybe);

Page 142: Java - A Helpful Hand

JAVA

MCA-III Page 142

yes.addActionListener(this);

no.addActionListener(this);

maybe.addActionListener(this);

}

public void actionPerformed(ActionEvent ae) {

String str = ae.getActionCommand();

if(str.equals("Yes")) {

msg = "You pressed Yes.";

}

else if(str.equals("No")) {

msg = "You pressed No.";

}

else {

msg = "You pressed Undecided.";

}

}

public static void main(String s[]) {

ButtonDemo1 b1=new ButtonDemo1();

b1.setSize(300,300);

Page 143: Java - A Helpful Hand

JAVA

MCA-III Page 143

b1.setVisible(true);

b1.add(yes);

b1.add(no);

b1.add(maybe);

System.out.println(msg);

}

}

4. // Demonstrate CardLayout.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="CardLayoutDemo" width=300 height=100>

</applet>

*/

public class CardLayoutDemo extends Applet

implements ActionListener, MouseListener {

Checkbox Win98, winNT, solaris, mac;

Page 144: Java - A Helpful Hand

JAVA

MCA-III Page 144

Panel osCards;

CardLayout cardLO;

Button Win, Other;

public void init() {

Win = new Button("Windows");

Other = new Button("Other");

add(Win);

add(Other);

cardLO = new CardLayout();

osCards = new Panel();

osCards.setLayout(cardLO); // set panel layout to card layout

Win98 = new Checkbox("Windows 98", null, true);

winNT = new Checkbox("Windows NT");

solaris = new Checkbox("Solaris");

mac = new Checkbox("MacOS");

// add Windows check boxes to a panel

Panel winPan = new Panel();

winPan.add(Win98);

Page 145: Java - A Helpful Hand

JAVA

MCA-III Page 145

winPan.add(winNT);

// Add other OS check boxes to a panel

Panel otherPan = new Panel();

otherPan.add(solaris);

otherPan.add(mac);

// add panels to card deck panel

osCards.add(winPan, "Windows");

osCards.add(otherPan, "Other");

// add cards to main applet panel

add(osCards);

// register to receive action events

Win.addActionListener(this);

Other.addActionListener(this);

// register mouse events

addMouseListener(this);

}

Page 146: Java - A Helpful Hand

JAVA

MCA-III Page 146

// Cycle through panels.

public void mousePressed(MouseEvent me) {

cardLO.next(osCards);

}

// Provide empty implementations for the other MouseListener

methods.

public void mouseClicked(MouseEvent me) {

}

public void mouseEntered(MouseEvent me) {

}

public void mouseExited(MouseEvent me) {

}

public void mouseReleased(MouseEvent me) {

}

public void actionPerformed(ActionEvent ae) {

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

cardLO.show(osCards, "Windows");

}

else {

cardLO.show(osCards, "Other");

Page 147: Java - A Helpful Hand

JAVA

MCA-III Page 147

}

}

}

5. // Demonstrate check box group.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="CBGroup" width=250 height=200>

</applet>

*/

public class CBGroup extends Applet implements ItemListener {

String msg = "";

Checkbox Win98, winNT, solaris, mac;

CheckboxGroup cbg;

public void init() {

cbg = new CheckboxGroup();

Win98 = new Checkbox("Windows 98", cbg, true);

winNT = new Checkbox("Windows NT", cbg, false);

solaris = new Checkbox("Solaris", cbg, false);

Page 148: Java - A Helpful Hand

JAVA

MCA-III Page 148

mac = new Checkbox("MacOS", cbg, false);

add(Win98);

add(winNT);

add(solaris);

add(mac);

Win98.addItemListener(this);

winNT.addItemListener(this);

solaris.addItemListener(this);

mac.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie) {

repaint();

}

// Display current state of the check boxes.

public void paint(Graphics g) {

msg = "Current selection: ";

msg += cbg.getSelectedCheckbox().getLabel();

g.drawString(msg, 6, 100);

Page 149: Java - A Helpful Hand

JAVA

MCA-III Page 149

}

}

6. // Demonstrate check boxes.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="CheckboxDemo" width=250 height=200>

</applet>

*/

public class CheckboxDemo extends Applet implements

ItemListener {

String msg = "";

Checkbox Win98, winNT, solaris, mac;

public void init() {

Win98 = new Checkbox("Windows 98", null, true);

winNT = new Checkbox("Windows NT");

solaris = new Checkbox("Solaris");

mac = new Checkbox("MacOS");

Page 150: Java - A Helpful Hand

JAVA

MCA-III Page 150

add(Win98);

add(winNT);

add(solaris);

add(mac);

Win98.addItemListener(this);

winNT.addItemListener(this);

solaris.addItemListener(this);

mac.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie) {

repaint();

}

// Display current state of the check boxes.

public void paint(Graphics g) {

msg = "Current state: ";

g.drawString(msg, 6, 80);

msg = " Windows 98: " + Win98.getState();

g.drawString(msg, 6, 100);

msg = " Windows NT: " + winNT.getState();

Page 151: Java - A Helpful Hand

JAVA

MCA-III Page 151

g.drawString(msg, 6, 120);

msg = " Solaris: " + solaris.getState();

g.drawString(msg, 6, 140);

msg = " MacOS: " + mac.getState();

g.drawString(msg, 6, 160);

}

}

7. // Demonstrate Choice lists.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="ChoiceDemo" width=300 height=180>

</applet>

*/

public class ChoiceDemo extends Applet implements ItemListener

{

Choice os, browser;

String msg = "";

public void init() {

Page 152: Java - A Helpful Hand

JAVA

MCA-III Page 152

os = new Choice();

browser = new Choice();

// add items to os list

os.add("Windows 98");

os.add("Windows NT");

os.add("Solaris");

os.add("MacOS");

// add items to browser list

browser.add("Netscape 1.1");

browser.add("Netscape 2.x");

browser.add("Netscape 3.x");

browser.add("Netscape 4.x");

browser.add("Internet Explorer 2.0");

browser.add("Internet Explorer 3.0");

browser.add("Internet Explorer 4.0");

browser.add("Lynx 2.4");

browser.select("Netscape 4.x");

Page 153: Java - A Helpful Hand

JAVA

MCA-III Page 153

// add choice lists to window

add(os);

add(browser);

// register to receive item events

os.addItemListener(this);

browser.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie) {

repaint();

}

// Display current selections.

public void paint(Graphics g) {

msg = "Current OS: ";

msg += os.getSelectedItem();

g.drawString(msg, 6, 120);

msg = "Current Browser: ";

msg += browser.getSelectedItem();

g.drawString(msg, 6, 140);

Page 154: Java - A Helpful Hand

JAVA

MCA-III Page 154

}

}

8. import java.applet.Applet;

import java.awt.*;

/*

<applet code="DialogDemo" width=250 height=200>

</applet>

*/

// Create frame window.

public class DialogDemo extends Applet {

Frame f;

public void init() {

f = new MenuFrame("Menu Demo");

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

setSize(width, height);

f.setSize(width, height);

f.setVisible(true);

Page 155: Java - A Helpful Hand

JAVA

MCA-III Page 155

}

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}

}

9. // Use left-aligned flow layout.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="FlowLayoutDemo" width=250 height=200>

</applet>

*/

public class FlowLayoutDemo extends Applet

implements ItemListener {

Page 156: Java - A Helpful Hand

JAVA

MCA-III Page 156

String msg = "";

Checkbox Win98, winNT, solaris, mac;

public void init() {

// set left-aligned flow layout

setLayout(new FlowLayout(FlowLayout.LEFT));

Win98 = new Checkbox("Windows 98", null, true);

winNT = new Checkbox("Windows NT");

solaris = new Checkbox("Solaris");

mac = new Checkbox("MacOS");

add(Win98);

add(winNT);

add(solaris);

add(mac);

// register to receive item events

Win98.addItemListener(this);

winNT.addItemListener(this);

solaris.addItemListener(this);

mac.addItemListener(this);

Page 157: Java - A Helpful Hand

JAVA

MCA-III Page 157

}

// Repaint when status of a check box changes.

public void itemStateChanged(ItemEvent ie) {

repaint();

}

// Display current state of the checkboxes.

public void paint(Graphics g) {

msg = "Current state: ";

g.drawString(msg, 6, 80);

msg = " Windows 98: " + Win98.getState();

g.drawString(msg, 6, 100);

msg = " Windows NT: " + winNT.getState();

g.drawString(msg, 6, 120);

msg = " Solaris: " + solaris.getState();

g.drawString(msg, 6, 140);

msg = " Mac: " + mac.getState();

g.drawString(msg, 6, 160);

}

}

Page 158: Java - A Helpful Hand

JAVA

MCA-III Page 158

10. // Demonstrate GridLayout

import java.awt.*;

import java.applet.*;

/*

<applet code="GridLayoutDemo" width=300 height=200>

</applet>

*/

public class GridLayoutDemo extends Applet {

static final int n = 4;

public void init() {

setLayout(new GridLayout(n, n));

setFont(new Font("SansSerif", Font.BOLD, 24));

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

for(int j = 0; j < n; j++) {

int k = i * n + j;

if(k > 0)

add(new Button("" + k));

}

}

Page 159: Java - A Helpful Hand

JAVA

MCA-III Page 159

}

}

11. // Demonstrate BorderLayout with insets.

import java.awt.*;

import java.applet.*;

import java.util.*;

/*

<applet code="InsetsDemo" width=400 height=200>

</applet>

*/

public class InsetsDemo extends Applet {

public void init() {

// set background color so insets can be easily seen

setBackground(Color.cyan);

setLayout(new BorderLayout());

add(new Button("This is across the top."),

BorderLayout.NORTH);

add(new Label("The footer message might go here."),

BorderLayout.SOUTH);

Page 160: Java - A Helpful Hand

JAVA

MCA-III Page 160

add(new Button("Right"), BorderLayout.EAST);

add(new Button("Left"), BorderLayout.WEST);

String msg = "The reasonable man adapts " +

"himself to the world;\n" +

"the unreasonable one persists in " +

"trying to adapt the world to himself.\n" +

"Therefore all progress depends " +

"on the unreasonable man.\n\n" +

" - George Bernard Shaw\n\n";

add(new TextArea(msg), BorderLayout.CENTER);

}

// add insets

public Insets getInsets() {

return new Insets(10, 10, 10, 10);

}

}

12. // Demonstrate Lists.

import java.awt.*;

import java.awt.event.*;

Page 161: Java - A Helpful Hand

JAVA

MCA-III Page 161

import java.applet.*;

/*

<applet code="ListDemo" width=300 height=180>

</applet>

*/

public class ListDemo extends Applet implements ActionListener {

List os, browser;

String msg = "";

public void init() {

os = new List(4, true);

browser = new List(4, false);

// add items to os list

os.add("Windows 98");

os.add("Windows NT");

os.add("Solaris");

os.add("MacOS");

// add items to browser list

browser.add("Netscape 1.1");

Page 162: Java - A Helpful Hand

JAVA

MCA-III Page 162

browser.add("Netscape 2.x");

browser.add("Netscape 3.x");

browser.add("Netscape 4.x");

browser.add("Internet Explorer 2.0");

browser.add("Internet Explorer 3.0");

browser.add("Internet Explorer 4.0");

browser.add("Lynx 2.4");

browser.select(1);

// add lists to window

add(os);

add(browser);

// register to receive action events

os.addActionListener(this);

browser.addActionListener(this);

}

public void actionPerformed(ActionEvent ae) {

Page 163: Java - A Helpful Hand

JAVA

MCA-III Page 163

repaint();

}

// Display current selections.

public void paint(Graphics g) {

int idx[];

msg = "Current OS: ";

idx = os.getSelectedIndexes();

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

msg += os.getItem(idx[i]) + " ";

g.drawString(msg, 6, 120);

msg = "Current Browser: ";

msg += browser.getSelectedItem();

g.drawString(msg, 6, 140);

}

}

13. import java.applet.Applet;

import java.awt.*;

// Create frame window.

public class MenuDemo extends Applet {

Frame f;

Page 164: Java - A Helpful Hand

JAVA

MCA-III Page 164

/* <applet code=MenuDemo width=300 height=100>

</applet>*/

public void init() {

f = new MenuFrame("Menu Demo");

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

setSize(new Dimension(width, height));

f.setSize(width, height);

f.setVisible(true);

}

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}

}

14. // Illustrate menus.

Page 165: Java - A Helpful Hand

JAVA

MCA-III Page 165

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="MenuDemo" width=250 height=250>

</applet>

*/

// Create a subclass of Frame

class MenuFrame extends Frame {

String msg = "";

CheckboxMenuItem debug, test;

MenuFrame(String title) {

super(title);

// create menu bar and add it to frame

MenuBar mbar = new MenuBar();

setMenuBar(mbar);

// create the menu items

Menu file = new Menu("File");

Page 166: Java - A Helpful Hand

JAVA

MCA-III Page 166

MenuItem item1, item2, item3, item4, item5;

file.add(item1 = new MenuItem("New..."));

file.add(item2 = new MenuItem("Open..."));

file.add(item3 = new MenuItem("Close"));

file.add(item4 = new MenuItem("-"));

file.add(item5 = new MenuItem("Quit..."));

mbar.add(file);

Menu edit = new Menu("Edit");

MenuItem item6, item7, item8, item9;

edit.add(item6 = new MenuItem("Cut"));

edit.add(item7 = new MenuItem("Copy"));

edit.add(item8 = new MenuItem("Paste"));

edit.add(item9 = new MenuItem("-"));

Menu sub = new Menu("Special");

MenuItem item10, item11, item12;

sub.add(item10 = new MenuItem("First"));

sub.add(item11 = new MenuItem("Second"));

sub.add(item12 = new MenuItem("Third"));

edit.add(sub);

// these are checkable menu items

Page 167: Java - A Helpful Hand

JAVA

MCA-III Page 167

debug = new CheckboxMenuItem("Debug");

edit.add(debug);

test = new CheckboxMenuItem("Testing");

edit.add(test);

mbar.add(edit);

// create an object to handle action and item events

MyMenuHandler handler = new MyMenuHandler(this);

// register it to receive those events

item1.addActionListener(handler);

item2.addActionListener(handler);

item3.addActionListener(handler);

item4.addActionListener(handler);

item5.addActionListener(handler);

item6.addActionListener(handler);

item7.addActionListener(handler);

item8.addActionListener(handler);

item9.addActionListener(handler);

item10.addActionListener(handler);

item11.addActionListener(handler);

item12.addActionListener(handler);

Page 168: Java - A Helpful Hand

JAVA

MCA-III Page 168

debug.addItemListener(handler);

test.addItemListener(handler);

// create an object to handle window events

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

}

public void paint(Graphics g) {

g.drawString(msg, 10, 200);

if(debug.getState())

g.drawString("Debug is on.", 10, 220);

else

g.drawString("Debug is off.", 10, 220);

if(test.getState())

g.drawString("Testing is on.", 10, 240);

else

g.drawString("Testing is off.", 10, 240);

}

Page 169: Java - A Helpful Hand

JAVA

MCA-III Page 169

}

class MyWindowAdapter extends WindowAdapter {

MenuFrame menuFrame;

public MyWindowAdapter(MenuFrame menuFrame) {

this.menuFrame = menuFrame;

}

public void windowClosing(WindowEvent we) {

menuFrame.setVisible(false);

}

}

class MyMenuHandler implements ActionListener, ItemListener {

MenuFrame menuFrame;

public MyMenuHandler(MenuFrame menuFrame) {

this.menuFrame = menuFrame;

}

// Handle action events

public void actionPerformed(ActionEvent ae) {

String msg = "You selected ";

String arg = (String)ae.getActionCommand();

if(arg.equals("New..."))

Page 170: Java - A Helpful Hand

JAVA

MCA-III Page 170

msg += "New.";

else if(arg.equals("Open..."))

msg += "Open.";

else if(arg.equals("Close"))

msg += "Close.";

else if(arg.equals("Quit..."))

msg += "Quit.";

else if(arg.equals("Edit"))

msg += "Edit.";

else if(arg.equals("Cut"))

msg += "Cut.";

else if(arg.equals("Copy"))

msg += "Copy.";

else if(arg.equals("Paste"))

msg += "Paste.";

else if(arg.equals("First"))

msg += "First.";

else if(arg.equals("Second"))

msg += "Second.";

else if(arg.equals("Third"))

msg += "Third.";

else if(arg.equals("Debug"))

Page 171: Java - A Helpful Hand

JAVA

MCA-III Page 171

msg += "Debug.";

else if(arg.equals("Testing"))

msg += "Testing.";

menuFrame.msg = msg;

menuFrame.repaint();

}

// Handle item events

public void itemStateChanged(ItemEvent ie) {

menuFrame.repaint();

}

}

/*

// Create frame window.

public class MenuDemo extends Applet {

Frame f;

public void init() {

f = new MenuFrame("Menu Demo");

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

setSize(new Dimension(width, height));

Page 172: Java - A Helpful Hand

JAVA

MCA-III Page 172

f.setSize(width, height);

f.setVisible(true);

}

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}

}

*/

13. // Demonstrate Dialog box.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="DialogDemo" width=250 height=250>

</applet>

*/

Page 173: Java - A Helpful Hand

JAVA

MCA-III Page 173

// Create a subclass of Dialog.

class SampleDialog extends Dialog implements ActionListener {

SampleDialog(Frame parent, String title) {

super(parent, title, false);

setLayout(new FlowLayout());

setSize(300, 200);

add(new Label("Press this button:"));

Button b;

add(b = new Button("Cancel"));

b.addActionListener(this);

}

public void actionPerformed(ActionEvent ae) {

dispose();

}

public void paint(Graphics g) {

g.drawString("This is in the dialog box", 10, 70);

}

}

Page 174: Java - A Helpful Hand

JAVA

MCA-III Page 174

// Create a subclass of Frame.

class MenuFrame extends Frame {

String msg = "";

CheckboxMenuItem debug, test;

MenuFrame(String title) {

super(title);

// create menu bar and add it to frame

MenuBar mbar = new MenuBar();

setMenuBar(mbar);

// create the menu items

Menu file = new Menu("File");

MenuItem item1, item2, item3, item4;

file.add(item1 = new MenuItem("New..."));

file.add(item2 = new MenuItem("Open..."));

file.add(item3 = new MenuItem("Close"));

file.add(new MenuItem("-"));

file.add(item4 = new MenuItem("Quit..."));

mbar.add(file);

Page 175: Java - A Helpful Hand

JAVA

MCA-III Page 175

Menu edit = new Menu("Edit");

MenuItem item5, item6, item7;

edit.add(item5 = new MenuItem("Cut"));

edit.add(item6 = new MenuItem("Copy"));

edit.add(item7 = new MenuItem("Paste"));

edit.add(new MenuItem("-"));

Menu sub = new Menu("Special", true);

MenuItem item8, item9, item10;

sub.add(item8 = new MenuItem("First"));

sub.add(item9 = new MenuItem("Second"));

sub.add(item10 = new MenuItem("Third"));

edit.add(sub);

// these are checkable menu items

debug = new CheckboxMenuItem("Debug");

edit.add(debug);

test = new CheckboxMenuItem("Testing");

edit.add(test);

mbar.add(edit);

Page 176: Java - A Helpful Hand

JAVA

MCA-III Page 176

// create an object to handle action and item events

MyMenuHandler handler = new MyMenuHandler(this);

// register it to receive those events

item1.addActionListener(handler);

item2.addActionListener(handler);

item3.addActionListener(handler);

item4.addActionListener(handler);

item5.addActionListener(handler);

item6.addActionListener(handler);

item7.addActionListener(handler);

item8.addActionListener(handler);

item9.addActionListener(handler);

item10.addActionListener(handler);

debug.addItemListener(handler);

test.addItemListener(handler);

// create an object to handle window events

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

Page 177: Java - A Helpful Hand

JAVA

MCA-III Page 177

}

public void paint(Graphics g) {

g.drawString(msg, 10, 200);

if(debug.getState())

g.drawString("Debug is on.", 10, 220);

else

g.drawString("Debug is off.", 10, 220);

if(test.getState())

g.drawString("Testing is on.", 10, 240);

else

g.drawString("Testing is off.", 10, 240);

}

}

class MyWindowAdapter extends WindowAdapter {

MenuFrame menuFrame;

public MyWindowAdapter(MenuFrame menuFrame) {

this.menuFrame = menuFrame;

}

public void windowClosing(WindowEvent we) {

Page 178: Java - A Helpful Hand

JAVA

MCA-III Page 178

menuFrame.dispose();

}

}

class MyMenuHandler implements ActionListener, ItemListener {

MenuFrame menuFrame;

public MyMenuHandler(MenuFrame menuFrame) {

this.menuFrame = menuFrame;

}

// Handle action events

public void actionPerformed(ActionEvent ae) {

String msg = "You selected ";

String arg = (String)ae.getActionCommand();

// Activate a dialog box when New is selected.

if(arg.equals("New...")) {

msg += "New.";

SampleDialog d = new

SampleDialog(menuFrame, "New Dialog Box");

d.setVisible(true);

}

// Try defining other dialog boxes for these options.

else if(arg.equals("Open..."))

Page 179: Java - A Helpful Hand

JAVA

MCA-III Page 179

msg += "Open.";

else if(arg.equals("Close"))

msg += "Close.";

else if(arg.equals("Quit..."))

msg += "Quit.";

else if(arg.equals("Edit"))

msg += "Edit.";

else if(arg.equals("Cut"))

msg += "Cut.";

else if(arg.equals("Copy"))

msg += "Copy.";

else if(arg.equals("Paste"))

msg += "Paste.";

else if(arg.equals("First"))

msg += "First.";

else if(arg.equals("Second"))

msg += "Second.";

else if(arg.equals("Third"))

msg += "Third.";

else if(arg.equals("Debug"))

msg += "Debug.";

else if(arg.equals("Testing"))

Page 180: Java - A Helpful Hand

JAVA

MCA-III Page 180

msg += "Testing.";

menuFrame.msg = msg;

menuFrame.repaint();

}

public void itemStateChanged(ItemEvent ie) {

menuFrame.repaint();

}

}

/*

// Create frame window.

public class DialogDemo extends Applet {

Frame f;

public void init() {

f = new MenuFrame("Menu Demo");

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

setSize(width, height);

f.setSize(width, height);

Page 181: Java - A Helpful Hand

JAVA

MCA-III Page 181

f.setVisible(true);

}

public void start() {

f.setVisible(true);

}

public void stop() {

f.setVisible(false);

}

}

*/

14. /* Demonstrate File Dialog box.

This is an application, not an applet.

*/

import java.awt.*;

import java.awt.event.*;

// Create a subclass of Frame

class SampleFrame extends Frame {

SampleFrame(String title) {

Page 182: Java - A Helpful Hand

JAVA

MCA-III Page 182

super(title);

// create an object to handle window events

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

}

}

class MyWindowAdapter extends WindowAdapter {

SampleFrame sampleFrame;

public MyWindowAdapter(SampleFrame sampleFrame) {

this.sampleFrame = sampleFrame;

}

public void windowClosing(WindowEvent we) {

sampleFrame.setVisible(false);

}

}

// Create frame window.

class FileDialogDemo {

public static void main(String args[]) {

Frame f = new SampleFrame("File Dialog Demo");

Page 183: Java - A Helpful Hand

JAVA

MCA-III Page 183

f.setVisible(true);

f.setSize(100, 100);

FileDialog fd = new FileDialog(f, "File Dialog");

fd.setVisible(true);

}

}

15. // Demonstrate scroll bars.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="SBDemo" width=300 height=200>

</applet>

*/

public class SBDemo extends Applet

implements AdjustmentListener, MouseMotionListener {

String msg = "";

Scrollbar vertSB, horzSB;

public void init() {

Page 184: Java - A Helpful Hand

JAVA

MCA-III Page 184

int width = Integer.parseInt(getParameter("width"));

int height = Integer.parseInt(getParameter("height"));

vertSB = new Scrollbar(Scrollbar.VERTICAL,

0, 1, 0, height);

horzSB = new Scrollbar(Scrollbar.HORIZONTAL,

0, 1, 0, width);

add(vertSB);

add(horzSB);

// register to receive adjustment events

vertSB.addAdjustmentListener(this);

horzSB.addAdjustmentListener(this);

addMouseMotionListener(this);

}

public void adjustmentValueChanged(AdjustmentEvent ae) {

repaint();

}

Page 185: Java - A Helpful Hand

JAVA

MCA-III Page 185

// Update scroll bars to reflect mouse dragging.

public void mouseDragged(MouseEvent me) {

int x = me.getX();

int y = me.getY();

vertSB.setValue(y);

horzSB.setValue(x);

repaint();

}

// Necessary for MouseMotionListener

public void mouseMoved(MouseEvent me) {

}

// Display current value of scroll bars.

public void paint(Graphics g) {

msg = "Vertical: " + vertSB.getValue();

msg += ", Horizontal: " + horzSB.getValue();

g.drawString(msg, 6, 160);

// show current mouse drag position

g.drawString("*", horzSB.getValue(),

vertSB.getValue());

Page 186: Java - A Helpful Hand

JAVA

MCA-III Page 186

}

}

16. // Demonstrate TextArea.

import java.awt.*;

import java.applet.*;

/*

<applet code="TextAreaDemo" width=300 height=250>

</applet>

*/

public class TextAreaDemo extends Applet {

public void init() {

String val = "There are two ways of constructing " +

"a software design.\n" +

"One way is to make it so simple\n" +

"that there are obviously no deficiencies.\n" +

"And the other way is to make it so complicated\n" +

"that there are no obvious deficiencies.\n\n" +

" -C.A.R. Hoare\n\n" +

"There's an old story about the person who wished\n" +

"his computer were as easy to use as his telephone.\n" +

"That wish has come true,\n" +

Page 187: Java - A Helpful Hand

JAVA

MCA-III Page 187

"since I no longer know how to use my telephone.\n\n" +

" -Bjarne Stroustrup, AT&T, (inventor of C++)";

TextArea text = new TextArea(val, 10, 30);

add(text);

}

}

17. // Demonstrate text field.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="TextFieldDemo" width=380 height=150>

</applet>

*/

public class TextFieldDemo extends Applet

implements ActionListener {

TextField name, pass;

public void init() {

Page 188: Java - A Helpful Hand

JAVA

MCA-III Page 188

Label namep = new Label("Name: ", Label.RIGHT);

Label passp = new Label("Password: ", Label.RIGHT);

name = new TextField(12);

pass = new TextField(8);

pass.setEchoChar('?');

add(namep);

add(name);

add(passp);

add(pass);

// register to receive action events

name.addActionListener(this);

pass.addActionListener(this);

}

// User pressed Enter.

public void actionPerformed(ActionEvent ae) {

repaint();

}

public void paint(Graphics g) {

Page 189: Java - A Helpful Hand

JAVA

MCA-III Page 189

g.drawString("Name: " + name.getText(), 6, 60);

g.drawString("Selected text in name: "

+ name.getSelectedText(), 6, 80);

g.drawString("Password: " + pass.getText(), 6, 100);

}

}

18. // Demonstrate text field.

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*

<applet code="TextFieldDemo1" width=380 height=150>

</applet>

*/

class SampleFrame extends Frame {

SampleFrame(String title) {

super(title);

// create an object to handle window events

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

Page 190: Java - A Helpful Hand

JAVA

MCA-III Page 190

}

}

class MyWindowAdapter extends WindowAdapter {

SampleFrame sampleFrame;

public MyWindowAdapter(SampleFrame sampleFrame) {

this.sampleFrame = sampleFrame;

}

public void windowClosing(WindowEvent we) {

sampleFrame.setVisible(false);

}

}

public class TextFieldDemo1 extends Applet

implements ActionListener {

TextField name, pass;

Button b1;

String s1;

Frame f;

public void init() {

Page 191: Java - A Helpful Hand

JAVA

MCA-III Page 191

Label namep = new Label("Name: ", Label.RIGHT);

Label passp = new Label("Password: ", Label.RIGHT);

name = new TextField(12);

pass = new TextField(8);

pass.setEchoChar('?');

b1=new Button("ok");

add(namep);

add(name);

add(passp);

add(pass);

add(b1);

// register to receive action events

name.addActionListener(this);

pass.addActionListener(this);

b1.addActionListener(this);

}

// User pressed Enter.

public void actionPerformed(ActionEvent ae) {

Page 192: Java - A Helpful Hand

JAVA

MCA-III Page 192

repaint();

String s=ae.getActionCommand();

if(s.equals("ok"))

f=new SampleFrame("button press");

f.setSize(200,200);

f.setVisible(true);

}

public void paint(Graphics g) {

g.drawString("Name: " + name.getText(), 6, 60);

g.drawString("Selected text in name: " +

name.getSelectedText(), 6, 80);

g.drawString("Password: " + pass.getText(), 6, 100);

}

}

19. import java.awt.*;

import java.awt.event.*;

import java.applet.*;

Page 193: Java - A Helpful Hand

JAVA

MCA-III Page 193

// Create a subclass of Dialog.

class SampleDialog1 extends Dialog implements ActionListener {

SampleDialog1(Frame parent, String title) {

super(parent, title, false);

setLayout(new FlowLayout());

setSize(300, 200);

add(new Label("Press this button:"));

Button b;

add(b = new Button("Cancel"));

b.addActionListener(this);

}

public void actionPerformed(ActionEvent ae) {

dispose();

}

public void paint(Graphics g) {

g.drawString("This is in the dialog box", 10, 70);

}

}

Page 194: Java - A Helpful Hand

JAVA

MCA-III Page 194

class MenuFrame extends Frame {

String msg = "";

CheckboxMenuItem debug, test;

MenuFrame(String title) {

super(title);

// create menu bar and add it to frame

MenuBar mbar = new MenuBar();

setMenuBar(mbar);

// create the menu items

Menu file = new Menu("File");

MenuItem item1, item2, item3, item4;

file.add(item1 = new MenuItem("New..."));

file.add(item2 = new MenuItem("Open..."));

file.add(item3 = new MenuItem("Close"));

file.add(new MenuItem("-"));

file.add(item4 = new MenuItem("Quit..."));

mbar.add(file);

Page 195: Java - A Helpful Hand

JAVA

MCA-III Page 195

// these are checkable menu items

debug = new CheckboxMenuItem("Debug");

file.add(debug);

test = new CheckboxMenuItem("Testing");

file.add(test);

// create an object to handle action and item events

MyMenuHandler handler = new MyMenuHandler(this);

// register it to receive those events

item1.addActionListener(handler);

item2.addActionListener(handler);

item3.addActionListener(handler);

item4.addActionListener(handler);

debug.addItemListener(handler);

test.addItemListener(handler);

// create an object to handle window events

Page 196: Java - A Helpful Hand

JAVA

MCA-III Page 196

MyWindowAdapter adapter = new MyWindowAdapter(this);

// register it to receive those events

addWindowListener(adapter);

}

public void paint(Graphics g) {

g.drawString(msg, 10, 200);

if(debug.getState())

g.drawString("Debug is on.", 10, 220);

else

g.drawString("Debug is off.", 10, 220);

if(test.getState())

g.drawString("Testing is on.", 10, 240);

else

g.drawString("Testing is off.", 10, 240);

}

}

class MyWindowAdapter extends WindowAdapter {

MenuFrame menuFrame;

public MyWindowAdapter(MenuFrame menuFrame) {

Page 197: Java - A Helpful Hand

JAVA

MCA-III Page 197

this.menuFrame = menuFrame;

}

public void windowClosing(WindowEvent we) {

menuFrame.dispose();

}

}

class MyMenuHandler implements ActionListener, ItemListener {

MenuFrame menuFrame;

public MyMenuHandler(MenuFrame menuFrame) {

this.menuFrame = menuFrame;

}

// Handle action events

public void actionPerformed(ActionEvent ae) {

String msg = "You selected ";

String arg = (String)ae.getActionCommand();

// Activate a dialog box when New is selected.

if(arg.equals("New...")) {

msg += "New.";

Page 198: Java - A Helpful Hand

JAVA

MCA-III Page 198

SampleDialog1 d = new SampleDialog1(menuFrame, "New

Dialog Box");

d.setVisible(true);

System.out.println("Hello World!");

}

// Try defining other dialog boxes for these options.

else if(arg.equals("Open...")){

msg += "Open.";

FileDialog d = new

FileDialog(menuFrame, "open Dialog

Box",FileDialog.LOAD);

d.setVisible(true);

}

else if(arg.equals("Quit"))

msg += "Quite.";

else if(arg.equals("Close"))

msg += "Close.";

else if(arg.equals("Debug"))

msg += "Debug.";

else if(arg.equals("Testing"))

msg += "Testing.";

Page 199: Java - A Helpful Hand

JAVA

MCA-III Page 199

menuFrame.msg = msg;

menuFrame.repaint();

}

public void itemStateChanged(ItemEvent ie) {

menuFrame.repaint();

}

}

class f1

{

public static void main(String[] args)

{

Frame f;

f = new MenuFrame("Menu Demo");

f.setSize(300, 300);

f.setVisible(true);

}

}

Page 200: Java - A Helpful Hand

JAVA

MCA-III Page 200

SWINGS PROGRAMS

1. import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*

<applet code="JButtonDemo" width=250 height=300>

</applet>

*/

public class JButtonDemo extends JApplet

implements ActionListener {

JTextField jtf;

public void init() {

// Get content pane

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

// Add buttons to content pane

Page 201: Java - A Helpful Hand

JAVA

MCA-III Page 201

ImageIcon france = new ImageIcon("france.gif");

JButton jb = new JButton(france);

jb.setActionCommand("France");

jb.addActionListener(this);

contentPane.add(jb);

ImageIcon germany = new ImageIcon("germany.gif");

jb = new JButton(germany);

jb.setActionCommand("Germany");

jb.addActionListener(this);

contentPane.add(jb);

ImageIcon italy = new ImageIcon("italy.gif");

jb = new JButton(italy);

jb.setActionCommand("Italy");

jb.addActionListener(this);

contentPane.add(jb);

ImageIcon japan = new ImageIcon("japan.gif");

jb = new JButton(japan);

jb.setActionCommand("Japan");

jb.addActionListener(this);

Page 202: Java - A Helpful Hand

JAVA

MCA-III Page 202

contentPane.add(jb);

// Add text field to content pane

jtf = new JTextField(15);

contentPane.add(jtf);

}

public void actionPerformed(ActionEvent ae) {

jtf.setText(ae.getActionCommand());

}

}

2. import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*

<applet code="JCheckBoxDemo" width=400 height=50>

</applet>

*/

public class JCheckBoxDemo extends JApplet

implements ItemListener {

JTextField jtf;

Page 203: Java - A Helpful Hand

JAVA

MCA-III Page 203

public void init() {

// Get content pane

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

// Create icons

ImageIcon normal = new ImageIcon("normal.gif");

ImageIcon rollover = new ImageIcon("rollover.gif");

ImageIcon selected = new ImageIcon("selected.gif");

// Add check boxes to the content pane

JCheckBox cb = new JCheckBox("C", normal);

cb.setRolloverIcon(rollover);

cb.setSelectedIcon(selected);

cb.addItemListener(this);

contentPane.add(cb);

cb = new JCheckBox("C++", normal);

cb.setRolloverIcon(rollover);

cb.setSelectedIcon(selected);

Page 204: Java - A Helpful Hand

JAVA

MCA-III Page 204

cb.addItemListener(this);

contentPane.add(cb);

cb = new JCheckBox("Java", normal);

cb.setRolloverIcon(rollover);

cb.setSelectedIcon(selected);

cb.addItemListener(this);

contentPane.add(cb);

cb = new JCheckBox("Perl", normal);

cb.setRolloverIcon(rollover);

cb.setSelectedIcon(selected);

cb.addItemListener(this);

contentPane.add(cb);

// Add text field to the content pane

jtf = new JTextField(15);

contentPane.add(jtf);

}

public void itemStateChanged(ItemEvent ie) {

JCheckBox cb = (JCheckBox)ie.getItem();

Page 205: Java - A Helpful Hand

JAVA

MCA-III Page 205

jtf.setText(cb.getText());

}

}

3. import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*

<applet code="JComboBoxDemo" width=300 height=100>

</applet>

*/

public class JComboBoxDemo extends JApplet

implements ItemListener {

JLabel jl;

ImageIcon france, germany, italy, japan;

public void init() {

// Get content pane

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

Page 206: Java - A Helpful Hand

JAVA

MCA-III Page 206

// Create a combo box and add it

// to the panel

JComboBox jc = new JComboBox();

jc.addItem("France");

jc.addItem("Germany");

jc.addItem("Italy");

jc.addItem("Japan");

jc.addItemListener(this);

contentPane.add(jc);

// Create label

jl = new JLabel(new ImageIcon("france.gif"));

contentPane.add(jl);

}

public void itemStateChanged(ItemEvent ie) {

String s = (String)ie.getItem();

jl.setIcon(new ImageIcon(s + ".gif"));

}

}

4. import java.awt.*;

import javax.swing.*;

Page 207: Java - A Helpful Hand

JAVA

MCA-III Page 207

/*

<applet code="JLabelDemo" width=250 height=150>

</applet>

*/

public class JLabelDemo extends JApplet {

public void init() {

// Get content pane

Container contentPane = getContentPane();

// Create an icon

ImageIcon ii = new ImageIcon("france.gif");

// Create a label

JLabel jl = new JLabel("France", ii, JLabel.CENTER);

// Add label to the content pane

contentPane.add(jl);

}

}

5. import java.awt.*;

Page 208: Java - A Helpful Hand

JAVA

MCA-III Page 208

import java.awt.event.*;

import javax.swing.*;

/*

<applet code="JRadioButtonDemo" width=300 height=50>

</applet>

*/

public class JRadioButtonDemo extends JApplet

implements ActionListener {

JTextField tf;

public void init() {

// Get content pane

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

// Add radio buttons to content pane

JRadioButton b1 = new JRadioButton("A");

b1.addActionListener(this);

contentPane.add(b1);

Page 209: Java - A Helpful Hand

JAVA

MCA-III Page 209

JRadioButton b2 = new JRadioButton("B");

b2.addActionListener(this);

contentPane.add(b2);

JRadioButton b3 = new JRadioButton("C");

b3.addActionListener(this);

contentPane.add(b3);

// Define a button group

ButtonGroup bg = new ButtonGroup();

bg.add(b1);

bg.add(b2);

bg.add(b3);

// Create a text field and add it

// to the content pane

tf = new JTextField(5);

contentPane.add(tf);

}

public void actionPerformed(ActionEvent ae) {

tf.setText(ae.getActionCommand());

Page 210: Java - A Helpful Hand

JAVA

MCA-III Page 210

}

}

6. import java.awt.*;

import javax.swing.*;

/*

<applet code="JScrollPaneDemo" width=300 height=250>

</applet>

*/

public class JScrollPaneDemo extends JApplet {

public void init() {

// Get content pane

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

// Add 400 buttons to a panel

JPanel jp = new JPanel();

jp.setLayout(new GridLayout(20, 20));

int b = 0;

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

Page 211: Java - A Helpful Hand

JAVA

MCA-III Page 211

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

jp.add(new JButton("Button " + b));

++b;

}

}

// Add panel to a scroll pane

int v =

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h =

ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

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

// Add scroll pane to the content pane

contentPane.add(jsp, BorderLayout.CENTER);

}

}

7. import javax.swing.*;

/*

<applet code="JTabbedPaneDemo" width=400 height=100>

</applet>

*/

Page 212: Java - A Helpful Hand

JAVA

MCA-III Page 212

public class JTabbedPaneDemo extends JApplet {

public void init() {

JTabbedPane jtp = new JTabbedPane();

jtp.addTab("Cities", new CitiesPanel());

jtp.addTab("Colors", new ColorsPanel());

jtp.addTab("Flavors", new FlavorsPanel());

getContentPane().add(jtp);

}

}

class CitiesPanel extends JPanel {

public CitiesPanel() {

JButton b1 = new JButton("New York");

add(b1);

JButton b2 = new JButton("London");

add(b2);

JButton b3 = new JButton("Hong Kong");

Page 213: Java - A Helpful Hand

JAVA

MCA-III Page 213

add(b3);

JButton b4 = new JButton("Tokyo");

add(b4);

}

}

class ColorsPanel extends JPanel {

public ColorsPanel() {

JCheckBox cb1 = new JCheckBox("Red");

add(cb1);

JCheckBox cb2 = new JCheckBox("Green");

add(cb2);

JCheckBox cb3 = new JCheckBox("Blue");

add(cb3);

}

}

class FlavorsPanel extends JPanel {

public FlavorsPanel() {

Page 214: Java - A Helpful Hand

JAVA

MCA-III Page 214

JComboBox jcb = new JComboBox();

jcb.addItem("Vanilla");

jcb.addItem("Chocolate");

jcb.addItem("Strawberry");

add(jcb);

}

}

8. import java.awt.*;

import javax.swing.*;

/*

<applet code="JTableDemo" width=400 height=200>

</applet>

*/

public class JTableDemo extends JApplet {

public void init() {

// Get content pane

Page 215: Java - A Helpful Hand

JAVA

MCA-III Page 215

Container contentPane = getContentPane();

// Set layout manager

contentPane.setLayout(new BorderLayout());

// Initialize column headings

final String[] colHeads = { "Name", "Phone", "Fax" };

// Initialize data

final Object[][] data = {

{ "Gail", "4567", "8675" },

{ "Ken", "7566", "5555" },

{ "Viviane", "5634", "5887" },

{ "Melanie", "7345", "9222" },

{ "Anne", "1237", "3333" },

{ "John", "5656", "3144" },

{ "Matt", "5672", "2176" },

{ "Claire", "6741", "4244" },

{ "Erwin", "9023", "5159" },

{ "Ellen", "1134", "5332" },

{ "Jennifer", "5689", "1212" },

{ "Ed", "9030", "1313" },

Page 216: Java - A Helpful Hand

JAVA

MCA-III Page 216

{ "Helen", "6751", "1415" }

};

// Create the table

JTable table = new JTable(data, colHeads);

// Add tree to a scroll pane

int v =

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h =

ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

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

// Add scroll pane to the content pane

contentPane.add(jsp, BorderLayout.CENTER);

}

}

9. import java.awt.*;

import javax.swing.*;

/*

<applet code="JTextFieldDemo" width=300 height=50>

</applet>

*/

Page 217: Java - A Helpful Hand

JAVA

MCA-III Page 217

public class JTextFieldDemo extends JApplet {

JTextField jtf;

public void init() {

// Get content pane

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

// Add text field to content pane

jtf = new JTextField(15);

contentPane.add(jtf);

}

}

10. import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.tree.*;

/*

<applet code="JTreeEvents" width=400 height=200>

</applet>

Page 218: Java - A Helpful Hand

JAVA

MCA-III Page 218

*/

public class JTreeEvents extends JApplet {

JTree tree;

JTextField jtf;

public void init() {

// Get content pane

Container contentPane = getContentPane();

// Set layout manager

contentPane.setLayout(new BorderLayout());

// Create top node of tree

DefaultMutableTreeNode top = new

DefaultMutableTreeNode("Options");

// Create subtree of "A"

DefaultMutableTreeNode a = new

DefaultMutableTreeNode("A");

top.add(a);

Page 219: Java - A Helpful Hand

JAVA

MCA-III Page 219

DefaultMutableTreeNode a1 = new

DefaultMutableTreeNode("A1");

a.add(a1);

DefaultMutableTreeNode a2 = new

DefaultMutableTreeNode("A2");

a.add(a2);

// Create subtree of "B"

DefaultMutableTreeNode b = new

DefaultMutableTreeNode("B");

top.add(b);

DefaultMutableTreeNode b1 = new

DefaultMutableTreeNode("B1");

b.add(b1);

DefaultMutableTreeNode b2 = new

DefaultMutableTreeNode("B2");

b.add(b2);

DefaultMutableTreeNode b3 = new

DefaultMutableTreeNode("B3");

b.add(b3);

// Create tree

tree = new JTree(top);

Page 220: Java - A Helpful Hand

JAVA

MCA-III Page 220

// Add tree to a scroll pane

int v =

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h =

ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

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

// Add scroll pane to the content pane

contentPane.add(jsp, BorderLayout.CENTER);

// Add text field to applet

jtf = new JTextField("", 20);

contentPane.add(jtf, BorderLayout.SOUTH);

// Anonymous inner class to handle mouse clicks

tree.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent me) {

doMouseClicked(me);

}

});

}

void doMouseClicked(MouseEvent me) {

Page 221: Java - A Helpful Hand

JAVA

MCA-III Page 221

TreePath tp = tree.getPathForLocation(me.getX(), me.getY());

if(tp != null)

jtf.setText(tp.toString());

else

jtf.setText("");

}

}

11. import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.tree.*;

/*

<applet code="JTreeEvents" width=400 height=200>

</applet>

*/

public class JTreeEvents1 extends JApplet {

JTree tree;

JTextField jtf;

Page 222: Java - A Helpful Hand

JAVA

MCA-III Page 222

public void init() {

// Get content pane

Container contentPane = getContentPane();

// Set layout manager

contentPane.setLayout(new BorderLayout());

// Create top node of tree

DefaultMutableTreeNode top = new

DefaultMutableTreeNode("Options");

// Create subtree of "A"

DefaultMutableTreeNode a = new

DefaultMutableTreeNode("A");

top.add(a);

DefaultMutableTreeNode a1 = new

DefaultMutableTreeNode("A1");

a.add(a1);

DefaultMutableTreeNode a2 = new

DefaultMutableTreeNode("A2");

a.add(a2);

Page 223: Java - A Helpful Hand

JAVA

MCA-III Page 223

// Create subtree of "B"

DefaultMutableTreeNode b = new

DefaultMutableTreeNode("B");

top.add(b);

DefaultMutableTreeNode b1 = new

DefaultMutableTreeNode("B1");

b.add(b1);

DefaultMutableTreeNode b2 = new

DefaultMutableTreeNode("B2");

b.add(b2);

DefaultMutableTreeNode b3 = new

DefaultMutableTreeNode("B3");

b.add(b3);

// Create tree

tree = new JTree(top);

// Add tree to a scroll pane

int v =

ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h =

ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

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

Page 224: Java - A Helpful Hand

JAVA

MCA-III Page 224

// Add scroll pane to the content pane

contentPane.add(jsp, BorderLayout.CENTER);

// Add text field to applet

jtf = new JTextField("", 20);

contentPane.add(jtf, BorderLayout.SOUTH);

// Anonymous inner class to handle mouse clicks

tree.addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent me) {

doMouseClicked(me);

}

});

}

void doMouseClicked(MouseEvent me) {

TreePath tp = tree.getPathForLocation(me.getX(), me.getY());

if(tp != null)

jtf.setText(tp.toString());

else

jtf.setText("");

}

Page 225: Java - A Helpful Hand

JAVA

MCA-III Page 225

}

NETWORKING PROGRAMS

1. //Demonstrate Sockets.

import java.net.*;

import java.io.*;

class a {

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

Socket s = new Socket("localhost", 777);

InputStream in = s.getInputStream();

BufferedReader br=new BufferedReader(new

InputStreamReader(in));

OutputStream out = s.getOutputStream();

String str;

while ((str=br.readLine()) != null) {

System.out.print("fro ser"+str);

}

br.close();

Page 226: Java - A Helpful Hand

JAVA

MCA-III Page 226

s.close();

}

}

2. // Demonstrate InetAddress.

import java.net.*;

class InetAddressTest

{

public static void main(String args[]) throws

UnknownHostException {

InetAddress Address = InetAddress.getLocalHost();

System.out.println(Address);

Address = InetAddress.getByName("starwave.com");

System.out.println(Address);

InetAddress SW[] =

InetAddress.getAllByName("www.nba.com");

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

System.out.println(SW[i]);

}

}

3. // Demonstrate URL.

import java.net.*;

class patrickURL {

Page 227: Java - A Helpful Hand

JAVA

MCA-III Page 227

public static void main(String args[]) throws

MalformedURLException {

URL hp = new

URL("http://www.starwave.com/people/naughton/");

System.out.println("Protocol: " + hp.getProtocol());

System.out.println("Port: " + hp.getPort());

System.out.println("Host: " + hp.getHost());

System.out.println("File: " + hp.getFile());

System.out.println("Ext:" + hp.toExternalForm());

}

}

4. //Demonstrate Sockets.

import java.net.*;

import java.io.*;

class ser {

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

ServerSocket ss = new ServerSocket(777);

Socket s=ss.accept();

System.out.print("connection established");

Page 228: Java - A Helpful Hand

JAVA

MCA-III Page 228

OutputStream out = s.getOutputStream();

PrintStream ps=new PrintStream(out);

String str = "hello client" ;

ps.println(str);

ps.println("bye");

ps.close();

s.close();

}

}

5. // Demonstrate URLConnection.

import java.net.*;

import java.io.*;

import java.util.Date;

class UCDemo

{

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

int c;

URL hp = new

URL("http://www.starwave.com/people/naughton/");

URLConnection hpCon = hp.openConnection();

Page 229: Java - A Helpful Hand

JAVA

MCA-III Page 229

System.out.println("Date: " + new Date(hpCon.getDate()));

System.out.println("Content-Type: " +

hpCon.getContentType());

System.out.println("Expires: " + hpCon.getExpiration());

System.out.println("Last-Modified: " +

new Date(hpCon.getLastModified()));

int len = hpCon.getContentLength();

System.out.println("Content-Length: " + len);

if (len > 0) {

System.out.println("=== Content ===");

InputStream input = hpCon.getInputStream();

int i = len;

while (((c = input.read()) != -1) && (--i > 0)) {

System.out.print((char) c);

}

input.close();

} else {

System.out.println("No Content Available");

}

}

}

6. //Demonstrate Sockets.

Page 230: Java - A Helpful Hand

JAVA

MCA-III Page 230

import java.net.*;

import java.io.*;

class Whois {

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

int c;

Socket s = new Socket("internic.net", 43);

InputStream in = s.getInputStream();

OutputStream out = s.getOutputStream();

String str = (args.length == 0 ? "starwave-dom" : args[0]) +

"\n";

byte buf[] = str.getBytes();

out.write(buf);

while ((c = in.read()) != -1) {

System.out.print((char) c);

}

s.close();

}

}

7. // Demonstrate Datagrams.

import java.net.*;

Page 231: Java - A Helpful Hand

JAVA

MCA-III Page 231

class WriteServer {

public static int serverPort = 666;

public static int clientPort = 999;

public static int buffer_size = 1024;

public static DatagramSocket ds;

public static byte buffer[] = new byte[buffer_size];

public static void TheServer() throws Exception {

int pos=0;

while (true) {

int c = System.in.read();

switch (c) {

case -1:

System.out.println("Server Quits.");

return;

case '\r':

break;

case '\n':

ds.send(new DatagramPacket(buffer,pos,

InetAddress.getLocalHost(),clientPort));

pos=0;

break;

Page 232: Java - A Helpful Hand

JAVA

MCA-III Page 232

default:

buffer[pos++] = (byte) c;

}

}

}

public static void TheClient() throws Exception {

while(true) {

DatagramPacket p = new DatagramPacket(buffer,

buffer.length);

ds.receive(p);

System.out.println(new String(p.getData(), 0,

p.getLength()));

}

}

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

if(args.length == 1) {

ds = new DatagramSocket(serverPort);

TheServer();

} else {

ds = new DatagramSocket(clientPort);

TheClient();

Page 233: Java - A Helpful Hand

JAVA

MCA-III Page 233

}

}

}