Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Assignment-1

Que. 1 Write a program in java converts Celsius to Fahrenheit


temp ?
Program:-
public class q1 {
public static void main(String args[]){
double cel =10.0;
double fhe =0.0;
fhe =(cel*1.8)+13;
System.out.println("Value of temperature in fahrenheit:"+fhe);
}
}
Output:-

Que.2 write a program in java finds diameter circum area of a


circle ?
Program:-
import java.util.Scanner;
public class q2 {
public static void main(String[] args) {
double radius, diameter, circumference, area;
Scanner op = new Scanner(System.in);
System.out.println("Enter,radius of circle:");
radius = op.nextDouble();
diameter = 2 * radius;
circumference = 2 * 3.14 * radius;
area = 3.14 * (radius * radius);
System.out.println("Diameter of circle=" + diameter + "units");
System.out.println("circumference of circle =" + circumference
+ "units");
System.out.println("area of circle =" + area + "sq.units"); }}
Output:-

Que.3 write a program in java to find out if a number is prime in


java ?

Program:-
public class q3 {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = true;
break;
}
}
if (!flag) {
System.out.println(num + " is a prime number");

} else {
System.out.println(num + " is not prime number");
}
}
}
Output:-

Que.4 write a program to check if a number is palindrome in


java?
Program:-

import java.util.Scanner;
public class q4 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("enter a number");
int n = sc.nextInt();
int sum = 0;
int r;
int temp = n;
while (n != 0) {
r = n % 10;
sum = sum * 10 + r;
n = n / 10;
}
if (sum == temp) {
System.out.println("palindrome");
} else {
System.out.println("not palindrome");
}
}
}
Output:-
Que.5 write a program to check if a check is Armstrong number
or not ?
Program:-

import java.util.Scanner;
class Q5
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int n=sc.nextInt();
int sum=0;
int r;
int temp=n;
while(n!=0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(sum==temp)
{
System.out.println("amstrom");
}
else {
System.out.println("non amstrom");
} }}

Q6. Write a program in java to print Fibonacci series up to given


number?
Program:-
import java.util.Scanner;
class Q6
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
int a=0,b=1,c,i=1;
while(i<=n)
{
c=a+b;
System.out.println(a+"\t");
a=b;
b=c;
i++;
} }}

Q7.Write a java program to calculate factorial of an interer


number?
Program:-
import java.util.Scanner;
class Q7
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a nubmer");
int n=sc.nextInt();
int f=1;
while(n>1)
{
f=f*n;
n--;
}
System.out.println(f);
}}

Q8. Print the following structure in java


*
***
*****
***
*
Program:-
class Q9
{
public static void main(String[] args)
{
for(int i=0;i<3;i++){
for(int j=1;j<=(2*i)+1;j++)
{
System.out.print("*");
}
System.out.println();
}
for(int i=2;i>0;i--){
for(int j=1;j<=(2*i)-1;j++)
{
System.out.print("*");
}
System.out.println();
} }}
Output:-

Q9.How to find if a number is power of 2 or not?


Program:-
import java.util.Scanner;
class Q9
{
public static void main(String agrs[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int n=sc.nextInt();
if (n>0)
{
while(n%2==0)
{
n/=2;
}
if(n==1)
{
System.out.println("no is power of 2");
}
else
{
System.out.println("no is not a power of 2");
}
}
else
{
System.out.println("invalid no");
}}}
Output:-
Q10.Write a java program to sort the given number in ascending
order.
Program:-
class Q10
{
public static void main(String args[])
{
int a[]={50,40,20,10,30,60},i,j,temp;
for(i=0;i<(a.length-1);i++)
{
for(j=(i+1);j<a.length;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}}}
System.out.println("After sorting");
for(int k:a)
{
System.out.println(k);
}}}
Output:-
Assignment 2
Q1 Find out if String has all Unique Characters?
Program:-
import java.util.*;
class A2q1 {
boolean uniqueCharacters(String str){
for (int i = 0; i < str.length(); i++)
for (int j = i + 1; j < str.length(); j++)
if (str.charAt(i) == str.charAt(j))
return false;
return true;
}
public static void main(String args[])
{
A2q1 obj = new A2q1();
String input = "nikesh";
if (obj.uniqueCharacters(input))
System.out.println("The String " + input + " has all unique
characters");
else
System.out.println("The String " + input + " has duplicate
characters");

}
}
Output:-

Q2. How to Count number of words in the String?


Program:-
class A2q2
{
public static void main(String args[])
{
String str="this is a java class";
int ch=0,sp=1;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==' ')
{
sp++;
}
else
{
ch++;
}
}
System.out.println("no of words="+sp);
}}
Output:-

