Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

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

Criteria JDK JRE JVM


Java Development Java Runtime
Abbreviation Java Virtual Machine
Kit 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 Java applications.
Definition 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
Main JDK is mainly used for environment JVM provides specifications for all for code
Purpose development 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
Libraries to execute
Summary Development tools execute Java byte code.
the application

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

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. What is the difference between Procedural programming and OOPS? What


is the meaning of “IS-A” and “HAS-A” relationship? What is Static Binding and
Dynamic Binding?
1. Procedural language is based on functions but object oriented language is based on real
world objects.

2. Procedural language gives importance on the sequence of function execution but object
oriented language gives importance on states and behaviors of the objects.
3. Procedural language exposes the data to the entire program but object oriented language
encapsulates the data.
4. Procedural language follows top down programming paradigm but object oriented
language follows bottom up programming paradigm.
5. Procedural language is complex in nature so it is difficult to modify, extend and maintain
but object oriented language is less complex in nature so it is easier to modify, extend and
maintain.
6. Procedural language provides less scope of code reuse but object oriented language provides
more scope of code reuse.

4. What is Aggregation? What is Composition? What is the difference


between Association and Dependency?5+5+5

Association is reference based relationship between two classes. Here a class A holds a class
level reference to class B. Association can be represented by a line between these classes with an
arrow indicating the navigation direction. In case arrow is on the both sides, association has
bidirectional navigation.

class Asset { ... }


class Player { Asset
asset;
public Player(Assest purchasedAsset) { ... } /*Set the asset via Constructor
or a setter*/
}

Dependency is often confused as Association. Dependency is normally created when you


receive a reference to a class as part of a particular operation / method. Dependency indicates
that you may invoke one of the APIs of the received class reference and any modification to that
class may break your class as well. Dependency is represented by a dashed arrow starting from
the dependent class to its dependency. Multiplicity normally doesn’t make sense on a
Dependency.
class Die { public void Roll() { ... } } class
Player
{
public void TakeTurn(Die die) /*Look ma, I am dependent on Die and it's Roll
method to do my work*/
{ die.Roll(); ... }
}

Aggregation is same as association and is often seen as redundant relationship. A common


perception is that aggregation represents one-to-many / many-to-many / part-whole relationships
(i.e. higher multiplicity), which of course can be represented by via association too (hence the
redundancy). As aggregation doesn’t convey anything more effective about a software design
than an association, there is no separate UML representation for it (though some developers use a
hollow diamond to indicate aggregation). You can give aggregation a miss unless you use it to
convey something special.

class Asset { ... }


class Player { List
assets;
public void AddAsset(Asset newlyPurchasedAsset) {
assets.Add(newlyPurchasedAssest); ... } ...
}

Composition relates to instance creational responsibility. When class B is composed by class A,


class A instance owns the creation or controls lifetime of instance of class B. Needless to say
when class instance A instance is destructed (garbage collected), class B instance would meet the
same fate. Composition is usually indicated by line connecting two classes with addition of a
solid diamond at end of the class who owns the creational responsibility. It’s also a perceived
wrong notion that composition is implemented as nested classes. Composition binds lifetime of a
specific instance for a given class, while class itself may be accessible by other parts of the
system.
public class Piece { ... } public
class Player
{
Piece piece = new Piece(); /*Player owns the responsibility of creating the
Piece*/
...
}

Though elementary, I hope above distills your thinking

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 is the process which is used serialization where we can get the objects back from
to convert the objects into byte stream the byte 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.
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?


Pointers are used in C/ C++. Why does Java not make use of pointers?
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 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.

4) What is meant by Overloading? Explain with example


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. What is message passing and why it is used? Explain Different ways to


create objects in Java.

Message Passing in terms of computers is communication between processes. It is a form of


communication used in object-oriented programming as well as parallel programming. Message
passing in Java is like sending an object i.e. message from one thread to another thread. It is used
when threads do not have shared memory and are unable to share monitors or semaphores or any
other shared variables to communicate. Suppose we consider an example of producer and
consumer, likewise what producer will produce, the consumer will be able to consume that only.
We mostly use Queue to implement communication between threads.
In the example explained below, we will be using vector(queue) to store the messages, 7 at a
time and after that producer will wait for the consumer until the queue is empty.

