Вы находитесь на странице: 1из 89

1

LAB
EXERCISE 1























2

PROGRAM -1

Write a program in java to generate the next 10 Fibonacci numbers
starting from the number that the user specifies.
import java.io.*;
class First
{
public static void main(String args[]) throws IOException
{
int first,second,sum;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first two nos from where you want to get the next 10 fibonacci nos:
");
first=Integer.parseInt(br.readLine());
second=Integer.parseInt(br.readLine());
System.out.println(first+" "+second);
for(int i=1;i<=10;i++)
{
sum=first+second;
System.out.print(" "+sum);
first=second;
second=sum;
}
}
}
OUTPUT


3

PROGRAM-2
Write a program in java to accept the year entry from user and then display
whether the entered year is a leap year or not.
import java.io.*;
class Second
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the year: ");
int year=Integer.parseInt(br.readLine());
if(year%4==0)
System.out.print("It is a leap year");
else
System.out.print("It is not a leap year");
}
}
OUTPUT






4

PROGRAM-3
Write a program in java to generate all the prime numbers less than the
value entered by the user.
import java.io.*;
class Third
{
public static void main(String args[]) throws IOException
{
int no;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no less than which you want the prime nos to be print: ");
no=Integer.parseInt(br.readLine());
for(int i=2; i < no; i++)
{
boolean isPrime = true;
for(int j=2; j < i ; j++)
{
if(i % j == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
System.out.print(i + " ");
}
}
} OUTPUT

5

PROGRAM-4
Write a program in java to calculate the factorial of the entered number.
import java.io.*;
class Forth
{
public static void main(String args[]) throws IOException
{
int no,factorial;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no whose factorial you want to find out: ");
no=Integer.parseInt(br.readLine());
int fact=1;
for(int i=no;i>=1;i--)
fact=fact*i;
System.out.println("The factorial of the entered no is: "+fact);
}
}

OUTPUT






6

PROGRAM-5
Write a program in java to find the sum of digits of the number entered
by the user.(use while loop)
import java.io.*;
class Fifth
{
public static void main(String args[]) throws IOException
{
int no,remainder,sum=0;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no. whose sum of digits you want to find out: ");
no=Integer.parseInt(br.readLine());
while(no!=0)
{
remainder=no%10;
sum+=remainder;
no=no/10;
}
sum=sum+no;
System.out.println("The sum of digits of the no. entered is "+sum);
}
}

OUTPUT

7

PROGRAM-6
Write a program in java to ask the user to enter a number and print its
digits in reverse order. (use while loop)
import java.io.*;
class Sixth
{
public static void main(String args[]) throws IOException
{
int num;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no. whose digits you want to be printed in reverse order ");
num=Integer.parseInt(br.readLine());
System.out.println("The reverse order for the no entered is ");
do
{
System.out.print(num-((num/10)*10));
num/=10;
}while(num>10);

System.out.print(num%10);
}
}

OUTPUT

\
8

PROGRAM-7
Write a program in java to print the next 15 even number series from
the specified number in the series. (Use do while loop)
import java.io.*;
class Seventh
{
public static void main(String args[]) throws IOException
{
int num,j=1;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the no. from where you want the next 15 even nos to be printed ");
num=Integer.parseInt(br.readLine());
System.out.print("The next 15 even no series from the specific no is ");

int i=num;
do
{
if(num%2==0)
{
System.out.print(num+" ");
j++;
}
num=num+1;
}while(j<=15);
}
}
OUTPUT


9

PROGRAM-8
Write a program to find the number of and sum of all integers greater
than 50 and less than 350 that are divisible by 3.
import java.io.*;
class Eight
{
public static void main(String args[]) throws IOException
{
int num=0,sum=0;
for(int i=50;i<350;i++)
{
if(i%3==0)
{
num++;
sum=sum+1;
}
}
System.out.print("The no of all the integers greater than 50 and less than 350 that are divisible by
3 are "+ num+". The sum of all the integers greater than 50 and less than 350 that are divisible by
3 is "+sum);
}
}

OUTPUT


10

PROGRAM-9
Write a program in java to accept a character from the user and print
whether the entered character is a vowel or not. (Use 'switch case')
import java.io.*;
class Ninth
{
public static void main(String args[]) throws IOException
{
char ch;
System.out.print("Enter any character between a-z/A-Z: ");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
ch=(char)br.read();
switch(ch)
{
case 'a':
System.out.println("Entered character is a vowel");
break;

case 'A':
System.out.println("Entered character is a vowel");
break;

case 'e':
System.out.println("Entered character is a vowel");
break;

case 'E':
System.out.println("Entered character is a vowel");
break;

case 'i':
System.out.println("Entered character is a vowel");
break;

case 'I':
System.out.println("Entered character is a vowel");
break;

case 'o':
System.out.println("Entered character is a vowel");
break;

case 'O':
System.out.println("Entered character is a vowel");
11

break;

case 'u':
System.out.println("Entered character is a vowel");
break;

case 'U':
System.out.println("Entered character is a vowel");
break;

default:
System.out.println("Entered character is not a vowel");
break;
}
}
}

OUTPUT


12

PROGRAM-10
Write a program in java that accepts a number between 0 and 10 along
with a string. Display the string the number of times specified.
import java.io.*;
class Tenth
{
public static void main(String args[]) throws IOException
{
int no;
String str;
System.out.println("Enter a no b/w 0 and 10: ");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
no=Integer.parseInt(br.readLine());
System.out.println("Enter the string which you want to print the specified no. of times: ");
str=(String)br.readLine();
for(int i=0;i<no;i++)
System.out.print(str+",");
}
}

OUTPUT





13

PROGRAM-11
Write a program in java to accept marks from the user and then display
grades
90-100 --------- grade A
90-70 ---------- grade B
70-50 ---------- grade C
50 below ------ grade D
(use if-else if )
import java.io.*;
class Eleventh
{
public static void main(String args[]) throws IOException
{
int marks;
System.out.print("Enter the marks for knowing your grade: ");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
marks=Integer.parseInt(br.readLine());
if(marks>90 && marks<=100)
System.out.print("Since the marks entered by you is in the range 90-100, so you have received
grade A");
else
if(marks>70 && marks<=90)
System.out.print("Since the marks entered by you is in the range 90-70, so you have received
grade B");
else
if(marks>=50 && marks<=70)
System.out.print("Since the marks entered by you is in the range 70-50, so you have received
grade C");
else
if(marks<50)
System.out.print("Since the marks entered by you is below 50, so you have received grade D");
}
}

14

OUTPUT



























15

PROGRAM-12
Design a class to convert the entered temperature in Centigrade to its
Fahrenheit equivalent.
import java.io.*;
class Twelvth
{
public static void main(String args[]) throws IOException
{
double cent,fahr;

System.out.print("Enter the temprature in Centigrade: ");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
cent=Double.parseDouble(br.readLine());
fahr=(cent*(9/5))+32;
System.out.print("The corresponding temprature in Fahrenheit is "+fahr);
}
}

OUTPUT




16

PROGRAM-13
Design an Employee class which takes input from the user for 5 different
employees emp_code, name and salary and then display all the three
attributes of those employees.
import java.io.*;
class Employee
{
public static void main(String args[]) throws IOException
{
int a;
System.out.println("How many employees details you wish to enter:");
BufferedReader br= new BufferedReader(new

InputStreamReader(System.in));
a=Integer.parseInt(br.readLine());
int emp_code[]=new int[a];
String name[]=new String[a];
Float salary[]=new Float[a];
for(int j=0;j<a;j++)
{
System.out.println("Enter details for the employee no." +(j+1));
System.out.println("emp_code:");
emp_code[j]=Integer.parseInt(br.readLine());
System.out.println("name:");
name[j]=(String)br.readLine();
System.out.println("salary:");
salary[j]=Float.parseFloat(br.readLine());
}
System.out.println("Details of "+a+" employees");
for(int j=0;j<a;j++)
{
System.out.println(" Employee " + ( j + 1 ) + " " + emp_code

[j]);
System.out.println(" Employee " + ( j + 1 ) + " " + name[j]);
System.out.println(" Employee " + ( j + 1 ) + " " + salary[j]);
}
}
}






17

OUTPUT









18

PROGRAM-14
Write a program for Pizza Ordering Process. Take choice of user and
calculate the total price of pizza based on different options choose by
user and show the order details to user.
import java.io.*;
import java.util.Scanner;
class Pizza
{
public static void main(String args[]) throws IOException
{
String size;
int quant;
int bill=0;
String type,topp,top_type,cheez;
System.out.println("--------Welcome to PIZZA MANIA!!!!--------- ");
System.out.println("Please select from the menu below: ");
System.out.println("SIZE: Small Medium Large");
System.out.println("TYPES: Doublecheez VegSurprise Mushroomie ChickenGrilled");
System.out.println("Price");
System.out.println("Doublecheez:");
System.out.println("Small-250 Medium-380 Large-450");
System.out.println("VegSurprise:");
System.out.println("Small-180 Medium-250 Large-350");
System.out.println("Mushroomie:");
System.out.println("Small-200 Medium-280 Large-375");
System.out.println("ChickenGrilled:");
System.out.println("Small-300 Medium-399 Large-450");
Label:
{
System.out.println("Enter the size of the pizza ");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
size=br.readLine();
System.out.println("Enter the type of the pizza Doublecheez-D,vegSurprise-V,Mushroomie-
M,ChickenGrilled-C");
type=br.readLine();
if(size.equals("Small") || size.equals("small"))
{
if(type.equals("D"))
{
bill=bill+250;
}
else if(type.equals("V"))
{
bill=bill+180;
19

}
else if(type.equals("M"))
{
bill=bill+200;
}
else if(type.equals("C"))
{
bill=bill+300;
}
}
if(size.equals("Medium") || size.equals("medium"))
{
if(type.equals("D"))
{
bill=bill+380;
}
else if(type.equals("V"))
{
bill=bill+250;
} else if(type.equals("M"))
{
bill=bill+280;
else if(type.equals("C"))
{
bill=bill+450;
}
}
if(size.equals("Large") || size.equals("large"))
{
if(type.equals("D"))
{
bill=bill+380;
}
else if(type.equals("V"))
{
bill=bill+250;
}
else if(type.equals("M"))
{
bill=bill+280;
}
else if(type.equals("C"))
{
bill=bill+399;
}
}
20


System.out.println("Enter the quantity of the above order: ");
quant=Integer.parseInt(br.readLine());
bill=bill*quant;
System.out.println("Do you wish to have extra toppings? Y/N Rs. 30 extra for each ");
topp=br.readLine();
if(topp.equals("Y") || topp.equals("y"))
{
System.out.println("Enter your choice:");
System.out.println("Pepronie(P),Sausage(S),DoubleDip(D)");
top_type=br.readLine();
bill=bill+30;
}
System.out.println("Do you wish to have extra cheese? Y/N Rs. 50 extra for each ");
cheez=br.readLine();
if(cheez.equals("Y") || cheez.equals("y"))
{
bill=bill+50;
}
}
System.out.println("Thank you for placing your order. Your order details are as follows:");
System.out.println("Type="+type+" "+"Size-"+size+" "+" "+"Quantity"+quant+"
Rs."+bill+"/-");
if(topp=="Y"|| topp=="y")
System.out.println("Toppings-Rs.30/-");
if(cheez=="Y"|| cheez=="y")
System.out.println("Extra Cheese- Rs.50/-");
System.out.println("Total bill Rs."+bill+"/-");
System.out.println("Hope you like our service. Good day!!! Please visit again...... ");
}
}










21

OUTPUT











22

Program-15
Design a Geometry Calculator that will calculate the area of circle,
rectangle and triangle. it should also calculate the circumference of a
circle and perimeter of triangle and rectangle based on choice of user
import java.util.Scanner;
public class Calculator
{
public static void main (String [] args)
{
int choice; //the users choice
double value = 0;
char letter;
double radius; //the radius of the circle
double length; //the length of the rectangle
double width; //the width of the rectangle
double height; //the height of the triangle
double base; //the base of the triangle
double side1; //the first side of the triangle
double side2; //the second side of the triangle
double side3; //the third side of the triangle
//create a scanner object to read from the keyboard
Scanner keyboard = new Scanner (System.in);
//do loop was chose to allow the menu to be displayed first
do
{
System.out.println("*****************************");
System.out.println("This is a geometry calculator");
System.out.println("*****************************");
System.out.println("");
System.out.print("Choose what you would like to calculate");
System.out.println("");
System.out.println("1. Find the area of a circle");
System.out.println("2. Find the area of a rectangle");
System.out.println("3. Find the area of a triangle");
System.out.println("4. Find the circumference of a circle");
System.out.println("5. Find the perimeter of a rectangle");
System.out.println("6. Find the perimeter of a triangle");
System.out.println("");
System.out.print("Enter the number of your choice : ");
choice = keyboard.nextInt();
System.out.println("");
switch (choice)
{
case 1:
23

System.out.print("Enter the radius of the circle : ");
radius = keyboard.nextDouble();
value = circleArea(radius);
System.out.println("The area of the circle is " + value);
break;
case 2:
System.out.print("Enter the length of the rectangle : ");
length = keyboard.nextDouble();
System.out.print("Enter the width of the rectangle : ");
width = keyboard.nextDouble();
value = rectangleArea(length,width);
System.out.println("The area of the rectangle is " + value);
break;
case 3:
System.out.print("Enter the height of the triangle : ");
height = keyboard.nextDouble();
System.out.print("Enter the base of the triangle : ");
base = keyboard.nextDouble();
value = triangleArea(height,base);
System.out.println("The area of the triangle is " + value);
break;
case 4:
System.out.print("Enter the radius of the circle : ");
radius = keyboard.nextDouble();
value = circleCircumference(radius);
System.out.println("The circumference of the circle is " + value);
break;
case 5:
System.out.print("Enter the length of the rectangle : ");
length = keyboard.nextDouble();
System.out.print("Enter the width of the rectangle : ");
width = keyboard.nextDouble();
value = rectanglePerimeter(length,width);
System.out.println("The perimeter of the rectangle is " + value);
break;
case 6:
System.out.print("Enter the length of side 1 " +"of the triangle : ");
side1 = keyboard.nextDouble();
System.out.print("Enter the length of side 2 " +"of the triangle : ");
side2 = keyboard.nextDouble();
System.out.print("Enter the length of side 3 " +"of the triangle : ");
side3 = keyboard.nextDouble();
value = trianglePerimeter(side1,side2,side3);
System.out.println("The perimeter of the " +"triangle is " + value);
break;
default:
24

System.out.println("You did not enter a valid choice.");
}
keyboard.nextLine();
System.out.print("Do you want to exit the program " + "(Y/N)?: ");
String answer = keyboard.nextLine();
letter = answer.charAt(0);
System.out.println("");
}
while (letter != 'Y' && letter != 'y');
}
static double circleArea(double radiusOne)
{
double area=0;
area = 22.7*radiusOne*radiusOne;
return area;
}
static double rectangleArea(double lengthOne, double widthOne)
{
double area=0;
area = lengthOne*widthOne;
return area;
}
static double triangleArea(double heightOne, double baseOne)
{
double area=0;
area = (baseOne*heightOne)/2;
return area;
}
static double circleCircumference(double radiusOne)
{
double circumference=0;
circumference = 2*22.7*radiusOne;
return circumference;
}

static double rectanglePerimeter(double lengthOne, double widthOne)
{
double perimeter=0;
perimeter = 2*lengthOne+2*widthOne;
return perimeter;
}
static double trianglePerimeter(double side1, double side2, double side3)
{
double perimeter=0;
perimeter = side1+side2+side3;
return perimeter;
25

}
}

OUTPUT



26

PROGRAM-16
Write a Television class having television attributes like power, volume,
size etc. and methods to set and get all these parameters.Test this class by
creating a TelevisonDemo.java class after creating different television
objects
import java.io.*;
import java.util.Scanner;
class Television
{
private final String MANUFACTURER;
private final int SCREEN_SIZE;
private boolean powerOn;
private int channel;
private int volume;
Television(String televisionMake,int televisionScreenSize)
{
MANUFACTURER = televisionMake;
SCREEN_SIZE = televisionScreenSize;
powerOn = false;
channel = 2;
volume = 20;
}
public void setChannel(int station)
{
channel = station;
}
public void power()
{
if(powerOn==true)
{
powerOn=!powerOn;
}
else
{
powerOn=!powerOn;
}
}
public void increaseVolume()
{
volume++;
}
public void decreaseVolume()
{
volume--;
27

System.out.println("********************************");
System.out.println("");
System.out.print("Please select your option : ");
menuChoice = keyboard.nextInt();
if(menuChoice==1)
{
bigScreen.power();
if(bigScreen.powerStatus()==true)
{
System.out.println(bigScreen.getManufacturer()+" is turned on now. you can enjoy the tv");
}
else
{
System.out.println(bigScreen.getManufacturer()+" is turned off now");
}
}
else if(menuChoice==2)
{
if(bigScreen.powerStatus()==true)
{
System.out.println("Current Channel : "+bigScreen.getChannel());
}
else
{
System.out.println("Please Turned On TV first to use this option");
}
}
else if(menuChoice==3)
{}
public int getChannel()
{
return channel;
}
public int getVolume()
{
return volume;
}
public String getManufacturer()
{
return MANUFACTURER;
}
public int getScreenSize()
{
return SCREEN_SIZE;
}
public boolean powerStatus()
28

{
return powerOn;
}
}
public class TelevisionDemo
{
public static void main(String[] args) throws IOException
{
final int MAX_VOL=25;
// declare minimum volume level
final int MIN_VOL=0;
//create a Scanner object to read from the keyboard
Scanner keyboard = new Scanner (System.in);
//declare variables
int station; //the users channel choice
char exitChoice = 'n'; //the user's program exit choice
int menuChoice; //the menu selection choice
//declare and instantiate a television object
Television bigScreen = new Television("Samsung LCD", 51);
// Showing the Menu to user
do
{
System.out.println("");
System.out.println("********************************");
System.out.println("********* Welcome To ***********");
System.out.println("**** "+bigScreen.getManufacturer()+" - "+bigScreen.getScreenSize()+"
Inch *****");
System.out.println("********************************");
System.out.println("** 1. Turn On / Turn Off **");
System.out.println("** 2. Get Channel **");
System.out.println("** 3. Set Channel **");
System.out.println("** 4. Increase Voulume **");
System.out.println("** 5. Decrease Voulume **");
System.out.println("** 6. Get Volume Level **");
System.out.println("** 7. Exit Program **");
System.out.println("********************************");
if(bigScreen.powerStatus()==true)
{
System.out.print("What channel do you want? ");
station = keyboard.nextInt();
bigScreen.setChannel(station);
}
else
{
System.out.println("Please Turned On TV first to use this option");
}
29

}
else if(menuChoice==4)
{
if(bigScreen.powerStatus()==true)
{
if(bigScreen.getVolume()<MAX_VOL)
{
bigScreen.increaseVolume();
}
else
{
System.out.println("This is maximum volume : "+bigScreen.getVolume());
}
}
else
{
System.out.println("Please Turned On TV first to use this option");
}
}
else if(menuChoice==5)
{
if(bigScreen.powerStatus()==true)
{
if(bigScreen.getVolume()>MIN_VOL)
{
bigScreen.decreaseVolume();
}
else
{
System.out.println("This is minimum volume : "+bigScreen.getVolume());
}
}
else
{
System.out.println("Please Turned On TV first to use this option");
}
}
else if(menuChoice==6)
{
if(bigScreen.powerStatus()==true)
{
if(bigScreen.getVolume()==0)
{
System.out.println("Volume Level : Mute("+MIN_VOL+")");
}
else if(bigScreen.getVolume()==100)
30

{
System.out.println("Volume Level : Maximum ("+MAX_VOL+")");
}
else
{System.out.println("Volume Level : "+bigScreen.getVolume());
}
}
else
{
System.out.println("Please Turned On TV first to use this option");
}
}
else if(menuChoice==7)
{
if(bigScreen.powerStatus()==true)
{
System.out.println("Please Turned Off TV first to exit the program");
}
else
{
Scanner keyboard1 = new Scanner (System.in);
System.out.print("Do you really want to exit program (y/n) : ");
String temp = keyboard1.nextLine();
exitChoice = temp.charAt(0);
if(exitChoice=='y' || exitChoice=='Y');
{
System.out.println("Thank you for using the "+bigScreen.getManufacturer()+" -
"+bigScreen.getScreenSize()+" Inch Television Program. You are out of program now");
}
}
}
}while(exitChoice=='n' || exitChoice=='N');
}
31

OUTPUT

32



33








LAB
EXERCISE 2






34

PROGRAM-1
Write a program in java to accepts 10 numbers fron the user and then
sort them in ascending and deccending order according to the choice of
the user.
import java.util.*;
class Sorting
{
public static void main(String args[])
{
int a[]=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter array elements:");
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
int ch;
do
{
System.out.println("1- Descending order \n 2- Ascending order \n 3- exit");
System.out.println("Enter ur choice");
ch=sc.nextInt();

switch(ch)
{
case 1:
System.out.println("Array in Descending order:");
for(int i=0;i<10;i++)
{
for(int j=i+1; j<10;j++)
{
if(a[i]<=a[j])
{
int temp=a[j];
a[j]=a[i];
a[i]=temp;
}
35

}
}
for(int i=0;i<10;i++)
{
System.out.println(a[i]);
}
break;
case 2:
System.out.println("Array in Ascending order:");
for(int i=0;i<10;i++)
{
for(int j=i+1; j<10;j++)
{
if(a[j]<a[i])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
} }
for(int i=0;i<10;i++) {
System.out.println(a[i]);
}
break;
case 3:
break;
default :
System.out.println("wrong choice");
}}
while(ch!=3); } }
36

OUTPUT



















37

PROGRAM-2
Design a class in java to accept 10 numbers from the user and at the end
display the largest and the lowest of all.
import java.util.*;
class Number
{
public static void main(String args[])
{
int arr[]=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Enter the numbers:");
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("The Largest of the entered number is:");

int i=0;
for(int j=0;j<10;j++)
{
if(arr[i]<arr[j])
{
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
System.out.println(arr[i]);

System.out.println("The Smallest of the entered number is:");
for(int j=0;j<10;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
38

}
}
System.out.println(arr[i]);
}
}
OUTPUT-





39

PROGRAM-3
Design a class to implement the concept of overloading.
Class Overload
{
void test()
{
System.out.println("There are no parameters");
}
void test(int a, int b)
{
int c=a+b;
System.out.println("Addition of a and b is:" +c);
}
void test(String a, String b)
{
String d= a + b;
System.out.println(" concatenated string is:" +d);
}
}
class OverloadDemo
{
public static void main(String args[])
{
Overload ob= new Overload();
ob.test();
ob.test(3,5);
ob.test("Anchal","Shruti");
}
}






40

OUTPUT-














41

PROGRAM-4
Create a package and use it in your program to perform different functions
like addition, subtractions, multiplication and division.
package Mathss;
public class addition
{
public int add(int x, int y)
{
return (x+y);
}
}
package Mathss;
public class subtraction
{
public int sub(int x, int y)
{
return (x-y);
}
}
package Mathss;
public class division
{
public double div(double x, double y)
{
return (x/y);
}}
package Mathss;
public class multiplication
{
public int mul(int x, int y)
{
return (x*y);
}
}
import Mathss.*;
class newprgm
{
42

public static void main(String args[])
{
addition a= new addition();
System.out.println("Addition:" + a.add(2,3));
subtraction s= new subtraction();
System.out.println("Subtraction:" + s.sub(6,2));
multiplication m= new multiplication();
System.out.println("Multiplication:" + m.mul(6,2));
division d= new division();
System.out.println("Division:"+ d.div(6,2));
}

















43

PROGRAM-5
Create an M by N array.
a) Display the content of the array
b) Row wise and column wise total
c) Reverse contents of specific row
d) Reverse contents of specific column
import java.util.*;
class Arraydemo
{
public static void main(String args[])
{
int row,col,i,j;
int [][]a=new int[3][3];

Scanner s=new Scanner(System.in);
System.out.println("Enter array:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a[i][j]=s.nextInt();
}
}
System.out.println();
System.out.println("The contents of the array:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
/*System.out.println("Enter 2nd array");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
44

Scanner s1=new Scanner(System.in);
b[i][j]=s1.nextInt();
}
}
System.out.println();
System.out.println("The contents of the 2nd array:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
System.out.print(b[i][j] + " ");
System.out.println();
}
System.out.println();
System.out.println("Sum is:");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}*/
System.out.println("The row wise total of the content of the array is:");
for(i=0;i<3;i++)
{
int n=0;
for(j=0;j<3;j++)
{
n=n+a[i][j];
}
System.out.println(i+1 + "Row total:" + n);
}
45


System.out.println("The column wise total of the content of the array is:");
for(j=0;j<3;j++)
{
int m=0;
for(i=0;i<3;i++)
{
m=m+a[i][j];
}
System.out.println(j+1 + "Column total:" + m);
}
System.out.println();
System.out.println("Enter the row no.whose content you want to get reversed:");
row=s.nextInt();
if(row==1)
{
System.out.println("Contents of the row after reversal:");
i=0;
for(j=2;j>=0;j--)
{
System.out.print(a[i][j] + " ");
}
}
else if(row==2)
{
System.out.println("Contents of the row after reversal:");
i=1;
for(j=2;j>=0;j--)
{
System.out.print(a[i][j] + " ");
}
}
else
{
System.out.println("Contents of the row after reversal:");
i=2;
for(j=2;j>=0;j--)
{
System.out.print(a[i][j] + " ");
46

}
}
System.out.println();
System.out.println("Enter the column no.whose content you want to get reversed:");
col=s.nextInt();
if(col==1)
{
System.out.println("Contents of the column after reversal:");
j=0;
for(i=2;i>=0;i--)
{
System.out.print(a[i][j] + " ");
}
}
else if(col==2)
{
j=1;
System.out.println("Contents of the column after reversal:");
for(i=2;i>=0;i--)
{
System.out.print(a[i][j] + " ");
}
}
else
{
System.out.println("Contents of the column after reversal:");
j=2;
for(i=2;i>=0;i--)
{
System.out.print(a[i][j] + " ");
}
}
}
}
OUTPUT-
47















48

PROGRAM-6
Write a program in java using arrays to get the output as follows-
A) 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
class Pattern5
{
public static void main(String []a)
{
int i,j,n=5;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
System.out.print(j+" ");
System.out.println("");
}
}
}
OUTPUT-



49

PROGRAM-6
B)
*
* * *
* * * * *
* * *
*
class Star
{
public static void main(String args[])
{
int i,j,k,l=0;
for(i=0;i<3;i++)
{
for(j=2;j>i;j--)
{
System.out.print(" ");
}
for(k=0;k<2*l+1;k++)
{
System.out.print("*");
}
System.out.println();
l++;
}
int m=1;
for(i=0;i<2;i++)
{
for(j=0;j<=i;j++)
{
System.out.print(" ");
}
for(k=0;k<2*m+1;k++)
{
System.out.print("*");
}
m--;
System.out.println();
50

}
}}
OUTPUT-

















51

PROGRAM-7
Write a program in java to implement method overriding.
import java.util.Scanner;
import java.io.*;
class Methoverriding
{
int x;
Furniture(int a)
{ x= a;
}
void display() {
System.out.println("Super x="+x);
}}
class Table extends Furniture {
int y;
Table(int a,int b) {
super(a);
y=b; }
void display() {
System.out.println("Super x="+x);
System.out.println("sub y="+y);
} }
class Chair extends Furniture {
int z;
Chair(int a,int c) {
super(a);
z=c; }
void display() {
System.out.println("Super x="+x);
System.out.println("sub z="+z);
} }
class OverrideTest {
public static void main(String args[]) {
Table s1=new Table(10,20);
s1.display();
Chair s2=new Chair(10,30);
s2.display();
52

}
}
OUTPUT-













53

PROGRAM-8
Write a program in java to implement multiple inheritance.
interface area
{
final static float pi=3.14F;
float compute(float x, float y);
}
class Rectangle implements area
{
public float compute(float x, float y)
{
return (x*y);
}
}
class Circle implements area
{
public float compute(float x, float y)
{
return (pi* x* x);
}
}
class demo
{
public static void main(String args[])
{
Rectangle r= new Rectangle();
Circle c= new Circle();
area Area;
Area=r;
System.out.println("Area of rectangle :" + Area.compute(10,20));
Area=c;
System.out.println("Area of circle :" + Area.compute(10,0));
}
}
54

OUTPUT


























55

PROGRAM-9
Write a program that has an interface student containing abstract functions-
studentaccept and studentdisplay and three classes undergraduate,
postgraduate and corporate course that implement the student interface and
an admission class where a menu is displayed to the user and depending on
the choice selected information about the particular course and student is
accepted and displayed.

import java.util.*;
import java.io.*;
interface Student
{
public void Studentaccept();
public void Studentdisplay();
}
class UnderGraduate implements Student
{
String name, course;
float percentage;
public void Studentaccept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name:");
name=sc.next();
System.out.println("Enter course:");
course=sc.next();
System.out.println("Enter your 12th percentage:");
percentage=sc.nextFloat();
}
public void Studentdisplay()
{
System.out.println("Name:"+name);
System.out.println("Course:"+course);
System.out.println("12th Percentage:"+percentage);
}
}
class PostGraduate implements Student
56

{
String name, course;
float percentage;
public void Studentaccept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name:");
name=sc.next();
System.out.println("Enter course:");
course=sc.next();
System.out.println("Enter your graduate percentage:");
percentage=sc.nextFloat();
}
public void Studentdisplay()
{
System.out.println("Name:"+name);
System.out.println("Course:"+course);
System.out.println("12th Percentage:"+percentage);
}
}
class CorporateCourse implements Student
{
String name, course;
String exp;
public void Studentaccept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name:");
name=sc.next();
System.out.println("Enter course:");
course=sc.next();
System.out.println("Do you have any experience:");
exp=sc.next();
}
public void Studentdisplay()
{
System.out.println("Name:"+name);
System.out.println("Course:"+course);
System.out.println("Experience:"+exp);
57

}
}
class Admission
{
public static void main(String args[]) throws IOException
{
int ch;
Scanner sc1=new Scanner(System.in);
do
{
System.out.println("MENU");
System.out.println("1-UnderGraduate course \n2- PostGraduate course \n3-Corporate Course
\n4-exit");
System.out.println("Enter your choice:");
ch=sc1.nextInt();
Student sd;
switch(ch)
{
case 1 :
System.out.println("You choosed Undergraduate");
UnderGraduate ug=new UnderGraduate();
sd=ug;
sd.Studentaccept();
System.out.println("Your details is:");
sd.Studentdisplay();
break;
case 2 :
System.out.println("You choosed Postgraduate");
PostGraduate pg=new PostGraduate();
sd=pg;
sd.Studentaccept();
System.out.println("Your details is:");
sd.Studentdisplay();
break;
case 3 :
System.out.println("You choosed Corporate course");
CorporateCourse cc=new CorporateCourse();
sd=cc;
sd.Studentaccept();
58

System.out.println("Your details is:");
sd.Studentdisplay();
break;
case 4 :
System.exit(1);
default :
System.out.println("Default");
}
}
while(ch!=4);
}
}
OUTPUT-






59

PROGRAM-10
Write a program in java to perform String Handling.

import java.util.Scanner;
import java.io.*;
class Handling
{
public static void main(String args[])
{
int i,j;
String temp=null;
String st[]=new String[5];
String name,age,salary;
String str=new String();
Scanner scr1=new Scanner(System.in);
System.out.println("Enter a string:");
str=scr1.nextLine();
int a= str.length();
System.out.println("Length of string="+a);
System.out.println("");

Scanner scr3=new Scanner(System.in);
System.out.println("Enter user name:");
name=scr3.nextLine();

Scanner scr4=new Scanner(System.in);
System.out.println("Enter age:");
age=scr4.nextLine();

Scanner scr5=new Scanner(System.in);
System.out.println("Enter salary:");
salary=scr5.nextLine();

System.out.println();
System.out.println("Details is:\n");
System.out.println("Name is:"+name);
System.out.println("Age is:"+age);
System.out.println("Salary is:"+salary);
60


String str1=new String();
Scanner scr6=new Scanner(System.in);
System.out.println();
System.out.println("Enter a string1:");
str1=scr6.nextLine();

String str2=new String();
Scanner scr7=new Scanner(System.in);
System.out.println("Enter a string2:");
str2=scr7.nextLine();

boolean b=str1.equalsIgnoreCase(str2);
System.out.println("Equality of String1 and String2 is:"+b);

System.out.println("Enter string:");
for(i=0;i<5;i++)
{
Scanner sc=new Scanner(System.in);
st[i]=sc.nextLine();
}
System.out.println();
System.out.println("String is:");
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
if(st[i].compareTo(st[j])>0)
{
temp=st[i];
st[i]=st[j];
st[j]=temp;
}
}
}
for(i=0;i<5;i++)
{
System.out.println(""+st[i]);
}
61

}
}
OUTPUT-










62

PROGRAM-11
Write a java program to find out whether string entered by user is
palindrome or not.

import java.lang.*;
import java.util.*;
class palindrome {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
String s1=sc.next();
String s2=s1;
StringBuffer sb=new StringBuffer(s2);
sb.reverse();
String s3=sb.toString();
if(s3.equals(s2)) {
System.out.println("palindrom");
}
else {
System.out.println("Not palindrom");
}
}
}
OUTPUT-


63

PROGRAM-12
Write a java program to take your name as input and display the reverse of it.
Also read name of two of your friends and append it to your name and display
the final string.
import java.lang.*;
import java.util.*;
class Reverse {
public static void main(String args[]) {
System.out.println("Enter string:");
Scanner sc =new Scanner(System.in);
String s1=sc.next();
int n=s1.length();
String s2=" ";
for(int i=n-1;i>=0;i--) {
s2=s2 + s1.charAt(i); }
System.out.println("Reverse String is:" + s2);
System.out.println("Enter two friends name:");
String s3= sc.next();
String s4=sc.next();
String s5= s2+" "+s3+" "+s4;
System.out.println("appened list is:" +s5); } }

OUTPUT-


64

PROGRAM-13
Write a java program to perform fuctions of vector.
import java.util.*;
class Vect
{public static void main(String args[])
{Vector v=new Vector(5);int i=v.size();
System.out.println("Size of vector="+i);
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
v.addElement(new Integer(5));
v.addElement(new Integer(6));
v.addElement(new Integer(7));
v.addElement(new Integer(8));
v.addElement(new Integer(9));
v.addElement(new Integer(10));
System.out.println("After adding Current no. of elements:" + v.capacity());
v.addElement(new Integer(54));
System.out.println("After adding Current no. of elements:" + v.capacity());
System.out.println("First element :" + (Integer)v.firstElement());
System.out.println("Last element :" + (Integer)v.lastElement());
Enumeration venum=v.elements();
System.out.println("\n Elements in Vector:");
while(venum.hasMoreElements())
{System.out.println(venum.nextElement() + " ");
}} }
OUTPUT


65

PROGRAM-14
Write a java program to draw human face using applet.
import java.applet.Applet;
import java.awt.*;
public class faceapplet extends Applet
{
public void paint(Graphics g)
{
g.drawOval(40,40,120,150);
g.drawOval(57,75,30,20);
g.drawOval(110,75,30,20);
g.fillOval(68,81,10,10);
g.fillOval(121,81,10,10);
g.drawOval(85,100,30,30);
g.fillArc(60,125,80,40,180,180);
g.drawOval(25,92,15,30);
g.drawOval(160,92,15,30);
}
}

// HTML FILE
<html>
<body>
<applet code="faceapplet.class" width=300 height=300>
</applet>
</body>
</html>


66

PROGRAM-15
Write a program to display the functioning of steps involved in different states
of the applet creation.
import java.applet.*;
import java.awt.*;
public class Angur extends Applet
{string msg="Checking Applet Life Cycle";
public void init()
{setBackground(Color.red);
msg+="Init Called";
}public void start()
{msg+="Start Called";
}public void paint(Graphics g)
{msg+="Paint Called";
g.drawString(msg,50,50);
}public void stop()
{msg+="Stop Called";
}public void destroy() {
msg+="Destroy Called";
} }

//HTML FILE
<html><body><applet code="angur" height=300 width=300></applet></body></html>

OUTPUT-


67

PROGRAM-16
Design a calculator in java which could perform all the functions such as
addition, subtraction, multiplication, division, square root.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.math.*;
public class Calculator extends Applet implements ActionListener
{

Button b_0,b_1,b_2,b_3,b_4,b_5,b_6,b_7,b_8,b_9;
Button b_add,b_sub,b_mul,b_div,b_sqrt,b_equal,b_clr;
TextField display= new TextField(10);
Panel p= new Panel();
Label header=new Label("CALCULATOR");
String msg="";
float num1,num2,res;
int c;
float z;
double k;
public void init()
{
b_0= new Button("0");
b_1= new Button("1");
b_2= new Button("2");
b_3= new Button("3");
b_4= new Button("4");
b_5= new Button("5");
b_6= new Button("6");
b_7= new Button("7");
b_8= new Button("8");
b_9= new Button("9");
b_add= new Button("+");
b_sub= new Button("-");
b_mul= new Button("*");
b_div= new Button("/");
b_equal= new Button("=");
68

b_sqrt= new Button("sqrt");
b_clr=new Button("CLR");
FlowLayout flow = new FlowLayout(FlowLayout.CENTER,10,10);
setLayout(flow);
add(header);
add(display);

GridLayout flow1 = new GridLayout(5,4,10,10);
p.setLayout(flow1);

p.add(b_0);
p.add(b_1);
p.add(b_2);
p.add(b_3);
p.add(b_4);
p.add(b_5);
p.add(b_6);
p.add(b_7);
p.add(b_8);
p.add(b_9);
p.add(b_add);
p.add(b_sub);
p.add(b_mul);
p.add(b_div);
p.add(b_equal);
p.add(b_sqrt);
p.add(b_clr);
add(p);
display.addActionListener(this);
b_0.addActionListener(this);
b_1.addActionListener(this);
b_2.addActionListener(this);
b_3.addActionListener(this);
b_4.addActionListener(this);
b_5.addActionListener(this);
b_6.addActionListener(this);
b_7.addActionListener(this);
b_8.addActionListener(this);
69

b_9.addActionListener(this);
b_add.addActionListener(this);
b_sub.addActionListener(this);
b_mul.addActionListener(this);
b_div.addActionListener(this);
b_equal.addActionListener(this);
b_sqrt.addActionListener(this);
b_clr.addActionListener(this);
}
float add(float a, float b) {
z=a+b;
return z;
}
float sub(float a, float b) {
z=a-b;
return z;
}

float mul(float a, float b) {
z=a*b;
return z;
}

float div(float a, float b) {
z=a/b;
return z;
}
public void actionPerformed(ActionEvent e) {

String str= e.getActionCommand();
System.out.println("e.getActionCommand()----"+str);

if (str.equals("0")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("1")) {
msg+=str;
display.setText(msg);
70

}
else if (str.equals("2"))
{
msg+=str;
display.setText(msg);
}
else if (str.equals("3")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("4")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("5")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("6")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("7")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("8")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("9")) {
msg+=str;
display.setText(msg);
}
else if (str.equals("+")) {
num1=Float.valueOf(display.getText()).floatValue();
msg="";
c=1;
71

}
else if (str.equals("-")) {
num1=Float.valueOf(display.getText()).floatValue();
msg="";
c=2;
}
else if (str.equals("*")) {
num1=Float.valueOf(display.getText()).floatValue();
msg="";
c=3;
}
else if (str.equals("/")) {
num1=Float.valueOf(display.getText()).floatValue();
msg="";
c=4;
}
else if (str.equals("sqrt")) {
num1=Float.valueOf(display.getText()).floatValue();
k=Math.sqrt(num1);
display.setText(""+k);
msg="";
}
else if (str.equals("=")) {
num2=Float.valueOf(display.getText()).floatValue();
switch (c) {
case 1:
res=add(num1,num2);
break;
case 2:
res=sub(num1,num2);
break;
case 3:
res=mul(num1,num2);
break;
case 4:
res=div(num1,num2);
break;

default: break;
72

}
msg ="";
display.setText(""+res);
}
else if(str.equals("CLR")) {
display.setText(" ");
} } }

//HTML FILE
<html>
<body>
<applet code ="Calculator" width =200 height= 300>
</applet>
</body>
</html>

OUTPUT







73

PROGRAM-17
Write a program in java to draw different figures using different colours. The
choice of the figure and color will depend on the user.
import java.awt.*;
import java.awt.event.*;
public class Fmenu extends Frame implements ActionListener {
String msg1,msg2;
MenuBar mb;
Menu m1,m2;
MenuItem item1, item2, item3, item4, item5,item6, item7, item8, item9;
fmenu() {
setSize(400,400);
mb=new MenuBar();
setMenuBar(mb);
m1=new Menu("Figure");
m1.add(item1=new MenuItem("rectangle"));
m1.add(item2=new MenuItem("triangle"));
m1.add(item3=new MenuItem("circle"));
m1.add(item4=new MenuItem("square"));
mb.add(m1);
m2=new Menu("Colors");
m2.add(item5=new MenuItem("magenta"));
m2.add(item6=new MenuItem("yellow"));
m2.add(item7=new MenuItem("green"));
m2.add(item8=new MenuItem("red"));
m2.add(item9=new MenuItem("blue"));
mb.add(m2);
setVisible(true);
item1.addActionListener(this);
item7.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==item1) {
msg1="Rectangle";
}
else if(ae.getSource()==item7) {
msg2="green";
74

}
draw(getGraphics());
}
public void draw(Graphics g)
{
if(msg1.equals("Rectangle") && msg2.equals("green"))
{
g.setColor(Color.green);g.fillRect(10,50,50,60);}
}
public static void main(String args[]) {
fmenu f=new fmenu();
}
}


//html file
<HTML>
<BODY>
<applet code="fmenu" height=300 width=300>
</applet>
</BODY>
</HTML>
OUTPUT-


75





LAB
EXERCISE 3













76

PROGRAM-1
Write a program to depict use of try catch and finally blocks.
import java.util.Scanner;
public class DivideByZero
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int number1;
int number2;
float div;
try{System.out.print( "Enter first integer: " );
number1 = input.nextInt();
System.out.print( "Enter second integer: " );
number2 = input.nextInt();
div = number1 / number2;
System.out.println( "Division is"+div );
}catch(ArithmeticException e)
{System.out.println("Divide by zero error");
}finally
{System.out.println("Finally block executed");
}}}
OUTPUT

