java final_merged

You might also like

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

2.

Differentiate between the following: 5x1=5


a) Abstract class and interface
b) Static and final keyword
e) Method overloading and method overriding.
f) Early binding and late binding

a)
 E)
b)Static
Method Overloading Method Overriding

Method overloading is a compile-time Method overriding is a run-time


polymorphism. polymorphism.

It is used to grant the specific implementation


It helps to increase the readability of the of the method which is already provided by its
program. parent class or superclass.

It is performed in two classes with inheritance


It occurs within the class. relationships.

Method overloading may or may not


require inheritance. Method overriding always needs inheritance.

In method overloading, methods must


have the same name and different In method overriding, methods must have the
signatures. same name and same signature.

In method overloading, the return type can


or can not be the same, but we just have to In method overriding, the return type must be
change the parameter. the same or co-variant.

Static binding is being used for overloaded Dynamic binding is being used for overriding
methods. methods.

It gives better performance. The reason behind


Poor Performance due to compile time this is that the binding of overridden methods
polymorphism. is being done at runtime.

Private and final methods can be


overloaded. Private and final methods can’t be overridden.

Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
 It can be applied to nested static class, variables, methods and block.
 It is not required to initialize the static variable when it is declared.

 This variable can be re-initialized.
 It can access the static members of the class only.
 It can be called only by other static methods.
 Objects of static class can’t be created.
 Static class can only contain static members.
 It is used to initialize the static variables.

Final

 It is a keyword.
 It is used to apply restrictions on classes, methods and variables.
 It can’t be inherited.
 It can’t be overridden.
 Final methods can’t be inherited by any class.
 It is needed to initialize the final variable when it is being declared.
 Its value, once declared, can’t be changed or re-initialized.
F)

3. What is the basic property of a static variable? Differentiate


among final, finally and finalize.
=>

Sr. Key final finally finalize


no.
1. Definition final is the keyword and finally is the block in finalize is the method in
access modifier which Java Exception Handling Java which is used to
is used to apply to execute the perform clean up
restrictions on a class, important code whether processing just before
method or variable. the exception occurs or object is garbage
not. collected.

2. Applicable Final keyword is used Finally block is always finalize() method is used
to with the classes, related to the try and with the objects.
methods and variables. catch block in exception
handling.

3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs
variable becomes important code even if the cleaning activities
constant and cannot be exception occurs or not. with respect to the object
modified. (2) finally block cleans before its destruction.
(2) final method cannot up all the resources
be overridden by sub used in try block
class.
(3) final class cannot be
inherited.

4. Execution Final method is Finally block is executed finalize method is


executed only when we as soon as the try-catch executed just before the
call it. block is executed. object is destroyed.

It's execution is not


dependant on the
exception.

Basic property of Static variable:

 Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final, and static. Constant
variables never change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class name
ClassName.VariableName.
 When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and final,
the naming syntax is the same as instance and local variables.

4. a) What are the methods in applet. B) Explain aggregation and


generalization.
o => init(): The init() method is the first method to run that
initializes the applet. It can be invoked only once at the time of
initialization. The web browser creates the initialized objects,
i.e., the web browser (after checking the security settings) runs
the init() method within the applet.
o start(): The start() method contains the actual code of the
applet and starts the applet. It is invoked immediately after the
init() method is invoked. Every time the browser is loaded or
refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from
one tab to another in the browser. It is in an inactive state until
the init() method is invoked.
o

o stop(): The stop() method stops the execution of the applet.


The stop () method is invoked whenever the applet is stopped,
minimized, or moving from one tab to another in the browser,
the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its
work is done. It is invoked when the applet window is closed or
when the tab containing the webpage is closed. It removes the
applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in
Java. It is used to draw shapes like circle, square, trapezium,
etc., in the applet. It is executed after the start() method and
when the browser or applet windows are resized.

What is Aggregation in UML


An association represents the relationship between two objects. Aggregation is a type
of association. In other words, it is a special case of association. When an object “has-
a” another object, then we can consider it as an aggregation. Therefore, aggregation
describes the “has a” relationship between objects.
Figure 1: Aggregation
The employee and address are linked with the “has a” relationship. An instance of the
Address class can exist without an instance of the Employee. It is an aggregation. In
UML, the diamond symbol represents an aggregation. The direction denotes which
object contains the other object.

What is Generalization in UML


Generalization is associated with inheritance, which is the process of allowing classes
to use the properties and methods of already existing classes. The existing class is
the superclass while the new class is the subclass. Generalization combines multiple
classes into a general class. Moreover, the superclass has the most general properties
and methods. Subclasses can share those properties and methods. Subclasses can
have specialized properties and methods. As a subclass is a type of super classes,
the generalization represents “is a” relationship.
Figure 2: Generalization

Employee is the superclass. Permanent and Temporary Employee are subclasses


whereas Employee is the generalized form of Permanent and Temporary Employee.
On the other hand, Permanent and Temporary Employee are specialized forms of
Employee. Employee has properties id, name, salary and the method display. The
subclasses Permanent and Temporary Employee can also use these properties and
methods. Furthermore, the subclasses have their own properties and meth ods. In
UML, an arrow represents generalization.

5. What is run-time polymorphism? Discuss with an example.


=> Method overriding is an example of runtime polymorphism. In method
overriding, a subclass overrides a method with the same signature as that of in
its superclass. During compile time, the check is made on the reference type.
However, in the runtime, JVM figures out the object type and would run the
method that belongs to that particular object.
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}

9. What are wrapper classes? Why do we need wrapper classes?


What is the difference between error and an exception?
=> The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.

o Change the value in Method: Java supports only call by value. So,
if we pass a primitive value, it will not change the original value. But,
if we convert the primitive value in an object, it will change the
original value.
o Serialization: We need to convert the objects into streams to
perform the serialization. If we have a primitive value, we can convert
it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading.
o java.util package: The java.util package provides the utility classes
to deal with objects.
o Collection Framework: Java collection framework works with
objects only. All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue,
ArrayDeque, etc.) deal with objects only.
Basis of Exception Error
Comparison

Recoverable/ Exception can be recovered by using the try-


Irrecoverable catch block. An error cannot be recovered.

Type It can be classified into two categories i.e. All errors in Java are
checked and unchecked. unchecked.

Occurrence It occurs at compile time or run time. It occurs at run time.

Package It belongs to java.lang.Exception package. It belongs to java.lang.Error