In Producer there are two synchronized methods putMessage() which will call form run()
method of Producer and add message in Vector whereas getMessage() extracts the message from
the queue for the consumer.

There are several ways by which we can create objects of a class in java as we all know a class
provides the blueprint for objects, you create an object from a class. This concept is under-rated
and sometimes proves to be beneficial as this concept is bypassed by many programmers and
sometimes even do ask from interview perceptive.

Methods:

There are many different ways to create objects in Java. Let us list them later discussing later
taking individually with the help of programs to illustrate internal working by which we can
create objects in Java.

1. Using new keyword


2. Using new instance
3. Using clone() method
4. Using deserialization
5. Using newInstance() method of Constructor class
Let us discuss them one by one and implement the same by appending a clean java program for
the same.

Method 1: Using new keyword

Using the new keyword in java is the most basic way to create an object. This is the most
common way to create an object in java. Almost 99% of objects are created in this way. By using
this method we can call any constructor we want to call (no argument or parameterized
constructors).

Example

// Java program to Illustrate Creation of Object

// Using new keyword

// Main class class


GFG {

// Declaring and initializing string


// Custom input string

String name = "GeeksForGeeks";

// Main driver method public


static void main(String[] args)
{
// As usual and most generic used we will

// be creating object of class inside main()


// using new keyword

GFG obj = new GFG();

// Print and display the object


System.out.println(obj.name);
}
}
Method 2: Using new instance

If we know the name of the class & if it has a public default constructor we can create an object
Class.forName. We can use it to create the Object of a Class. Class.forName actually loads the
Class in Java but doesn’t create any Object. To create an Object of the Class you have to use the
new Instance Method of the Class.

Example

// Java program to Illustrate Creation of Object

// Using new Instance

// Main class class