77

PROGRAM-2
Write a program to catch divide by 0 exception.

import java.util.Scanner;
public class DivideByZero
{
public static void main( String args[] )
{
Scanner input = new Scanner( System.in );
int number1;
int number2;
float div;
try{System.out.print( "Enter first integer: " );
number1 = input.nextInt();
System.out.print( "Enter second integer: " );
number2 = input.nextInt();
div = number1 / number2;
System.out.println( "Division is"+div );
}catch(ArithmeticException e)
{System.out.println("Divide by zero error");}}}

OUTPUT

78

PROGRAM- 3
Write a program to depict nested try catch block.
class NestedTryCatch
{
public static void main(String args[])
{
try{
int a = args.length;
int b=42/a;
System.out.println("a="+a);
try{
if(a==1)
a=a/(a-a);
if(a==2){
int c[]={1};
c[42]=99;}}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index out-of-bounds:"+e);
}
}catch(ArithmeticException e){
System.out.println("Divide by 0:"+e);
}}}

OUTPUT


79

PROGRAM-4
Take two numbers minimum and maximum numbers as input from user.
Write a program to define and throw InvalidRange Exception if the
maximum number is greater than maximum number.
import java.util.Scanner;
import java.lang.Exception;
class InvalidRangeEx extends Exception{
InvalidRangeEx(String message){super (message);}}
public class InvalidRange{
public static void main( String args[] ) throws InvalidRangeEx{Scanner input = new Scanner(
System.in );
int number1;int number2;int sum;
try{System.out.print( "Enter first integer: " );
number1 = input.nextInt();
System.out.print( "Enter second integer: " );
number2 = input.nextInt();
sum = number1 + number2;
System.out.printf( "Sum is %d\n", sum );
if(number1>number2){
throw new InvalidRangeEx("InvalidRange Exception caught!!!");}}
catch(InvalidRangeEx e){
e.printStackTrace();}}}
OUTPUT


