0% found this document useful (0 votes)
24 views

Java

Uploaded by

Mauparna Nandan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Java

Uploaded by

Mauparna Nandan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

M1

1. What are the differences between JVM, JRE and JDK in Java? 5

Criteria JDK JRE JVM


Java Runtime
Abbreviation Java Development Kit Java Virtual Machine
Environment
JVM is a platform-dependent,
JDK is a complete JRE is a software abstract machine comprising of 3
software development package providing specifications - document describing
kit for developing Java class libraries, the JVM implementation
Definition Java applications. It JVM and all the requirements, computer program
comprises JRE, required components meeting the JVM requirements and
JavaDoc, compiler, to run the Java instance object for executing the Java
debuggers, etc. applications. byte code and provide the runtime
environment for execution.
JRE is mainly used
JDK is mainly used
Main for environment JVM provides specifications for all
for code development
Purpose creation to execute the implementations to JRE.
and execution.
the code.
JDK provides tools JRE provides
JVM does not include any tools, but
Tools like compiler, libraries and classes
instead, it provides the specification
provided debuggers, etc for required by JVM to
for implementation.
code development run the program.
JRE = (JVM) +
JDK = (JRE) + JVM = Runtime environment to
Summary Libraries to execute
Development tools execute Java byte code.
the application

2. What is meant by the Local variable and the Instance variable? What is Encapsulation?
2+3

Answer:

Local variables are defined in the method and scope of the variables that exist inside the method
itself.

Instance variable is defined inside the class and outside the method and the scope of the
variables exists throughout the class.

Purpose of Encapsulation:

 Protects the code from others.


 Code maintainability.
Example:

We are declaring ‘a’ as an integer variable and it should not be negative.

public class Addition(){


int a=5;
}

If someone changes the exact variable as “a = -5” then it is bad.

In order to overcome the problem we need to follow the steps below:

 We can make the variable private or protected.


 Use public accessor methods such as set<property> and get<property>.
 So that the above code can be modified as:

public class Addition(){


private int a = 5; //Here the variable is marked as private
}

 The code below shows the getter and setter.


 Conditions can be provided while setting the variable.

get A(){
}
set A(int a){
if(a&gt;0){// Here condition is applied
.........
}
}

For encapsulation, we need to make all the instance variables private and create setter and
getter for those variables. Which in turn will force others to call the setters rather than
access the data directly.

3. ……………15

4………………….15

M2

1) Difference between Serialization and Deserialization in Java. 5


Answer: These are the differences between serialization and deserialization in java:

Serialization Deserialization
Deserialization is the opposite process of serialization
Serialization is the process which is used to
where we can get the objects back from the byte
convert the objects into byte stream
stream.
An object is serialized by writing it an An object is deserialized by reading it from an
ObjectOutputStream. ObjectInputStream.

2.In Java, static as well as private method overriding is possible. Comment on the
statement.5

The statement in the context is completely False. The static methods have no relevance with the
objects, and these methods are of the class level. In the case of a child class, a static method with
a method signature exactly like that of the parent class can exist without even throwing any
compilation error.

The phenomenon mentioned here is popularly known as method hiding, and overriding is
certainly not possible. Private method overriding is unimaginable because the visibility of the
private method is restricted to the parent class only. As a result, only hiding can be facilitated
and not overriding

3) Can java be said to be the complete object-oriented programming language?


2+3

It is not wrong if we claim that java is the complete object-oriented programming language.
Because Everything in Java is under the classes. And we can access that by creating the objects.

But also if we say that java is not a completely object-oriented programming language because it
has the support of primitive data types like int, float, char, boolean, double, etc.

Now for the question: Is java a completely object-oriented programming language? We can
say that - Java is not a pure object-oriented programming language, because it has direct access
to primitive data types. And these primitive data types don't directly belong to the Integer
classes.

Pointers are used in C/ C++. Why does Java not make use of pointers?

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code
simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause
potential errors. Moreover, security is also compromised if pointers are used because the users
can directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the
usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java
makes use of references as these cannot be manipulated, unlike pointers.

