Você está na página 1de 60

Experiment 1

AIM: Write a JAVA program to print a welcome message.

public class Welcome1


{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1

[1]
Experiment 2

AIM: Write a JAVA program to perform various arithmetic operations using switch-case statement.

import java.util.Scanner;
public class airthmetic
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("enter numbers");
int a=s.nextInt();
int b=s.nextInt();
System.out.println("entered numbers are:"+a+"and"+b);
System.out.println("enter your choice");
int ch=s.nextInt();
switch(ch)
{
case 1: int h=a+b;
System.out.println("addition is:"+h);
break;
case 2: int q=a/b;
System.out.println("division is:"+q);
break;
case 3: int w=a*b;
System.out.println("mutiplication is:"+w);
break;
case 4: int e=a-b;
System.out.println("subtraction is:"+e);
break;
}}}

[2]
Experiment 3

AIM: Write a JAVA program to compare two numbers.

import java.util.Scanner; // program uses class Scanner

public class Comparison


{
// main method begins execution of Java application
public static void main( String[] args )
{
// create Scanner to obtain input from command line
Scanner input = new Scanner( System.in );

int number1; // first number to compare


int number2; // second number to compare

System.out.print( "Enter first integer: " ); // prompt


number1 = input.nextInt(); // read first number from user

System.out.print( "Enter second integer: " ); // prompt


number2 = input.nextInt(); // read second number from user

if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );

if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );

if ( number1 < number2 )


System.out.printf( "%d < %d\n", number1, number2 );

[3]
if ( number1 > number2 )
System.out.printf( "%d > %d\n", number1, number2 );

if ( number1 <= number2 )


System.out.printf( "%d <= %d\n", number1, number2 );

if ( number1 >= number2 )


System.out.printf( "%d >= %d\n", number1, number2 );
} // end method main
} // end class Comparison

[4]
Experiment 4

AIM: write a JAVA program for matrix Multiplication.

import java.util.Scanner;

public class MatrixMultiplication {

public static void main(String[] args) {


Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in A: ");
int rowsInA = s.nextInt();
System.out.print("Enter number of columns in A / rows in B: ");
int columnsInA = s.nextInt();
System.out.print("Enter number of columns in B: ");
int columnsInB = s.nextInt();
int[][] a = new int[rowsInA][columnsInA];
int[][] b = new int[columnsInA][columnsInB];
System.out.println("Enter matrix A");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("Enter matrix B");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
b[i][j] = s.nextInt();
}
}
int[][] c = multiply(a, b);

[5]
System.out.println("Product of A and B is");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}

public static int[][] multiply(int[][] a, int[][] b) {


int rowsInA = a.length;
int columnsInA = a[0].length; // same as rows in B
int columnsInB = b.length;
int[][] c = new int[rowsInA][columnsInB];
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return c;
}
}

[6]
Experiment 5

AIM: write a JAVA program to implement Tower of Hanoi using recursion with three disks.

public class Toh


{
public static String hanoi(int nDisks, int fromPeg, int toPeg)
{
int helpPeg;
String Sol1, Sol2, MyStep, mySol; // Contains moves

if ( nDisks == 1 )
{
return fromPeg + " -> " + toPeg + "\n";
}
else
{
helpPeg = 6 - fromPeg - toPeg; // Because fromPeg + helpPeg + toPeg = 6

Sol1 = hanoi(nDisks-1, fromPeg, helpPeg);

MyStep = fromPeg + " -> " + toPeg + "\n";

Sol2 = hanoi(nDisks-1, helpPeg, toPeg);

mySol = Sol1 + MyStep + Sol2; // + = String concatenation !

return mySol;
}
}
public static void main (String[] args)

[7]
{
int n = 3;

String StepsToSolution;

StepsToSolution = hanoi(n, 1, 3);

System.out.println(StepsToSolution);
}
}

[8]
Experiment 6

AIM: write a JAVA program to implement addition of two complex numbers.