Q3. How to remove all the white-spaces in the String?


Program:-
public class A2q3
{
public static void main(String args[])
{
String str1="Remove white spaces";
str1 = str1.replaceAll("\\s+", "");
System.out.println("String after removing all the white spaces : "
+ str1);
}
}
Output:-
Q5. How to calculate total number of characters in the String?
Program:-
class A2q5
{
public static void main(String args[])
{
String str="this is a java class";
int ch=0,sp=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==' ')
{
sp++;
}
else{
ch++;
}
}
System.out.println("no of character="+ch);
}}
Output:-

Q10. Find the length of the string without using length method?
Program:-
class A2q10
{
public static void main(String args[])throws Exception
{
String str="samplestring";
int i=0;
for(char c:str.toCharArray())
{
i++;
}
System.out.println("Length of the given string:"+i);
}}
Output :-
Q6. How to calculate total no of vowels in a string?
Program:-
class A2q6
{
public static void main(String args[])
{
String str="hey this is kamakshi";
int vovel=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='a' ||str.charAt(i)=='e' ||str.charAt(i)=='i' ||
str.charAt(i)=='o'|| str.charAt(i)=='u')
{
vovel++;
}}
System.out.println("No.of vovels="+vovel);
}}
Output:-
Q8. How does substring() method works in java?
class A2q8
{
public static void main(String args[])
{
String str="COMPUTER";
String p=str.substring(3);
System.out.println("Substring starting from index 3: " +p);
}}
Output:-

Q7. String concatenation in java?


Write different ways for String concatenation in java?
Input: “Java” and “Program”
Output: “JavaProgram”
class A2q7
{
public static void main(String args[])
{
String s="java"+"Program";
System.out.println(s);
}}
Output:-

Q9. How to Count occurrences of each character in a String in


java?
import java.util.Scanner;
class A2q9
{
public static void main(String args[])
{
String str;
int i, len;
int counter[] = new int[256];
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a string: ");
str = sc.nextLine();
len = str.length();

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


{
counter[(int) str.charAt(i)]++;
}
//print Frequency of characters
for (i = 0; i < 256; i++)
{
if (counter[i] != 0)
{
System.out.println((char) i + " --> " + counter[i]);
}} } }
Q4. Print all permutations of the String ?
Program:-
Assignment 3
Q1. Shapes with getArea and getValue . reuse this class to
calculate the area and volume of square ,cube and sphere?
Program:-
import java.util.Scanner;
import java.math.*;
abstract class shapes {
public abstract void getArea();

public abstract void getVolume();


}
class Measure extends shapes {
Scanner i = new Scanner(System.in);

public void getArea() {


System.out.println(">>Area<<");
float a;
System.out.print("Enter Side of Square: ");
a = i.nextFloat();
float c = a * a;
System.out.println("Area of Square is: " + c);
double ra;
System.out.print("Enter Radius Of Circle: ");
ra = i.nextDouble();
double p = (Math.PI) * (ra * ra);
System.out.println("Area Of Circle: " + p);
double k;
System.out.print("Enter Side of Cube: ");
k = i.nextDouble();
double j = 6 * (k * k);
System.out.println("Area of Cube: " + j);
double m;
System.out.print("Enter Radius of Sphere: ");
m = i.nextDouble();
double q = 4 * (Math.PI) * (m * m);
System.out.println("Area of Sphere: " + q);
}
public void getVolume() {
System.out.println(">>Volume<<");
float a;
System.out.print("Enter Side of Square: ");
a = i.nextFloat();
float c = a * a * a;
System.out.println("Volume of Square is: " + c);
double ra;
System.out.print("Enter Radius Of Circle: ");
ra = i.nextDouble();
double p = (Math.PI) * (ra * ra * ra);
System.out.println("Volume Of Circle: " + p);
double k;
System.out.print("Enter Side of Cube: ");
k = i.nextDouble();
double j = 6 * (k * k * k);
System.out.println("Volume of Cube: " + j);
double m;
System.out.print("Enter Radius of Sphere: ");
m = i.nextDouble();
double q = 4 * (Math.PI) * (m * m * m);
System.out.println("Volume of Sphere: " + q);
}
}
public class AQ3 {
public static void main(String[] args) {
Measure l = new Measure();
l.getArea();
l.getVolume(); }}
Output:-
Q2. Create an abstract class employee with method getamount()
which display the amount paid to employee. Reuse this class to
claculate the amount to be paid to weeklyemployee and
houremployee according to no. Of hours and total hours for
hourlyemployee and no. Of weeks and total weeks for
weeklyemployee.

