0% found this document useful (0 votes)
20 views11 pages

Java Programs for Exception Handling and Applets

The document provides examples of Java programs demonstrating various concepts: 1. It shows how to create a package called "mypackage" with two classes - Addition and Subtraction. Main method in another class imports and uses these classes. 2. It demonstrates handling of ArithmeticException by dividing a number by zero. 3. It shows use of multiple catch blocks to handle different exceptions. 4. It creates a custom exception class that extends Exception and demonstrates throwing and catching it. 5. It creates two threads by extending Thread class and prints output to demonstrate multithreading.

Uploaded by

Lady Bug
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)
20 views11 pages

Java Programs for Exception Handling and Applets

The document provides examples of Java programs demonstrating various concepts: 1. It shows how to create a package called "mypackage" with two classes - Addition and Subtraction. Main method in another class imports and uses these classes. 2. It demonstrates handling of ArithmeticException by dividing a number by zero. 3. It shows use of multiple catch blocks to handle different exceptions. 4. It creates a custom exception class that extends Exception and demonstrates throwing and catching it. 5. It creates two threads by extending Thread class and prints output to demonstrate multithreading.

Uploaded by

Lady Bug
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

15.

Write a Java program to demonstrate package

Step 1: Create the subdirectory “mypackage”.

Step 2: Create the classes that are to be placed inside mypackage folder.

This class should contain following statement in the beginning of the program.

package mypackage;

Create the class “ [Link] “ inside the subdirectory as follows:

package mypackage;
package mypackage;
public class subtraction
public class addition
{
{
int m,n;
int m,n;
public subtraction(int x,int y)
public addition(int x,int y)
{
{
m=x;
m=x;
n=y;
n=y;
}
}
public void subpkg()
public void addpkg()
{
{
[Link]("subtraction="+(m-n));
[Link]("addition="+(m+n));
}
}
}
}

Step 3: Now package folder is ready. We have to use this package in the main program. So the first
statement in the main program has to be as follows:

import mypackage.*;

Outside the subdirectory create the file “[Link]” as follows:


import mypackage.*;
class packagedemo
{
public static void main(String args[])
{
addition a=new addition(8,9);
[Link]();

subtraction s=new subtraction(8,5);


[Link]();
}
}

16. Write a java program to demonstrate ArithmeticException


class ari
{
public static void main(String args[])
{
int a=15,b=5,c=5,x,y;
try
{
x=a/(b-c);
[Link]("X="+x);
}
catch(ArithmeticException e)
{
[Link]("\nHandling Exception divide by zero exception");
}
y=a/(b+c);
[Link]("Y="+y);
}
}
/*output
C:\bcafy\new list>javac [Link]
C:\bcafy\new list>java ari
Handling Exception divide by zero exception
Y=1
*/
17. Write a java program to demonstrate Multiple Catch Exception

class multiplecatch
{
public static void main(String args[])
{
float div;
int arr[]={6,2};
try
{
div=arr[1]/arr[2];
[Link]("Division ="+div);
}
catch(ArithmeticException e)
{
[Link]([Link]());
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]([Link]());
}
catch(NumberFormatException e)
{
[Link]([Link]());
}
}
}
/* output
C:\bcafy\new list>javac [Link]

C:\bcafy\new list>java multiplecatch


[Link]: 2

*/
18. Write a java program to demonstrate your own exception.
import [Link];
class MyException extends Exception
{
MyException(String msg)
{
super(msg); } }
class ownexception
{
public static void main(String args[])
{
int x=15,y=15;
try{
int z=x/y;
if(z==1)
{
throw new MyException("Division is equal to one");
}
}
catch(MyException e)
{
[Link]("Caught my exception");
[Link]([Link]());
}
}
}
/*
C:\bcafy\new list>javac [Link]
C:\bcafy\new list>java ownexception
Caught my exception
Division is equal to one
*/
19. Write a java program to demonstrate multithreading.

class A extends Thread


{
int i;
public void run()
{
for(i=1;i<=5;i++)
{
[Link]("From Thread A "+i);
}
[Link]("End of A");
}
}
class B extends Thread
{
int j;
public void run()
{
for(j=1;j<=5;j++)
{
[Link]("From Thread B "+j);
}
[Link]("End of B");
}
}
class testthread
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
[Link](Thread.MAX_PRIORITY);
[Link](Thread.MIN_PRIORITY);
[Link]("Thread A");
[Link]();
[Link]("Thread B");
[Link]();
}
}
/*output
C:\bcafy\new list>javac [Link]
C:\bcafy\new list>java testthread
Thread AThread BFrom Thread A 1
From Thread B 1
From Thread A 2
From Thread B 2
From Thread A 3
From Thread A 4
From Thread B 3
From Thread A 5
From Thread B 4
End of A
From Thread B 5
End of B */
20. Write a java program to display addition of two numbers using applet and event
handling
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=300 height=200></applet>*/
public class readapplet extends Applet implements ActionListener
{ Label l1, l2, l3;
int x,y,z;
TextField t1, t2,t3;
Button b1;
public void init()
{
setLayout(new GridLayout(4, 2));
t1 =new TextField(8);
t2 = new TextField(8);
t3 = new TextField(8);
b1=new Button("Calculate");
l1 = new Label("Number 1");
l2 = new Label("Number 2");
l3 = new Label("Result");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);

[Link]("0");
[Link]("0");
[Link]("0");

[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]() == b1)
{
x = [Link]([Link]());
y = [Link]([Link]());
z = x + y;
[Link]([Link](z));
}
}
}
21. Write a java program to display parents information using applet and event
handling

