[go: up one dir, main page]

0% found this document useful (0 votes)
3 views12 pages

JAva

An exception is an unexpected event during program execution that disrupts normal flow, and can be handled using keywords like try, except, finally, raise, and catch. Thread synchronization ensures that only one thread accesses a shared resource at a time, using monitors and synchronized methods or statements. Applets are small Java programs running in web browsers with a defined lifecycle including methods like init(), start(), stop(), and destroy(), allowing for interactive content.
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)
3 views12 pages

JAva

An exception is an unexpected event during program execution that disrupts normal flow, and can be handled using keywords like try, except, finally, raise, and catch. Thread synchronization ensures that only one thread accesses a shared resource at a time, using monitors and synchronized methods or statements. Applets are small Java programs running in web browsers with a defined lifecycle including methods like init(), start(), stop(), and destroy(), allowing for interactive content.
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/ 12

1.What is Exception? what are the keywords to handle exception? Explain with example?

Ans: An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run
time that disrupts the normal flow of the program’s instructions.

EXCEPTION HANDLING

 If we want the program to continue with the execution of the remaining code, then we should try to catch the
exception object thrown by the error condition and then display an appropriate message for taking corrective
actions by using below keywords. This task is known as Exception handling.

Types:

1. try: This keyword is used to start a block of code that might raise an exception.
2. except: This keyword is used to catch and handle exceptions that occur within the
corresponding try block.
3. finally: This keyword is used to define a block of code that will always be executed,
regardless of whether an exception occurred in the try block or not.
4. raise: This keyword is used to manually raise exceptions in Python.
5. catch: In some languages like Java, this is used instead of except to catch exceptions.

Try: Syntax

try { statements; }, catch(Exception class ref) { Statements; }, finally { Statements; }