Program:-

import java.util.Scanner;

abstract class Employee {


public abstract void getAmount(int i);
}
class weeklyEmployeed extends Employee {
public void getAmount(int i) {
int w;
Scanner q = new Scanner(System.in);
System.out.print("Enter Total Number of Week: ");
w = q.nextInt();
int f = i * w;
System.out.println("Your Total Salary Of Working in Weeks: " +
f);
}
}
class HourlyEmployee extends Employee {
public void getAmount(int u) {
float r;
Scanner t = new Scanner(System.in);
System.out.print("Enter total Number of Hour: ");
r = t.nextFloat();
float g = r * u;
System.out.println("Your Total Salary of Working in Hours: " +
g);
}
}
public class AQ3_2 {
public static void main(String[] args) {
weeklyemployeed p = new weeklyemployeed();
p.getAmount(12000);
HourlyEmployee v = new HourlyEmployee();
v.getAmount(180);
}
}
Output:-

Q3. Create an interface vehicle with method getamount , calculate


the amount to be paid to lnvoice and employee by implementing
interface.
Program:-

interface payable {
void getAmount(int i);
}

class Employe implements payable {


public void getAmount(int i) {
System.out.println("Amount to be paid is: " + i);
}}

public class AQ3_3 {


public static void main(String[] args) {
Employe p = new Employe();
p.getAmount(30000);
}}
Output:-

Q4. Create an interface vehicle with methodgetcolor (),


getnumber(), getconsumption(). Calculate the fuel consumed name
and color for Twowheeler and fourwheeler by implementing
interface vechicle.

Programe :-