package.

Known or Only checked exceptions are known to the Errors will not be known to the
unknown compiler. compiler.

Causes It is mainly caused by the application itself. It is mostly caused by the


environment in which the
application is running.

Example Checked Exceptions: SQLException, Java.lang.StackOverFlow,


IOException java.lang.OutOfMemoryError
Unchecked
Exceptions: ArrayIndexOutOfBoundException,
NullPointerException, ArithmaticException

11)And can you explain when you are using Abstract classes?

 => An abstract class is used if you want to provide a common, implemented


functionality among all the implementations of the component. Abstract
classes will allow you to partially implement your class, whereas interfaces
would have no implementation for any members whatsoever.

12. What is user-defined exception in java? Explain garbage


collection? How you can force the garbage collection?

=>In Java, we can create our own exceptions that are derived classes of
the Exception class. Creating our own Exception is known as custom
exception or user-defined exception. Basically, Java custom exceptions
are used to customize the exception according to user need.

=>Garbage Collection is process of reclaiming the runtime unused


memory automatically. In other words, it is a way to destroy the unused
objects.

To do so, we were using free() function in C language and delete() in C++.


But, in java it is performed automatically. So, java provides better memory
management.

Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes


the unreferenced objects from heap memory.
o It is automatically done by the garbage collector (a part of JVM) so
we don't need to make extra efforts.

=> How to force Java garbage collection

While a developer can never actually force Java garbage collection, there
are ways to make the JVM prioritize memory management functions. In
review, five ways to try and force Java garbage collection are:

1. Call the System.gc() command.

2. Call the getRuntime().gc() command.

3. Use the jmap command.

4. Use the jcmd command.

5. Use JConsole or Java Mission Control.


14. Describe the wrapper classes in Java? What are different types of
inner classes?

=> Wrapper classes in Java provides a way to wrap or represent the value of primitive
data types as an object. By creating an object to the wrapper class, a data field is created
and in this field we can store the value of a primitive data type.
It also include methods to unwrap the objects back into the primitive data types. It is
one of the classes provided in the java.lang package and all of the primitive wrapper
classes in Java are immutable.

Primitive Data Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

char Character

=>

1. Nested Inner Class


2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes
17. What is synchronized keyword? In what situations we will Use it?
=> The synchronized keyword can be used to ensure that only one
thread at a time executes a particular section of code. This is a simple way
to prevent race conditions, which occur when several threads change
shared data at the same time in a way that leads to incorrect results.
With synchronized either entire methods or selected blocks can be
single-threaded.
18. What is serialization? What does the Serializable interface do?
=> Serialization is a mechanism of converting the state of an object into a
byte stream. Deserialization is the reverse process where the byte stream is
used to recreate the actual Java object in memory. This mechanism is used
to persist the object.
The Serializable interface is present in java.io package. It is a marker
interface. A Marker Interface does not have any methods and fields.
Thus classes implementing it do not have to implement any methods.
Classes implement it if they want their instances to be Serialized or
Deserialized. Serialization is a mechanism of converting the state of an
object into a byte stream. Serialization is done
using ObjectOutputStream.

19. What is the difference between ‘throw’ and ‘throws’? And it’s
application?
=>

S. Key
No. Difference throw throws

The throws keyword is


The throw keyword is used in the function
used inside a function. It signature. It is used when
is used when it is the function has some
Point of required to throw an statements that can lead to
1. Usage Exception logically. exceptions.
S. Key
No. Difference throw throws

The throws keyword can


be used to declare multiple
exceptions, separated by a
The throw keyword is comma. Whichever
used to throw an exception occurs, if
exception explicitly. It matched with the declared
Exceptions can throw only one ones, is thrown
2. Thrown exception at a time. automatically then.

Syntax of throw keyword


includes the instance of Syntax of throws keyword
the Exception to be includes the class names
thrown. Syntax wise of the Exceptions to be
throw keyword is thrown. Syntax wise throws
followed by the instance keyword is followed by
3. Syntax variable. exception class names.

throw keyword cannot


propagate checked
exceptions. It is only
used to propagate the
unchecked Exceptions
Propagation that are not checked throws keyword is used to
of using the throws propagate the checked
4. Exceptions keyword. Exceptions only.

=>Throw keyword throws the exception explicitly from a method or a block


of code, whereas the throws keyword is used in the signature of the method.

22) What do you understand by the java final keyword?

=> The final keyword is a non-access modifier used for


classes, attributes and methods, which makes them non-
changeable (impossible to inherit or override).

The final keyword is useful when you want a variable to


always store the same value, like PI (3.14159...).

The final keyword is called a "modifier".


24)In System.out.println() ,what is System, out and println? What are
Encapsulation, Inheritance and Polymorphism?
ava System.out.println() is used to print an argument that is passed to it.
The statement can be broken into 3 parts which can be understood
separately as:
1. System: It is a final class defined in the java.lang package.

2. out: This is an instance of PrintStream type, which is a public


and static member field of the System class.

3. println(): As all instances of PrintStream class have a public


method println(), hence we can invoke the same on out as
well. This is an upgraded version of print(). It prints any
argument passed to it and adds a new line to the output. We
can assume that System.out represents the Standard Output
Stream.

=>Encapsulation in Java is a process of wrapping code and data together


into a single unit, for example, a capsule which is mixed of several
medicines.
We can create a fully encapsulated class in Java by making all the data
members of the class private. Now we can use setter and getter methods
to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

=>In Java, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

=> Polymorphism in Java is a concept by which we can perform a single


action in different ways. Polymorphism is derived from 2 Greek words: poly
and morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism


and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.

29. What is the difference between a JDK (Java Development Kit) and a JVM
(Java Virtual Machine)? What is the base class of all classes? What is a package?
Which package is imported by default?

(25)What is JVM
It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.

Following are the important differences between JDK,JRE and JVM

Sr. Key JDK JRE JVM


No.

Definition JDK (Java JRE (Java Runtime JVM (Java Virtual


Development Kit) Environment) is the Machine) is an abstract
is a software implementation of machine that is platform-
development kit to JVM and is defined as dependent and has three
develop a software package notions as a specification,
applications in that provides Java a document that describes
Java. In addition to class libraries, along requirement of JVM
JRE, JDK also with Java Virtual implementation,
contains number of Machine (JVM), and implementation, a
1 development tools other components to computer program that
(compilers, run applications meets JVM requirements,
JavaDoc, Java written in Java and instance, an
Debugger etc.). programming. implementation that
executes Java byte code
provides a runtime
environment for executing
Java byte code.

