0% found this document useful (0 votes)
60 views19 pages

102 Avani Practical Ass3

This document contains an assignment submitted by Avani Joshi (Roll No: 102) that includes 10 programming problems demonstrating various concepts in Java including exception handling, multithreading, synchronization, and user-defined exceptions. The problems cover using try, catch, throw, throws and finally keywords, ensuring finally blocks execute, creating custom exceptions, displaying the time using threads, accepting user input, and demonstrating parallel thread execution and synchronization between threads using shared resources.

Uploaded by

p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views19 pages

102 Avani Practical Ass3

This document contains an assignment submitted by Avani Joshi (Roll No: 102) that includes 10 programming problems demonstrating various concepts in Java including exception handling, multithreading, synchronization, and user-defined exceptions. The problems cover using try, catch, throw, throws and finally keywords, ensuring finally blocks execute, creating custom exceptions, displaying the time using threads, accepting user input, and demonstrating parallel thread execution and synchronization between threads using shared resources.

Uploaded by

p
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

ASSIGNMENT-3

1. Write a program which show example of Exception handling in which all keywords try,
catch, finally, throw and throws are used.

class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch (IllegalAccessException e)
{
System.out.println("caught in main.");
}
finally
{
System.out.println("this is finally block");
}
}
}

2. Write a program which show finally block is called after try/catch block.

class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
finally

1
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

{
System.out.println("this is finally block");
}
try
{
fun();
}
catch (IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}

3. Write a program which show finally block is called before function return.

class FinallyDemo
{
public static int myMethod()
{
try
{
return 0;
}
finally
{
System.out.println("Inside Finally block");
}
}
public static void main(String args[])
{
System.out.println(FinallyDemo.myMethod());
}
}

4. Create your own User defined exception GreaterTenException if value is given greater
than 10.

import java.io.*;

class GreaterTenException extends RuntimeException

2
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

{
private int detail;
GreaterTenException(int a)
{
detail = a;
}
public String toString()
{
return "GreaterTenException["+detail+"]";
}
}
class Demo
{
static void takeSmallerTen(int a)
{
if(a<10)
System.out.println(a);
else
throw new GreaterTenException(a);
}
public static void main(String args[])
{
int a=0;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.print("Enter value (value<10):");
a = Integer.parseInt(br.readLine());
takeSmallerTen(a);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

5. Create your own User defined exception InvalidCharException if any one of the char
@,*,? is present in given string.

3
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

class GFG
{
public static void main (String[] args)
{
// array of size 4.
int[] arr = new int[4];

try
{
int i = arr[4];
// this statement will never execute
// as exception is raised by above statement
System.out.println("Inside try block");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Exception caught in catch block");
}
finally
{
System.out.println("finally block executed");
}

// rest program will be executed


System.out.println("Outside try-catch-finally clause");
}
}

6. Create java application which display clock. Display time using thread concept.

import java.applet.*;
import java.awt.*;
import java.util.*;
import java.text.*;

class digitalclock extends Applet implements Runnable


{
Thread t1 = null;
int hours = 0, minutes = 0, seconds = 0;
String time = "";

4
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

public void init()


{
setBackground( Color.green);
}
public void start()
{
t1 = new Thread( this );
t1.start();
}
public void run()
{
try
{
while (true)
{
Calendar cal = Calendar.getInstance();
hours = cal.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = cal.get( Calendar.MINUTE );
seconds = cal.get( Calendar.SECOND );
SimpleDateFormat formatter = new
SimpleDateFormat("hh:mm:ss");
Date d = cal.getTime();
time = formatter.format( d );
repaint();
t1.sleep( 1000 );
}
}
catch (Exception e)
{
}
}
public void paint( Graphics g )
{
g.setColor( Color.blue );
g.drawString( time, 50, 50 );
}
}

7. Write a program to accept 10 names from the user and print all the names which start
from B with interval of 2 sec.

5
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

import java.util.Scanner;

public class MultipleStringInputExample1


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the number of strings you want to enter: ");
String[] string = new String [sc.nextInt()];
sc.nextLine();
for (int i = 0; i < string.length; i++)
{
string[i] = sc.nextLine();
}
System.out.println("\nYou have entered: ");
for(String str: string)
{
System.out.println(str);
}

}
}