GFG {

// Declaring and initializing string

String name = "GeeksForGeeks";

// Main driver method public static


void main(String[] args) {

// Try block to check for exceptions


try {

Class cls = Class.forName("GFG");

// Creating object of main class

// using instance method

GFG obj = (GFG)cls.newInstance();

// Print and display

System.out.println(obj.name);

// Catch block to handle the exceptions


// Catch block 1

// Handling ClassNotFound Exception


catch (ClassNotFoundException e) {

// Display the exception along with line number


// using printStacktrace() method
e.printStackTrace();
}

// Catch block 2
// Handling InstantiationException
catch (InstantiationException e) {

e.printStackTrace();

// Catch block 2

// Handling IllegalAccessException
catch (IllegalAccessException e) {

e.printStackTrace();

}
}
}

Method 3: Using clone() method

Whenever clone() is called on any object, the JVM actually creates a new object and copies all
content of the previous object into it. Creating an object using the clone method does not invoke
any constructor. In order to use the clone() method on an object we need to implement Cloneable
and define the clone() method in it.

Example
// Java program to Illustrate Creation of Object

// Using clone() method

// Main class
// Implementing Cloneable interface class
GFG implements Cloneable {

// Method 1 @Override protected


Object clone() throws
CloneNotSupportedException
{
// Super() keyword refers to parent class
return super.clone();
}

// Declaring and initializing string

String name = "GeeksForGeeks";

// Method 2 // main driver method


public static void main(String[] args)
{

GFG obj1 = new GFG();

// Try block to check for exceptions


try {

// Using the clone() method


GFG obj2 = (GFG)obj1.clone();

// Print and display the main class object

// as created above
System.out.println(obj2.name);
}

// Catch block to handle the exceptions


catch (CloneNotSupportedException e) {

// Display the exception


// using printStackTrace() method
e.printStackTrace();
}

}
}

ss.

6. Write a program to ascending sort an array and display it.


Java 7 has come up with a new class Objects that have 9 static utility methods for operating on
objects. These utilities include null-safe methods for computing the hash code of an object,
returning a string for an object, and comparing two objects.

Using Objects class methods, one can smartly handle NullPointerException and can also show
customized NullPointerException message(if an Exception occur).

String toString(Object o) : This method returns the result of calling toString() method for a
nonnull argument and “null” for a null argument.

Syntax : public static String


toString(Object o)
Parameters :
o - an object
Returns :
the result of calling toString() method for a non-null argument and
"null" for a null argument

String toString(Object o, String nullDefault) : This method is overloaded version of above


method. It returns the result of calling toString() method on the first argument if the first
argument is not null and returns the second argument otherwise.

Syntax : public static String toString(Object o, String


nullDefault)
Parameters :
o - an object
nullDefault - string to return if the first argument is null
Returns : the result of calling toString() method on the first
argument if it is not null and
the second argument otherwise.

boolean equals(Object a,Object b) : This method true if the arguments are equal to each other
and false otherwise. Consequently, if both arguments are null, true is returned and if exactly one
argument is null, false is returned. Otherwise, equality is determined by using the equals()
method of the first argument.
Syntax : public static boolean equals(Object
a,Object b)
Parameters : a
- an object
b - an object to be compared with a for equality
Returns :
true if the arguments are equal to each other and false otherwise
• boolean deepEquals(Object a,Object b) :This method returns true if the arguments are deeply equal
to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the
algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by
using the equals method of the first argument.
Syntax : public static boolean deepEquals(Object
a,Object b)
Parameters : a
- an object
b - an object to be compared with a for equality
Returns :
true if the arguments are deeply equals to each other and false otherwise
• T requireNonNull(T obj) : This method checks that the specified object reference is not null. This
method is designed primarily for doing parameter validation in methods and constructors, as
demonstrated in below example:
Syntax : public static T
requireNonNull(T obj)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
Returns :
obj if not null
Throws:
NullPointerException - if obj is null
• T requireNonNull(T obj,String message) : This method is overloaded version of above method with
customized message printing if obj is null as demonstrated in below example:
Syntax : public static T requireNonNull(T
obj,String message)
Type Parameters:
T - the type of the reference
Parameters :
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException
is thrown Returns :
obj if not null
Throws:
NullPointerException - if obj is null

int hashCode(Object o) : This method returns the hash code of a non-null argument and 0 for a
null argument.
Syntax :
public static int hashCode(Object o)
Parameters : o
- an object
Returns :
the hash code of a non-null argument and 0 for a null argument int hash(Object…
values) : This method generates a hash code for a sequence of input values. The hash code is
generated as if all the input values were placed into an array, and that array were hashed by
calling Arrays.hashCode(Object[]).
This method is useful for implementing Object.hashCode() on objects containing multiple fields.
For example, if an object that has three fields, x, y, and z, one could write:
@Override public int
hashCode() {
return Objects.hash(x, y, z);
}

• int compare(T a,T b,Comparator c) : As usual, this method returns 0 if the arguments are
identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned.

Note that if one of the arguments is null, a NullPointerException may or may not be thrown
depending on what ordering policy, if any, the Comparator chooses to have for null values.
Syntax : public static int compare(T a,T
b,Comparator c)
Type Parameters:
T - the type of the objects being compared
Parameters : a
- an object
b - an object to be compared with a
c - the Comparator to compare the first two arguments
Returns :
0 if the arguments are identical and c.compare(a, b) otherwise.

1. Define state, data member, attribute, property.


- They all refer to one thing, that is, the data fields that provide data specification for
the class.
- Example: see the data members defined in the “protected:” section below. class

Point{ private: protected: double x;

double y;

int id; double

size; void

randID();

public:

};

2. What is “this”? Explain with a program.5

- A private constant pointer that points to the current instance of a class and only can be accessed
by the class itself.

3. How to resolve conflicts in naming between multiple parent classes if they are called
from a child? Compare Class & Struct. Define process abstraction
5+5+5

- Members (data and functions): class = private by default, struct = public by default. - Access-
specifier of base class / inheritance: class = private by default, struct = public by default.

- Derived class redefines the multiply-defined function in parents or,


- Derived class invokes member function in a particular base class using scope resolution
operator ::
- Compiler errors occur if derived class uses base class function without one of above solutions.

Define process abstraction


Separating the process (method, procedure, function, subroutine or subprogram) signature/prototype
from the detailed actual definition and implementation, so that the user is not concerned with how the
process is implemented but rather how to use it.
- Example: a method is defined to sort a list of elements and can be implemented using insertion sort or
selection sort and the only thing the user has to worry about is how to call it.

4. What are literals in java? Write down two programs to define call by value and call by reference.
5+5+5
Literals in Java
In Java, literal is a notation that represents a fixed value in the source code. In lexical analysis,
literals of a given type are generally known as tokens. In this section, we will discuss the term
literals in Java.

Literals

In Java, literals are the constant values that appear directly in the program. It can be assigned
directly to a variable. Java has various types of literals. The following figure represents a literal.

Types of Literals in Java

There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:

• Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may
have a positive (+) or negative (-) Note that between numbers commas and non-digit
characters are not permitted. For example, 5678, +657, -89, etc.

1. int decVal = 26;

• Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.


For example, 045, 026,

1. int octVal = 067;

• Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as


hexadecimal integers. It may also include a character from a to f or A to F that represents
numbers from 10 to 15, respectively. For example, 0xd, 0xf,

1. int hexVal = 0x1a;

• Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create
binary literals in Java SE 7 and later). Prefix 0b represents the Binary system. For
example, 0b11010.

1. int binVal = 0b11010;

Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.

Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:

\n: It is used for a new line

\t: It is used for horizontal tab

\b: It is used for blank space

\v: It is used for vertical tab

\a: It is used for a small beep


\r: It is used for carriage return

\': It is used for a single quote

\": It is used for double quotes

Character Literals
A character literal is expressed as a character or an escape sequence, enclosed in a single quote
('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.

String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.

Floating Point Literals


The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.

• Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is a 32-bit
float literal.
• Floating-point literals for double type end with D or d. It is optional to write D or d. For example,
6d, 8.354D, etc. It is a 64-bit double literal.
• It can also be represented in the form of the exponent.

Floating:

1. float length = 155.4f;

Decimal:

1. double interest = 99658.445; Decimal

in Exponent form:

1. double val= 1.234e2;

Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.
1. boolean isEven = true;

Null Literals
Null literal is often used in programs as a marker to indicate that reference type object is
unavailable. The value null may be assigned to any variable, except variables of primitive types.

1. String stuName = null;


2. Student age = null;

Class Literals
Class literal formed by taking a type name and appending .class extension. For example,
Scanner.class. It refers to the object (of type Class) that represents the type itself.

1. class classType = Scanner.class;

Invalid Literals

There is some invalid declaration of literals.

float g = 6_.674f; float g = 6._674F; long

phoneNumber = 99_00_99_00_99_L;

int x = 77_; int

y = 0_x76; int

z = 0X_12; int

z = 0X12_;

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. 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.

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[1] = “book” name.add(“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. Write a program to demonstrate the method overloading by changing a number


of arguments? What are the rules we need to follow during method overriding?
Write a program to demonstrate method overriding?

class Addition{
static int add(int x, int y)
{ return
x+y; }
static double add(double x, double y)
{ return
x+y;
} }
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(22,22));
System.out.println(Adder.add(12.5,12.5)); }}