import java.io.*;
class complex
{
int r,i;
complex()
{
r =0;
i=0;
}
void sum(complex c,complex d)
{
complex a=new complex();
a.r=c.r+d.r;
a.i=c.i+d.i;
System.out.println("The sum is "+a.r+"+"+a.i+"i");
}
void read()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter the real part");
r=Integer.parseInt(br.readLine());
System.out.println("\nEnter the imaginary part");
i=Integer.parseInt(br.readLine());
System.out.println("\nYou have entered : "+r+"+"+i+"i");
}
public static void main(String s[])throws IOException
{

[9]
complex c=new complex();
complex d=new complex();
System.out.println("First number");
c.read();
System.out.println("\nSecond number");
d.read();
d.sum(c,d);
}
}

[10]
Experiment 7

AIM: write a JAVA program to implement single inheritance.

class employee
{
private int eno;
private String ename;
public void setemp(int no,String name)
{
eno = no;
ename = name;
}
public void putemp()
{
System.out.println("Empno : " + eno);
System.out.println("Ename : " + ename);
}
}
class department extends employee
{
private int dno;
private String dname;
public void setdept(int no,String name)
{
dno = no;
dname = name;
}
public void putdept()
{
System.out.println("Deptno : " + dno);

[11]
System.out.println("Deptname : " + dname);
}
public static void main(String args[])
{
department d = new department();
d.setemp(100,"aaaa");
d.setdept(20,"Sales");
d.putemp();
d.putdept();
}
}

[12]
Experiment 8

AIM: write a JAVA program to implement multilevel inheritance.


class students
{
private int sno;
private String sname;
public void setstud(int no,String name)
{
sno = no;
sname = name;
}
public void putstud()
{
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}
}
class marks extends students
{
protected int mark1,mark2;
public void setmarks(int m1,int m2)
{
mark1 = m1;
mark2 = m2;
}
public void putmarks()
{
System.out.println("Mark1 : " + mark1);
System.out.println("Mark2 : " + mark2);
}

[13]
}
class finaltot extends marks
{
private int total;
public void calc()
{
total = mark1 + mark2;
}
public void puttotal()
{
System.out.println("Total : " + total);
}
public static void main(String args[])
{
finaltot f = new finaltot();
f.setstud(100,"Nithya");
f.setmarks(78,89);
f.calc();
f.putstud();
f.putmarks();
f.puttotal();
}
}

[14]
Experiment 9

AIM: write a JAVA program to implement multiple inheritance using interface.


interface I1{
public int i=1;
void abc();
}
interface I2 extends I1{
public int j=10;
void abc(); //Ok. but no meaning as its just a declaration, not overriding
}
interface I3{
public int l=1000;
}
interface I4 extends I2,I3{ //multiple inheritance
public int k=100;
void pqr();
}

public class InterfaceTest implements I4{

public static void main(String[] args) {


InterfaceTest intf = new InterfaceTest();
intf.abc();
intf.pqr();
}

//Implementation of the methods..


public void pqr() {
System.out.println("in pqr()");
//Using inherited properties as if they are local properties.

[15]
System.out.println("i in I1 : "+i);
System.out.println("j in I2 : "+j);
System.out.println("l in I3 : "+l);
System.out.println("k in I4 : "+k);
}

public void abc() {


System.out.println("in abc()");
}

[16]
Experiment 10

AIM: write a JAVA program to implement hierarchical inheritance.


//A.java
class A
{
void DisplayA()
{
System.out.println("I am in A");
}
}

//B.java
class B extends A
{
void DisplayB()
{
System.out.println("I am in B");
}
}

//c.java
class C extends A
{
void DisplayC()
{
System.out.println("I am in C");
}
}

//MainClass.java

[17]
public class hierarchical
{
public static void main(String args[])
{
System.out.println("Calling for subclass C");
C c = new C();
c.DisplayA();
c.DisplayC();

System.out.println("Calling for subclass B");


B b = new B();
b.DisplayA();
b.DisplayB();
}
}

[18]
Experiment 11

AIM: write a JAVA program to implement exception handling.


import java.io.*;
public class ExceTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}

