[go: up one dir, main page]

0% found this document useful (0 votes)
16 views34 pages

OOPP Question Bank

Oops

Uploaded by

mmegala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views34 pages

OOPP Question Bank

Oops

Uploaded by

mmegala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

UNIT I INTRODUCTION TO OBJECT ORIENTED PROGRAMMING AND JAVA

Introduction to Object Oriented Programming concepts: Class, Object, Encapsulation,


Polymorphism, Inheritance, Abstraction; Overview of Java - Difference between C and Java-
Java Buzzwords –– Programming Structures in Java - Data Types, Variables and Arrays –
Operators – Control Statements –– Defining classes in Java – Constructors: Types of
constructors – Constructor Overloading – Constructor Chaining - Methods – Access specifiers
– this keyword - Static members - Packages – Packages and Member Access –Importing
Packages.
PART -A
1 List the four cornerstones of OOP.
Abstraction: Can manage complexity through abstraction. Gives the complete
overview of a particular task and the details are handled by its derived classes.
Ex : Car.
Encapsulation: Nothing but data hiding, like the variables declared under private
of a particular class is accessed only in that class and cannot access in any other the
class.
Inheritance: Is the process in which one object acquires the properties of another
object, ie., derived object.
Polymorphism: One method different forms, ie., method overriding and interfaces
are the examples of polymorphism.
2 What are the OOP Principles?
The principles of object-oriented programming: Class
inheritance, interface implementation, abstraction of data and behavior,
encapsulation of data and class implementation, polymorphism and virtual
methods.
3 Illustrate any 4 differences between C and Java.
C Java
C is a procedural Language Java is Object Oriented Language
C is a compiled language. Java is an Interpreted language
C uses the top-down JAVA uses The bottom-up {on the
{sharp smooth} approach rocks}approach.
C does not support overloading JAVA supports Method Overloading
4 What are the features of Object Oriented Programming?
✓ Emphasis is on data rather than procedure.
✓ Programs are divided into objects.
✓ Data structures are designed such that they characterize the objects.
✓ Functions that operate on the data of an object are tied together.
✓ Data is hidden and cannot be accessed by external functions.
✓ Objects may communicate with each other through functions.
✓ New data and functions can easily be added whenever necessary.

1
✓ Follows bottom-up approach.
5 Modify the following while loop into for loop
int n=10;
int i=1;
while(n>5)
{ i=i*2; n=n+2; }
System.out.println(i);

Answer:
int n = 10;
int i = 1;
for ( n > 5; n = n + 2) {
i = i * 2;
}
System.out.println(i);

✓ The initialization of i and n is done before the for loop starts.


✓ The condition n > 5 is used to control the loop's execution.
✓ The update expression n = n + 2 is included in the for loop to adjust n on each
iteration.
✓ The loop body (i = i * 2;) remains the same as in the while loop.

This for loop will achieve the same result as the original while loop.
6 What are the features of Java Language?
The features of Java Language are Simple, Object-Oriented, Portable, Platform
independent, Secured, Robust, Architecture neutral, Dynamic, Interpreted, High
Performance, Multithreaded and Distributed.
Infer how Java supports platform independency.
7 ✓ The meaning of platform independent is that, the java source code can run on
all operating systems. a compiler is a program that translates the source code
for another program from a programming language into executable code.
✓ This executable code may be a sequence of machine instructions that can be
executed by the CPU directly, or it may be an intermediate representation that is
interpreted by a virtual machine. This intermediate representation in Java is the
Java Byte Code.
✓ It is the Bytecode that makes it platform independent. This adds to an
important feature in the JAVA language termed as portability. Every system
has its own JVM which gets installed automatically when the jdk software is
installed. For every operating system separate JVM is available which is
capable to read the .class file or byte code. An important point to be noted is
✓ that while JAVA is platform-independent language, the JVM is platform-
dependent.
8 Give the contents of Java Environment (JDK).
2
✓ The Java Development Kit (JDK) is a software development environment
used for developing Java applications and applets.
✓ It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a
compiler (javac), an archiver (jar), a documentation generator (javadoc) and
other tools needed in Java development.
9 Give any 4 differences between C++ and Java.
C++ Java
C++ generates object code and the Java is interpreted for the most part and
same code may not run on different hence platform independent.
platforms.
C++ supports structures, unions, Java does not support pointers, templates,
templates, operator overloading, unions, operator overloading, structures
pointers and pointer etc.
arithmetic.
C++ support destructors, is Java support automatic garbage
which is collection. It does not support destructors
automatically invoked when the as C++ does.
object destroyed.
10 Explain about the get Property() and set Property() of beans in jsp.
✓ The setProperty and getProperty action tags are used for developing web
application with Java Bean. In web devlopment, bean class is mostly used
because it is a reusable software component that represents data.
✓ The jsp:setProperty action tag sets a property value or values in a bean using
the setter method.
<jsp:setProperty name=”bean” property=”username” />
✓ The jsp:getProperty action tag returns the value of the property.
<jsp:getProperty name=”obj” property=”name” />
11 Distinguish between procedure oriented programming (POP) and
Object oriented programming.(OOP)
POP OOP
In POP, program is divided into In OOP, program is divided into parts
small parts called
called functions. objects.
POP does not have any access OOP has access specifiers named Public,
specifier. Private, Protected, etc.
POP does not have any proper OOP provides Data Hiding so provides
way for hiding more
data so it is less secure. security.
In POP, Overloading is not In OOP, overloading is possible in the
possible. form of Function Overloading and
Operator Overloading.