import java.util.Scanner;
interface vechicle
{
void getcolor(String h);
void getname(String n);
void getConsumption();
} class TwoWheelear implements vechicle
{ public
void getcolor(String h)
{
System.out.println("Colour of Bike is: " + h);
} public
void getname(String n)
{
System.out.println("Name of Bike is: " + n);
} public
void getConsumption()
{
float liters, km;
Scanner o = new Scanner(System.in);
System.out.print("Enter Kilometer Driven By Driver: ");
km = o.nextFloat();
float fuel = (km/50) ;
System.out.println("Your Fuel Consumption is: " + fuel + " liters");
}
} class FourWheelear implements vechicle
{ public
void getcolor(String h)
{
System.out.println("Colour of Car is: " + h);
} public
void getname(String n) { System.out.println("Name of Car is: " + n); }
public
void getConsumption()
{
float liters, km;
Scanner o = new Scanner(System.in);
System.out.print("Enter Kilometer Driven By Driver: ");
km = o.nextFloat();
float fuel = (km/10);
System.out.println("Your Fuel Consumption is: " + fuel + "
liters");
}
}
public class aq3_4
{
static void main(String[] args)
{ int k;
System.out.print("Enter 1 for Two Wheeler and 2 for Four Wheeler:
");
Scanner p = new Scanner(System.in);
k = p.nextInt();
switch (k)
{ case 1:
TwoWheelear l = new TwoWheelear();
l.getcolor("Black");
l.getcolor("CBR 600 RR");
l.getConsumption();
break;
case 2:
FourWheelear i = new FourWheelear();
i.getcolor("Neon blue");
i.getname("Lamborghini");
i.getConsumption();
break;
}}}

Output :-
Enter 1 for Two Wheeler and 2 for Four Wheeler: 1
Colour of Bike is: Black
Colour of Bike is: CBR 600 RR
Enter Kilometer Driven By Driver: 6
Your Fuel Consumption is: 0.12 liters

Output:2
Enter 1 for Two Wheeler and 2 for Four Wheeler: 2
Colour of Car is: Neon blue
Name of Car is: Lamborghini
Enter Kilometer Driven By Driver: 6
Your Fuel Consumption is: 0.6 liters

Q5. Create an interface fare with method getamount () to get the


amount paid for fare of travelling calculate the fare paid by bus
and train implementing interface fare.
Program :-

interface fare {
void getAmount();
}

class bus implements fare {


public void getAmount() {
int local_rate = 20;
int outofdistrict = 200;
System.out.println("Local Rate in Bus is: " + local_rate);
System.out.println("Going Out of District rate in Bus: " +
outofdistrict);
System.out.println();
}
}

class train implements fare {


public void getAmount() {
int local_rate = 15;
int outofdistrict = 150;

System.out.println("Local Rate in train is: " + local_rate);


System.out.println("Going Out of District rate in train: " +
outofdistrict);
}
}

public class Provide {


public static void main(String[] args) {
bus k = new bus();
k.getAmount();
train i = new train();
i.getAmount();
}}

Output:-

Local Rate in Bus is: 20


Going Out of District rate in Bus: 200

Local Rate in train is: 15


Going Out of District rate in train: 150
Q6. Create interface studentfee with method getamount(), getfirst
name(), getlastname(), getaddress(), gatcontact(). calculate the
amount paid by the hostler and nonhostler student by
implementing interface studenfee.
Program:-

import java.util.Scanner;
interface studentfee {
void getAmount();
void getFirstName();
void getLastName();
void getAddress();
void getContact();
}
class hostler implements studentfee {
Scanner i = new Scanner(System.in);
public void getFirstName() {
String name;
System.out.print("Enter Student First Name: ");
name = i.nextLine();
}
public void getLastName() {
String last;
System.out.print("Enter Student Last Name: ");
last = i.nextLine();
}
public void getAddress() {
String address;
System.out.print("Enter Student Full Address : ");
address = i.nextLine();
}
public void getContact() {
long num;
System.out.print("Enter Student Phone Number: ");
num = i.nextLong();
}
public void getAmount() {
int fee = 75000;
System.out.println("Annual Fees for Hostler Student is: " + fee);
}
}
class nonhostler implements studentfee {
Scanner i = new Scanner(System.in);
public void getFirstName() {
String name;
System.out.print("Enter Student First Name: ");
name = i.nextLine();
}
public void getLastName() {
String last;
System.out.print("Enter Student Last Name: ");
last = i.nextLine();
}
public void getAddress() {
String address;
System.out.print("Enter Student Full Address : ");
address = i.nextLine();
}
public void getContact() {
long num;
System.out.print("Enter Student Number: ");
num = i.nextLong();
}
public void getAmount() {
int fee = 88000;
System.out.println("Annual Fees for Non-Hostler Student is: " +
fee);
}
}

public class Student {


public static void main(String[] args) {
Scanner l = new Scanner(System.in);
int k;
System.out.print("Enter 1 For Hostler Student And 2 for
NonHostler: ");
k = l.nextInt();
switch (k) {
case 1:
System.out.println(" >>Hostler Student<<");
hostler p = new hostler();
p.getFirstName();
p.getLastName();
p.getAddress();
p.getContact();
p.getAmount();
break;
case 2:
System.out.println(" >>Non-Hostler Student<<");
nonhostler e = new nonhostler();
e.getFirstName();
e.getLastName();
e.getAddress();
e.getContact();
e.getAmount();
break;
}}}
Output:-
Output:1
Enter 1 For Hostler Student And 2 for Non-Hostler: 1
>>Hostler Student<<
Enter Student First Name: Hrithik
Enter Student Last Name: Chouriya
Enter Student Full Address : Shankar Nagar Partala
Enter Student Phone Number: 8609685558
Annual Fees for Hostler Student is: 75000

Output:2
Enter 1 For Hostler Student And 2 for Non-Hostler: 2
>>Non-Hostler Student<<
Enter Student First Name: Rohan
Enter Student Last Name: Sharma
Enter Student Full Address : M.p Nagar
Enter Student Number: 9875624159
Annual Fees for Non-Hostler Student is: 88000

Q7. Write a program to create your own package package. should


have more than 2 classes. write a class then uses the package.
Program 1:-

package nikesh;
import java.util.Scanner;
class hrc {
void sum() {
int g, r, t;
Scanner i = new Scanner(System.in);
System.out.print("Enter First Number: ");
r = i.nextInt();
System.out.print("Enter Second Number: ");
t = i.nextInt();
g = r + t;
System.out.println("Sum of " + r + " and " + t + " is: " + g);
}
}

class hrc2 {
void multiply() {
float g, r, t;
Scanner i = new Scanner(System.in);
System.out.print("Enter First Number: ");
r = i.nextFloat();
System.out.print("Enter Second Number: ");
t = i.nextFloat();
g = r * t;
System.out.println("Multiplication of " + r + " and " + t + " is: " +
g);
}
}
Program 2:-

import java.util.Scanner;
import nikesh.hrc;
import nikesh.hrc2;

public class Usepack {


public static void main(String[] args) {
int k;
Scanner i = new Scanner(System.in);
System.out.print("Choose 1 for sum" +
"and Choose 2 for Multiplication: ");
k = i.nextInt();
switch (k) {
case 1:
hrc o = new hrc();
o.sum();
break;

case 2:
hrc2 p = new hrc2();
p.multiply();
break;
}}}

Output:-
Output : 1
Choose 1 for sumand Choose 2 for Multiplication: 1
Enter First Number: 89
Enter Second Number: 56
Sum of 89 and 56 is: 145

Output : 2
Choose 1 for sumand Choose 2 for Multiplication: 2
Enter First Number: 56
Enter Second Number: 48
Multiplication of 56.0 and 48.0 is: 2688.0

Assignment 4

Q1. Exception handling program for division of 2 number then


accept numbers from user.
Program:-

import java.io.IOException;
import java.util.Scanner;

public class Exceptionhand {


public static void main(String[] args) throws IOException {
try {
int t, y, u;
Scanner p = new Scanner(System.in);
System.out.print("Enter First Number: ");
y = p.nextInt();
System.out.print("Enter Second Number: ");
u = p.nextInt();
t = y / u;
System.out.println("Division of " + y + " and " + u + " is: "
+t);
} catch (ArithmeticException e) {
System.out.println("Code Not Run Because: " + e);
} }}

Output:-
Output: 1

Enter First Number: 10


Enter Second Number: 5 Division of 10 and 5
is: 2

Output: 2

Enter First Number: 50


Enter Second Number: 0
Code Not Run Because: java.lang.ArithmeticException: / by
zero
Q2. Exception handling program for sorting values in array of
integer or string that results that into buffer or overflow.
Program:-

import java.util.Scanner;
public class array {
public static void main(String[] args) {
try {
Scanner o = new Scanner(System.in);
int n;
System.out.print("Enter Number Of elements you want to
store: ");
n = o.nextInt();
int arr[] = new int[n];
System.out.print("Enter Elements in Array: ");
for (int i = 0; i < n; i++) {
arr[i] = o.nextInt();
}
System.out.print("You Entered Elements in Array are: ");
for (int e = 0; e < n; e++) {
System.out.print(arr[e]);
}
} catch (ArrayIndexOutOfBoundsException r) {
System.out.println("Exception is: " + r);

}}}

Output:-

Enter Number Of elements you want to store: 5


Enter Elements in Array: 1 2 3 4 5
You Entered Elements in Array are: 12345

Q3. . Exception handling program for calculating eoots of


quadratic equation that accepts coefficients from user.
Program:-

import java.util.Scanner;
class solve {
void question() {
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = input.nextDouble();
System.out.print("Enter the value of b: ");
double b = input.nextDouble();
System.out.print("Enter the value of c: ");
double c = input.nextDouble();
double d = b * b - 4.0 * a * c;
if (d > 0.0) {
double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
} else if (d == 0.0) {
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
} else {
System.out.println("Roots are not real.");
}}}

public class Quadratic {


public static void main(String[] Strings) {
solve i = new solve();
i.question();
}}

Output:-
Output:1
Enter the value of a: 5
Enter the value of b: 56
Enter the value of c: 5
The roots are -0.09000907441763602 and -11.109990925582363

Output:2
Enter the value of a: 5
Enter the value of b: 6
Enter the value of c: 4 Roots are not real.

Q4. Exception handling program for or nullpointerexception -


thrown if the JVM attempts to perform an operation on an object
that points to on data on null.
Program:-

public class Nullexception {


private static void printLength(String str) {
System.out.println(str.length());
}

public static void main(String args[]) {


String myString = null;
printLength(myString);
}
}
Output:-

Exception in thread "main" java.lang.NullPointerException: Cannot


invoke
"String.length()" because "str" is null
at
Nullexception.printLength(Nullexception.java:3)
at Nullexception.main(Nullexception.java:7)

Q5. Exception handling program for numberformatexception for


if a program is after attempting to convert a string to numerical
data type and the string contains in appropriate character(i.e
‘z’or ‘q’).
Program:-

public class stringtoint {


public static void main(String[] args) {
try {
String y = "a";
int x = Integer.parseInt(y);
System.out.println("This Is String: " + y);
System.out.println("This is Converted String to Integer: " + x);
} catch (NumberFormatException e) {
System.out.println("Exception is: " + e);
}}}

Output:-

Exception is: java.lang.NumberFormatException: For input


string: "a"
Assignment 5

Q1. Write a program to change the priority of thread.

Program:-

import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " +
th1.getPriority());
System.out.println("Priority of the thread th2 is : " +
th2.getPriority());
System.out.println("Priority of the thread th2 is : " +
th2.getPriority());
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " +
th1.getPriority());
System.out.println("Priority of the thread th2 is : " +
th2.getPriority());
System.out.println("Priority of the thread th3 is : " +
th3.getPriority());
System.out.println("Currently Executing The Thread : " +
Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPriority());
}}
Output:-