Prime JDK is primarily On other hand JRE is JVM on other hand


functionality used for code majorly responsible specifies all the
execution and has for creating implementations and
2 prime functionality environment for code responsible to provide
of development. execution. these implementations to
JRE.

Platform JDK is platform Like of JDK JRE is JVM is platform


Independence dependent i.e for also platform independent.
different platforms dependent.
3 different JDK
required.
Sr. Key JDK JRE JVM
No.

Tools As JDK is On other hand JRE JVM does not include


responsible for does not contain tools software development
prime development such as compiler or tools.
so it contains tools debugger etc. Rather it
4
for developing, contains class libraries
debugging and and other supporting
monitoring java files that JVM requires
application. to run the program.

Implementation JDK = Java JRE = Java Virtual JVM = Only Runtime


Runtime Machine (JVM) + environment for executing
5 Environment (JRE) Libraries to run the the Java byte code.
+ Development application
tools

=> The super base class of all the Java classes is the
java.lang.Object class. In Java, each Java descends from the
Object.

=>lang Package. Java compiler imports java. lang package internally by


default.

A java package is a group of similar types of classes, interfaces and sub-


packages.

Package in java can be categorized in two form, built-in package and


user-defined package. Java package is used to categorize the classes and
interfaces so that they can be easily maintained. Java package provides
access protection. Java package removes naming collision.

7. What are Checked and UnChecked Exception?


1. a) What is multithreading? Write a program in Java to show the use of
multithreading. b) What is Applet? What is the difference between
Applet programming & Application Programming? C) Write a program
in Java to show the use of Applet? d) Clearly illustrate with an example
the difference between classes and objects. 2+3+1+3+4+2=15

=> Multithreading in Java is a process of executing two or more threads


simultaneously to maximum utilization of CPU. Multithreaded applications
execute two or more threads run concurrently. Hence, it is also known as
Concurrency in Java. Each thread runs parallel to each other. Mulitple
threads don’t allocate separate memory area, hence they save memory.
Also, context switching between threads takes less time .
Example of Multi thread:

package demotest;
public class GuruThread1 implements Runnable
{
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are
following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}
}

=>

Parameters Java Application Java Applet

Meaning A Java Application also known The Java applet works on the
as application program is a type client side, and runs on the
of program that independently browser and makes use of
executes on the computer. another application program so
that we can execute it.

Requirement of Its execution starts with the It does not require the use of any
main( ) method main( ) method only. The use of main() method. Java applet
the main( ) is mandatory. initializes through init( ) method.

Execution It cannot run independently, It cannot start independently but


but requires JRE to run. requires APIs for use (Example.
APIs like Web API).

Installation We need to install the Java Java applet does not need to be
application first and obviously pre-installed.
on the local computer.

Connectivity It is possible to establish It cannot establish connection to


with server connections with other servers. other servers.

Operation It performs read and write tasks It cannot run the applications on
on a variety of files located on a any local computer.
local computer.
File access It can easily access a file or data It cannot access the file or data
available on a computer system found on any local system or
or device. computer.

Security Java applications are pretty Java applets are less reliable. So,
trusted, and thus, come with no they need to be safe.
security concerns.

C) =>
1. import java.applet.Applet;
2. import java.awt.Graphics;
3. public class First extends Applet{
4.
5. public void paint(Graphics g){
6. g.drawString("welcome",150,150);
7. }
8.
9. }

No. Object Class

1) Object is an instance of a class. Class is a blueprint or


template from which
objects are created.

2) Object is a real world entity such as pen, laptop, Class is a group of similar
mobile, bed, keyboard, mouse, chair etc. objects.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly Class is declared using class
e.g. keyword e.g.
Student s1=new Student(); class Student{}

5) Object is created many times as per requirement. Class is declared once.


6) Object allocates memory when it is created. Class doesn't allocated
memory when it is created.

7) There are many ways to create object in java There is only one way to
such as new keyword, newInstance() method, define class in java using
clone() method, factory method and class keyword.
deserialization.
(Class is a detailed description, the definition, and the template of what an
object will be. But it is not the object itself. Also, what we call, a class is the
building block that leads to Object-Oriented Programming. It is a user-defined
data type, that holds its own data members and member functions, which can
be accessed and used by creating an instance of that class. It is the blueprint
of any object. Once we have written a class and defined it, we can use it to
create as many objects based on that class as we want. In Java, the class
contains fields, constructors, and methods. For example, consider
the Class of Accounts. There may be many accounts with different names
and types, but all of them will share some common properties, as all of them
will have some common attributes like balance, account holder name, etc.
So here, the Account is the class.
Object is an instance of a class. All data members and member functions of
the class can be accessed with the help of objects. When a class is defined,
no memory is allocated, but memory is allocated when it is instantiated (i.e. an
object is created). For Example, considering the objects for the
class Account are SBI Account, ICICI account, etc.) (Just for
understanding Rajarshi)
=>Any code as an example.

2. a) Explain function of a JVM in brief. b) What might be the difference in


functionality between a machine with only JDK installed and another
machine with only JRE installed? c) Discuss the requirement of each keyword
in the following JAVA program statement public static void main(String
args[]) d)”Multiple inheritance can be performed in JAVA” explain how?
Write a JAVA program in support of your views. 3+2+3+4+3=15

=> a)What is JVM?


Java Virtual Machine (JVM) is a engine that provides runtime environment to
drive the Java Code or applications. It converts Java bytecode into machines
language. JVM is a part of Java Runtime Environment (JRE). In other
programming languages, the compiler produces machine code for a particular
system. However, Java compiler produces code for a Virtual Machine known
as Java Virtual Machine.

How JVM Works?


First, Java code is compiled into bytecode. This bytecode gets interpreted on
different machines

Between host system and Java source, Bytecode is an intermediary language.

JVM in Java is responsible for allocating memory space.

b) If your machine has JRE, then it can run all java applets and applications, jre provides
environment for them to run.

While if your machine has jdk than you can also develop java applications.. It provides
compiler and debugger for development purpose..

Jdk is superset of jre.

What jre has, jdk has and more.

c) 1. Public

It is an Access modifier, which specifies from where and who can access the
method. Making the main() method public makes it globally available. It is
made public so that JVM can invoke it from outside the class as it is not
present in the current class.