4) What is meant by Overloading? Explain with example 5+5+5

What is meant by Method Overriding? Explain with example

State the difrence between Overloading & Method Overriding

Answer: Method overriding happens if the sub-class method satisfies the below conditions
with the Super-class method:

 Method name should be the same


 The argument should be the same
 Return type should also be the same

The key benefit of overriding is that the Sub-class can provide some specific information about
that sub-class type than the super-class.

Example:

public class Manipulation{ //Super class


public void add(){
………………
}
}

Public class Addition extends Manipulation(){


Public void add(){
………..
}
Public static void main(String args[]){
Manipulation addition = new Addition(); //Polimorphism is applied
addition.add(); // It calls the Sub class add() method
}
}

addition.add() method calls the add() method in the Sub-class and not the parent class. So it
overrides the Super-class method and is known as Method Overriding.

Answer: Method overloading happens for different classes or within the same class.

For method overloading, sub-class method should satisfy the below conditions with the
Super-class method (or) methods in the same class itself:

 Same method name


 Different argument types
 There may be different return types

Example:

public class Manipulation{ //Super class


public void add(String name){ //String parameter
………………
}
}

Public class Addition extends Manipulation(){


Public void add(){//No Parameter
………..
}
Public void add(int a){ //integer parameter

}
Public static void main(String args[]){
Addition addition = new Addition();
addition.add();
}
}

Here the add() method has different parameters in the Addition class is overloaded in the same
class as with the super-class.

5………….15

6…………….15

M3

1-5

2-5

3-15

4-15

M4

1) Difference between String, String Builder, and String Buffer.5

Answer:

String: String variables are stored in a “constant string pool”. Once the string reference changes
the old value that exists in the “constant string pool”, it cannot be erased.

Example:
String name = “book”;

Constant string pool

If the name-value has changed from “book” to “pen”.

Constant string pool

Then the older value remains in the constant string pool.

String Buffer:

 Here string values are stored in a stack. If the values are changed then the new value
replaces the older value.
 The string buffer is synchronized which is thread-safe.
 Performance is slower than the String Builder.

Example:

String Buffer name =”book”;

Once the name value has been changed to “pen” then the “book” is erased in the stack.
String Builder:

This is the same as String Buffer except for the String Builder which is not threaded safely that is
not synchronized. So obviously the performance is fast.

2) Explain about Public and Private access specifiers.5

Answer: Methods and instance variables are known as members.

Public:

Public members are visible in the same package as well as the outside package that is for other
packages.

Public members of Class A are visible to Class B (same package) as well as Class C (different
packages).

Private:

Private members are visible in the same class only and not for the other classes in the same
package as well as classes in the outside packages.

Private members in class A are visible only in that class. It is invisible for class B as well as
class C.
3) Difference between Array and Array List.5

Answer: The Difference between Array and Array List can be understood from the table
below:

Array Array List


Size should be given at the time of array Size may not be required. It changes the size
declaration. dynamically.

String[] name = new String[2] ArrayList name = new ArrayList


To put an object into array we need to specify
No index required.
the index.
name.add(“book”)
name[1] = “book”
ArrayList in java 5.0 are parameterized.
Array is not type parameterized
Eg: This angle bracket is a type parameter which
means a list of String.

4) Difference between HashMap and HashTable. Difference between HashSet and


TreeSet.5

Answer: The difference between HashMap and HashTable can be seen below:

HashMap HashTable
Methods are not synchronized Key methods are synchronized
Not thread safety Thread safety
Iterator is used to iterate the values Enumerator is used to iterate the values
Allows one null key and multiple null values Doesn’t allow anything that is null
Performance is high than HashTable Performance is slow

Answer: The difference between HashSet and TreeSet can be seen below:

HashSet TreeSet
Inserted elements are in random order Maintains the elements in the sorted order
Can able to store null objects Couldn’t store null objects
Performance is fast Performance is slow
5…………………15

6…………………..15
7…………………………15