3
In POP, Most function uses In OOP, data cannot move easily from
Global data for sharing that can function to function, it can be kept public
be accessed freely from function or private so we can control the access of
to function in the system. data.
Example of POP are : C, VB, Example of OOP are : C++, JAVA,
FORTRAN, VB.NET,
Pascal C#.NET.
12 What are the data types supported in Java?
Operator in java is a symbol that is used to perform operations. For example: +, -,
*, / etc. There are many types of operators in java which are Unary Operator,
Arithmetic Operator, Shift Operator, Relational Operator, Bitwise Operator,
Logical Operator, Ternary Operator and, Assignment Operator
13 Define Abstraction.
Abstraction refers to the act of representing the essential features without
including the background details or explanations. It reduces the complexity and
increases the efficiency. Small programs can be easily upgraded to large programs.
Software complexity can easily be managed
14 What is Polymorphism?
Polymorphism is the ability to take more than one form and refers to an operation
exhibiting different behavior instances. Object oriented programs use
polymorphism to carry out the same operation in a manner customized to the
object. It allows a single name/operator to be associated with different operation
depending on the type of data passed to it.
15 Define Objects and Classes in Java
Each class is a collection of data and the function that manipulate the data.The data
components of the class are called data fields and the function components of the
class are called member functions or methods. The class that contains main
function is called main class.
Object is an instance of a class. The objects represent real world entity. The objects
are used to provide a practical basis for the real world. Objects are used to
understand the real world. The object can be declared by specifying the name of
the class.
Write the syntax for declaration of class and creation of objects?
16 A class is declared using class keyword. A class contains both data and method
that operate on that data. Thus, the instance variables and methods are known as
class members. When creating an object from a class
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor.This
call initializes the new object.
class Student
{

4
String name;
int rollno;
int age;
}
Student std=new Student();
• std is instance/object of Student class.
• new keyword creates an actual physical copy of the object and assign it to the
std variable.
The new operator dynamically allocates memory for an object.
17 Define Encapsulation
The wrapping up of data and functions into a single unit is known as data
encapsulation. Here the data is not accessible to the outside the class. The data
inside that class is accessible by the function in the same class. It is normally not
accessible from the outside of the component.

What are the steps for execution of a java program?


18 A program is written in JAVA, the javac compiles it.The result of the JAVA
compiler is the .class file or the bytecode and not the machine native code (unlike
C compiler).
The bytecode generated is a non-executable code and needs an interpreter to execute
on a machine. This interpreter is the JVM and thus the Bytecode is executed by the
JVM.
And finally program runs to give the desired output.

19 What do you mean by BYTECODE? What is JVM and JIT?


Bytecode is an intermediate form of java programs.We get bytecode after
compiling the java program using a compiler called javac. The bytecode is to be
executed by java runtime environment which is called as Java Virtual
Machine(JVM). The programs that are running on JVM must be compiled into a
binary format which is denoted by .class files. The JVM executes
.class or .jar files, by either interpreting it or using a just-in-time compiler (JIT).
5
The JIT is used for compiling and not for interpreting the file. It is used in most
JVMs today to achieve greater
speed.
20 What is array? How to declare array and how to allocate the memory to for array?
Java array contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
data_type array_name [];
and to allocate the memory-
array_name=new data_type[size];
where array_name represent name of the array, new is a keyword used to allocate the
memory for arrays, data_type specifies the data type of array elements and size
represents the size of an array.
For example:int a=new int[10];
PART – B
1 Explain the various features of the Object Oriented Programming Language
2 Explain the Concepts of the Object Oriented Programming Language
3 i) Describe the typical java program structure.
ii) Explain the general java program compilation and execution.
4 Discuss in detail the access specifiers available in Java.
5 Explain Constructors with examples.
6 Explain in detail the various operators in Java.
7 Illustrate in detail about static variable and static method in Java with example
8 Write a Java program to sort set of names stored in an array in alphabetical order
9 Create a simple Java program to implement basic Calculator operations
10 Develop a Java Program to find i) Largest of three numbers using Ternary
Operator ii) Smallest of three numbers using Ternary Operator

6
UNIT II INHERITANCE, ABSTRACT CLASSES AND INTERFACES
Overloading Methods - Inheritance: Basics – Types of Inheritance - Constructors and
Inheritance - Super keyword - Method Overriding – Dynamic Method Dispatch – Abstract
Classes and Methods – final keyword - Interfaces: Defining an interface – implementing an
interface – Multiple Inheritance through interface.
PART -A
1 List the order of execution of constructor during creation of class Hierarchy.
While implementing inheritance in a Java program, every class has its own constructor.
Therefore the execution of the constructors starts after the object initialization. It follows
a certain sequence according to the class hierarchy. There can be different orders of
execution depending on the type of inheritance.
1. Order of execution of constructor in Single inheritance
2. Order of execution of constructor in Multilevel inheritance
3. Calling same class constructor using this keyword
4. Calling superclass constructor using super keyword
2 Define abstract class.
Abstract class is a class that has no instances. An abstract class is written with the
expectation that its concrete subclasses will add to its structure and behavior,
typically by implementing its abstract operations.
✓ An abstract class must be declared with an abstract keyword.
✓ It can have abstract and non-abstract methods.
✓ It cannot be instantiated.
✓ It can have constructors and static methods also.
✓ It can have final methods which will force the subclass not to change the body of
the method.
Syntax:
abstract class A{}
3 How can you access the super class version of an overridden method? How?
When invoking a superclass version of an overridden method the super keyword is
used.
class Animal {
public void move() {
System.out.println("Animals can move");
}}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
1
}}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}}