Output:
44
25

What are the rules we need to follow during method overriding?


The rules are as follows:

• The method must have the same parameters as present in the parent class.
• There must be an IS-A relationship which is called inheritance.
• The method should have the name same as that of the class name.

6. What is the drawback to Garbage Collection? Explain the difference between a minor, major and full
garbage collection. When does a Java object become available for garbage collection?
What do you mean by mark-and-sweep? What is a daemon thread and Is
Garbage Collection a daemon thread?

What is a daemon thread and Is Garbage Collection a daemon thread?


A thread which runs behind the application for performing background operations is referred to
as a daemon thread.

Yes, GC is a daemon thread which starts by JVM.

What do you mean by mark-and-sweep?


Mark and Sweep are the two states of garbage collection. In the Mark stage, JVM identifies
whether an object is still needed or not. The object is marked for garbage collection when the
object is not needed.

In the Sweep stage, JVM performs memory reclamation and garbage collection algorithms.

What is the drawback to Garbage Collection ?-The main drawback of Garbage Collection is that it
freezes all those threads which are currently active at the time of occurring memory recovery
phase. The garbage collection algorithms take time in seconds or minutes to run, and due to this,
garbage collection routines can't be scheduled.

Explain the difference between a minor, major and full garbage collection.
1. Full garbage collection works on the tenured space.
2. Major garbage collection works on the survivor space.
3. Minor garbage collection works on the Eden space to perform a mark-and-sweep routine.