import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=300 height=200></applet>*/
public class printinfo extends Applet implements ActionListener
{
TextField t1, t2;
Button b1,b2;
public void init()
{
t1=new TextField(30);
t2=new TextField(30);
b1=new Button("Mother");
b2=new Button("Father");
add(b1);
add(b2);
add(t1);
add(t2);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b1)
{
[Link]("Mary");
[Link]("Home Minister");
}
if([Link]()==b2)
{
[Link]("John");
[Link]("Chemical Engineer");
}

}}

22. Write a java program to demonstrate ItemListener using applet and event
handling
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="[Link]" width=300 height=300></applet>*/
public class addapp1f extends Applet implements ItemListener
{

String msg;
Checkbox r1,r2;
CheckboxGroup cbg;

public void init()


{
cbg=new CheckboxGroup();
r1=new Checkbox("Male",cbg,false);
r2=new Checkbox("Female",cbg,false);
add(r1);
add(r2);

[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
msg="Gender is:";
msg=msg+[Link]().getLabel();
[Link](msg,50,100);
}
}
[Link] a java program to demonstrate passing parameters to the Applet
import [Link].*;
import [Link].*;
public class helloparam extends Applet
{
String str;
public void init()
{
setBackground([Link]);
str=getParameter("string");
if(str==null)
str="5BCA";
str="hello"+" "+str;
}
public void paint(Graphics g)
{
[Link](str,50,50);
}
}

/*<applet code=[Link] height=300 width=250>


<param name="string" value="BSC"> </applet>*/
[Link] a java program to display image on the Applet

import [Link].*;
import [Link].*;

public class eventimg extends Applet {

Image picture;

public void init() {


picture = getImage(getDocumentBase(),"[Link]");
}

public void paint(Graphics g) {


[Link](picture, 30,30, this);
}

}
/*
<applet code="[Link]" width=250 height=350></applet>
*/

Common questions

Powered by AI

In Source 1, the use of multiple catch blocks allows a Java program to handle different types of exceptions that may be thrown within a try block. Each catch block is designed to catch and handle a specific type of exception, such as ArithmeticException, ArrayIndexOutOfBoundsException, or NumberFormatException. This ensures that the program can provide specific error-handling responses for each type of exception scenario it encounters .

The Java program in Source 1 demonstrates the use of a custom exception class by creating a class "MyException" that extends the "Exception" class. In the program, an integer division operation is performed, and if the result is exactly one, the custom exception is thrown using the "throw" keyword. This demonstrates how developers can create and handle their own exceptions if specific conditions are met .

Multi-threading in Java is implemented by creating classes that extend the Thread class. In Source 1, it demonstrates this by defining classes A and B, each extending Thread and overriding the run method. Each thread outputs numbers sequentially in its run method. The testthread class instantiates these thread objects and starts them using the start method. The example also sets the priority for the threads, showing how threads can be prioritized. This implementation allows both threads to run concurrently, which illustrates multi-threading .

The getParameter method in applet development is used to retrieve parameters passed from the HTML page in which the applet is embedded. In Source 2, the applet 'helloparam' uses getParameter to obtain a string parameter. This allows the applet to dynamically receive and use external input at runtime, passed through the <param> tag in the HTML. The ability to accept parameters enables applets to be more flexible and configurable, adapting their behavior based on the input they receive from the web page .

In Source 2, item selection in Java applets is managed using ItemListener. The applet uses a CheckboxGroup to group checkboxes for an exclusive choice, allowing only one checkbox to be selected at a time, like radio buttons. When a change in selection occurs, the itemStateChanged method is triggered, which updates the applet. The CheckboxGroup ensures only one checkbox within the group is selected at a time, enforcing mutually exclusive choices. This is useful for scenarios where a single selection from multiple options is necessary .

In Source 2, a Java applet handles user interactions through event handling by implementing the ActionListener interface. The applet creates GUI components such as buttons and text fields. For example, the applet named 'readapplet' contains components including TextFields and a Button. The ActionListener is registered with the button, so when an action event (e.g., a button click) occurs, the actionPerformed method is called to handle this event. The method reads input from text fields, performs calculations, and outputs results to another text field, thus managing user interactions dynamically .

Packages in Java offer a way to group related classes together, enabling better modularity and namespace management. Source 1 demonstrates this by creating a package 'mypackage' which contains separate classes for arithmetic operations like addition and subtraction. The advantages include avoiding name conflicts, controlled access with package-private scope, and ease of maintenance. It also simplifies locating and using libraries of related classes by leveraging the import mechanism, thus promoting organized development practices .

In Source 2, Java applets render images by using the getImage method along with the paint method. The applet 'eventimg' initializes by calling getImage, passing the base URL and image file name to load the image. Within the paint method, Graphics object's drawImage is used to draw the loaded image onto the applet's display area. This demonstrates how applets can load and render graphics within their visual interface, allowing for enriched multimedia content in applet-based applications .

Java's event model supports GUI development by decoupling events from their handlers, allowing components to listen for and process events asynchronously. In Source 2, for instance, GUI components like Buttons and Checkboxes are registered with listeners (e.g., ActionListener and ItemListener). When an event occurs, such as a button click or a checkbox state change, the corresponding listener's method (actionPerformed, itemStateChanged) is invoked. This model facilitates responsive GUI applications by enabling developers to define specific actions for events, streamlining interactive software design .

In Source 1, although thread priority can be set using methods like setPriority, the actual execution order and time slices each thread receives are determined by the underlying thread scheduler, which can vary between different JVM implementations and operating systems. Due to this variability, and because the JVM does not guarantee strict priority-based scheduling, the intended effect of setting a thread to MAX_PRIORITY or MIN_PRIORITY may not be observed. This behavior illustrates that thread priority is more of a hint than a rule, which can lead to unexpected results if relied upon for precise control of thread execution order .

You might also like