2. Static

It is a keyword that is when associated with a method, making it a class-


related method. The main() method is static so that JVM can invoke it
without instantiating the class. This also saves the unnecessary wastage of
memory which would have been used by the object declared only for calling
the main() method by the JVM.
3. Void

It is a keyword and is used to specify that a method doesn’t return anything.


As the main() method doesn’t return anything, its return type is void. As soon
as the main() method terminates, the java program terminates too. Hence, it
doesn’t make any sense to return from the main() method as JVM can’t do
anything with the return value of it.

5. String[] args

It stores Java command-line arguments and is an array of


type java.lang.String class. Here, the name of the String array is args but it
is not fixed and the user can use any name in place of it.

d)C++ , Common lisp and few other languages supports multiple


inheritance while java doesn’t support it. Java doesn’t allow multiple
inheritance to avoid the ambiguity caused by it. One of the
example of such problem is the diamond problem that occurs in
multiple inheritance.
There are 2 reasons mentioned that will give you a idea why we
don’t have multiple inheritance in java.
1.The Diamond Problem
2.Simplicity
Although, multiple inheritance is no more a part of Java but still,
there is a way we can implement the same along with resolving the
ambiguity of the above-explained problem.
The solution to the problem is interfaces.
The only way to implement multiple inheritance is to implement
multiple interfaces in a class.
In java, one class can implements two or more interfaces. This also
does not cause any ambiguity because all methods declared in
interfaces are implemented in class
interface Interface1
{
public void show();
}
interface Interface2
{
public void show();
}
class SubClass implements Interface1, Interface2
{
public void show()
{
System.out.println("A class can implements more than one interfaces");
}
public static void main(String args[]){
SubClass obj = new SubClass();
obj.show();
}
}

3. a) Explain the advantages of Object Oriented programming over Procedure


Oriented Programming. b) What are major and minor elements? c) Describe
with example.Write a JAVA program to accept 3 command line arguments
and display the same in one line at the output. d) What is the difference
between method overloading & method overriding? 4+4+3+4=15
=>a)

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program In object-oriented programming, the


is divided into small parts program is divided into small parts
called functions. called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

Object-oriented programming has access


There is no access specifier in procedural specifiers like private, public, protected,
programming. etc.

Adding new data and functions is not


easy. Adding new data and function is easy.

Procedural programming does not have


any proper way of hiding data so it is less Object-oriented programming provides
secure. data hiding so it is more secure.

In procedural programming, overloading Overloading is possible in object-


is not possible. oriented programming.

In object-oriented programming, the


In procedural programming, there is no concept of data hiding and inheritance is
concept of data hiding and inheritance. used.

In procedural programming, the function In object-oriented programming, data is


is more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.

Procedural programming uses the concept Object-oriented programming uses the


of procedure abstraction. concept of data abstraction.
Procedural Oriented Programming Object-Oriented Programming

Code reusability absent in procedural Code reusability present in object-


programming, oriented programming.

Examples: C, FORTRAN, Pascal, Basic,


etc. Examples: C++, Java, Python, C#, etc.

b)major element: Encapsulation, modularity, abstraction and


hierarchy.
Minor element: Persistence, typing and concurrency.

d)

Method Overloading Method Overriding

Method overloading is a compile- Method overriding is a run-time


time polymorphism. polymorphism.

It is used to grant the specific


implementation of the method which is
It helps to increase the readability already provided by its parent class or
of the program. superclass.

It is performed in two classes with


It occurs within the class. inheritance relationships.

Method overloading may or may not Method overriding always needs


require inheritance. inheritance.

In method overloading, methods In method overriding, methods must


must have the same name and have the same name and same
different signatures. signature.
Method Overloading Method Overriding

In method overloading, the return


type can or can not be the same,
but we just have to change the In method overriding, the return type
parameter. must be the same or co-variant.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

It gives better performance. The


reason behind this is that the binding
Poor Performance due to compile of overridden methods is being done
time polymorphism. at runtime.

Private and final methods can be Private and final methods can’t be
overloaded. overridden.

Argument list should be different Argument list should be same in


while doing method overloading. method overriding.

4. a) What is interface? Why we use it? b)How can we implement multiple


inheritances in Java? c)Why Dynamic method dispatch is called run-time
polymorphism? Explain with suitable example. d) Explain the life cycle of an
Applet.

=>a) The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.

Java Interface also represents the IS-A relationship


b) See 2(d)
c)

 Dynamic method dispatch is also known as run time polymorphism.


 It is the process through which a call to an overridden method is resolved
at runtime.
 This technique is used to resolve a call to an overridden method at
runtime rather than compile time.
 To properly understand Dynamic method dispatch in Java, it is important
to understand the concept of upcasting because dynamic method dispatch
is based on upcasting.

Eg: class Phone{


public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){

System.out.println("Turning on Phone...");
}
}
class SmartPhone extends Phone{
public void music(){

System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}

}
public class CWH {
public static void main(String[] args) {

Phone obj = new SmartPhone(); // Yes it is allowed

// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not Allowed

}
}

d) Applet Life Cycle in Java


In Java, an applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.

The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has
five core methods namely init(), start(), stop(), paint() and destroy().These methods are
invoked by the browser to execute.

Along with the browser, the applet also works on the client side, thus having less
processing time.
o init(): The init() method is the first method to run that initializes the applet. It
can be invoked only once at the time of initialization. The web browser creates
the initialized objects, i.e., the web browser (after checking the security settings)
runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time
the browser is loaded or refreshed, the start() method is invoked. It is also
invoked whenever the applet is maximized, restored, or moving from one tab
to another in the browser. It is in an inactive state until the init() method is
invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method
is invoked whenever the applet is stopped, minimized, or moving from one tab
to another in the browser, the stop() method is invoked. When we go back to
that page, the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the
webpage is closed. It removes the applet object from memory and is executed
only once. We cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to
draw shapes like circle, square, trapezium, etc., in the applet. It is executed after
the start() method and when the browser or applet windows are resized.
6. a) Differentiate between 'up casting' and 'down casting' with
suitable examples. b) What is thread? Explain thread creation
methods. c) How does synchronized keyword works? Why is thread
synchronization important for Multithreaded process? d)What are
packages and what are they used for? 3+4+4+4=15
=>a) https://www.geeksforgeeks.org/upcasting-vs-downcasting-in-
java/
b) In java, a thread is a lightweight process. Every java program executes by a thread called
the main thread. When a java program gets executed, the main thread created automatically.
All other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.

 Using Thread class (by extending Thread class)


 Uisng Runnable interface (by implementing Runnable interface)