When does a Java object become available for garbage collection?


An object becomes available for garbage collection when:

1. It is marked as null.
2. It goes out of scope.
3. Within an application, if it is no longer referenced by any non-null objects.

7. Is String immutable or final in Java and If so, then what are the benefits of Strings being Immutable? What
does the string intern() method do in Java? How to convert an Array to String in Java?
Difference between Scanner and BufferedReader ? Write a program to Ask user to give two double input
for length and breadth of a rectangle and print area type casted to int.
Yes, Strings are immutable in Java. Immutable objects mean they can't be changed or altered
once they've been created. However, we can only modify the reference to the string object. The
String is immutable in Java because of many reasons like security, caching, synchronization and
concurrency, and class loading

What does the string intern() method do in Java?


If you apply the intern() method to a few strings, you will ensure that all strings having the same
content share the same memory. As soon as a String object is invoked with intern(), it first
checks if the string value of the String object is already present in the string pool and if it is
available, then the reference to that string from the string constant pool is returned. If not, a new
string object is added to the string pool, and a reference to it is returned.

Example:
String str1 = new String("Scaler by InterviewBit").intern(); //Line1
String str2 = new String("Scaler by InterviewBit").intern(); //Line2
System.out.println(str1 == str2); //prints true

As you can see, the intern() method is invoked on the String objects. When Line1 is executed,
memory is allocated within the SCP. In line 2, no new string objects are created in the SCP
because str1 and str2 have the same content. As a result, the reference to the object created in
line1 is returned. This means that str1 and str2 both point to the same memory. Therefore, the
print statement prints true

How to convert an Array to String in Java?


An array can be converted to a string in four different ways such as Arrays.toString() method,
String.Join() method, StringBuilder.append() method, and Collectors.joining() method. Here, we
will see an example of the Array.toString() method. Arrays.toString() returns a string
representation of the array contents. The string represents the array's elements as a list, enclosed
in square brackets ("[]"). The characters ", " (a comma) followed by a space are used to separate
adjacent elements. It returns “null” if the array is null.
import java.util.Arrays; public
class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = { "Scaler", "by", "InterviewBit"};
String str1 = ConvertArraytoString(strArray);
System.out.println("An array converted to a string: " + str1);
}
// Using the Arrays.toString() method
public static String ConvertArraytoString(String[] strArray)
{
return Arrays.toString(strArray);
}
}

Difference between Scanner and BufferedReader ? Which one is faster and Why ?

Ans. Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads
the stream.

BufferedReader read files efficiently by using a buffer to avoid physical disk operations.

Buffer size of Scanner is usually smaller than the Buffered Writer.

BufferedReader is faster that Scanner as it just reads the Stream and doesn't Parse the tokens to read
the stream into primitive data types.

Ask user to give two double input for length and breadth of a rectangle and print area type
casted to int.
import java.util.Scanner; class
Ans{
public static void main(String[] args){
Scanner s = new Scanner(System.in);
double x = s.nextDouble(); double y =
s.nextDouble(); double area = x*y;
System.out.println((int)area);
} }

What are the different string methods in Java?


There are various string operations in Java that allow us to work with strings. These methods or
operations can be used for string handling in Java as well as string manipulation in Java. Some of
such methods are as follows:

• split(): Split/divide the string at the specified regex.


• compareTo(): Compares two strings on the basis of the Unicode value of each string
character.
• compareToIgnoreCase(): Similar to compareTo, but it also ignores case differences.
• length(): Returns the length of the specified string.
• substring(): Returns the substring from the specified string.
• equalsIgnoreCase(): Compares two strings ignoring case differences.
• contains(): Checks if a string contains a substring.
• trim(): Returns the substring after removing any leading and trailing whitespace from the
specified string.
• charAt(): Returns the character at specified index.
• toLowerCase(): Converts string characters to lower case.
• toUpperCase(): Converts string characters to upper case.
• concat(): Concatenates two strings

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?

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)
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. What is the reason why multiple inheritances are not supported in Java and Explain it with an
example. How does Multiple inheritance implement in Java? 5+3+7