8. Write a program which show threads are working simultaneously (parallel) in


multithreading concept.

class multithreading extends Thread


{
public void run()
{
System.out.println("task one");
}
public static void main(String args[])
{
multitheading t1=new multitheading();
multitheading t2=new multitheading();
multitheading t3=new multitheading();
t1.start();
t2.start();
t3.start();

6
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

}
}

9. Write a program which show synchronization concept using synchronized method


between two Threads. Take one resource object and use its methods to display [ ]. Give 1
sec interval between “*“ and “+” in display method. ( output: * +* + )

class MyResource
{
synchronized void useRes()
{
System.out.print("[");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
System.out.print("]");
}
}
class MyThread implements Runnable
{
Thread t;
MyResource res;
MyThread(MyResource r)
{
res = r;
t = new Thread(this);
t.start();
}
public void run()
{
res.useRes();
}
}
class Demo
{
public static void main(String args[])
{

7
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

MyResource ob = new MyResource();


MyThread t1 = new MyThread(ob);
MyThread t2 = new MyThread(ob);
}
}

10. Write a program which take one resource object and use its display method to display
0 to 5 for One Thread and same method display 10 to 15 for other thread. Use
synchronization concept by using synchronized block on resource object and called its
disp(int n) method in it. (output : 0 1 2 3 4 5 10 11 12 13 14 15 )

class Table
{
synchronized void disp(int n, int m)
{
for(;n<=m;n++)
{
System.out.println(n);
try
{
Thread.sleep(200);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.disp(0, 5);
}
}

8
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.disp(10, 15);
}
}
class TestSynchronization1
{
public static void main(String args[])
{
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

11. Write a program which show deadlock in the concept of synchronization in java.

class Res1
{
synchronized void task1(Res2 r2)
{
System.out.print("[");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
r2.fun2();
System.out.print("]");
}

9
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

synchronized void task2()


{
System.out.println("tast2 of Res1");
}
}
class Res2
{
synchronized void fun1(Res1 r1)
{
System.out.print("(");
Try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
r1.task2();
System.out.print(")");
}
synchronized void fun2()
{
System.out.println("fun2 of Res2");
}
}
class MyThread implements Runnable
{
Thread t;
Res1 re1;
Res2 re2;
MyThread(Res1 r1, Res2 r2)
{
re1 = r1; re2 = r2;
t = new Thread(this);
t.start();
}
public void run()
{
if(t.getName().equals("Thread-0"))
re1.task1(re2);
else

10
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

re2.fun1(re1);
}
}
class Demo
{
public static void main(String args[])
{
Res1 ob1 = new Res1();
Res2 ob2 = new Res2();
MyThread t1 = new MyThread(ob1,ob2);
MyThread t2 = new MyThread(ob1,ob2);
}
}

12. Write a program which show inter-thread communication.

class MyResource
{
int n;
boolean valueSet = false;
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(Exception e)
{
}
this.n = n;GUAGE
valueSet = true;
System.out.println("Put: " + n);
notify();
}
synchronized void get()
{
if(!valueSet)
try
{
wait();

11
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

}
catch(Exception e)
{
}
System.out.println("Got: " + n);
valueSet = false;
notify();
}
}
class Producer implements Runnable
{
MyResource res;
Thread t;
Producer(MyResource r)
{
res = r;
t = new Thread(this, "Producer");
t.start();
}
public void run()
{
for(int i=0;i<3;i++)
{
res.put(i*2);
}
}
}
class Consumer implements Runnable
{
MyResource res;
Thread t;
Consumer(MyResource r)
{
res = r;
t = new Thread(this, "Consumer");
t.start();
}
public void run()
{
for(int i=0;i<3;i++)
{

12
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

res.get();
}
}
}
class PCFixed
{
public static void main(String args[])
{
MyResource ob = new MyResource();
new Producer(ob);
new Consumer(ob);
}
}

13. Write a program which show use of join and isAlive methods in multithreading system.

class MyThread implements Runnable


{
Thread t;
MyThread(String tnam)
{
t = new Thread(this,tnam);
t.start();
}
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(t.getName()+":"+i);
}
}
}
class Demo
{
public static void main(String args[])
{
System.out.println("main Start");
MyThread t1 = new MyThread("c1");
MyThread t2 = new MyThread("c2");
System.out.println("c1 isAlive :" + t1.t.isAlive());
System.out.println("c2 isALive :" + t2.t.isAlive());

13
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

try
{
t1.t.join();
t2.t.join();
}
catch(InterruptedException e)
{
System.out.println(“Error caught”);
}
System.out.println("c1 isAlive :" + t1.t.isAlive());
System.out.println("c2 isALive :" + t2.t.isAlive());
System.out.println("main exit");
}
}

