Java
Java
1. What are the differences between JVM, JRE and JDK in Java? 5
2. What is meant by the Local variable and the Instance variable? What is Encapsulation?
2+3
Answer:
Local variables are defined in the method and scope of the variables that exist inside the method
itself.
Instance variable is defined inside the class and outside the method and the scope of the
variables exists throughout the class.
Purpose of Encapsulation:
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.
3. ……………15
4………………….15
M2
Serialization Deserialization
Deserialization is the opposite process of serialization
Serialization is the process which is used to
where we can get the objects back from the byte
convert the objects into byte stream
stream.
An object is serialized by writing it an An object is deserialized by reading it from an
ObjectOutputStream. ObjectInputStream.
2.In Java, static as well as private method overriding is possible. Comment on the
statement.5
The statement in the context is completely False. The static methods have no relevance with the
objects, and these methods are of the class level. In the case of a child class, a static method with
a method signature exactly like that of the parent class can exist without even throwing any
compilation error.
The phenomenon mentioned here is popularly known as method hiding, and overriding is
certainly not possible. Private method overriding is unimaginable because the visibility of the
private method is restricted to the parent class only. As a result, only hiding can be facilitated
and not overriding
It is not wrong if we claim that java is the complete object-oriented programming language.
Because Everything in Java is under the classes. And we can access that by creating the objects.
But also if we say that java is not a completely object-oriented programming language because it
has the support of primitive data types like int, float, char, boolean, double, etc.
Now for the question: Is java a completely object-oriented programming language? We can
say that - Java is not a pure object-oriented programming language, because it has direct access
to primitive data types. And these primitive data types don't directly belong to the Integer
classes.
Pointers are used in C/ C++. Why does Java not make use of pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code
simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause
potential errors. Moreover, security is also compromised if pointers are used because the users
can directly access memory with the help of pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the
usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java
makes use of references as these cannot be manipulated, unlike pointers.
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:
Example:
}
Public static void main(String args[]){
Addition addition = new Addition();
addition.add();
}
}
Here the add() method has different parameters in the Addition class is overloaded in the same
class as with the super-class.
5………….15
6…………….15
M3
1-5
2-5
3-15
4-15
M4
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.
Public:
Public members are visible in the same package as well as the outside package that is for other
packages.
Public members of Class A are visible to Class B (same package) as well as Class C (different
packages).
Private:
Private members are visible in the same class only and not for the other classes in the same
package as well as classes in the outside packages.
Private members in class A are visible only in that class. It is invisible for class B as well as
class C.
3) Difference between Array and Array List.5
Answer: The Difference between Array and Array List can be understood from the table
below:
Answer: The difference between HashMap and HashTable can be seen below:
HashMap HashTable
Methods are not synchronized Key methods are synchronized
Not thread safety Thread safety
Iterator is used to iterate the values Enumerator is used to iterate the values
Allows one null key and multiple null values Doesn’t allow anything that is null
Performance is high than HashTable Performance is slow
Answer: The difference between HashSet and TreeSet can be seen below:
HashSet TreeSet
Inserted elements are in random order Maintains the elements in the sorted order
Can able to store null objects Couldn’t store null objects
Performance is fast Performance is slow
5…………………15
6…………………..15
7…………………………15
M5
1) Difference between Abstract class and Interface. What is meant by Interface? What is
meant by Abstract class? What is meant by object class?
5+4+3+3
Answer: The differences between Abstract Class and Interface are as follows:
Abstract Class:
Abstract classes have a default constructor and it is called whenever the concrete subclass
is instantiated.
It contains Abstract methods as well as Non-Abstract methods.
The class which extends the Abstract class shouldn’t require the implementation of all the
methods, only Abstract methods need to be implemented in the concrete sub-class.
Abstract class contains instance variables.
Interface:
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:
2.What is dynamic method dispatch? Explain different types of inheritance in java with
example. What are the practical benefits, if any, of importing a specific class rather
than an entire package (e.g. import Java.net.* versus import Java.net.Socket)?
3+7+5
What are the practical benefits, if any, of importing a specific class rather than an entire
package (e.g. import Java.net.* versus import Java.net.Socket)?
Ans: It makes no difference in the generated class files since only the classes that are actually
used are referenced by the generated class file. The practical benefit of importing single classes
can be realized when two (or more) packages with the same class name, like, java.util.Timer and
Javax.swing.Timer.
If you import java.util.* and Javax.swing.* and then try to use “Timer”, you will get an error
while compiling (the class name is ambiguous between both packages). Let’s say what you really
wanted was the Javax.swing.Timer class and the only classes you plan on using in Java.util are
Collection and HashMap. In this case, some people will prefer to import java.util.Collection and
import java.util.HashMap instead of importing Java.util.*.
This will now allow them to use Timer, Collection, HashMap, and other Javax.swing classes
without using fully qualified class names in.
3………………..15
4……………….15
5.What are the differences between constructor and method of a class in Java?5
Constructor Method
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 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{
public static void main(String[] args){
add();
}
Public void add(){
try{
addition();
}catch(Exception e){
e.printStacktrace();
}
}
}
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:
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:
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.
Example:
Answer: Multiple threads are executed simultaneously. Each thread starts its own stack based on
the flow (or) priority of the threads.
Example Program:
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
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:
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.
Example:
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.
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);
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.
Example:
public static void main (String[] args){
Thread t = new Thread ();
t.start ();
}
public void run(){
Thread.yield();
}
}
M7
Answer :
Answer :
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.
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.
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().
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
Answer :
Mostly due to security reasons, the following restrictions are imposed on Java applets:
What Are The Advantages Of The Event-delegation Model Over The Event-
inheritance Model?
Answer :
Event-delegation model has two advantages over event-inheritance model. a)Event
delegation model enables event handling by objects other than the ones that generate the
events. This allows a clean separation between a component's design and its use. b)It
performs much better in applications where many events are generated. This performance
improvement is due to event-delegation model does not have to be repeatedly process
unhandled events as is the case of the event-inheritance.