80

PROGRAM-5
Write a program that creates three Threads from the Main class and
suspends their execution in sequential order i.e. when one is executing, the
others are in the Sleeping mode, count the no of active threads at this point of
time and the Program terminates when all the threads have completed their
execution and returned the control to the Main Thread.
class NewThread implements Runnable {
String name;
Thread t;
boolean suspendFlag;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
suspendFlag = false;
t.start(); // Start the thread
}

public void run() {
try {
for(int i = 15; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(200);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
81

synchronized void myresume() {
suspendFlag = false;
notify();
}
}

class SuspendResume {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
try {
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
ob2.mysuspend();
System.out.println("Suspending thread Two");
Thread.sleep(1000);
ob2.myresume();
System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}



82

OUTPUT





83

PROGRAM-6
Write a Sample Java Program depicting the use of wait, notify and
synchronized methods of multithreading.
class Methods implements Runnable
{
Thread t;
String name;
public Methods(String n)
{
name = n;
System.out.println(name +" Thread started");
t = new Thread(this);
t.start();
}
public void run()
{
try
{
for (int i = 0; i < 50; i++)
{
System.out.print(i+" ");
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println(name +" Thread Exited");

}
}
public class ThreadMethods
{
public static void main(String args[])
84

{
System.out.println("Main Thread started" );
Methods obj1 = new Methods ("one");
Methods obj2 = new Methods ("Two");
System.out.println("Thread one is alive: " + obj1.t.isAlive());
System.out.println("Thread Two is alive: " + obj2.t.isAlive());
try
{
Thread.sleep(1000);
System.out.println("Suspending thread one");
obj1.t.suspend();
Thread.sleep(1000);
System.out.println("resuming thread one");
obj1.t.resume();
Thread.sleep(1000);
System.out.println("Suspending thread two");
obj2.t.suspend();
Thread.sleep(1000);
System.out.println("resuming thread two");
obj2.t.resume();
}catch (InterruptedException e)
{e.printStackTrace();
}
try
{
obj1.t.join();
obj2.t.join();
}
catch (InterruptedException e)
{
e.printStackTrace();}
System.out.println("Thread one is alive: " + obj1.t.isAlive());
System.out.println("Thread Two is alive: " + obj2.t.isAlive());
System.out.println("Main Thread Exited");
}
}



85





LAB
EXERCISE 4












86

PROGRAM-1
Write a program to implement TCP Client server architecture Socket and
ServerSocketclasses using unicast.
import java.net.*;
import java.io.*;
class tcpip_server
{
public static void main(String args[]) throws IOException
{
ServerSocket n1=null;
try
{
n1=new ServerSocket(2591);
}
catch(IOException e)
{
System.err.println("Port 98 could not be found");
System.exit(1);
}

Socket c=null;
try
{
c=n1.accept();
System.out.println("Connection from "+c);
}
catch(IOException e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter out=new PrintWriter(c.getOutputStream(),true);
BufferedReader in=new BufferedReader(new InputStreamReader(c.getInputStream()));
String n;
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Ready to type now");
while((n=sin.readLine())!=null)
87

{
out.println(n);
}
out.close();
c.close();
n1.close();
}
}

import java.net.*;
import java.io.*;
class tcpip_client
{
public static void main(String args[]) throws IOException
{
Socket s=null; BufferedReader b=null;
try
{
s=new Socket(InetAddress.getLocalHost(),98);
b=new BufferedReader(new InputStreamReader(s.getInputStream()));
}
catch(UnknownHostException u)
{
System.err.println("I don't know host");
System.exit(0);
}
String inp;
while((inp=b.readLine())!=null)
{
System.out.println(inp);
}
b.close();
s.close();
}
}



88

PROGRAM-2
Write a program to implement UDP client server architecture program.
import java .net.*;
import java .io.*;
class Server
{
public static void main(String args[]) throws IOException
{
byte b[]=new byte[1024];
DatagramSocket ds=new DatagramSocket(5001);
DatagramPacket dp=new DatagramPacket(b,1024);
System.out.println("receiving");
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
System.out.println("Received File"+str);

FileReader fr=new FileReader(str);
BufferedReader br1=new BufferedReader(fr);
while((str=br1.readLine())!=null)
{
b=str.getBytes();
ds.send(new DatagramPacket(b,b.length,InetAddress.getLocalHost(),5000));
}
ds.close();
}
}
import java .net.*;
import java .io.*;
class Client
{
public static void main(String args[]) throws IOException
{
byte b[]=new byte[1024];
DatagramSocket ds=new DatagramSocket(5000);
DatagramPacket dp=new DatagramPacket(b,1024);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter file name n");
String str1;
89

str1=dis.readLine();
b=str1.getBytes();
ds.send(new DatagramPacket(b,b.length,InetAddress.getLocalHost(),5001));
System.out.println("Contents of file:" +str1+"n");

while(str1!=null)
{
ds.receive(dp);
str1=new String(dp.getData(),0,dp.getLength());
System.out.println(str1);

}
ds.close();
} }
OUTPUT-

Вам также может понравиться