M5

1) Difference between Abstract class and Interface. What is meant by Interface? What is
meant by Abstract class? What is meant by object class?

5+4+3+3

Answer: The differences between Abstract Class and Interface are as follows:

Abstract Class:

 Abstract classes have a default constructor and it is called whenever the concrete subclass
is instantiated.
 It contains Abstract methods as well as Non-Abstract methods.
 The class which extends the Abstract class shouldn’t require the implementation of all the
methods, only Abstract methods need to be implemented in the concrete sub-class.
 Abstract class contains instance variables.

Interface:

 It doesn’t have any constructor and couldn’t be instantiated.


 The abstract method alone should be declared.
 Classes that implement the interface should provide the implementation for all the
methods.
 The interface contains only constants.

What is meant by Interface?

Answer: Multiple inheritances cannot be achieved in java. To overcome this problem the
Interface concept is introduced.

An interface is a template which has only method declarations and not the method
implementation.

Example:

Public abstract interface IManupulation{ //Interface declaration


Public abstract void add();//method declaration
public abstract void subtract();
}

 All the methods in the interface are internally public abstract void.
 All the variables in the interface are internally public static final that is constants.
 Classes can implement the interface and not extends.
 The class which implements the interface should provide an implementation for all the
methods declared in the interface.

public class Manupulation implements IManupulation{ //Manupulation class uses


the interface
Public void add(){
……………
}
Public void subtract(){
…………….
}
}

What is meant by Abstract class?

Answer: We can create the Abstract class by using the “Abstract” keyword before the class
name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a
concrete class.

Abstract method:

The method which has only the declaration and not the implementation is called the abstract
method and it has the keyword called “abstract”. Declarations ends with a semicolon.

Example:

public abstract class Manupulation{


public abstract void add();//Abstract method declaration
Public void subtract(){
}
}

 An abstract class may have a non- abstract method also.


 The concrete Subclass which extends the Abstract class should provide the
implementation for abstract methods.

What is meant by object class?

2.What is dynamic method dispatch? Explain different types of inheritance in java with
example. What are the practical benefits, if any, of importing a specific class rather
than an entire package (e.g. import Java.net.* versus import Java.net.Socket)?
3+7+5

What are the practical benefits, if any, of importing a specific class rather than an entire
package (e.g. import Java.net.* versus import Java.net.Socket)?
Ans: It makes no difference in the generated class files since only the classes that are actually
used are referenced by the generated class file. The practical benefit of importing single classes
can be realized when two (or more) packages with the same class name, like, java.util.Timer and
Javax.swing.Timer.

If you import java.util.* and Javax.swing.* and then try to use “Timer”, you will get an error
while compiling (the class name is ambiguous between both packages). Let’s say what you really
wanted was the Javax.swing.Timer class and the only classes you plan on using in Java.util are
Collection and HashMap. In this case, some people will prefer to import java.util.Collection and
import java.util.HashMap instead of importing Java.util.*.

This will now allow them to use Timer, Collection, HashMap, and other Javax.swing classes
without using fully qualified class names in.

3………………..15

4……………….15

5.What are the differences between constructor and method of a class in Java?5

Constructor Method

Method is used for exposing the


Constructor is used for initializing the object state.
object's behavior.

Method should have a return type.


Constructor has no return type. Even if it does not return anything,
return type is void.

Method has to be invoked on the


Constructor gets invoked implicitly.
object explicitly.

If the constructor is not defined, then a default constructor is If a method is not defined, then the
provided by the java compiler. compiler does not provide it.

The name of the method can have


The constructor name should be equal to the class name.
any name or have a class name too.

A constructor cannot be marked as final because whenever a class


A method can be defined as final but
is inherited, the constructors are not inherited. Hence, marking it
it cannot be overridden in its
final doesn't make sense. Java throws compilation error saying -
subclasses.
modifier final not allowed here

A final variable if initialised inside a


