Você está na página 1de 15

5th QUESTIONS

Two Marks:
1. What is Java Virtual Machine (JVM)?.
Java compiler produces an intermediate code known as bytecode for a machine that does not
exist. This machine is called as Java Virtual Machine and it exits only inside the computer
memory. It is a simulated computer within the computer and does all major functions of a real
computer.

The virtual machine code is not machine specific. The machine specific code (known as machine
code) is generated by the Java interpreter by acting as an intermediary between the virtual
machine and the real machine as show in figure.

2. What is Threading ?

A thread is similar to a program that has a single flow of control.


It has a beginning, a body, and an end, and executes commands sequentially. In fact, all main
programs in our earlier examples can be called single-threaded programs. Every program will
have at least one thread. In other words, Java enables us to use multiple flows of control in
developing programs. Each flow of control may be thought of as a separate tiny program(or
module) known as a thread that runs in parallel.

3. What are Final Variables and Final Methods ?


Whenever we want to prevent a base calss from deriving subclasses ,we can do so by
declaring the base class as “final class” by final keyword. We can also declare variables or
methods as “final”, whenever we want to prevent subclasses from overriding the members of the
super class. Eg:
final int size=100;
final void showstatus() {………….}
4. What is the difference between Error and Exceptions in Java ?
 Error:
Erros are the wrongs that make our programme go wrong. An error may produce an incorrect
output or may terminate the execution of the program abruptly or even may cause the system to
crash. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception:
In Java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime .The exception handling in java is one of the powerful mechanism to handle
the runtime errors so that normal flow of the application can be maintained.

5. Mention any two built in packages in Java .

6. What is Multithreading ?

We can execute several programs simultaneously. This ability is known as multitasking.


In system's terminology, it is called multithreading. Multithreading is a conceptual
programming paradigm where a program {process) is divided into two or more subprograms
(processes), which can be implemented at the same time in parallel.
7. What is Package ?
If we need to use classes from other programs without physically copying them into the program
under development, This can be accomplished in Java by using what is known as Packages, a
concept similar to “Class Libraries” in other languages. Packages of Java’s way of grouping a
variety of classes or interfaces together.

Ten Marks:
1. a) What is threading? Write a Java program for Multithreading.

A thread is similar to a program that has a single flow of control. It has a beginning, a body, and
an end, and executes commands sequentially. In fact, all main programs in our earlier examples
can be called single-threaded programs. Every program will have at least one thread. In other
words, Java enables us to use multiple flows of control in developing programs. Each flow of
control may be thought of as a separate tiny program(or module) known as a thread that runs in
parallel.

Example for multi threading

class ThreadDemo implements Runnable


{
Thread t;
ThreadDemo()
{
t=new Thread(this);
System.out.println("ChildThread:" );
t.start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println("ChildThread:" + i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("ChildThread Interrupted ");
}
System.out.println("Exiting ChildThread");
}
}
class MultipleThread
{
public static void main(String arg[])
{
new ThreadDemo();
try
{
for(int i=5;i>0;i--)
{
System.out.println("MainThread:" + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("MainThread Interrupted");
}
System.out.println("Exiting MainThread ");
}

b) Write a note on Packages.

If we need to use classes from other programs without physically copying them into the program
under development, This can be accomplished in Java by using what is known as Packages, a
concept similar to “Class Libraries” in other languages. Packages of Java’s way of grouping a
variety of classes or interfaces together.
 Packages of Java’s way of grouping a variety of classes or interfaces together.
 By organizing our classes into packages we have following benefits
1. The classes contained in the packages of other programs are easily reused.
2. In packages, classes can be unique compared with classes in other packages. That is, two
classes in two different packages can have the same name. They may be referred by their fully
qualified name, comprising the package name and the class name.
3. Packages provide a way to "hide"' classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding”. First we can design
classes and decide their relationships, and then we can implement the Java code needed for the
methods. It is possible to change the implementation of any method without affecting the rest of
the design.

2. a) Explain Life Cycle of Thread .

During the life time of a thread, there are many states it can enter. They include:
1. Newborn State
2. Runnable state
3. Running state
4. Blocked state
5. Dead Slate
A thread is always in one of these five states. It can move from one state to another via a variety of
Newborn ways as shown in fig.

1.Newborn State:

• When we create a thread object, the thread is born and is said to be in newborn state.
• The thread is not yet scheduled for running. At this state, we can do only one of the
following things with it:
1. Schedule it for running using start ( ) method.
2. Kill it using stop( ) method.

2. Runnable State:

 The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are waiting for
execution.
 If all threads have equal priority, then they are given time slots for execution in round robin
fashion. i.e., first-come, first-serve manner.
 The thread that relinquishes control joins the queue at the end and again waits for its turn.
This process of assigning time to threads is known as time-slicing.
 However, if we want a thread to relinquish control to another thread to equal priority before
its turn comes, we can do so by using the yield() method.

3. Running State:

• Running means that the processor has given its time to the thread for its execution.
• The thread runs until it relinquishes control on its own or it is preempted by a higher
priority thread. A running thread may relinquish its control in one or the following situations.
1. It has been suspended using suspend( ) method. A suspended thread can be revived by using
the resume( ) method. This approach is useful when we want to suspend a thread for some time
due to certain reason, but do not want to kill it.
 . It has been made to sleep. We can put a thread to sleep for a specified time period using
the methods sleep(time) where time is in milliseconds. This means that the thread is out of the
queue during this time period. The thread re-enters the runnable state as soon as this time period is
elapsed.

It has been told to wait until some event occurs. This is done using the
wait( ) method. The thread can be scheduled to run again using the
notify( ) method.

4. Blocked State:

• A thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state.
• This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain
requirements.
• A blocked thread is considered ''not runnable" but not dead and therefore fully qualified
to run again.

5. Dead State:
• Every thread has a life cycle. A running thread ends its life when it has completed
executing its run( ) method, It is a natural death.
• However, we can kill it by sending the stop message to it at any state thus causing a
premature death to it. A thread can be killed as soon it is born, or while it is running, or even when
it is in "not runnable” (blocked) condition.

b) Explain any two Thread methods.