14. create an applet program which display rotated text of your name at one place.

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

public class appletRotateword extends Applet


{
string msg = "ALIS";
char ch;
public void init()
{
Font f = new Font("Arial",Font.BOLD,30);
setFont(f);
}
public void paint( Graphics g )
{
g.setcolor(color.red);
g.drawstring(msg,30,30);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg=msg+ch;
try
{
Thread.sleep(1000);
}
catch(execption e)

14
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

{
}
repaint();
}
}

15. create an applet program to display your name which move in window left to right.

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

public class displayname extends Applet implements Runnable


{
private String display;
private int x, y, flag;
Thread t;
public void init()
{
display = "alis kheni";
x = 100;
y = 100;
flag = 1;
t = new Thread(this, "MyThread");
t.start();
}
public void update()
{
x = x + 10 * flag;
if (x > 300)
flag = -1;
if (x < 100)
flag = 1;
}
public void run()
{
while (true)
{
repaint();
update();
try
{

15
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

Thread.sleep(1000);
}
catch (InterruptedException ie)
{
System.out.println(ie);
}
}
}
public void paint(Graphics g)
{
g.drawString(display, x, y);
}
}

16. create an applet program which take input from parameters through param tag for
EMP class and Display name, age, salary, city of employee.

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

public class MyApplet extends Applet


{
String name;
String age;
String city;
String salary;
public void init()
{
name = getParameter("name");
age = getParameter("age");
city= getParameter("city");
salary=getParameter("salary");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + name, 20, 20);
g.drawString("Age is: " + age, 20, 40);
g.drawString("City is: "+ city, 20, 40);
g.drawString("Salary is: "+ salary, 20, 40);
}
}

16
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

17. create an applet program which display triangle having circle. Circle have to touch with
all edges of triangle. Also write your name between circle.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class CircleInsideTriangle extends Applet


{
public void paint(Graphics g)
{
int xPoints[] = {120, 220, 30};
int yPoints[] = {30, 220, 220};
g.setColor(Color.YELLOW);
g.fillPolygon(xPoints, yPoints, 3);
g.setColor(Color.BLUE);
g.fillOval(90, 120, 70, 70);
g.drawString("alis",140,150);
}
}

18. Write an applet program which show Digital Clock.

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

public class appletDigitalClock extends Applet


{
string timestring;
public void init()
{
Font f = new Font("Arial",Font.BOLD,30);
setFont(f);
}
public void paint( Graphics g )
{
timestring=new date.to string().substring(10,19);
g.drawstring(timestring,50,50);
try

17
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

{
Thread.sleep(1000);
}
catch(execption e)
{
}
repaint();
}
}

19. Write an applet program which display image in window.

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

class appletdispimage extends Applet


{
Image picture;
public void init()
{
Font f = new Font("arial",Font.BOLD,30);
setFont(f);
picture = getImage(getDocumentBase(),"android-logo.jpeg");
}
public void paint(Graphics g)
{
g.drawString(""+getDocumentBase(),20,20);
g.drawString(""+getCodeBase(),40,40);
g.drawImage(picture,50,50,this);
}
}

20. Write an applet program which change background color by click on different buttons.

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

public class appletbuttonclick extends Applet implements ActionListener


{

18
SYBCA-DIV-2-JAVA AVANI JOSHI ROLL NO:-102

Button b1,b2;
string s;
public void init()
{
b1=new Button("red");
b2=new Button("yellow");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionperfromed(ActionEvent e)
{
s=e.getActionCommand();
if(s=="red")
{
setForeground(color.red);
}
if(s=="yellow")
{
setForeground(color.yellow);
}
}
public void paint(Graphics g)
{
g.fillOval(50,50,70,70);
}
}

19

You might also like