Let's see how to create threads using each of the above.

Extending Thread class


The java contains a built-in class Thread inside the java.lang package. The Thread class
contains all the methods that are related to the threads.
To create a thread using Thread class, follow the step given below.

 Step-1: Create a class as a child of Thread class. That means, create a class that extends
Thread class.
 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Call the start( ) method on the object created in the above step.

Look at the following example program.

Example
class SampleThread extends Thread{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
System.out.println("Thread about to start...");
t1.start();
}
}

Implementng Runnable interface


The java contains a built-in interface Runnable inside the java.lang package. The Runnable
interface implemented by the Thread class that contains all the methods that are related to the
threads.
To create a thread using Runnable interface, follow the step given below.

 Step-1: Create a class that implements Runnable interface.


 Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
 Step-3: Create the object of the newly created class in the main( ) method.
 Step-4: Create the Thread class object by passing above created object as parameter to
the Thread class constructor.
 Step-5: Call the start( ) method on the Thread class object created in the above step.

Look at the following example program.

Example
class SampleThread implements Runnable{

public void run() {


System.out.println("Thread is under Running...");
for(int i= 1; i<=10; i++) {
System.out.println("i = " + i);
}
}
}

public class My_Thread_Test {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread thread = new Thread(threadObject);
System.out.println("Thread about to start...");
thread.start();
}

c) The synchronized keyword can be used to ensure that only one


thread at a time executes a particular section of code. This is a simple way
to prevent race conditions, which occur when several threads change
shared data at the same time in a way that leads to incorrect results.
With synchronized either entire methods or selected blocks can be
single-threaded.

In java, when two or more threads try to access the same resource
simultaneously it causes the java runtime to execute one or more
threads slowly, or even suspend their execution. In order to overcome
this problem, we have thread synchronization.
Synchronization means coordination between multiple
processes/threads.

Thread synchronization basically refers to The concept of one thread


execute at a time and the rest of the threads are in waiting state. This
process is known as thread synchronization. It prevents the thread
interference and inconsistency problem.
Synchronization is build using locks or monitor. In Java, a monitor is an
object that is used as a mutually exclusive lock. Only a single thread at
a time has the right to own a monitor. When a thread gets a lock then
all other threads will get suspended which are trying to acquire the
locked monitor. So, other threads are said to be waiting for the monitor,
until the first thread exits the monitor. In a simple way, when a thread
request a resource then that resource gets locked so that no other
thread can work or do any modification until the resource gets released.

=>d) Package in Java is a mechanism to encapsulate a group of


classes, sub packages and interfaces. Packages are used for:
 Preventing naming conflicts. For example there can be two
classes with name Employee in two packages,
college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces,
enumerations and annotations easier
 Providing controlled access: protected and default have
package level access control. A protected member is
accessible by classes in the same package and its subclasses.
A default member (without any access specifier) is accessible
by classes in the same package only.
 Packages can be considered as data encapsulation (or data-
hiding)

7. a) Explain Data Abstraction with example.


=>Data abstraction is a programming and design tool that displays basic
information about a device while hiding its internal functions. Users can
look at an interface and determine how a machine works, but they're
unable to see how the machine can actually respond to their commands.
In other words, they can understand what a machine does, but not how
it's doing it.

For example, when using a cell phone, you can figure out how to answer
incoming calls and respond to text messages.

c) What is constructor? What are the properties of the constructor?.? Write a


program to show the use of Constructor. d) What is inheritance? How many
types of inheritances are there? Explain them with Diagram.

=>A constructor is a special member function of a class with the same


name as the class name. Whenever an object of a class is created using
a new keyword, it invokes a constructor of that class.
Features of Constructors in Java:

 The constructor name has the same as the Class


Name. Explanation: Compiler uses this character to differentiate
constructors from the other member functions of the class.
 A constructor must not have any return type. Not even
void. Explanation: It automatically calls and is commonly used for
initializing values.
 The constructor automatically gets calls when an object
creates for the class.
 Unlike, Constructors in C++, Java doesn’t allow the constructor
definition outside the class.
 Constructors usually make use to initialize all the data
members (variables) of the class.
 In addition, more than one constructor can also declare inside a class
with different parameters. It’s called “Constructor Overloading.”

 class Bike1{
 //creating a default constructor
 Bike1(){System.out.println("Bike is created");}
 //main method
 public static void main(String args[]){
 //calling a default constructor
 Bike1 b=new Bike1();
 }
 }

=>Inheritance in Java is a mechanism in which one object acquires all


the properties and behaviors of a parent object. It is an important part
of OOPs

(Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class,
you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.
9. a) What is “this” Keyword? Why we use this keyword? b) What
are wrapper classes? C) Difference between String class and
StringBuffer class.d) When do we declare a method or class
final?e)Explain Nested class with proper example. 4+2+4+2+3=15

=>The this keyword refers to the current object in a method or


constructor.

The most common use of the this keyword is to eliminate the


confusion between class attributes and parameters with the
same name (because a class attribute is shadowed by a
method or constructor parameter). If you omit the keyword in
the example above, the output would be "0" instead of "5".

this can also be used to:

 Invoke current class constructor


 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

=>The wrapper class in Java provides the mechanism to convert


primitive into object and object into primitive.

=>given below:

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

2) String is slow and consumes more memory StringBuffer is fast and consumes
when we concatenate too many strings because less memory when we
every time it creates new instance. concatenate t strings.
3) String class overrides the equals() method of StringBuffer class doesn't
Object class. So you can compare the contents override the equals() method of
of two strings by equals() method. Object class.

4) String class is slower while performing StringBuffer class is faster while


concatenation operation. performing concatenation
operation.

5) String class uses String constant pool. StringBuffer uses Heap memory

d)The main purpose of using a class being declared as final is to prevent the
class from being subclassed. If a class is marked as final then no class can
inherit any feature from the final class.

e) Java inner class or nested class is a class that is declared inside the class or
interface.

We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

Additionally, it can access all the members of the outer class, including private data
members and methods.