[19]
Experiment 12

AIM: write a JAVA program to implement interface.


interface Animal {

public void eat();


public void travel();
}
/* File name : Mamal.java */
public class Mamal implements Animal{

public void eat(){


System.out.println("Mamal eats");
}

public void travel(){


System.out.println("Mamal travels");
}

public static void main(String args[]){


Mamal m = new Mamal();
m.eat();
m.travel();
}
}

[20]
Experiment 13

AIM: write a JAVA program to create a package, import it in a class which check whether a string is
palindrome or not.
package mypackage;
public class Palindrome
{
public boolean test(String str)
{
char givenstring[];
char reverse[] = new char[str.length()];
boolean flag = true;
int count = 0, ctr = 0;
givenstring = str.toCharArray();
for(count = str.length() - 1; count >= 0; count--)
{
reverse[ctr] = givenstring[count];
ctr++;
}
for(count = 0; count < str.length(); count++)
{
if(reverse[count] != givenstring[count])
flag = false;
}
return flag;
}

}
/* Save the code as Palindrome.java in the current working directory. Compile the program using the
following command:
javac -d . Palindrome.java

[21]
*/
// class using above package
import mypackage.*;
class Palintest
{
public static void main(String args[])
{
String s=args[0];
Palindrome objPalindrome = new Palindrome();
System.out.println(objPalindrome.test(s));
}
}

[22]
Experiment 14

AIM: write a JAVA program to read a file called temp.txt and output the file line by line on the
console.
import java.io.*;

public class Fileread {


public static void main(String [] args) {

// The name of the file to open.


String fileName = "temp.txt";

// This will reference one line at a time


String line = null;

try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);

// Always wrap FileReader in BufferedReader.


BufferedReader bufferedReader =
new BufferedReader(fileReader);

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


System.out.println(line);
}

// Always close files.


bufferedReader.close();
}

[23]
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}

[24]
Experiment 15

AIM: Write a java program that creates a file called temp.txt and writes some lines of text to it.
import java.io.*;

public class Filewrite {


public static void main(String [] args) {

// The name of the file to open.


String fileName = "temp.txt";

try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);

// Always wrap FileWriter in BufferedWriter.


BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);

// Note that write() does not automatically


// append a newline character.
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");

// Always close files.


bufferedWriter.close();
}