Output:
Animals can move
Dogs can walk and run
4 Can we instantiate an abstract class? Justify
Abstract class are classes which can have abstract methods and it can’t be instantiated.
We cannot instantiate an abstract class in Java because it is abstract, it is not complete,
hence it cannot be used.
Java does not allow the direct instantiation of abstract classes. Hence it is not feasible to
create an instance of an abstract class. However, there are a few ways to create an instance
of an abstract class indirectly, by using a concrete subclass or an anonymous class.

Using a Concrete Subclass


The most common way to create an instance of an abstract class is to use a concrete
subclass. To do this, first create a concrete subclass that implements all of the abstract
methods in the abstract class. Following that, you can make an instance of this concrete
subclass and use it in place of an instance of the abstract class.

Using an Anonymous Class


Using an anonymous class is another method for producing an instance of an abstract
class. An instance of an abstract class can be created using an anonymous class, which is
a class that is declared without a name.
5 Illustrate why Creating an object of the sub class invokes also the constructor of the
super class.
When you create an object of a subclass in object-oriented programming, the
constructor of the superclass is invoked as well. This behavior ensures that the entire
object is properly initialized and that the base class's state and behavior are correctly set
up before the subclass-specific initialization occurs.
// Superclass
class Animal {
// Constructor of the superclass
Animal() {
System.out.println("Animal constructor called");
}}

2
// Subclass
class Dog extends Animal {
// Constructor of the subclass
Dog() {
System.out.println("Dog constructor called");
}}

// Main class to test the constructors


public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
}}

Output:
Animal constructor called
Dog constructor called
6 Multiple inheritance is not supported. Why?
The major reason behind Java’s lack of support for multiple inheritance lies in its design
philosophy of simplicity and clarity over complexity. By disallowing Multiple
Inheritance, Java aims to prevent the ambiguity and complexities that can arise from
having multiple parent classes.

The diamond problem is the classic issue that can arise with multiple inheritance. It
occurs when the class inherits from the two classes that have a common ancestor. This
situation forms the diamond-shaped inheritance hierarchy. It can lead to ambiguity in
the method resolution. Consider the scenario where class D inherits from classes B and
C which both inherits from Class A. This creates the diamond-shaped inheritance
hierarchy.
In this scenario, both the classes B and C override the check() method inherited from
the class A. Now when the class D inherits from the B and C then the conflict arises
because class D doesn’t know which check() method to use.

7 Define Upcasting with an example?


Upcasting is a type of object typecasting in which a child object is typecasted to
a parent class object. By using the Upcasting, we can easily access the variables and

3
methods of the parent class to the child class. Here, we don't access all the variables and
the method. We access only some specified variables and methods of the child
class. Upcasting is also known as Generalization and Widening.

If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

8 What is method overriding and mention its rules?


✓ If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
✓ In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
✓ Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
✓ Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
✓ The method must have the same name as in the parent class
✓ The method must have the same parameter as in the parent class.
✓ There must be an IS-A relationship (inheritance).
9 Define Abstract Method() with its syntax?
A method declared using the abstract keyword within an abstract class and does not have
a definition (implementation) is called an abstract method.When we need just the method
declaration in a super class, it can be achieved by declaring the methods as abstracts.

4
Abstract method is also called subclass responsibility as it doesn't have the
implementation in the super class. Therefore a subclass must override it to provide the
method definition.

Syntax for abstract method:


1. abstract return_type method_name( [ argument-list ] );
10 Differentiate between Class and Interface.
Class Interface

The keyword used to create a class The keyword used to create an interface is
is “class” “interface”

A class can be instantiated i.e., An Interface cannot be instantiated i.e.


objects of a class can be created. objects cannot be created.

Classes do not support multiple


The interface supports multiple inheritance.
inheritance.

It can be inherited from another


It cannot inherit a class.
class.

It can be inherited by a class by using the


It can be inherited by another class keyword ‘implements’ and it can be
using the keyword ‘extends’. inherited by an interface using the keyword
‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class


can be declared using any access All variables and methods in an interface
specifier(public, private, default, are declared as public.
protected).

Variables in a class can be static,


All variables are static and final.
final, or neither.

5
11 Multiple Inheritance creates Diamond Problem Ambiguity. Explain?
The diamond problem is a classic illustration of the complexities associated with
multiple inheritance. It occurs in a scenario where a class inherits from two classes that
both inherit from a common base class. If both parent classes override a method from the
base class, and the child class does not provide its own implementation, it's unclear which
version of the method the child class should inherit. This ambiguity complicates method
resolution and can lead to unexpected behaviours.

The diamond problem is illustrated in this diagram with a more complex hierarchy.
Here, Child inherits from two intermediate classes (Intermediate1 and Intermediate2),
which both inherit from Parent1 and Parent2 respectively.
Both Parent1 and Parent2 classes again inherit from the same Base class. This creates
a "diamond-shaped" inheritance structure, where the Base class is at the
top, Parent1 and Parent2 form the middle, and Child is at the bottom.
The problem arises because there are two paths from the Child class to the Base class,
through Intermediate1 and Intermediate2. If Base class's +doSomething() method is
overridden in both Parent1 and Parent2, and Intermediate1 and Intermediate2 do not
override it, the Child class faces ambiguity in deciding which version of the method to

6
inherit. This situation complicates method resolution and can lead to unexpected
behaviour.
Java's approach to this problem is to disallow multiple inheritance of classes, thus
preventing the formation of such diamond-shaped hierarchies. Java allows a class to
implement multiple interfaces but limits inheritance to a single parent class, effectively
avoiding the diamond problem and the associated complexities in method resolution.
12 How do Interface differ from Abstract Class?
Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods.