1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
1. Nested classes represent a particular type of relationship
that is it can access all the members (data members and
methods) of the outer class, including private.
2. Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3. Code Optimization: It requires less code to write.
a) Garbage Collection in JAVA: Garbage collection in Java is the process by
which Java programs perform automatic memory management. Java
programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM,
objects are created on the heap, which is a portion of memory
dedicated to the program. Eventually, some objects will no longer be
needed. The garbage collector finds these unused objects and deletes
them to free up memory. Java garbage collection is an automatic
process. Automatic garbage collection is the process of looking at heap
memory, identifying which objects are in use and which are not, and
deleting the unused objects. An in-use object, or a referenced object,
means that some part of your program still maintains a pointer to that
object. An unused or unreferenced object is no longer referenced by
any part of your program. So the memory used by an unreferenced
object can be reclaimed. The programmer does not need to mark objects
to be deleted explicitly. The garbage collection implementation lives in
the JVM.

b) JAVA Virtual Machine: t is:

1. A specification where working of Java Virtual Machine is specified.


But implementation provider is independent to choose the
algorithm. Its implementation has been provided by Oracle and
other companies.
2. An implementation Its implementation is known as JRE (Java
Runtime Environment).
3. Runtime Instance Whenever you write java command on the
command prompt to run the java class, an instance of JVM is created.

c) Association:

=> Association in Java defines the connection between two classes that
are set up through their objects. Association manages one-to-one, one-
to-many, and many-to-many relationships. In Java, the multiplicity
between objects is defined by the Association. It shows how objects
communicate with each other and how they use the functionality and
services provided by that communicated object. Association
manages one-to-one, one-to-many, many-to-one and many-to-
many relationships. Let's take an example of each relationship to manage
by the Association.

1. A person can have only one passport. It defines the one-to-one


2. If we talk about the Association between a College and Student, a
College can have many students. It defines the one-to-many
3. A state can have several cities, and those cities are related to that
single state. It defines the many-to-one
4. A single student can associate with multiple teachers, and multiple
students can also be associated with a single teacher. Both are
created or deleted independently, so it defines the many-
to-many

d) Aggregation: When an object A contains a reference to another object B or


we can say Object A has a HAS-A relationship with Object B, then it is termed
as Aggregation.
Aggregation helps in reusing the code. Object B can have utility methods and
which can be utilized by multiple objects. Whichever class has object B then it
can utilize its methods.

Example

public class Vehicle{}


public class Speed{}

public class Van extends Vehicle {


private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed,
we do not have to put the entire code that belongs to speed inside the Van class,
which makes it possible to reuse the Speed class in multiple applications.
In the Object-Oriented feature, the users do not need to bother about which object
is doing the real work. To achieve this, the Van class hides the implementation
details from the users of the Van class. So, basically what happens is the users
would ask the Van class to do a certain action and the Van class will either do
the work by itself or ask another class to perform the action. This concept of
containing an object to do action is termed as Aggregation.

e) Abstraction: Data abstraction is the process of hiding certain details


and showing only essential information to the user.
Abstraction can be achieved with either abstract
classes or interfaces (which you will learn more about in the next chapter).

The abstract keyword is a non-access modifier, used for classes and


methods:

 Abstract class: is a restricted class that cannot be used to create


objects (to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does


not have a body. The body is provided by the subclass (inherited
from).

An abstract class can have both abstract and regular methods:

abstract class Animal {

public abstract void animalSound();

public void sleep() {

System.out.println("Zzz");

h) Exception handler: The Exception Handling in Java is one of the


powerful mechanism to handle the runtime errors so that the normal flow of the
application can be maintained. he core advantage of exception handling is to
maintain the normal flow of the application. An exception normally disrupts the
normal flow of the application; that is why we need to handle exceptions There are
mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of
exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Encapsulation:(age ache)
Inheritance: (ager ta)
Wrapper Class. (age)
String Tokenizer Class. The string tokenizer class allows an
application to break a string into tokens. The tokenization
method is much simpler than the one used by
the StreamTokenizer class.
The StringTokenizer methods do not distinguish among
identifiers, numbers, and quoted strings, nor do they recognize
and skip comments
import java.util.*;
public class Sample {
public static void main(String[] args) {
// creating string tokenizer
StringTokenizer st = new StringTokenizer("Come to learn");
// checking next token
System.out.println("Next token is : " + st.nextToken());
}
}

Output
Next token is : Come

12)Write the differences between interface and abstract


class.

=>
Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Part c
1. What are main differences of Structured Programming Language and Object oriented
programming language? Why Java is so important to the internet? 3+2 [8+5 Minutes]
Importance of Java to the Internet
Java has had a profound effect on the Internet because it allows objects to move freely in
Cyberspace. In a network there are two categories of objects that are transmitted between the
Server and the Personal computer.

Passive information

Dynamic active programs

The Dynamic Self-executing programs cause serious problems in the areas of Security and
probability. But Java addresses those concerns and by doing so has opened the door to an
exciting new form of program called the Applet.

2 Which members are called static members? When do all static members get memory
location and by whom? 2+3[5+8 Minutes]
3 What is the order of execution of all static variables? What is the lifetime and scope of
static variable? 2+3[5+8 Minutes]
Ans : When you have all the three in one class, the static blocks are executed first, followed by
constructors and then the instance methods.
A static variable stays in the memory and retains its value until the program execution ends
irrespective of its scope. Scope is of four types: file, block, function and prototype
scope. Lifetime is of three types: static, auto and dynamic lifetime
4. How JVM execute the static variables before its main method even if it is defined after the
main method? Can we declare local variable or parameters as static? Explain. 3+2[8+5
Minutes]
Ans:- First, JVM executes the static block, then it executes static methods, and then it creates the
object needed by the program. Finally, it executes the instance methods. JVM executes a static
block on the highest priority basis. It means JVM first goes to static block even before it looks for
the main() method in the program.

Eg-
You can use Static only on local variables. This means the declaration context for a Static
variable must be a procedure or a block in a procedure, and it cannot be a source file, namespace,
class, structure, or module.
5. Show the JVM architecture of static variables. When a method is called as static method?
Can we nest static blocks? 2+3[8+5 Minutes]

Static methods are the methods in Java that can be called without creating an object of class.
They are referenced by the class name itself or reference to the Object of that class.
Both, nesting of instance and static blocks, does not make sense - and both is not allowed.
6. What is the order of execution of static variable, static block, static method and main
method? When user defined methods should declare as static methods? 3+2[8+5 Minutes]

Order of execution
When you have all the three in one class, the static blocks are executed first, followed
by constructors and then the instance methods.
You should consider making a method static in Java : 1) If a method doesn't modify the state of
the object, or not using any instance variables. 2) You want to call the method without creating
an instance of that class.
Overloading and overriding
7. Why Dynamic method dispatch is called run-time polymorphism? Why java does not
support operator overloading? 3+2[8+5 Minutes]