class Ex
{
public static void main(String args[])
{
try
{
System.out.println("open
the files");int n=args.length;
System.out.println("n= "+n);
int a=45/n;
System.out.println("
a= "+a);
}
catch(ArithmeticException ae)
{
//display the exception details
System.out.println(ae);
System.out.println("please pass
data whilerunning this program");
}
finally
{
//close the files
System.out.println("clos
e files");
}
}
}
O/P: F:\JAVA>javac
exception1.java
F:\JAVA>java Ex
n=0
java.lang.ArithmeticException: / by
zero please pass data while running
this programclose files

2.(a).Explain Thread Synchronization with example?

A monitor (semaphore) is used to synchronize access to a shared resource. A


region of code, representing a shared resource, can be associated with a monitor.
Threads gain access to a shared resource by first acquiring the monitor associated
with the resource. At any given time, no more than one thread can own the monitor
and thereby have access to the shared resource. A monitor thus implements mutually
exclusive locking mechanism.

The monitor mechanism enforces the following rules of synchronization:


a) No other thread can enter a monitor if a thread has already acquired the monitor.
Threads wishing to acquire the monitor will wait for the monitor to become available.

b) When a thread exists a monitor, awaiting thread is given the monitor, and can
proceed to access the shared resource associated with this monitor.

Thread synchronization is necessary to access the shared resource by only


one thread at a time, is achieved by the concept of synchronization in multi
threading.

You can synchronize your code in either of two ways.


1) By using synchronized methods.
By using the synchronized statementsUsing synchronized methods :

Synchronization is easy in java, because all objects have their own implicit
monitor associated with them. To enter an objects monitor, just call a method that
has been modified with the synchronized keyword. While a thread is inside a
synchronized method, all other threads that try to call it on the same instance have
to wait. To exit the monitor and relinquish control of the object to the next waiting
thread, the owner of the monitor simply returns from the synchronized method.

class Callme
{

synchronized void call(String msg)


{

System.out.print(“[“+ms
g); try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{

System.out.println(“Interrupted”);
}

System.out.println(“]”);
}
}
class SyncEx implements Runnable
{

String
msg;
Callme
obj;
Thread t;
SyncEx (Callme ob, String s)
{

Obj=o
b;
msg=s
;
t=new
Thread(this);
t.start();
}
public void run( )
{
obj.call(msg);
}
public static void main(String args[ ])
{
Callme ob =new Callme();
SyncEx ob1=new SyncEx (ob, “Hello”);
SyncEx ob2=new SyncEx (ob,
“Synchronized”); SyncEx ob3=new
SyncEx (ob, “World”);
tr
y
{
ob1.t.join();
ob2.t.join();
ob3.t.join();

catch(InterruptedException e)
{

System.out.println(“Interrupted”);
} }

}
Output :
[Hello]
[Synchr
onized]
[World]
In the above example program if the call( ) method is not
synchronized we can get the mixed output as follows.
[hello[synchronized[world]
]

Using the synchronized statement:

The general form of synchronized

statement is

snchronized(object){

//statements to be synchronized
}

Here, Object is a reference to the object being synchronized. A


synchronized block ensures that a call to a method that is a member of
object occurs only after the current thread has successfully entered
object’s monitor.

public void run( )


{

snchronized(obj)
{

obj.call(msg);
}
}
(b).Explain keyword throws with example?

 This keyword is used to pass exceptions to the


next level instead of handling it in a method. This
keyword is associated with method declaration.
For a method we can associate any number of
exceptions with throws clause. It is associated
with a method declaration means the method has
doubtful code but not handled it. It is the
responsibility of the calling method to handle the
exceptions.

 Syntax:
Return type mehod() throws exception1, exception2, exception3
{
//body of the method
}
Even if the programmer is not handling runtime exceptions, the java
compiler will not give any error related to runtime exceptions. But
the rule is that the programmer should handle checked exceptions.
Incase the programmer does not want to handle the checked
exceptions; he should throw them out using throws clause.
Otherwise, there will be anerror flagged by java compiler
import
java.io.*;
class Sample
{
p
ri
v
a
t
e
S
t
ri
n
g
n
a
m
e
;
v
o
i
d
a
c
c
e
p
t
()
{
BufferedReader
br=new
BufferedReader(new
InputStreamReader(S
ystem.in));
System.out.println("e
nter name: ");
name=br.readLine();
}
void display()
{
System.out.println("Name: "+name);
}
}
class Ex1
{
public static void main(String args[])
{
Samp
le
s=ne
w
Samp
le();
s.acc
ept();
s.display();
}
}
O/P: F:\JAVA>javac
throws.java
throws.java:11: error:
unreported exception
IOException; must be
caught or declared to be
thrown
name=br.readLine();
^

1 error
3.Explain Flow and border layout with example?

Flow layout and border layout are two different layout managers used in graphical user interface
(GUI) development, particularly in Java Swing.
1. Flow Layout:
 Flow layout is the default layout manager for many GUI components in Java
Swing.
 In a flow layout, components are laid out from left to right, and when the row is
filled, they continue on the next row.
 Components are added one after another, without regard for any specific
alignment or arrangement.
 It's often used for simple GUIs where you want components to be arranged in a
natural order as they're added.
 To use flow layout, you can either specify it explicitly when adding components to
a container or rely on its default behavior.
2. Border Layout:
 Border layout is another layout manager in Java Swing that divides the container
into five regions: north, south, east, west, and center.
 Components are added to one of these regions and are resized to fill the
available space in that region.
 The "center" region takes up the remaining space in the container after the other
regions have been filled.
 Border layout is useful for creating more structured GUIs where you want certain
components to occupy specific areas of the container, such as having a menu bar
at the top (north), a status bar at the bottom (south), and main content in the
center.
 You can explicitly specify the region when adding components to a container
using border layout.

import javax.swing.*;
import java.awt.*;
public class LayoutExample extends JFrame {
public LayoutExample() {
setTitle("Layout Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Flow layout example


JPanel flowPanel = new JPanel(new FlowLayout());
flowPanel.add(new JButton("Button 1"));
flowPanel.add(new JButton("Button 2"));
flowPanel.add(new JButton("Button 3"));

// Border layout example


JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.add(new JButton("North Button"),
BorderLayout.NORTH);
borderPanel.add(new JButton("South Button"),
BorderLayout.SOUTH);
borderPanel.add(new JButton("East Button"),
BorderLayout.EAST);
borderPanel.add(new JButton("West Button"),
BorderLayout.WEST);
borderPanel.add(new JButton("Center Button"),
BorderLayout.CENTER);

// Adding panels to the frame


getContentPane().setLayout(new GridLayout(2, 1)); // GridLayout
for arranging panels vertically
getContentPane().add(flowPanel);
getContentPane().add(borderPanel);

pack();
setLocationRelativeTo(null); // Center the frame
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
new LayoutExample().setVisible(true);
});
}
}

4.Define applet? Explain Applet life cycle with example?

An applet is a small Java program that runs within a web browser. Applets are
typically embedded in web pages and provide interactive and dynamic content to
users. They were popular in the early days of the internet for creating animations,
games, simulations, and other interactive content.

Key characteristics of applets include:

1. Platform Independence: Like all Java programs, applets are platform-


independent, meaning they can run on any system that has a Java Virtual
Machine (JVM) installed, regardless of the underlying operating system.
2. Security: Applets are subject to strict security restrictions imposed by the
browser environment. They run within a sandbox that limits their access to
system resources and prevents them from performing potentially harmful
actions such as accessing the file system or executing arbitrary commands.
3. GUI Components: Applets can create graphical user interfaces (GUIs) using
Java's Abstract Window Toolkit (AWT) or Swing library. This allows them to
display buttons, text fields, images, and other GUI elements for user
interaction.
4. Lifecycle: Applets have a defined lifecycle consisting of methods such as
init() , start() , stop() , and destroy(), which are called at different stages of the
applet's execution. These methods allow developers to perform initialization,
start animations, handle user interactions, and clean up resources.
5. Embedded in Web Pages: Applets are embedded in HTML web pages using
the <applet> or <object> tag. The browser loads the applet's bytecode (.class
files) and executes it within the webpage, allowing users to interact with the
applet's content.
6. Initialization:
1. init() : This method is called when the applet is first loaded into
memory. It is used for initializing the applet, such as setting up
variables, loading resources, and preparing the applet for display. This
method is called only once during the lifetime of the applet.
7. Starting:
1. start() : After initialization, the start() method is called. It is invoked
every time the user visits a webpage containing the applet or when the
user returns to the webpage from another webpage. This method is
typically used to start any actions or animations within the applet.
8. Running:
1. The applet remains in the running state as long as the webpage
containing it is active and visible in the browser. During this time, user
interactions and animations take place within the applet.
9. Stopping:
1. stop() : When the user navigates away from the webpage containing the
applet or minimizes the browser window, the stop() method is called.
This method is used to suspend any ongoing activities within the
applet, such as animations or background tasks.
10. Destroying:
1. destroy() : When the browser unloads the webpage containing the
applet, or when the user closes the browser, the destroy() method is
called. This method is used to perform any cleanup operations, release
resources, and free up memory used by the applet. It is called only
once during the lifetime of the applet.
Program:

import java.applet.Applet;

import java.awt.*;

public class MyApplet extends Applet {

@Override

public void init() {

// Initialization code

@Override

public void start() {

// Start code

@Override

public void stop() {

// Stop code

}
@Override

public void destroy() {

// Cleanup code

@Override

public void paint(Graphics g) {

// Rendering code

You might also like