In the following code, we have created 3 Classes A, B, and C. Class C extends Class B and
Class B extends Class A. Each class has a method m1(), is there any way to call A’s m1()
method from Class C?
public class A
{
void m1(){
System.out.println("m1 in class A");
} }
public class B extends A
{
void m1() {
System.out.println("m1 in class B");
} }
public class C extends B
{
void m1() {
System.out.println("m1 in class C");
} }
public class Test {
public static void main(String[] args)
{
C c = new C();
c.m1();
} }
Ans: Multiple inheritance can be implemented in Java by using interfaces. A class cannot extend
more than one class but a class can implement more than one interface.

Java doesn’t support multiple inheritances in order to reduce the complexity and simplify the
language. An example of multiple inheritances in Java is given below:

class X{ void
msg()
{
System.out.println("Hello");}
} class
Y{ void
msg()
{
System.out.println("Welcome");}
}
class Z extends X,Y{//suppose if it were public
static void main(String args[]){ Z obj=new Z();
obj.msg();//Now which msg() method would be invoked?
} }

Output:

Compile-time error

So, the above example shows that Java doesn’t support multiple inheritances.

Can we declare the main() method of our class as private?


In Java, main() method must be always public static to run any application or program correctly.
Suppose, if the main method is declared as private there will be no complications but it will give
a runtime error.

How does Multiple inheritance implement in Java?

Ans: Multiple inheritance can be implemented in Java by using interfaces. A class cannot extend
more than one class but a class can implement more than one interface.

In the following code, we have created 3 Classes A, B, and C. Class C extends Class B and
Class B extends Class A.

Each class has a method m1(), is there any way to call A’s m1() method from Class C?
public class 2
void m1(){ System.out.println("m1 in class A"); } } public class
B extends 31
{ 31
void m1() { System.out.println("m1 in class B"); } } public class
C extends 31

{
{
void m1() {
System.out.println("m1 in class C");
}
}
public class Test {
public static void main(String[] args)
{
C c = new C();
c.m1();
}
}

Ans: In the above code, every class has m1() method with the same signature thus Class B is
overriding A’s m1() method and Class C is overriding Class B’s m1() method.

Now, it is possible for class B and class C to call their super class’s m1() method by using
super.m1() call.

But here, the question is asking to invoke A’s m1() method from Class C, which is not possible
because it violates the OOPs concept in Java and also not super.super in java.

Since Java does not allow multiple inheritance, that means C can see only one superclass which
will have just one m1() method implementation. C can never see A’s m1() method.

We also call this scenario as the Diamond Problem of Multiple Inheritance. The only way to call
A’s m1() method from Class C is if Class B and class C call super.m1() method in its m1()
implementation.

4. How to use user-defined packages in Java? Why do we use user-defined packages? What is a
predefined package in Java? Can we import same package/class twice? Will the JVM load the package
twice at runtime? 5+3+4+3

Ans: There are two fundamental steps to access and use the user-defined packages:

Step-1: Set the classpath to user-defined package ,i.e..in which directory the user-defined
package is stored up to that directory set the classpath. Example: set classpath
=E:\softwaretestingo\myprograms (Assume that our programs are created in the above path)
Step-2: Using import keyword we can import all the specific user-defined and standard packages
also.
Example:

import org.softwaretestingo.pacakgesprograms.userdefinedpackges; class

RunProgram

{ public static void main(String

args[])

Employe e1=new Employe();

System.out.println(e1.showEmpDetails();

Department d1=new Department();

System.out.println(d1.getDeptId());

Can we import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM
complains anything about it. JVM will internally load the class only once no matter how many
times one imports the same class.

What is a predefined package in Java?


Java classes are structured into different packages based upon there functionality. •
Say for instance 'java.lang' package contains classes which are essential to
Java programming language e.g. Thread, Exception Error, Object etc.
• On the other hand package like 'java.util' contains all utility classes e.g. Collection
classes, Scanner and other utility.
• 'java.io' package contains Java classes related to Input and Output functionality.
• 'java.util.concurrent' also known as the sub package of 'java.util' contains concurrent
utility classes like CountDownLatch, CyclicBarrier, Semaphore etc.

Why do we use user-defined packages?


Ans: We can use user-defined packages to:

• Group related class files into a separate namespace.


• Provide the same level of security
• Make applications available to other parts of the application and in the same application
also.

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
Constructor Method

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


Eventinheritance 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