2) It doesn’t support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. 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();
} }
13 How a subclass can call a constructor defined by its superclass?
A subclass can call a constructor defined by its superclass by use of the following form
of super: super(parameter-list);

7
Here, parameter-list specifies any parameters needed by the constructor in the
superclass. super( ) must always be the first statement executed inside a subclass
constructor.
14 What is an Interface?
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
Java Interface also represents the IS-A relationship.

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the fields
are public, static and final by default. A class that implements an interface must
implement all the methods declared in the interface.

Syntax:
1. interface <interface_name>{
2. // declare constant fields
3. // declare methods that abstract
4. // by default.
5. }
15 When a Class must be declared as Abstract?
✓ In Java, a class must be declared as abstract when it has an abstract method or
doesn't provide an implementation for abstract methods in its superclasses. Abstract
classes are also used when the child classes of the base class are closely related.
✓ Abstract classes can't be directly instantiated, which means an object can't be created
from them. This protects code from being used incorrectly.
✓ Abstract classes require subclasses to further define attributes necessary for
individual instantiation. When an abstract class is subclassed, the subclass usually
provides implementations for all of the abstract methods in its parent class. If it
doesn't, then the subclass must also be declared abstract.
16 Outline the use of extends keyword in Java with syntax.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

8
class Employee{
1. float salary=40000;
2. }
3. class Programmer extends Employee{
4. int bonus=10000;
5. public static void main(String args[]){
6. Programmer p=new Programmer();
7. System.out.println("Programmer salary is:"+p.salary);
8. System.out.println("Bonus of Programmer is:"+p.bonus);
} }

Output:
Programmer salary is:40000.0
Bonus of programmer is:10000

Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.
17 State the uses of Interfaces in Java.
There are mainly three reasons to use interface. They are given below.
✓ It is used to achieve abstraction.
✓ By interface, we can support the functionality of multiple inheritance.
✓ It can be used to achieve loose coupling.
Syntax:
6. interface <interface_name>{
7. // declare constant fields
8. // declare methods that abstract
9. // by default.
}

9
18 Exemplify the uses of Super Keyword.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor

19 Define Extending an Interface with its syntax.


An interface contains variables and methods like a class but the methods in an interface
are abstract by default unlike a class. An interface extends another interface like a class
implements an interface in interface inheritance.

A program that demonstrates extending interfaces in Java is given as follows:

interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
public void funcB() {
System.out.println("This is funcB");
}}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
}}

Output:
This is funcA
This is funcB
20 Define Runtime Polymorphism.
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.

10
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.
PART –B & C
1 Explain how to define an interface? Why do the members of interface are static and final?
2 Explain Extending Interfaces with a Program & Variables in a Program.
3 How can we Overload the Constructor? Explain by using Multilevel Inheritance.
4 Can you give a detailed sketch of the differences between Single, Multilevel &
Hierarchical Inheritance?
5 Create an abstract Reservation class which has Reserve() abstract method. Implement the
sub-classes like ReserveTrain and ReserveBus classes and implement the same. Use
necessary variables, methods for reserving tickets.
6 Describe about the Dynamic Method Dispatch using the Hierarchical Levels of
Inheritance with explanation.
7 Discuss how reusability of code can be achieved through inheritance with an example.
8 Outline Method Overloading and Method Overriding in Java with code fragments.
9 Explain about Super Keyword and how it can be used to access the superclass with an
example.
10 Brief about the Abstract Class and Abstract Methods. Explain it by using Multilevel
Inheritance.

11
UNIT III EXCEPTION HANDLING AND MULTTITHREADING
Exception Handling basics – Multiple catch Clauses – Nested try Statements – Java’s Built-in
Exceptions – User-defined Exceptions; Multithreaded Programming: Differences between multi-
threading and multitasking - Thread Life Cycle – Creating Threads – Thread Priorities – Thread
Synchronization – Inter-Thread Communication.
PART -A
1 What is an exception?
Exception is an event which disrupts the flow of a program. When an exception occurs, an
exception object is created, which contains the information regarding the error, type, and
state of the program when the error occurred.
2 Write the types of Exceptions in Java.
It has two types of exceptions in Java: Checked and Unchecked. Checked exceptions are
the exceptions checked at compile time by the compiler. Unchecked Exceptions are those
not checked at the compile time by the compiler.
3 List the Exception handling keywords in Java.
Java provides controls to handle exception in the program. These controls are listed below.
• try: It is used to enclose the suspected code.
• catch: It acts as exception handler.
• finally: It is used to execute necessary code.
• throw: It throws the exception explicitly.
• throws: It informs for the possible exception.
4 Give the difference between Error and Exception in Java.
Errors are all unchecked, but exceptions can be checked or unchecked. Errors occur at the
run time, whereas the exceptions occur at the compile time.
5 What are built-in Exceptions?
The exceptions already present in the Java Libraries and can help handle certain error
situations are called built-in Exceptions. Examples are ArithmeticException,
ArrayIndexOutOfBoundException, etc.
6 Can we write only try block without a catch and finally blocks?
No, it throws a compilation error. The try block should be followed by either catch or a
finally block. Either one of them can be removed but not both.
7 Write the difference between throw and throws in Java.
1. throw is a keyword in java used to throw an exception manually. Exception should be
of type java.lang.Throwable class or its subclasses.
Example:
class ThrowExample{
void method() throws Exception
{

1
Exception ex = new Exception();
throw ex;
}}