Q2. Write a java program for producer consumer problem (w/o


synchronization)

Program:-

import java.util.LinkedList;
public class AQ5_2 {
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();

Thread t1 = new Thread(new Runnable() {


@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}}});
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}}});

t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}

public static class PC {


LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
while (list.size() == capacity)
wait();
System.out.println("Producer produced-" + value);
list.add(value++);
notify();
Thread.sleep(1000);
}}}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();

System.out.println("Consumer consumed-" + val);


notify();
Thread.sleep(1000);
}} } }}
Output:-
Q3. Create a java for producer consumer problem (with
synchronization).
Program:-

import java.util.concurrent.Semaphore;
class Que {
int item;
static Semaphore Con = new Semaphore(0);
static Semaphore Prod = new Semaphore(1);
void get()
{
try {
Con.acquire();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consumer consumed item: " + item);
Prod.release();
}
void put(int item)
{
try {
Prod.acquire();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item;
System.out.println("Producer produced item: " + item);
Con.release();
}
}
class Producer implements Runnable {
Que q;
Producer(Que q)
{
this.q = q;
new Thread(this, "Producer").start();
}

public void run()


{
for (int i = 0; i < 5; i++)
q.put(i);
}}
class Consumer implements Runnable {
Que q;
Consumer(Que q)
{
this.q = q;
new Thread(this, "Consumer").start();
}

public void run()


{
for (int i = 0; i < 5; i++)
q.get();
}}
class AQ5_3{
public static void main(String args[])
{
Que q = new Que();
new Consumer(q);
new Producer(q);
}}

Output:-
Q4. Create an application of cash withdrawal from the bank
account that have no of users that are operating the accounts
(synchronization).

Program:-

class Bank {
int total = 100;
void withdrawn(String name, int withdrawal)
{
if (total >= withdrawal) {
System.out.println(name + " withdrawn " + withdrawal);

total = total - withdrawal;


System.out.println("Balance after withdrawal: " + total);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
System.out.println(name + " you can not withdraw " +
withdrawal);
System.out.println("your balance is: " + total);
try {
Thread.sleep(1000);
}

catch (InterruptedException e) {

e.printStackTrace();
}
}
}
void deposit(String name, int deposit)
{
System.out.println(name + " deposited " + deposit);
total = total + deposit;
System.out.println("Balance after deposit: " + total);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class AQ5_4 {
public static void main(String[] args)
{
Bank obj = new Bank();
obj.withdrawn("Arnab", 20);
obj.withdrawn("Monodwip", 40);
obj.deposit("Mukta", 35);
obj.withdrawn("Rinkel", 80);
obj.withdrawn("Shubham", 40);
}
}

Output:-
Q5. Create a class called mycurrent that implements runnable
interface.
1) The mycurrentDate class displays the current date time 10
times ,with 100 millisecond interval – use sleep() method for
interval.

Program:-

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class AQ5_5 {
public static void main(String[] args) {
System.out.println("The required packages have been
imported");
System.out.println("A LocalDateTime object has been
defined");
DateTimeFormatter date_time =
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("The current date and time is: "
+date_time.format(now));
}
}
Output:-

2) Create a class called mymain which contains main() method


,in which 3 instances of mycurrentData threads are being run.

Program:-

class Worker extends Thread {


@Override
public void run() {
for (int i = 0; i <= 3; i++) {
System.out.println(Thread.currentThread().getName() +
": " + i);
} }}

public class AQ5_5_2 {


public static void main(String[] args) {
Thread t1 = new Worker();
Thread t2 = new Worker();
Thread t3 = new Worker();
t1.start();
t2.start();
t3.start();
}}

Output:-
Assignment 6

Q1

You might also like