Final variable instantiations are possible inside a constructor and method ensures that the variable
the scope of this applies to the whole class and its objects. cant be changed only within the
scope of that method.
6. Identify the output of the below java program and Justify your answer.
class Main {
public static void main(String args[]) {
Scaler s = new Scaler(5);
}
}
class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class Scaler extends InterviewBit{
Scaler(){
System.out.println(" Welcome to Scaler Academy ");
}
Scaler(int x){
this();
super();
System.out.println(" Welcome to Scaler Academy 2");
}
}

The above code will throw the compilation error. It is because the super() is used to call the
parent class constructor. But there is the condition that super() must be the first statement in the
block. Now in this case, if we replace this() with super() then also it will throw the compilation
error. Because this() also has to be the first statement in the block. So in conclusion, we can say
that we cannot use this() and super() keywords in the same block.

7. What is a Constructor, Constructor Overloading in Java and Copy-


Constructor ?5

A constructor gets invoked when a new object is created. Every class has a constructor. In case
the programmer does not provide a constructor for a class, the Java compiler (Javac) creates a
default constructor for that class. The constructor overloading is similar to method overloading in
Java. Different constructors can be created for a single class. Each constructor must have its own
unique parameter list. Finally, Java does support copy constructors like C++, but the difference
lies in the fact that Java doesn’t create a default copy constructor if you don’t write your own.

M6

1.What are the different ways to handle exceptions? Do final, finally and finalize
keywords have the same function? DIFFERENTIATE BETWEEN THROW &
THROWS KEYWORD
7+4+4

Answer: Two different ways to handle exceptions are explained below:

a) Using try/catch:

The risky code is surrounded by try block. If an exception occurs, then it is caught by the catch
block which is followed by the try block.

Example:

class Manipulation{
public static void main(String[] args){
add();
}
Public void add(){
try{
addition();
}catch(Exception e){
e.printStacktrace();
}
}
}

b) By declaring throws keyword:

At the end of the method, we can declare the exception using throws keyword.

Example:

class Manipulation{
public static void main(String[] args){
add();
}
public void add() throws Exception{
addition();
}
}

Do final, finally and finalize keywords have the same function?

All three keywords have their own utility while programming.

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in
handy. Inheritance of a final class and overriding of a final method is restricted by the use of the
final keyword. The variable value becomes fixed after incorporating the final keyword. Example:

final int a=100;


a = 0; // error
The second statement will throw an error.

Finally: It is the block present in a program where all the codes written inside it get executed
irrespective of handling of exceptions. Example:

try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}

Finalize: Prior to the garbage collection of an object, the finalize method is called so that the
clean-up activity is implemented. Example:

public static void main(String[] args) {


String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}

Q. DIFFERENTIATE BETWEEN THROW & THROWS KEYWORD .

 The ‘throw’ keyword is used to manually throw the exception to the calling method.
 And the ‘throws’ keyword is used in the function definition to inform the calling method
that this method throws the exception. So if you are calling, then you have to handle the
exception.

Example -

class Main {
public static int testExceptionDivide(int a, int b) throws
ArithmeticException{
if(a == 0 || b == 0)
throw new ArithmeticException();
return a/b;
}
public static void main(String args[]) {
try{
testExceptionDivide(10, 0);
}
catch(ArithmeticException e){
//Handle the exception
}
}
}

2. Explain the thread life cycle in Java. How to stop a thread in java? Explain about
sleep () method in a thread? Difference between notify() method and notifyAll() method in
Java.

5+2+3+5

Answer: Thread has the following states:

 New
 Runnable
 Running
 Non-runnable (Blocked)
 Terminated

 New: In New state, a Thread instance has been created but start () method is not yet
invoked. Now the thread is not considered alive.
 Runnable: The Thread is in the runnable state after the invocation of the start () method,
but before the run () method is invoked. But a thread can also return to the runnable state
from waiting/sleeping. In this state, the thread is considered alive.
 Running: The thread is in a running state after it calls the run () method. Now the thread
begins the execution.
 Non-Runnable(Blocked): The thread is alive but it is not eligible to run. It is not in the
