Professional Documents
Culture Documents
Java - Suggestions - Solutions
Java - Suggestions - Solutions
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:
Example:
get A(){
} set A(int a){ if(a>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.
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.
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.
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
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.
Answer: Method overriding happens if the sub-class method satisfies the below conditions
with the Super-class method:
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:
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:
}
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.
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.
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
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
System.out.println(obj.name);
// Catch block 2
// Handling InstantiationException
catch (InstantiationException e) {
e.printStackTrace();
// Catch block 2
// Handling IllegalAccessException
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
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
// Main class
// Implementing Cloneable interface class
GFG implements Cloneable {
// as created above
System.out.println(obj2.name);
}
}
}
ss.
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.
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.
double y;
size; void
randID();
public:
};
- 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.
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.
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.
• 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.
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:
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 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:
Decimal:
in Exponent form:
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.
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.
Invalid Literals
phoneNumber = 99_00_99_00_99_L;
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”;
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:
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
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:
Size should be given at the time of array Size may not be required. It changes the size
declaration. dynamically.
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
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
• 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?
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.
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
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
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.
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);
} }
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:
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:
• 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.
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:
• The concrete Subclass which extends the Abstract class should provide the
implementation for abstract methods.
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.
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:
RunProgram
args[])
System.out.println(e1.showEmpDetails();
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.
5.What are the differences between constructor and method of a class in Java?5
Constructor Method
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.
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.
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
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{
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();
}
}
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
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
• 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.
• 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:
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.
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.
Answer: Multiple threads are executed simultaneously. Each thread starts its own stack based on
the flow (or) priority of the threads.
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.
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
• 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){
{
}}
• 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.
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 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);
a) Extend Thread class: Extending a Thread class and override the run method. The thread
is available in java.lang.thread.
Example:
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:
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.
M7
1. How Do Applets Differ From Applications? 5
Answer :
Answer :
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.
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();
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.
Answer :
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
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.
Mostly due to security reasons, the following restrictions are imposed on Java applets:
• 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.