2. throws is also a keyword in java used in the method declaration to indicate that this
method may throw exceptions.
Example:
class ThrowsExample
{
void methodOne() throws SQLException
{
//This method may throw SQLException
}}
8 What are the advantages of Exceptional Handling?
✓ Exception handling is crucial for the proper functioning of applications.
✓ With exception handling, developers define the steps for addressing compilation or
runtime errors to ensure that there are no interruptions of program flow.
✓ As a result, applications are more stable and have a better user experience. And because
coding errors that lead to exceptions can be points of vulnerability for cyberattacks,
effective exception handling can lead to more secure code.
9 Is it possible to have a return statement in the catch or finally block?
Yes, it can have a return statement in the catch or finally block; if we write a return statement
at the end, the code will execute successfully, and the code below it will become a part of
unreachable code.
10 Define Multiple Catch Clauses.
✓ A try block can be followed by multiple catch blocks. It can have any number of catch
blocks after a single try block. If an exception occurs in the guarded code (try block) the
exception is passed to the first catch block in the list.
✓ If the exception type matches with the first catch block it gets caught, if not the exception
is passed down to the next catch block. This continue until the exception is caught or
falls through all catches.
Syntax:
try{ // suspected code
}
catch(Exception1 e) { // handler code
}
catch(Exception2 e) { // handler code
}

2
11 Define Thread.
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
12 How to create a thread in Java?
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
13 Brief about Thread class.
Java provides Thread class to achieve thread programming. Thread class provide
constructors and methods to create and perform operations on a thread. Thread class extends
Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
14 Define Thread.sleep() in Java with Examples
✓ The Java Thread class provides the two variant of the sleep() method.
✓ First one accepts only an arguments, whereas the other variant accepts two arguments.
The method sleep() is being used to halt the working of a thread for a given amount of
time.
✓ The time up to which the thread remains in the sleeping state is known as the sleeping
time of the thread.
✓ After the sleeping time is over, the thread starts its execution from where it has left.

The sleep() Method Syntax:


1. public static void sleep(long mls) throws InterruptedException
2. public static void sleep(long mls, int n) throws InterruptedException
15 What is Multithreading and Multitasking?
Multithreading in Java involves running multiple threads within a single process, allowing
concurrent execution of tasks within that process.
Multitasking, on the other hand, involves running multiple independent processes or tasks
concurrently.
16 Identify the steps involved in creating packages.
A package is defined as a collection of built-in classes. Packages in Java can be classified
into two types namely:
• Built-In packages

3
• User-defined packages
To create a package, it has to implement the following steps:
1. First, we create a directory as a sub-directory of bin whose name is the same as the
package’s name. For example, create a directory with the name MyPack.
2. Now, move into the new directory. Then, create a Java class whose first statement
of the file should be a package statement, package MyPack;
3. After creating the class, save it with the class-name and compile it. In this way, we
can create multiple classes in the new package where each class is created as a
separate Java file.
4. After creating the package with a set of classes, move into bin directory. Now, the
classes in the new package can be imported to our Java applications using
the import statements, import MyPack.*;
17 Assess how will you set and get the priority for a thread.
Priorities in threads is a concept where each thread is having a priority which in layman’s
language one can say every object is having priority here which is represented by numbers
ranging from 1 to 10.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
The accepted value of priority for a thread is in the range of 1 to 10.

To get and set priority of a thread in java.


1. public final int getPriority(): java.lang.Thread.getPriority() method returns priority of
given thread.
2. public final void setPriority(int newPriority): java.lang.Thread.setPriority() method
changes the priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond minimum(1)
and maximum(10) limit.
18 Prepare how to create a thread using Thread Class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){

4
Multi t1=new Multi();
t1.start();
}
}
Output:
thread is running...
19 Differentiate between the Thread class and Runnable interface for creating a thread.
• The thread can be created by extending the Thread class
• The thread can be created by implementing the Runnable interface
Thread Class Runnable Interface
It has multiple methods like start() and It has only abstract method run()
run()
Each thread creates a unique object and gets Multiple threads share the same objects
associated with it
More memory required Less memory required
Multiple Inheritance is not allowed in Java If a class implements the runnable
hence after a class extends the Thread class, interface, it can extend another class.
it can not extend any other class
20 Discuss the states in the lifecycle of a Thread.
✓ New: A Thread class object is created using a new operator, but the thread is not alive.
The thread doesn't start until we call the start() method.
✓ Runnable: The thread is run after calling the start() method. It is waiting in the ready or
runnable queue to be allocated to the processor.
✓ Running: In this state, the thread scheduler picks the thread from the ready state and
the thread executes.
✓ Waiting/Blocked: In this state, a thread is not running but still alive, or waiting for the
other thread to finish.
✓ Dead/Terminated: The thread exits or stops executing due to some unusual happenings.
PART –B & C
1 Define exception. Why it is needed? Explain the different types of exceptions and the
exception hierarchy with appropriate examples using Java.
2 Illustrate the use of try-catch clauses by sample statements of rare type of run time error.
3 Examine Inter Thread Communication. Why is this feature required and how is it achieved?
4 Explain the task for running a task in a separate thread and running multiple threads.
5 Develop the Java program to handle
i. Checked exceptions
ii. Unchecked Exceptions
6 i. What is synchronization? With an example explain how thread synchronization is
carried out in Java.
ii. Justify the purpose of using Inter-thread communication. Demonstrate how threads are

5
suspended, stopped and resumed with an example.
7 i. What is a Java exception? How Java exception handling is managed? Outline.
ii. Outline Java's checked exceptions defined a java.lang package.
8 Outline the Java’s multithreading system. Also mention any two ways to create a thread
with an example
9 Discuss in detail about the life cycle of a Java thread with neat diagram.
10 Explain in details about how exceptions are handled in Java. Illustrate division by zero
exception with a suitable example.