runnable state but also, it will return to the runnable state after some time. Example:
wait, sleep, block.
 Terminated: Once the run method is completed then it is terminated. Now the thread is
not alive.

How to stop a thread in java? Explain about sleep () method in a thread?

Answer: We can stop a thread by using the following thread methods:

 Sleeping
 Waiting
 Blocked
Sleep: Sleep () method is used to sleep the currently executing thread for the given amount of
time. Once the thread is wake up it can move to the runnable state. So sleep () method is used to
delay the execution for some period.

It is a static method.

Example:

Thread. Sleep (2000)

So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted


exception, hence we need to surround the block with try/catch.

public class ExampleThread implements Runnable{


public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
}
}

Difference between notify() method and notifyAll() method in Java.

Answer: The differences between notify() method and notifyAll() method are enlisted
below:

notify() notifyAll()
This method is used to send a signal to wake up a This method sends the signal to wake up all
single thread in the waiting pool. the threads in a waiting spool.

 3. Explain about wait () method. What is Multi-threading?Explain with example.


What is Synchronization? What is the disadvantage of Synchronization?

4+2+4+3+2

Answer: wait () method is used to make the thread to wait in the waiting pool. When the wait ()
method is executed during a thread execution then immediately the thread gives up the lock on
the object and goes to the waiting pool. Wait () method tells the thread to wait for a given
amount of time.

Then the thread will wake up after notify () (or) notify all () method is called.

Wait() and the other above-mentioned methods do not give the lock on the object immediately
until the currently executing thread completes the synchronized code. It is mostly used in
synchronization.

Example:

public static void main (String[] args){


Thread t = new Thread ();
t.start ();
Synchronized (t) {
Wait();
}
}
What is Multi-threading?Explain with example.

Answer: Multiple threads are executed simultaneously. Each thread starts its own stack based on
the flow (or) priority of the threads.

Example Program:

public class MultipleThreads implements Runnable


{
public static void main (String[] args){//Main thread starts here
Runnable r = new runnable ();
Thread t=new thread ();
t.start ();//User thread starts here
Addition add=new addition ();
}
public void run(){
go();
}//User thread ends here
}

On the 1st line execution, JVM calls the main method and the main thread stack looks as shown
below.

Once the execution reaches, t.start () line then a new thread is created and the new stack for the
thread is also created. Now JVM switches to the new thread and the main thread are back to the
runnable state.
The two stacks look as shown below.

Now, the user thread executed the code inside the run() method.

Once the run() method has completed, then JVM switches back to the main thread and the user
thread has completed the task and the stack was disappeared

What is Synchronization? What is the disadvantage of Synchronization?

 Answer: Synchronization makes only one thread to access a block of code at a time. If
multiple threads accesses the block of code, then there is a chance for inaccurate results at
the end. To avoid this issue, we can provide synchronization for the sensitive block of
codes.
 The synchronized keyword means that a thread needs a key in order to access the
synchronized code.
 Locks are per objects. Every Java object has a lock. A lock has only one key. A thread
can access a synchronized method only if the thread can get the key to the objects to lock.
 For this, we use the “Synchronized” keyword.
 Example:

public class ExampleThread implements Runnable{


public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
synchronized(object){
{
}
}

What is the disadvantage of Synchronization?