8. Why static method can’t be overloaded? Can we override constructor? Explain 3+2 [8+5
Minutes
Overloading: Overloading is also a feature of OOP languages like Java that is
related to compile-time (or static) polymorphism. This feature allows different
methods to have the same name, but different signatures, especially the number
of input parameters and type of input parameters. Note that in both C++ and
Java, methods cannot be overloaded according to the return type.
Can we overload static methods?
The answer is ‘Yes’. We can have two or more static methods with the same
name, but differences in input parameters. For example, consider the following
Java program.
Constructor looks like method but it is not. It does not have a return type and its name is same
as the class name.
But, a constructor cannot be overridden. If you try to write a super class’s constructor in the
sub class compiler treats it as a method and expects a return type and generates a compile time
error.

9. Can we overload the main method? Give reason to support your answer. What is the
difference between compile time and runtime polymorphism? 2+3[5+8 Minutes]

Yes, we can overload the main() method in Java. A Java class can have any number of
overloaded main() methods. But the very first thing JVM (Java Virtual Machine) seeks is the
original main() method, i.e., public static void main(String[] args) to execute. The class
will compile but won't run without the original main() method.

The main method is a special method in Java that acts as an entry point for running any Java
program. It always has the same syntax, i.e., public static void main (String[] args). One
can only change the name of the String array argument, for example, args as str.

As JVM starts its execution by invoking the main method of the class, so, it must have
an exact signature as mentioned above. The following methods are overloaded main method:

public static void main (String args)


public static void main (Integer[] args)
public static void main (int a, int b)
In compile-time polymorphism, the compiler resolves the method call at compile-time (static
binding). In runtime polymorphism, it is resolved at runtime(dynamic binding) by the JVM.

Inheritance
10. Why java class does not support multiple inheritances? Why subclass variable can’t
refer to super class object? 3+2 [8+5 Minutes]

Because an instance of the superclass isn't (necessarily) an instance of a subclass. For example, a
Parrot is an Animal , but not every Animal is a Parrot .
Blocks
11. Can we write a program without main method? Why static blocks are executed only
once where as instance blocks are executed for each object? 2+3[5+8 Minutes]

When we execute a particular class, JVM performs two actions at the runtime. They are as:

1. JVM loads the corresponding dot class file (byte code) into memory.

2. During the dot class file loading into memory, a static block is executed. After loading the dot
class file, JVM calls the main method to start execution. Therefore, the static block is executed
before the main method.

or in simple word’s we can also say that static block always gets executed first in Java
because it is stored in the memory at the time of class loading and before the object
creation.

First, JVM executes the static block, then it executes static methods, and then it creates the
object needed by the program. Finally, it executes the instance methods. JVM executes a
static block on the highest priority basis. It means JVM first goes to static block even before
it looks for the main() method in the program.
Final keyword
12. Explain why abstract class can’t be declared as Final. If a class is declared as final
whether all its members are final? Explain 3+2[8+5 Minutes

Abstract keyword
13. When we will use an Interface and an Abstract class? Does abstract class have
constructor? 3+2 [8+5 Minutes]
An abstract class is used if you want to provide a common, implemented functionality among all
the implementations of the component. Abstract classes will allow you to partially implement
your class, whereas interfaces would have no implementation for any members whatsoever.
As we all know abstract classes also do have a constructor. So if we do not define any
constructor inside the abstract class then JVM (Java Virtual Machine) will give a default
constructor to the abstract class.
Inner class
14. What are the advantages and disadvantages of using inner classes? If you compile a file
containing inner class how many .class files are created and can we access them accessible in
usual way? 3+2 [8+5 Minutes]
Advantage:- Note that inner classes can access outer class private members and at the same
time we can hide inner class from outer world. Keeping the small class within top-level classes
places the code closer to where it is used and makes the code more readable and maintainable
Disadvantage:- Inner classes have their disadvantages. From a maintenance point of
view, inexperienced Java developers may find the inner class difficult to understand. The use of
inner classes will also increase the total number of classes in your code.
Two files are created will be created. Though a separate inner class file is generated, the inner
class file is not accessible in the usual way.
15. Can you define a class without name? What are different types of anonymous classes
and do anonymous classes have constants? 2+3 [5+8 Minutes]

Yes, we can create a class without a name using the Anonymous class.
Anonymous class is an inner class which does not have a name and whose instance is created
at the time of the creation of class itself and these classes are somewhat different from normal
classes in its creation.

An anonymous class can have static members provided that they are constant variables.
16. Can anonymous class define method of its own? Can an anonymous can implement an
interface and also extend a class at the same time? 2+3 [5+8 Minutes]

A normal class can implement any number of interfaces but the anonymous inner class can
implement only one interface at a time. A regular class can extend a class and implement any
number of interfaces simultaneously. But anonymous Inner class can extend a class or can
implement an interface but not both at a time.

Interface
17. Can we compile and execute interface? Can interface have concrete members? Can we
declare interface method as private and protected? Why interface members are by default
public? 2+3 [5+8 Minutes]
 Open a command prompt and navigate to the directory containing your Java program. Then
type in the command to compile the source and hit Enter . The interface is now ready to be
implemented by a Java program. The Java program declares that it will implement the interface
by using the implements keyword.
 All the methods in an interface must be abstract, you cannot have a concrete method (the one
which has body) if you try to do so, it gives you a compile time error saying “interface abstract
methods cannot have body”.
 In general, the protected fields can be accessed in the same class or, the class inheriting it. But,
we do not inherit an interface we will implement it. Therefore, cannot declare the fields of an
interface protected.
 Default methods are defined with the default modifier, and static methods with the static
keyword. All abstract, default, and static methods in an interface are implicitly public , so you can
omit the public modifier. In addition, an interface can contain constant.
18. Can we create an empty interface? What is the marker interface, what are the
predefined marker interfaces? What is the use of an interface? 2+3 [5+8 Minutes]
 An empty interface in Java is known as a marker interface i.e. it does not contain any methods
or fields by implementing these interfaces a class will exhibit a special behavior with respect to
the interface implemented. java. lang. Cloneable and java.
 A marker interface is an interface that doesn't have any methods or constants inside it. It
provides run-time type information about objects, so the compiler and JVM have additional
information about the object. A marker interface is also called a tagging interface.

 Interfaces are useful for the following: Capturing similarities among unrelated classes without
artificially forcing a class relationship. Declaring methods that one or more classes are expected
to implement. Revealing an object's programming interface without revealing its class.
Enum keyword
19. Explain the advantages of enum? Can we create a normal variables, methods, blocks
and constructors in enum? 2+3 [5+8 Minutes]
Enumerations in Java can be compared usign == operator. Safe comparison because enum
constants are static and final by default. We can use enum parameter in a switch case. This makes
constants driven computations better and faster.
 It can have constructors, methods and instance variables. It is created using the enum keyword.
By default, each enumeration constant is public, static and final. Even though enumeration defines
a class type and has constructors, you do not need to instantiate an enum using the new variable.
20. Write the difference between default constructor in class and enum? Can we create
object of enum like normal class and can create enum from another enum? 2+3
[5+8Minutes]
 Difference between Enums and Classes
The only difference is that enum constants are public , static and final (unchangeable - cannot be
overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can
implement interfaces).

 An enum can, just like a class , have attributes and methods. The only difference is that enum
constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be
used to create objects, and it cannot extend other classes (but it can implement interfaces).

Package
21. Why package concept is useful in JAVA? What are the difference between
a. import pkg.*;
b. import pkg.C; 2+3[5+8 Minutes]
Make easy searching or locating of classes and interfaces. Implement data encapsulation (or
data-hiding). Provide controlled access: The access specifiers protected and default have access
control on package level.


22. How to access non packaged classes from packaged class? Explain static imports in
JAVA. 2+3[5+8 Minutes]

There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
In Java, static import concept is introduced in 1.5 version. With the help of static
import, we can access the static members of a class directly without class name or any
object. For Example: we always use sqrt() method of Math class by using Math class
i.e. Math.sqrt(), but by using static import we can access sqrt() method directly.
According to SUN microSystem, it will improve the code readability and enhance coding.
But according to the programming experts, it will lead to confusion and not good for
programming. If there is no specific requirement then we should not go for static import.
Thread
23. Why multithreading is so important with respect to OS? What thread is called light
weight process? 3+2 [8+5 Minutes]
Multithreading in an interactive application may allow a program to continue running even if a
part of it is blocked or is performing a lengthy operation, thereby increasing responsiveness to the
user.

Threads are sometimes called lightweight processes because they have their own stack but can
access shared data. Because threads share the same address space as the process and other threads
within the process, the operational cost of communication between the threads is low, which is an
advantage.
24. What are the differences between multithreading and multiprocessing? Why
synchronization is so important in real life? 3+2 [5+8 Minutes]

Data synchronization ensures accurate, secure, compliant data and successful team and customer
experiences. It assures congruence between each source of data and its different endpoints. As data
comes in, it is cleaned, checked for errors, duplication, and consistency before being put to use. Local
synchronization involves devices and computers that are next to each other, while remote
synchronization takes place over a mobile network.

Data must always be consistent throughout the data record. If data is modified in any way, changes
must upgrade through every system in real-time to avoid mistakes, prevent privacy breaches, and
ensure that the most up-to-date data is the only information available. Data synchronization ensures
that all records are consistent, all the time.
Exception handling
25. Why exception handling mechanism has been introduced in java? Explain. Does finally
block executes always? 3+2 [8+5 Minutes]

It is one of the powerful mechanisms to handle runtime exceptions and makes it bug-free.
Exception handling helps in maintaining the flow of the program. An exception handling is
defined as an abnormal condition that may happen at runtime and disturb the normal flow of
the program.
Checked Exceptions: Unchecked Exceptions
Occur at compile time: Occur at runtime
Can be handled at the compilation time: Can’t ...
 The finally block always executes when the try block exits. This ensures that the finally block is
executed even if an unexpected exception occurs.
26. Does catch block is mandatory for every try block? Explain. When NullPointerException is
thrown? Explain. 3+2 [8+5 Minutes]
Yes, It is possible to have a try block without a catch block by using a final block.
As we know, a final block will always execute even there is an exception occurred in a try
block, except System.exit() it will execute always.

Class NullPointerException
Thrown when an application attempts to use null in a case where an object is required. These
include: Calling the instance method of a null object. Accessing or modifying the field of a null
object. Taking the length of null as if it were an array.
Applet
27. Why Applets are not being used today? Explain. What is the order of method invocation in
an Applet? 2+3[5+8 Minutes]
Applets are a technology that are very much of their time, and they have not aged well. The
technology proved to be very difficult to evolve, and so applets have not been considered to be a
modern development platform for many years now.
 It basically has five core methods namely init(), start(), stop(), paint() and destroy().These
methods are invoked by the browser to execute. Along with the browser, the applet also works on the
client side, thus having less processing time.

28. How will you communicate between two Applets? Can Applet have constructors? 3+2[8+5
Minutes]
A Java applet can communicate with other Java applets by using JavaScript functions in the parent
web page. JavaScript functions enable communication between applets by receiving messages from
one applet and invoking methods of other applets.
 Applets can have a default constructor, but it is better to perform all initializations in the init
method instead of the default constructor. This method is automatically called after Java calls the init
method.
Event handling
29. What is the difference between panel and frame? What is the default layout of the panel and
frame? 3+2 [8+5 Minutes]
1. Panel requires a Frame to display it. A frame can consist of a panel or a set of panels.

2. A-frame is a top-level window. It has a title bar, menu bar, borders, and resizing corners.

3. A Panel is a subclass of Container while Frame is a subclass of Window.

4. Frame is used for standalone desktop applications.

5. Panel is a component object containing another component object.

6. Panel represents an area used for more complex operations or applications

Panel uses FlowLayout as default layout manager while Frame uses BorderLayout as
default layout manager

Arial
30. Applet using AWT or using Swing which one is better and why? Explain. What is the difference
between an applet and a Japplet? 3+2 [8+5 Minutes]

Java AWT has comparatively less functionality as compared to Swing. Java Swing has
more functionality as compared to AWT

AWT doesn't support pluggable look and feel.

Swing supports pluggable look and feel. AWT provides less components than Swing.
Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.

 A JApplet expects to be embedded in a page and used in a viewing environment that


provides it with resources. In all other respects, however, applets are just ordinary Panel
objects.

You might also like