6
UNIT IV GENERIC PROGRAMMING AND EVENT DRIVEN PROGRAMMING
Introduction to Generic Programming – Generic classes – Generic Methods – BoundedTypes –
Restrictions and Limitations. Graphics Programming using AWT: Frame –Components -
Working with Color, Font, and Image – Layout Management - Basics of event handling – Java
Event classes and Listener interfaces - Adaptor classes – MouseEvent, KeyEvent, WindowEvent,
ActionEvent, ItemEvent, Dialog Boxes
PART -A
1 Define Graphics Programming.
Graphics programming in Java is the process of using the Graphics class to draw on
components and off-screen images in Java applications. The Graphics class is the base class
for all graphics contexts and includes methods for drawing strings, lines, shapes, and
images. It also manages a graphics context, which allows drawing on the screen by drawing
pixels that represent graphical objects and text
2 Define Event Listener.
The Event listener represent the interfaces responsible to handle events. Java provides us
various Event listener classes. Every method of an event listener method has a single
argument as an object which is subclass of EventObject class. For example, mouse event
listener methods will accept instance of MouseEvent, where MouseEvent derives from
EventObject.
3 What is the purpose of the KeyEvent() method?
In Java, the KeyEvent method is a low-level event that indicates a keystroke has occurred in a
component. The method is generated by a component object, such as a text field, when a key
is pressed, released, or typed.
There are three types of KeyEvent that correspond to these three actions:
✓ keyPressed: Called when the user presses a key
✓ keyReleased: Called when the user releases a key
✓ keyTyped: Called when the user types a character
4 How to declare a java generic bounded type parameter?
1. List the type parameter’s name,
2. Along with the extends keyword
3. And by its upper bound. (which in the below example c is A.)
Syntax
<T extends superClassName>
Note that, in this context, extends is used in a general sense to mean either “extends” (as in
classes). Also, This specifies that T can only be replaced by superClassName or subclasses
of superClassName. Thus, a superclass defines an inclusive, upper limit.
5 How Events are handled?
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events.
6 Why do we need generics in Java?
Code that uses generics has many benefits over non-generic code: Stronger type checks

1
at compile time. A Java compiler applies strong type checking to generic code and
issues errors if the code violates type safety. Fixing compile-time errors is easier than
fixing runtime errors,which can be difficult to find.
7 How to create generic class?
A class that can refer to any type is known as generic class. Here, we are using T type
parameter to create the generic class of specific type.
Example to create and use the generic class.
class MyGen<T>{
T obj;
void add(T obj)
{
this.obj=obj;
}
T get()
{
return obj;
}}

Creating generic class:


The T type indicates that it can refer to any type (like String, Integer, Employee etc.).
The type you specify for the class, will be used to store and retrieve the data.
8 How to declare a java generic bounded type parameter?
To declare a bounded type parameter, list the type parameter’s name, followed by the
extends keyword, followed by its upper bound, similar like below method.
Public static<T extends Comparable<T>>int compare(Tt1, Tt2)
{ return t1.compareTo(t2);}
The invocation of these methods is similar to unbounded method except that if we will
try to use any class that is not Comparable, it will throw compile time error.Bounded type
parameters can be used with methods as well as classes and interfaces
9 State the two challenges of generic programming in virtual machines.
✓ Generics are checked at compile-time for type-correctness. The generic type
information is then removed in a process called type erasure.
✓ Type parameters cannot be determined at run-time
10 What are wildcards in generics?
In generic code, the question mark (?), called the wildcard, represents an unknown
type. The wildcard can be used in a variety of situations: as the type of a parameter, field,
or local variable; sometimes as a return type (though it is better programming practice to
be more specific).
11 When to use bounded type parameter?
There may be times when you want to restrict the types that can be used as type arguments
in a parameterized type. For example, a method that operates on numbers might only want
to accept instances of Number or its subclasses. This is what bounded type parameters are

2
for.
12 What are the restrictions on generics?
To use Java generics effectively, it must consider the following restrictions:
✓ Cannot Instantiate Generic Types with Primitive Types
✓ Cannot Create Instances of Type Parameters
✓ Cannot Declare Static Fields Whose Types are Type Parameters
✓ Cannot Use Casts or instance of With Parameterized Types
✓ Cannot Create Arrays of Parameterized Types
✓ Cannot Create, Catch, or Throw Objects of Parameterized Types
✓ Cannot Overload a Method Where the Formal Parameter Types of Each Overload
Erase to the Same Raw Type
13 Mention some Event Classes and Interface
Event Classes Description Listener Interface
generated when button is pressed, menu-
ActionEvent ActionListener
item is selected, list-item is double clicked
generated when mouse is dragged,
MouseEvent moved,clicked,pressed or released and MouseListener
also when it enters or exit a component
generated when input is received from
KeyEvent KeyListener
keyboard
generated when check-box or list item is
ItemEvent ItemListener
clicked
generated when value of textarea or
TextEvent TextListener
textfield
is changed
generated when component is hidden,
ComponentEvent ComponentEventListener
moved, resized or set visible
generated when component is added or
ContainerEvent ContainerListener
removed from container
14 How Does a radio button in java differ from a check box?
✓ Radio buttons are used when there is a list of two or more options that are mutually
exclusive and the user must select exactly one choice. In other words, clicking a non-
selected radio button will deselect whatever other button was previously selected in
the list.
✓ Checkboxes are used when there are lists of options and the user may select any
number of choices, including zero, one, or several. In other words, each checkbox is
independent of all other checkboxes in the list, so checking one box doesn't uncheck
the others.
15 Components of Event Handling
Event handling has three main components,