 Ans: Synchronization is not recommended to implement all the methods. Because if one
thread accesses the synchronized code then the next thread should have to wait. So it
makes a slow performance on the other end.

4.Explain about Exception Propagation. Is it compulsory for a Try Block to be followed by a


Catch Block in Java for Exception handling? Is there any way to skip Finally block of exception
even if some exception occurs in the exception block?

2+2+1

Answer: Exception is first thrown from the method which is at the top of the stack. If it doesn’t
catch, then it pops up the method and moves to the previous method and so on until they are got.

This is called Exception propagation.

Example:

public class Manipulation{


public static void main(String[] args){
add();
}
public void add(){
addition();
}

From the above example, the stack looks like as shown below:

If an exception occurs in the addition() method is not caught, then it moves to the method add().
Then it is moved to the main() method and then it will stop the flow of execution. It is called
Exception Propagation.

Is it compulsory for a Try Block to be followed by a Catch Block in Java for


Exception handling?

Ans: Try block needs to be followed by either Catch block or Finally block or both. Any
exception thrown from try block needs to be either caught in the catch block or else any specific
tasks to be performed before code abortion are put in the Finally block.

Is there any way to skip Finally block of exception even if some exception occurs
in the exception block?
Ans: If an exception is raised in Try block, control passes to catch block if it exists otherwise to
finally block. Finally block is always executed when an exception occurs and the only way to
avoid execution of any statements in Finally block is by aborting the code forcibly by writing
following line of code at the end of try block:

System.exit(0);

5.How do you make a thread in Java?5

Answer: There are two ways available to make a thread.

a) Extend Thread class: Extending a Thread class and override the run method. The thread is
available in java.lang.thread.

Example:

Public class Addition extends Thread {


public void run () {
}
}

The disadvantage of using a thread class is that we cannot extend any other classes because we
have already extended the thread class. We can overload the run () method in our class.

b) Implement Runnable interface: Another way is by implementing the runnable interface. For
that, we should provide the implementation for the run () method which is defined in the
interface.

Example:

Public class Addition implements Runnable {


public void run () {
}
}

6.What does the yield method of the Thread class do?5

Answer: A yield () method moves the currently running thread to a runnable state and allows the
other threads for execution. So that equal priority threads have a chance to run. It is a static
method. It doesn’t release any lock.

Yield () method moves the thread back to the Runnable state only, and not the thread to sleep (),
wait () (or) block.

Example:
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
Thread.yield();
}
}

M7

1. How Do Applets Differ From Applications? 5

Answer :

Following are the main differences:


Application: Stand Alone, doesn’t need web-browser.
Applet: Needs no explicit installation on local machine. Can be transferred through Internet on
to the local machine and may run as part of web-browser.
Application: Execution starts with main() method. Doesn’t work if main is not there.
Applet: Execution starts with init() method.
Application: May or may not be a GUI.
Applet: Must run within a GUI (Using AWT). This is essential feature of applets.

2.What Are The Applets Life Cycle Methods? Explain Them?5

Answer :

methods in the life cycle of an Applet:


► init() method - called when an applet is first loaded. This method is called only once in the
entire cycle of an applet. This method usually intialize the variables to be used in the applet.
► start( ) method - called each time an applet is started.
► paint() method - called when the applet is minimized or refreshed. This method is used for
drawing different strings, figures, and images on the applet window.
► stop( ) method - called when the browser moves off the applet’s page.
► destroy( ) method - called when the browser is finished with the applet.

3. What Is The Order Of Method Invocation In An Applet?

Answer :
► public void init() : Initialization method called once by browser.
► public void start() : Method called after init() and contains code to start processing. If the user
leaves the page and returns without killing the current browser session, the start () method is
called without being preceded by init ().
► public void stop() : Stops all processing started by start (). Done if user moves off page.
► public void destroy() : Called if current browser session is being terminated. Frees all
resources used by applet.

4. How To Insert Your Applets Into Frontpage? Can We Pass Parameters To An Applet
From Html Page To An Applet and How? How Do I Select A Url From My Applet And
Send The Browser To That Page?5+5+5

Answer :

1. Place the .class file in the directory containing the HTML document into which you want to
insert the applet.
2. Copy the <applet>...</applet> tag from your applet implementation or examples to the
clipboard.
3. In FrontPage select the "HTML" tab from the lower left hand corner.
4. Paste the <applet>...</applet> tag in an appropriate place between the <body> and </body>
tags. You'll find a gray box with the aqua letter "J" in the "Normal" view indicating the the applet
tag has been inserted.
5. To see the applet appearance select the "Preview" tab.

Can We Pass Parameters To An Applet From Html Page To An Applet? How?

Answer :