[25]
catch(IOException ex) {
System.out.println("Error writing to file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}

[26]
Experiment 16

AIM: Write a JAVA program to implement Life Cycle of an Applet.

/*
<applet code="LifeCycle.class" width=300 height=300></applet>
*/

import java.applet.Applet;
import java.awt.*;

public class LifeCycle extends Applet


{
String output = "";
String event;

public void init()


{
event = "Initializing...";
printOutput();
}

public void start()


{
event = "Starting...";
printOutput();
}

public void stop()


{
event = "Stopping...";

[27]
printOutput();
}

public void destroy()


{
event = "Destroying...";
printOutput();
}

private void printOutput()


{
System.out.println(event);
output += event;
repaint();
}

public void paint(Graphics g)


{
g.drawString(output, 10, 10);
}

[28]
Experiment 17

AIM: Write a JAVA program to draw rectangle using applet.

/*
<applet code="Polygon.class" width=3000 height=800></applet>
*/

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

public class Polygon extends Applet{


public void paint(Graphics g){
g.drawRect(300,150,200,100);
g.setColor(Color.yellow);
g.fillRect( 300,150, 200, 100 );
g.setColor(Color.magenta);
g.drawString("Rectangle",500,150);
}
}

[29]
Experiment 18

AIM: Write a JAVA program for implementing constructor overloading.

class Language {
String name;

Language() {
System.out.println("Constructor method called.");
}

Language(String t) {
name = t;
}

public static void main(String[] args) {


Language cpp = new Language();
Language java = new Language("Java");

cpp.setName("C++");

java.getName();
cpp.getName();
}

void setName(String t) {
name = t;
}
void getName() {
System.out.println("Language name: " + name);
}}

[30]
Experiment 19

AIM: Write a JAVA program for extraction of characters from a string.

import java.io.*;

class Charextract
{
public static void main(String args[])
{
String s,str,substr;
int extract,start,len,check;

try{
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String : ");
System.out.flush();
str=obj.readLine();
len=str.length();

System.out.print("Enter Starting position to extract characters : ");


System.out.flush();
s=obj.readLine();
start=Integer.parseInt(s);
start=start-1;
if(start<0 || start>len)
{
System.out.println("INVALID POSITION");
System.exit(1);
}

[31]
System.out.print("Enter how many characters you want to extract : ");
System.out.flush();
s=obj.readLine();
extract=Integer.parseInt(s);
check=extract+start;
if(check<0 || check>len )
{
System.out.println("TRYING TO EXTRACT INVALID POSITION");
System.exit(1);
}

substr=str.substring(start,check);
System.out.println("\nEXTRACTED STRING IS "+substr);
}
catch(Exception e) {}
}
}

[32]
Experiment 20

AIM: Write a JAVA program for comparing two strings.

import java.util.Scanner;

class Comparestrings
{
public static void main(String args[])
{
String s1, s2;
Scanner in = new Scanner(System.in);

System.out.println("Enter the first string");


s1 = in.nextLine();

System.out.println("Enter the second string");


s2 = in.nextLine();

if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
}
}

[33]
Experiment 21

AIM: Write a JAVA program for implementing various string operations.

public class StringExample{

public static void main(String args[]){

String word;

//assign the string to the variable:


word = "AmitBagrecha";

//preform some actions on the string:

//1. retrieve the length by calling the


//length method:
int length = word.length();
System.out.println("Length: " + length);

//2. use the case functions:


System.out.println("toUpperCase: " + word.toUpperCase());
System.out.println("toLowerCase: " + word.toLowerCase());

//3. use the trim function to eliminate leading


//or trailing white spaces:
word = word.trim();
System.out.println("trim: " + word);

//4. check for a certain character using indexOf()


System.out.println("indexOf('s'): " + word.indexOf('s'));

[34]
//5. print out the beginning character using charAt()
System.out.println("first character: " + word.charAt(0));

//6. make the string shorter


word = word.substring(0, 4);
System.out.println("shorter string: " + word);
}
}

[35]
Experiment 22

AIM: Write a JAVA program for implementing method overloading.

class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class Methodoverload
{
public static void main(String args[])
{
Sample sObj = new Sample();

System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2));
}
}

[36]
Experiment 23

AIM: Write a JAVA program for implementing method overriding with the help of super keyword.

class Superclass {

public void printMethod() {


System.out.println("Printed in Superclass.");
}
}
//Here is a subclass, called Subclass, that overrides printMethod():

class Subclass extends Superclass {

// overrides printMethod in Superclass


public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}

[37]
Experiment 24

AIM: Write a JAVA program for demonstrating use of final keyword.

public class FinalVariable


{

public static void main(String[] args) {

final int hoursInDay=24;

//This statement will not compile. Value can't be changed.

//hoursInDay=12;

System.out.println("Hours in 5 days = " + hoursInDay * 5);

}
}

[38]
Experiment 25

AIM: Write a JAVA program for implementing abstract class.

abstract class Shape


{
void display()
{
}
}

class Circle extends Shape


{
void display()
{
System.out.println("You are using circle class");
}
}

class Rectangle extends Shape


{
void display()
{
System.out.println("You are using rectangle class");
}
}

class Triangle extends Shape


{
void display()
{

[39]
System.out.println("You are using triangle class");
}
}

class Abstract
{
public static void main(String args[])
{
Shape sobj = new Circle();
sobj.display();

sobj = new Rectangle();


sobj.display();

sobj = new Triangle();


sobj.display();
}
}

[40]
Experiment 26

AIM: Write a JAVA program for demonstrating use of access control and static keyword.

class student {

static int count;//Does not Require initialization.


int count1 = 0;//Non Static Member Variable must to be initialized

student() {
acc_details(); //Accessed only within the class
}

public static void stu_details() //static method can be called without the object
{
System.out.println("Name:XXXX");
System.out.println("Roll No:123456");
count++;
//count1++;here it cannot be used because non static member could not be used in the static function
}

private void acc_details() //non static method can be called only with the object
{
System.out.println("Entered into Private Access Specifiers");
System.out.println("Password:*******");
count++;
count1++;
}

protected void att_details() //non static method can be called only with the object
{

[41]
System.out.println("Attendance Details");
count++;
count1++;

}
}

class staff extends student {

protected static void sta_details()//static method can be called without the object
{
count++;
//count1++; here it cannot be used because non static member could not be used in the static function
System.out.println("Name:YYYY");

}
}

class hod extends staff {

protected static void hod_details() //static method can be called without the object
{
count++;

//count1++; here it cannot be used because non static member could not be used in the static function

System.out.println("Name:ZZZ");

}
}

[42]
class college extends hod {

public static void main(String a[]) {

stu_details();//College can view the student details because it is in public mode


/*
* static method can be called without the object .If you didnt specify
* as static during the declaration of this function you will get an
* error message during the calling of this function
*/

sta_details();//College can view the staff details because it is in public mode


/*
* static method can be called without the object .If you didnt specify
* as static during the declaration of this function you will get an
* error message during the calling of this function
*/

hod_details();//College can view the hod details because it is in public mode


/*
* static method can be called without the object .If you didnt specify
* as static during the declaration of this function you will get an
* error message during the calling of this function
*/
staff s1 = new staff();
s1.stu_details();//staff can also view the student details because it is in public mode

hod s2 = new hod();


s2.stu_details();//hod can also view the student details because it is in public mode

[43]
s1.att_details();//staff can also view the student attendance details because it is inherited so it has an
//access over protected details.

s2.att_details();//staff can also view the student attendance details because it is inherited so it has an
//access over protected details.

//acc_details() cannot not be viewed by any of the classes like staff,hod and college becuase it is in
//private mode.
student s = new student();
//s.acc_details(); it cannot be called because private mode function only accessed within the function.
s.stu_details();
s.att_details();
System.out.println("Count value without object:" + count);//count variable can be called without an
//object
//System.out.println("Count1 Value:" + count1); count1 variable cannot be called without an
object //because it is non-static
System.out.println("Count value with object of class student:" + s.count);
System.out.println("Count value with object of class staff:" + s1.count);
System.out.println("Count value with object of class hod:" + s2.count);
System.out.println("Count1 value with object of class student:" + s.count1);
System.out.println("Count1 value with object of class staff:" + s1.count1);
System.out.println("Count1 value with object of class hod:" + s2.count1);
}
}

[44]
Experiment 27

AIM: write a JAVA program for implementing various thread methods.

class ThreadTest1
{
public static void main(String args[])
{
MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}

class MyThread extends Thread


{
static String message[] =
{ "Java", "is", "secure,", "dynamic,", "and", "invigorating."};

[45]
public MyThread(String id)
{
super(id);
}

public void run()


{
String name = getName();
for (int i=0;i<message.length;++i) {
randomWait();
System.out.println(name + message[i]);
}
}

void randomWait()
{
try {
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}

[46]
Experiment 28

AIM: Write a JAVA program for thread synchronization.

class ThreadSynchronization
{
public static void main(String args[])
{
MyThread thread1 = new MyThread("thread1: ");
MyThread thread2 = new MyThread("thread2: ");
thread1.start();
thread2.start();
boolean thread1IsAlive = true;
boolean thread2IsAlive = true;
do {
if (thread1IsAlive && !thread1.isAlive()) {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
}
if (thread2IsAlive && !thread2.isAlive()) {
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
}
} while(thread1IsAlive || thread2IsAlive);
}
}

class MyThread extends Thread


{
static String message[] =
{ "Java", "is", "hot,", "aromatic,", "and", "invigorating."};

[47]
public MyThread(String id)
{
super(id);
}

public void run()


{
SynchronizedOutput.displayList(getName(),message);
}

void randomWait()
{
try {
sleep((long)(3000*Math.random()));
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}

class SynchronizedOutput
{
public static synchronized void displayList(String name,String list[])
{
for(int i=0;i<list.length;++i) {
MyThread t = (MyThread) Thread.currentThread();
t.randomWait();
System.out.println(name+list[i]);
}
}}

[48]
Experiment 29

AIM: Write a JAVA program for creating a calculator using applet.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code="cal" width=500 height=500></applet>
public class cal extends Applet implements ActionListener
{
int a,b,c;
TextField t1;
Button

b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
String s,s1,s2,s3,s4;
public void init()
{
setLayout(null);
t1=new TextField(10);
t1.setBounds(80,200,260,40);
add(t1);
b1=new Button("0");
b2=new Button("1");
b3=new Button("2");
b4=new Button("3");
b5=new Button("4");
b6=new Button("5");
b7=new Button("6");
b8=new Button("7");
b9=new Button("8");

[49]
b10=new Button("9");
b11=new Button("+");
b12=new Button("-");
b13=new Button("*");
b14=new Button("/");
b15=new Button("=");
b16=new Button("CLR");
b1.setBounds(90,260,40,30);
add(b1);
b2.setBounds(140,260,40,30);
add(b2);
b3.setBounds(190,260,40,30);
add(b3);
b4.setBounds(240,260,40,30);
add(b4);
b5.setBounds(290,260,40,30);
add(b5);
b6.setBounds(90,300,40,30);
add(b6);
b7.setBounds(140,300,40,30);
add(b7);
b8.setBounds(190,300,40,30);
add(b8);
b9.setBounds(240,300,40,30);
add(b9);
b10.setBounds(290,300,40,30);
add(b10);
b11.setBounds(90,340,40,30);
add(b11);
b12.setBounds(140,340,40,30);
add(b12);

[50]
b13.setBounds(190,340,40,30);
add(b13);
b14.setBounds(240,340,40,30);
add(b14);
b15.setBounds(290,340,40,30);
add(b15);
b16.setBounds(90,380,70,20);
add(b16);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
b16.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
s=ae.getActionCommand();
if(s.equals("0") || s.equals("1") || s.equals("2")||

[51]
s.equals("3") || s.equals("4") || s.equals("5")||s.equals

("6")||s.equals("7")||s.equals("8")||s.equals("9"))
{
s1=t1.getText()+s;
t1.setText(s1);
}

if(s.equals("+"))
{
s2=t1.getText();
t1.setText("");
s3="+";
}

if(s.equals("-"))
{
s2=t1.getText();
t1.setText("");
s3="-";
}

if(s.equals("*"))
{
s2=t1.getText();
t1.setText("");
s3="*";
}

if(s.equals("/"))
{

[52]
s2=t1.getText();
t1.setText("");
s3="/";
}

if(s.equals("="))
{
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals("+"))
c=a+b;

if(s3.equals("-"))
c=a-b;

if(s3.equals("*"))
c=a*b;
if(s3.equals("/"))
c=a/b;
t1.setText(String.valueOf(c));
}

if(s.equals("CLR"))
{

t1.setText("");

[53]
public void paint(Graphics g)
{
setBackground(Color.green);
g.drawRect(80,200,260,200);
showStatus("ASHUSOFTECH");
g.drawString("CALCULATER",200,50);
}
}

[54]
Experiment 30

AIM: Write a JAVA program using continue statement.

class jump
{
public static void main(String args[])
{
for(int count=1;count <= 10;count++)
{
System.out.print(count + " ");
if (count==5)
continue;
System.out.println("");

}
}
}

[55]
Experiment 31

AIM: write a JAVA program to print numbers from 1 to 10 using while statement.

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}

[56]
Experiment 32

AIM: write a JAVA program for printing numbers from 1 to 10 using do-while loop.

class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}

[57]
Experiment 33

AIM: write a JAVA program for implementing exception handling using throw and finally.

// Demonstrate finally.
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}

[58]
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

[59]
[60]

Você também pode gostar