3
✓ Events : An event is a change in state of an object.
✓ Events Source : Event source is an object that generates an event.
✓ Listeners : A listener is an object that listens to the event. A listener gets notified
when an event occurs.
16 How Events are handled in java ?
A source generates an Event and send it to one or more listeners registered with the
source.Once event is received by the listener, they process the event and then return.
Events are supported by a number of Java packages, like java.util, java.awt and
java.awt.event.
17 What is a layout manager and what are different types of layout managers available in
java AWT?
A layout manager is an object that is used to organize components in a container. The
different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout
and GridBagLayout.
18 Mention the Differences between AWT and swing
Java AWT Java Swing
AWT components are platform- Java swing components are
dependent. platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT provides less components than Swing provides more powerful
Swing. components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
AWT doesn't follows MVC Swing follows MVC.
19 What is the difference between scrollbar and scrollpane?
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and
handles its own events and perform its own scrolling.
20 What is the use of JButton and mention the constructor of JButton class.
JButton class provides functionality of a button. JButton class has three
constuctors,Button(Iconic),JButton(String str),JButton(String str, Icon ic)
PART –B & C
1 Describe the key aspects of working with color, font, and image in AWT. Provide examples
demonstrating their usage in a graphical application.
2 Illustrate briefly about the working of frames and setting the properties to it.
3 Explain in detail about event classes provided by java.
4 Discuss the benefits of using generic classes in software development. How generic classes
differ from generic method. Give its Restrictions and Limitations.
5 Which steps are must for event handling and what are the models available for event
handling?
6 Explain in detail about generic classes and methods in java with suitable example.
7 Develop a java program that have 11 text fields one submit button. When you press the

4
button first 10 text field’s average has to be displayed in the 11th text field.
8 What is an adapter class? Describe about various adapter classes in detail?
9 Explain the layout managers in Java also describe the concept of menu creation.
10 What is event handling in java? List out the available event classes and listener
interfaces with suitable example

5
UNIT V DHTML: HTML, CSS AND JAVASCRIPT
HTML 5: Introduction – Formatting Tags – Tables – Lists – Hyperlinks – Images – Forms; CSS3 –
Introduction and core syntax – Types of Selector Strings – Types of CSS – Backgrounds – Box
Model; JavaScript: An introduction to JavaScript – Functions – Built-in Objects – Document Object
Model - Event Handling – Form Validation using Regular Expression.
PART -A
1 List four new features of HTML 5.
✓ Introduction to Audio and Video - The <audio> and <video> tags are the two major
addition to HTML5.
✓ Vector Graphics - This is a new addition to the revised version which has hugely
impacted the use of Adobe Flash in websites.
✓ Figure and Figcaption - HTML5 allows to use a <figure> element to mark up a photo in a
document, and a <figcaption> element to define a caption for the photo.
✓ HTML Nav Tag - The <nav> tag defines a set of navigation links. It is used for the part of
an internet site that links to different pages at the website.
2 What are the difference between Java and Javascript?
Java JavaScript
This is OOP or Object-Oriented This is an object based scripting language
programming language
A stand-alone language Not stand-alone, incorporated into HTML
program for operation
Strongly typed language is used, and data Language utilised is loosely typed, so that the user
type of variable is decided before declaring does not have to worry about the data type before
or using it the declaration
Code has to be compiled The code is all text
Slightly more complex Easier in comparison
Used to perform complex tasks Complex tasks cannot be executed
Large amount of memory is required Memory consumption is lesser
Programs are saved with “.java” extension Programs are saved with JavaScript, “.js”
extension
Stored in the / client host machine under Stored in host or client machine as “source” code
the “Byte” code
3 Write a HTML5 code to display:
A B
C D

Answer :
< ! DOCTYPE HTML>

1
<HTML>
<HEAD></HEAD>
<BODY>
<TABLE BORDER=”4”>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR>
<TD>C</TD>
<TD>D</TD>
</TR>
</TABLE>
</BODY>
</HTML>
4 What is CSS? What are its types?
✓ Cascading style sheet is defined as a style sheet in which, allthe style information of a web
page can be defined.
✓ It separates the contents and the decoration of a HTML page. It helps developers to give
consistent appearance to all the elements in the web page.
Types:-
✓ Inline style sheets <p style=”color:green; font-size:15px”>
✓ Embedded style sheets <style>......</style>
✓ External style sheet Stored in a separate file (ex.css)
✓ Imported style sheets @import URL(path)
5 What are the types of positioning in CSS?
✓ Relative positioning
✓ Absolute positioning
✓ Float positioning
6 What is the significance of <head> and <body> tag in HTML?
<head> Tag
<head> tag provides the information about the document. It should always be enclosed in the
<html> tag. This tag contains the metadata about the webpage and the tags which are enclosed
by head tag like <link>, <meta>, <style>, <script>, etc. are not displayed on the web page. Also,
there can be only 1 <head> tag in the entire Html document and will always be before the
<body> tag.

<body> Tag
<body> tag defines the body of the HTML document. It should always be enclosed in the
<html> tag. All the contents which needs to be displayed on the web page like images, text,