We can pass parameters to an applet using <param> tag in the following way:
► <param name=”param1″ value=”value1″>
► <param name=”param2″ value=”value2″>
Access those parameters inside the applet is done by calling getParameter() method inside the
applet. Note that getParameter() method returns String value corresponding to the parameter
name.

How Do I Select A Url From My Applet And Send The Browser To That Page?

Answer :

Ask the applet for its applet context and invoke showDocument() on that context object.
URL targetURL;
String URLString
AppletContext context = getAppletContext();
try
{
targetURL = new URL(URLString);
}
catch (MalformedURLException e)
{
// Code for recover from the exception
}
context. showDocument (targetURL);

5. Can Applets On Different Pages Communicate With Each Other? How Will You
Communicate Between Two Applets? What Are The Attributes Of Applet Tags?

5+5+5

Answer :

Use the getSize() method, which the Applet class inherits from the Component class in the
Java.awt package. The getSize() method returns the size of the applet as a Dimension object,
from which you extract separate width, height fields.
The following code snippet explains this:
Dimension dim = getSize();
int appletwidth = dim.width();
int appletheight = dim.height();

How Will You Communicate Between Two Applets?

Answer :

The simplest method is to use the static variables of a shared class since there's only one instance
of the class and hence only one copy of its static variables.
A slightly more reliable method relies on the fact that all the applets on a given page share the
same AppletContext.
We obtain this applet context as follows:
AppletContext ac = getAppletContext();
AppletContext provides applets with methods such as getApplet(name),
getApplets(),getAudioClip, getImage, showDocument and showStatus().

What Are The Attributes Of Applet Tags?

Answer :

 height : Defines height of applet


 width: Defines width of applet
 align: Defines the text alignment around the applet
 alt: An alternate text to be displayed if the browser support applets but cannot run this
applet
 archive: A URL to the applet when it is stored in a Java Archive or ZIP file
 code: A URL that points to the class of the applet
 codebase: Indicates the base URL of the applet if the code attribute is relative
 hspace: Defines the horizontal spacing around the applet
 vspace: Defines the vertical spacing around the applet
 name: Defines a name for an applet
 object: Defines the resource name that contains a serialized representation of the applet
 title: Display information in tool tip

6. What Is A Signed Applet? What are the restrictions imposed on Java applets ? What
Are The Advantages Of The Event-delegation Model Over The Event-inheritance
Model?

5+5+5

Answer :

 A signed Applet is a trusted Applet.


 By default, and for security reasons, Java applets are contained within a "sandbox". This
means that the applets cannot do anything, which might be construed as threatening to the
user's machine (e.g. reading, writing or deleting local files, putting up message windows,
or querying various system parameters).
 Early browsers had no provisions for Java applets to reach outside of the sandbox. Recent
browsers, however (Internet Explorer 4 on Windows etc), have provisions to give
"trusted" applets the ability to work outside the sandbox.
 For this power to be granted to one of your applets, the applet's code must be digitally
signed with your unforgeable digital ID, and then the user must state that he trusts applets
signed with your ID.
 The untrusted applet can request to have privileges outside the sandbox but will have to
request the user for privileges every time it executes. But with the trusted applet the user
can choose to remember their answer to the request, which means they won't be asked
again.

What are the restrictions imposed on Java applets ?

Mostly due to security reasons, the following restrictions are imposed on Java applets:

 An applet cannot load libraries or define native methods.


 An applet cannot ordinarily read or write files on the execution host.
 An applet cannot read certain system properties.
 An applet cannot make network connections except to the host that it came from.
 An applet cannot start any program on the host that’s executing it.

What Are The Advantages Of The Event-delegation Model Over The Event-
inheritance Model?

 Answer :
 Event-delegation model has two advantages over event-inheritance model. a)Event
delegation model enables event handling by objects other than the ones that generate the
events. This allows a clean separation between a component's design and its use. b)It
performs much better in applications where many events are generated. This performance
improvement is due to event-delegation model does not have to be repeatedly process
unhandled events as is the case of the event-inheritance.

You might also like