We have various methods which can be called on Thread class object. These methods are very
useful when writing a multithreaded application. Thread class has following important methods.

Thread.sleep()

We actually saw a sneak preview of Thread.sleep() in our Java threading introduction. This static
method asks the system to put the current thread to sleep for (approximately) the specified
amount of time, effectively allowing us to implement a "pause". A thread can be interrupted from
its sleep.

For more details, see: Thread.sleep() (separate page).

interrupt()

As mentioned, you can call a Thread object's interrupt() method to interrupt the corresponding
thread if it is sleeping or waiting. The corresponding thread will "wake up" with an IOException at
some point in the future. See thread interruption for more details.

setPriority() / getPriority()

Sets and queries some platform-specific priority assignment of the given thread. When calculating
a priority value, it's good practice to always do so in relation to the
constants Thread.MIN_PRIORITY, Thread.NORM_PRIORITY and Thread.MAX_PRIORITY. In practice, values
go from 1 to 10, and map on to some machine-specific range of values: nice values in the case of
Linux, and local thread priorities in the case of Windows. These are generally the range of values of
"normal" user threads, and the OS will actually still run other threads beyond these values (so, for
example, you can't preempt the mouse pointer thread by setting a thread to MAX_PRIORITY!).

Three main issues with thread priorities are that:

 they don't always do what you might intuitively think they do;
 their behaviour depends on the platform and Java version: e.g. in Linux, priorities don't
work at all in Hotspot before Java 6, and the mapping of Java to OS priorities changed under
Windows between Java 5 and Java 6;
 in trying to use them for some purpose, you may actually interfere with more sensible
scheduling decisions that the OS would have made anyway to achieve your purpose.

For more information, see the section on thread scheduling and the discussion on thread priorities,
where the behaviour on different platforms is compared.

join()
The join() method is called on the Thread object representing enother thread. It tells
the current thread to wait for the other thread to complete. To wait for multiple threads at a
time, you can use a CountDownLatch.

Thread.yield()

This method effectively tells the system that the current thread is "willing to relinquish the CPU".
What it actually does is quite system-dependent. For more details, see: Thread.yield() (separate
page).

setName() / getName()

Threads have a name attached to them. By default, Java will attach a fairly dull name such
as Thread-12. But for debugging purposes you might want to attach a more meaningful name such
as Animation Thread, WorkerThread-10 etc. (Some of the variants of the Thread constructor actually
allow you to pass in a name from the start, but you can always change it later.)

3.A) Explain with an example, steps to Create and Run Java applets .
b) Write a Java program to draw a circle and polygon.
import java.awt.*;

import java.applet.*;

public class Rect extends Applet

public void paint(Graphics g)

g.setColor(Color.green);

g.drawOval(80,180,200,120);

g.setColor(Color.red);

g.fillOval(270,30,100,100);

int x[]={500,420,220,500};

int y[]={500,620,20,500};

int n=4;

g.drawPolygon(x,y,n);

}
}

4. Write a note on Exceptions.

In Java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime. The exception handling in java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can be maintained.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.

Types of Exception
• There are mainly two types of exceptions: Checked and Unchecked where error is
considered as unchecked exception.
• The sun microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

1) Checked Exception
• The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at
compile-time.

2) Unchecked Exception

• The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.

3) Error

• Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


5. Write a program to explain effect of thread priorities.

Example:
6. Write a note on Java strings .

7. How can we pass values to Applet?.


It is often useful to be able to pass parameters from a HTML page to an applet. This
allows us to modify the action of an applet without actually having to re-code or re-compile
the applet. For example earlier, we wrote an applet that displayed the string "Hello
World!". We may wish to re-write that applet to display Hello Derek!, or whatever name
we desire at a specific location that we can change within the HTML code.

To do this we use the <param> markup tag within the <applet> markup tag of the HTML
page. So to re-write the code in the section called “A Simple Applet Example - Hello
World!” to add the param tags to our HTML page, one for each parameter.

Java applet has the feature of retrieving the parameter values passed from the html page. So, you can
pass the parameters from your html page to the applet embedded in your page. The param tag(<parma
name="" value=""></param>) is used to pass the parameters to an applet. For the illustration about the
concept of applet and passing parameter in applet, a example is given below.
In this example, we will see what has to be done in the applet code to retrieve the value from
parameters. Value of a parameter passed to an applet can be retrieved using getParameter() function.
E.g. code:
String strParameter = this.getParameter("Message");

Printing the value:


Then in the function paint (Graphics g), we prints the parameter value to test the value passed from
html page. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will
display the value passed as parameter. In our case applet should display "Welcome in Passing
parameter in java applet example." message.

Você também pode gostar