2
audio, video, contents, using elements like <p>, <img>, <audio>, <heading>, <video>, <div>,
etc. will always be enclosed by the <body> tag. Also, there can be only 1 body element in an
HTML document and will always be after the <head> tag.
7 Are the HTML tags and elements the same thing?
No. HTML elements are defined by a starting tag, may contain some content and a closing
tag.For example, <h1>Heading 1</h1> is a HTML element but just <h1> is a starting tag and
</h1> is a closing tag
8 How to specify the link in HTML and explain the target attribute?
HTML provides a hyperlink - <a> tag to specify the links in a webpage. The ‘href’ attribute is
used to specify the link and the ‘target’ attribute is used to specify, where do we want to open
the linked document.
The ‘target’ attribute can have the following values:
1. _self: This is a default value. It opens the document in the same window or tab as it was
clicked.
2. _blank: It opens the document in a new window or tab.
3. _parent: It opens the document in a parent frame.
4. _top: It opens the document in a full-body window.
9 Difference between link tag <link> and anchor tag <a>?
The anchor tag <a> is used to create a hyperlink to another webpage or to a certain part of the
webpage and these links are clickable, whereas, link tag <link> defines a link between a
document and an external resource and these are not clickable
10 How to include javascript code in HTML?
HTML provides a <script> tag using which can run the javascript code and make the HTML
page more dynamic.
<!DOCTYPE html>
<html>
<body>
<h1>
<span>This is a demo for </span>
<u><span id="demo"></span></u>
</h1>
<script>
document.getElementById("demo").innerHTML = "script Tag"
</script>
</body>
</html>
11 What is a JavaScript statement? Give an example.
✓ A JavaScript statement is a piece of code used to instruct the computer on an action to
execute.
✓ These statements are made up of different
parts: Values, Operators, Keywords, Expressions, and Comments. Each statement is
executed by the browser in the order it appears, line by line.Semicolons are used to

3
separate JavaScript statements. They mark the end of a statement.

Example:
let a, b, c;
a = 2;
b = 3;
c = a + b;
console.log("The value of c is " + c + ".");
Output:
The value of c is 5.
12 What are the Build-in objects in JavaScript?
JavaScript provides several built-in objects that offer a wide range of functionality and can be
used to perform various tasks. These built-in objects serve as containers for methods and
properties that allow you to perform operations related to specific concepts or data types.
Example:
Math
let randomNumber = Math.random();
let roundedNumber = Math.floor(3.7);
Date
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
13 Mention the need for cascading style sheets.
✓ Faster Page Speed
✓ Better User Experience
✓ Quicker Development Time
✓ Easy Formatting Changes
✓ Compatibility Across Devices
14 State the types of JavaScript statements with examples.
A JavaScript statement is a piece of code used to instruct the computer on an action to
execute.
Example:
let bestColor;
The code in the snippet above is a JavaScript statement instructing the computer to create
a let variable named bestColor.
There are five typical types of JavaScript statements:
• Declaration statements
• Expression statements
• Conditional statements
• Loops statements
• Error handling statements
15 Justify the advantage of HTML5.0.
✓ It supports Multimedia
✓ Short and simple syntax

4
✓ Improved security features
✓ Inlcude semantic tags
✓ Cross-platform support
16 How to use a Variable in Regular Expression in JavaScript?
Regexps can be used in JavaScript to build dynamic patterns that match various strings
depending on the value of the variable. In this article, we will see how to utilize the variable
with the regular expression.
Syntax:
// Initializing an GFG variable
let GFG = "GeeksForGeeks";

// Using Regular expression


const myRegex = `Hello ${GFG}`
17 What are forms and how to create forms in HTML?
The HTML form is used to collect the user inputs. HTML provides a <form> tag to create
forms. To take input from the user we use the <input> tag inside the form so that all collected
user data can be sent to the server for processing. There are different input types like ‘button’,
‘checkbox’, ‘number’, ‘text’, ‘password’, ‘submit’ etc.
Example:
<form action="/submit_data.php">
<label>Enter your name: </label>
<input type="text" name="name" />
<label>Enter Mobile number </label>
<input type="number" name="mobile_no"/>
<input type="submit" value="Submit">
</form
18 Why do we use the word “debugger” in javascript?
The debugger for the browser must be activated in order to debug the code. Built-in debuggers
may be switched on and off, requiring the user to report faults. The remaining section of the
code should stop execution before moving on to the next line while debugging.
19 Is JavaScript a dynamically typed or statically typed language?
JavaScript is a dynamic language and not static, which means that variables can hold values of
different types during runtime.
20 How can you create objects in JavaScript?
Javascript is fundamentally an object oriented scripting language, it encourages and supports
using objects when developing web based application.
Example :
const person = {
firstName: 'testFirstName',
lastName: 'testLastName'
};

5
PART – B
1 Illustrate Frameset, Frame Tag. Divide the web page into four equal parts each individual part
displays different web page.
2 Explain in detail about CSS3. Give the illustration for CSS3 animation
3 Explain about the get Property() and set Property() of beans in jsp.
4 a. Write JavaScript to find sum of first ‘n’ even numbers and display the result. Get the
value of ‘n’ from user. (7)
b. Write JavaScript to find factorial of a given number. (6)
5 a. Name some new features which were not present in HTML but are added to HTML5? (6)
b. Write an HTML code to form a table to show the below values in a tabular form with
heading as Roll No., Student name, Subject Name, and values. (7)
6 Write a detailed note on JavaScript objects.
7 Design an online shopping cart application cart application using Javascript. Consider a login
validation page and one billing page for bill processing.
8 a. Describe the various font and text properties of cascading style sheets. (8)
b. List out the operators supported in JavaScript. (5)
9 Explain in detail about the Document Object Model in javascript with example.
10 How to validate form using Regular Expression in JavaScript ?

You might also like