Oops Question Bank 2024-Updated-1

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

UNIT I

INTRODUCTION TO OOP AND JAVA FUNDAMENTALS


Object Oriented Programming - Abstraction – Objects And Classes - Encapsulation-
Inheritance -Polymorphism- characteristics of Java-Java Environment- Java source File-
compilation –Fundamental Programming Structures In Java –Data types-variables-
operators-control flow- Defining Classes In Java – Constructors, Methods -Access
Specifiers - Static Members - Arrays ,Javadoc Comments

PARTA QUESTIONS WITH ANSWERS

1.Define Class and Objects. Give example.


A class in Java is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For
example, Student is a class while a particular student named Ravi is an object.

2. Define type conversion and type casting.


Type Casting: In typing casting, a data type is converted into another data type by the
programmer using the casting operator during the program design. In typing casting, the
destination data type may be smaller than the source data type when converting the data type to
another data type, that‟s why it is also called narrowing conversion.
Example:
double num = 10.99;
int data = (int)num;
Type conversion : In type conversion, a data type is automatically converted into another data
type by a compiler at the compiler time. In type conversion, the destination data type cannot be
smaller than the source data type, that‟s why it is also called widening conversion. One more
important thing is that it can only be applied to compatible data types.
Example:
int x=30;
float y;
y=x;

3.Differentiate static variable and instance variable.


static variable instance variable
A static variable is associated with the class An instance variable is associated with a
itself, not with any particular instance of the specific instance of a class.
class.
All instances of the class share the same copy Each instance of a class has its own copy of an
of a static variable. instance variable.
Static variable can be accessed directly using An instance variable can be access using an
the class name, without creating an object of object reference.
the class.
4.Interpret the following statement “java is platform independent”.
Java is platform independent because the Java compiler converts the source code to bytecode,
which is Intermediate Language. Bytecode can be executed on any platform (OS) using Java
Virtual Machine (JVM).

5.Determine the various types of access modifiers with its scope.


The access modifiers in Java specify the accessibility or scope of a field, method, constructor, or
class. There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

6. Define Abstraction.
Abstraction in Java refers to hiding the implementation details of a code and exposing only the
necessary information to the user. It provides the ability to simplify complex systems by ignoring
irrelevant details and reducing complexity.

7.What do you mean by Encapsulation?


Encapsulation in java is a process of wrapping code and data together into a single unit.
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. In Java the basis of encapsulation is the class. A
class defines the structure and behaviour (data and code) that will be shared by a set of objects.

8.What is meant by bytecode in Java?


Byte Code can be defined as an intermediate code generated by the compiler after the compilation
of source code (JAVA Program). This intermediate code makes Java a platform-independent
language.

9. List the Data Types in Java.


Integers - This group includes byte, short, int, and long, which are for whole valued signed
numbers.
Floating -point numbers- This group includes float and double, which represent numbers with
fractional precision.
Characters - This group includes char, which represents symbols in a character set, like letters and
numbers.
Boolean - This group includes boolean, which is a special type for representing true/false values.
10. Differentiate constructor and method in java.
constructor method
Used to initialize an object when it is created. Performs a specific action or operation on an
object.
Must have the same name as the class. Can have any valid identifier, but should follow
naming conventions.
Does not have a return type. Can have any return type, including void if it
doesn't return a value.
Called automatically when an object is created Explicitly called on an object using the dot
using the new keyword. operator.

11. How do you declare and Initialize Array in java? Give Example.
An array is a collection of similar type of elements which has contiguous memory location.
a. Declaration of the array: Declaration of array means the specification of array variable,
data_type and array_name.
Syntax to Declare an Array in java:
dataType[] arrayRefVar; (or)
dataType []arrayRefVar; (or)
dataType arrayRefVar[];
Example: int[] floppy; (or) int []floppy (or) int floppy[];
b. Instantiation of the array: Allocating memory spaces for the declared array in memory
(RAM) is called as Instantiation of an array.
Syntax: arrayRefVar=new datatype[size];
Example: floppy=new int[10];
c. Initialization of arrays: Storing the values in the array element is called as Initialization of
arrays.
Syntax: arrayRefVar[index value]=constant or value;
Example: floppy[0]=20;

Part B
1. Discuss in detail about the basic concepts of object-oriented Programming.

2. Illustrate the Java Programming and Runtime Environment. Explain the roles of each component
of it while compiling and executing a java program.

3. a.Write a java program to receive a color code from the user (an alphabet).The program should
then print the color name, based on the color code given. The following are the color codes and their
corresponding color names. R-> Red, B->Blue, G->Green, O->Orange, Y->Yellow, W->White. If
color code provided by the user is not valid then print “Invalid Code”.

b.Write a Java code using do-while loop that counts down to 1 from 10 printing exactly ten lines
of „hello‟.

4. Explain Java‟s control flow statements with examples.

5. Explain in detail about various operators in java.


6. Illustrate different types of constructors with example.

7. Create a class Rectangle which has length and breadth as data members. Define a parameterized
constructor to set the length and breadth. Write a java program to compute area and perimeter of
rectangle.

8. Write a program to initialize an integer array and find the maximum minimum value of the array.

9. a.Describe the static fields and methods used in Java.

b.Create a new class called Calculator with the following methods: A static method called
powerInt(int num1, int num2). This method should return num1 to the power num2. Another static
method called owerDouble(double num1, int num2). This method should return num1 to the power
num2. Invoke both the methods and test the functionalities. (Hint: use Math.pow(double, double)
to calculate the power.

10.Write a Java program to accept two square matrices, store them in an array, multiply the matrices
and display the result using Class and methods.

11. Display a basic calculator supporting addition, subtraction, multiplication, division, and modulus
operations. Use switch-case statements and demonstrate the use of assignment operators (=, +=, -=,
*=, /=, %=) using java program.

12. i. Experiment static variables and methods with example(6)


ii. Evaluate Fibonacci series of a number using recursive method.(7)
UNIT II

INHERITANCE, PACKAGES AND INTERFACES


Inheritance – Types of Inheritance-Super Keyword- Method Overrriding- Dynamic method
Dispatch– Abstract classes and methods- Final classes-Object Class – Inner Class - Packages –
Defining Packages – Finding Packages And CLASSPATH -Importing Packages - Interfaces –
Defining an Interface, Implementing Interface and Extending Interfaces .

PART A QUESTIONS WITH ANSWERS

1.List the advantages of Inheritance.

•Reusability of Code: Inheritance is mainly used for code reusability (Code reusability means
that we can add extra features to an existing class without modifying it).

•Effort and Time Saving: The advantage of reusability saves the programmer time and effort
since the main code written can be reused in various situations as needed.

•Increased Reliability: The program with inheritance becomes more understandable and easily
maintainable as the sub classes are created from the existing reliably working classes.

2.Tabulate the difference between the keyword “super” and “this” in java.

super this

The current instance of the parent class is The current instance of the class is
represented by the super keyword. represented by this keyword.

In order to call the default constructor of the In order to call the default constructor of the
parent class, we can use the super keyword. current class, we can use this keyword.

It can't be referred to from a static context. It It can be referred to from a static context. It
means it cannot be invoked from a static means it can be invoked from the static
context. context.

We can use it to access the data members and We can use it to access only the current class
member functions of the parent class. data members and member functions.

3.What is Object class in java?

The Object class sits at the top (root) of the class hierarchy tree in the Java development
environment. Every class in the Java system is a descendent (direct or indirect) of the Object
class. The Object class defines the basic state and behavior that all objects must have, such as
the ability to compare oneself to another object, to convert to a string, to wait on a condition
variable, to notify other objects that a condition variable has changed, and to return the
object's class.
4.Display the syntax for importing packages in a java source file and give an example.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Syntax: import package1[.package2][.package3].classname or *;

Example: import pack.Factorial.FactorialClass;

5.Solve the drawback of multiple inheritances in java.

The Java language does not support multiple inheritances in classes because it can
result in a diamond problem, whereas there are better ways to achieve the same result than
using multiple inheritances. Consider the situation where class B extends class A and class C,
and both classes have the same display() method. It is now impossible for java compilers to
decide which display method to inherit.

To prevent such situations, Java does not allow multiple inheritances. Java has overcome
the problem of multiple inheritances by allowing classes to implement one or more interfaces.

6.Describe the use of interface in java.

 It is used to achieve fully abstraction.

 By interface, we can support the functionality of multiple inheritance.

 It can be used to achieve loose coupling.

 Used to Write flexible and maintainable code.

7.State the condition for method overriding in java.

In Java, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes. When a method in a subclass has the same name, the same parameters or signature,
and the same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.

8.What are the differences between classes and interface?

Classes can contain variables and methods, or functions that specify how a given data type
behaves. An interface is like a template which defines a group of related methods with empty
bodies. The implementation of the methods is provided by the class that implements the
interface.

9.Outline the use of extends keyword in java with syntax.

The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
Syntax:
[accessspecifier] interface InterfaceName extends interface1, interface2,…..
{
Code for interface
}

10.When a class must be declared as abstract?

If a class contains at least one abstract method then compulsory that we should declare the
class as abstract otherwise we will get a compile-time error, If a class contains at least one
abstract method then, implementation is not complete for that class, and hence it is not
recommended to create an object so in order to restrict object creation for such partial classes
we use abstract keyword.

PART B

1. Demonstrate Inheritance and its types with suitable example.


2. i)How to use the super keyword to invoke a superclass's variable, constructor and methods?
ii)What is Inner class? Discuss in detail.
3. Explain about final class, final method, and final variable with suitable example.
4. Assess how to create and import package inside a program. Show how to find packages and
its class path.
5. Create a java code to find area of polygons using interface and extends that interface with
classes.
6. Outline method overriding with an example
7. Write a note on interfaces and present the syntax for defining an interface. Outline how
interfaces are implemented in Java with an example.
8. What is an Abstract class? Illustrate with an example to demonstrate abstract class.
9. Explain in detail about Dynamic method dispatch with suitable example.
10. Analyze a java code to declare an abstract class to represent a bank account with data
member’s name, account number, address and abstract methods withdraw and deposit.
Method display () is needed to show balance. Derive a subclass Savings Account and add the
following details: return on investment and the method calcAmt() to show the amount in the
account after 1 year. Create instance of Savings Account and show the use of withdraw and
deposit abstract methods
UNIT III

MULTITHREADING AND EXCEPTION HANDLING


Thread-Thread life cycle, creating threads, synchronizing threads, Inter-thread
communication, daemon threads, thread groups - Exceptions - exception hierarchy - throwing
and catching exceptions – built-in exceptions, creating own exceptions, Stack Trace Elements.
PART A QUESTIONS WITH ANSWERS

1.Define thread.
A thread is a lightweight sub-process that defines a separate path of execution. It is the
smallest unit of processing that can run concurrently with the other parts (other threads) of the
same process.
2.Compare Process and Thread.
S.NO PROCESS THREAD

1) Process is a heavy weight program Thread is a light weight process

2) Each process has a complete set of its own Threads share the same data
variables

3) Processes must use IPC (Inter-Process Threads can directly communicate with each
Communication) to communicate with other with the help of shared variables
sibling processes

4) Cost of communication between processes Cost of communication between threads is


is high. low.

5) Process switching uses interface in Thread switching does not require calling an
operating system. operating system.

6) Processes are independent of one another Threads are dependent of one another

7) Each process has its own memory and All threads of a particular process shares the
resources common memory and resources

8) Creating & destroying processes takes Takes less overhead to create and destroy
more overhead individual threads

3.What is daemon thread and which method is used to create the daemon thread?
Daemon thread is a low priority thread that runs in background to perform tasks such as
garbage collection. Its life depend on the mercy of user threads i.e. when all the user threads
dies, JVM terminates this thread automatically.
Methods: The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void setDaemon(boolean status) is used to mark the current thread as daemon thread
or user thread.
2) public boolean isDaemon() is used to check that current thread is daemon or not.

4. Analyze the different states of thread.


Different states, a thread (or applet/servlet) travels from its object creation to object removal
(garbage collection) is known as life cycle of thread. A thread goes through various stages in
its life cycle. At any time, a thread always exists in any one of the following state:
1.New State
2.Runnable State
3.Running State
4.Waiting/Timed Waiting/Blocked state
5.Terminated State/ dead state

5.What is synchronization? Give example.


When two or more threads need to use a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process of ensuring single thread
access to a shared resource at a time is called synchronization.
Syntax to use synchronized method:
Access_modifier synchronized return_type method_name(parameters)
{ …….. }

6.Differentiate exception and error in java.


S.No. Exception Error

1. Exceptions can be recovered Errors cannot be recovered

2. Exceptions are of type java.lang.Exception Errors are of type java.lang.Error

Exceptions can be classified into two types: There is no such classification for errors.
3. Errors are always unchecked.
a)Checked Exceptions
b)Unchecked Exceptions
In case of Checked Exceptions, compiler In case of Errors, compiler won‟t have
will have knowledge of checked exceptions knowledge of errors. Because they happen
4. and force to keep try…catch block. at run time.
Unchecked Exceptions are not known to
compiler because they occur at run time.

Exceptions are mainly caused by the Errors are mostly caused by the
5. application itself. environment in which application is
running.

Examples: Examples:

6. Checked Exceptions: Java.lang.StackOverFlowError,


java.lang.OutOfMemoryError
SQLException, IOException
Unchecked Exceptions:

ArrayIndexOutOfBoundsException,
NullPointerException

7.What is an exception?
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of
a program, i.e. at run time, that disrupts the normal flow of the program‟s instructions.
Exceptions can be caught and handled by the program. When an exception occurs within a
method, it creates an object. This object is called the exception object. It contains information
about the exception, such as the name and description of the exception and the state of the
program when the exception occurred.

8.How does Java differentiate between checked and unchecked exceptions?


A checked exception is the one that the compiler checks or notifies during compilation.
Checked Exceptions are also known as compile-time exceptions. These exceptions cannot be
ignored. If a code within a function throws a checked exception, the function must handle the
exception or specify it using the throws keyword.
An unchecked exception occurs during the execution process. Unchecked Exceptions are
also known as runtime exceptions. Programming mistakes, such as logic errors or improper
use of an API, are examples of this. Runtime exceptions are ignored during compilation.

9.Formulate the advantages of using exception handling.


•Exceptions separate error handling code from regular code.
Benefit: Cleaner algorithms, less clutter
•Exceptions propagate errors up the call stack.
Benefit: Nested methods do not have to explicitly catch-and-forward errors (less work,
more reliable)
•Exception classes group and differentiate error types.
You can group errors by their generalize parent class, or Differentiate errors by their
actual class
•Exceptions standardize error handling.
10.What are the two methods available in Stack Trace Elements?
Method Name Description

String getFileName() Gets the name of the source file containing the execution
point represented by the StackTraceElement.

int getLineNumber() Gets the line number of the source file containing the
execution point represented by the StackTraceElement.

String getClassName() Gets the fully qualified name of the class containing the
execution point represented by the StackTraceElement.

String getMethodName() Gets the name of the method containing the execution
point represented by the StackTraceElement.

boolean isNativeMethod() Returns true if the execution point of the


StackTraceElement is inside a native method.

String toString() Returns a formatted string containing the class name,


method name, file name and the line number, if available.

11.Differentiate between throw and throws.


throw keyword throws keyword
1) throw is used to explicitly throw an
throws is used to declare an exception.
exception.
2) checked exception cannot be checked exception can be propagated with
propagated without throws. throws.
3) throw is followed by an instance. throws is followed by class.
4) throw is used within the method. throws is used with the method signature.
You can declare multiple exception
5)You cannot throw multiple exception e.g. public void method()throws
IOException,SQLException.

PART B

1. Explain different states of thread in detail.

2. Explain how to create threads. Write a java program that prints numbers from 1 to 10 line
by line after every 5 seconds.

3. Illustrate the two methods for creation of threads with examples.

4. Demonstrate the java synchronized methods and java synchronized blocks.

5. Create a Bank database application program to illustrate the use of multithreading.

6. Explain the exception hierarchy in java.

7. Write a java program to test the” Divide by Zero exception” and


“ArrayIndexOutofBouund” with example program (get inputs from the user).

8. Discuss the role of the finally block in exception handling. Create a Java program that
demonstrates its use and explains how it ensures that certain code is executed regardless of
whether an exception occurs.

9. Illustrate how Java handles overflows and underflows exception with example.

10. Create your own exception for “Temperature>40” in an “Atomic Reactor Based
Application” and write appropriate exception handling code in the main program.
UNIT IV
STRING, I/O AND COLLECTION FRAMEWORK

Strings:String class, String Buffer Class-Input / Output Basics – Streams – Byte streams and
Character streams – Reading and Writing Console – Reading and Writing Files- Collection
Framework: ArrayList, Set, Map.

PART A QUESTIONS WITH ANSWERS


1.Define String and String Buffer class.
The String class in Java represents a sequence of characters. Strings are immutable, meaning
once a String object is created, its value cannot be changed. Any operation that seems to
modify a String actually creates a new String object.
The StringBuffer class in Java is used to create mutable (modifiable) strings. Unlike String,
StringBuffer objects can be modified without creating new objects.

2.Examine the method used for finding length of a string?


In Java, the method used to find the length of a string is length(), which is a built-in method of
the String class. The length() method returns the number of characters in a given String. It
counts all characters, including letters, digits, spaces, punctuation, and special characters.

3.Outline the console stream classes hierarchy with neat sketch.

4.Identify three predefined stream variables in a system class.


System.in: For input (keyboard).
System.out: For standard output (console).
System.err: For error output (console).
These predefined streams are fundamental for performing console-based I/O operations in
Java applications.

5.Which method is used to write console output?


In Java, the primary method used to write console output is the println() method of the
PrintStream class, which is accessed through the System.out stream.
println(): Prints the specified message followed by a newline character.
print(): Prints the specified message without a newline character at the end.
printf(): Prints formatted output using a format string, similar to C's printf(). It allows for
more complex output formatting.

6.Sketch the console stream classes for hierarchy.


java.lang.Object
└── java.io.InputStream
│ ├── java.io.FileInputStream
│ ├── java.io.ByteArrayInputStream
│ ├── java.io.BufferedInputStream
│ └── java.io.DataInputStream
└── java.io.OutputStream
├── java.io.FileOutputStream
├── java.io.ByteArrayOutputStream
├── java.io.BufferedOutputStream
└── java.io.DataOutputStream
└── java.io.Reader
├── java.io.FileReader
├── java.io.BufferedReader
├── java.io.InputStreamReader
└── java.io.StringReader
└── java.io.Writer
├── java.io.FileWriter
├── java.io.BufferedWriter
├── java.io.OutputStreamWriter
└── java.io.StringWriter

7.Name two classes from the java.io package that are used for byte stream operations.
In the java.io package, two commonly used classes for byte stream operations are:
FileInputStream: This class is used to read raw byte data from a file. It is a subclass of
InputStream and provides methods to read bytes from a specified file.
FileOutputStream: This class is used to write raw byte data to a file. It is a subclass of
OutputStream and provides methods to write bytes to a specified file.

8.Execute a java code to change the element in an ArrayList.


import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList and add some elements
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Display the original list
System.out.println("Original ArrayList: " + fruits);

// Change an element at index 1 (Banana to Orange)


fruits.set(1, "Orange");

// Display the modified list


System.out.println("Updated ArrayList: " + fruits);
}
}

9.Implement a simple java code to find union of two sets.


import java.util.HashSet;
import java.util.Set;

public class SetUnionExample {


public static void main(String[] args) {
// Create the first set
Set<Integer> setA = new HashSet<>();
setA.add(1);
setA.add(2);
setA.add(3);

// Create the second set


Set<Integer> setB = new HashSet<>();
setB.add(3);
setB.add(4);
setB.add(5);

// Display the original sets


System.out.println("Set A: " + setA);
System.out.println("Set B: " + setB);

// Find the union of the two sets


Set<Integer> unionSet = new HashSet<>(setA); // Start with setA
unionSet.addAll(setB); // Add all elements from setB

// Display the union of the sets


System.out.println("Union of Set A and Set B: " + unionSet);
}
}
10.Write down the methods which are used in the Map Interface
V put(Object key, Object value) It is used to insert an entry in the map.

void putAll(Map map) It is used to insert the specified map in


the map.

V putIfAbsent(K key, V value) It inserts the specified value with the


specified key in the map only if it is not
already specified.

V remove(Object key) It is used to delete an entry for the


specified key.

boolean remove(Object key, Object value) It removes the specified values with the
associated specified keys from the map.

Set keySet() It returns the Set view containing all the


keys.

Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the


keys and values.

void clear() It is used to reset the map.

PART B
11.Implement the following String Buffer class methods append(), replace(), delete(),
reverse() and length() with a suitable java code.
12.Elaborate on the role of Input/Output (I/O) streams in Java. Describe the class hierarchy
of I/O streams.
13.Develop a Java program to transfer the content of one file to another file
14.Explain how to read from and write to the console in Java. Write a program that takes
multiple lines of input from the user, processes the input to count the number of words,
and outputs the result. Discuss the limitations of console-based input and how they can
be prevented.
15.Prepare a Java program that reads a text file (source.txt), searches for a specific word
(oldWord), and replaces it with another word (newWord). Save the modified content to
a new file (output.txt). Ensure efficient handling of character data and proper error
handling.
16.Compare and contrast byte streams and character streams in Java. Write a program
that reads from a text file using both byte streams and character streams, and discuss
the advantages and disadvantages of each approach.
17.Explain the ArrayList class in the Java Collection Framework with suitable example.
18.Discuss the different types of sets in the Java Collection Framework, Compare their
performance characteristics and use cases. Write a Java program that demonstrates the
use of these sets to store and manipulate a collection of unique numbers.
19.Evaluate the methods in Map with suitable java program
20.Develop a Java application for processing a large text file containing employee records.
Each record is stored as a line of text with fields separated by commas. Implement a
program that reads this text file (employee.txt), parses each record using character
streams, and computes the net_salary for all employees. Ensure efficient handling of
character data and proper error handling.
UNIT V
GENERIC PROGRAMMING AND EVENT DRIVEN PROGRAMMING
Generic Programming – Generic classes – Generic methods – Bounded Types – Restrictions
and Limitations-Basics of event handling - event handlers - adapter classes - actions - mouse
and key events –AWT - Introduction to Swing – layout management - Swing Components –
Windows–Menus– Dialog Boxes.
PART A QUESTIONS WITH ANSWERS

1.Define Generic program with example


Generic programming refers to writing code that will work for many types of data.
Example:
class Gen <T>
{
T obj;
Gen(T x)
{
obj= x;
}

T show()
{
return obj;
}

void disp()
{
System.out.println(obj.getClass().getName());
}
}

public class Test


{
public static void main (String[] args)
{
Gen < String> ob = new Gen<>("java programming with Generics");
ob.disp();
System.out.println("value : " +ob.show());

Gen < Integer> ob1 = new Gen<>(550);


ob1.disp();
System.out.println("value :" +ob1.show());
}
}

Output:
java.lang.String
value : java programming with Generics
java.lang.Integer
value :550

2.Give the Restrictions and Limitations in generic program.


1)In Java, generic types are compile time entities. The runtime execution is possible only if it
is used along with raw type.
2)Primitive type parameters are not allowed for generic programming.
For example:
Stack<int> is not allowed.
3)For the instances of generic class throw and catch keywords are not allowed.
For example:
public class Test<T> extends Exception
{
// code// Error: can‟t extend the Exception class
}
4)Instantiation of generic parameter T is not allowed.
For Example:
new T();// Error
new T[10];// Error
5)Arrays of parameterized types are not allowed.
For Example:
New Stack<String>[10];// Error

3.What is a bounded type parameter in Java Generics?


Bounded Type Parameter is a type parameter with one or more bounds. The bounds restrict
the set of types that can be used as type arguments and give access to the methods defined by
the bounds.
For example, a method that operates on numbers might only want to accept instances of
Number or its subclasses.
Syntax:
<T extends superclass>
4.Compare between adapter class and listener interface.
An EventListener interface defines the methods that must be implemented by an event
handler for a particular kind of an event whereas an Event Adapter class provides a default
implementation of an EventListener interface.
Adapter class
Used when only a few methods of an interface need to be overridden. An adapter class
provides default implementations for methods in listener interfaces, making it easier to create
event handlers. For example, a WindowAdapter is an implementation of WindowListener, so
you only need to override the methods you want to deal with.
Listener interface
Used when most of the interface methods will be used. All methods declared in a listener
interface must be implemented because these methods are final. For example, a listener can
listen to events fired during a test suite and react to them.

5.Sketch the steps needed to show a Frame.


There are two ways to create a frame in AWT.
•By extending Frame class (Inheritance)
•By creating the object of Frame class (Association)

Method 1: By Extending Frame class (Inheritance)

Create a subclass of Frame.


In the Subclass constructor
o Change the frame title by calling superclass [Frame] constructor using
super(String) method call.

oSet the size of the window explicitly by calling the setSize( ) method.
oMake the frame visible by calling setVisible() method.
In main() method
Create an instance of subclass.

Method 2: By creating the object of Frame class (Association)

Create an instance of a Frame class.


Frame f=new Frame(“ frame name”);
Set the frame size
f.setSize(500,500);
Make the frame visible
f.setVisible(true);

6.Show what method can be used for changing font of Characters?

The Font class is used to define the font style, size, and type.
The setFont() method applies the font to the specified component.

7.What is event handling? Give its three components.


Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism has the code which is known as event handler that is
executed when an event occurs.
There are three major components in the delegation event model:
1. Events
2. Event Sources
3. Event Listeners
8.Compare the JavaAWT and JavaSwing.
S.No. Swing AWT
Swing is also called as
AWT stands for Abstract
1 JFC’s (Java Foundation
windows toolkit.
classes).
Swings are called light
weight component because
AWT components are called
2 swing components sits on
Heavyweight component.
the top of AWT components
and do the work.
3 Complex components Primitive components

Swing components require AWT components require


4
javax.swing package. java.awt package.
Look and Feel feature is
5 Pluggable Look and Feel
not supported
Swing components are made
AWT components are
6 in purely java and they
platform dependent.
are platform independent.

7 Works faster than AWT Works slow

9.Write a java code for Button creation.


import java.awt.*;
public class Use_Button
{
public static void main(String[] args)
{
Frame fr=new Frame("Using Buttons");
fr.setSize(400,200);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Button B1=new Button();
B1.setLabel("Ok");
Button B2=new Button("CANCEL");
Button button[]=new Button[3];
String colors[]={"Red","Blue","Green"};
for(int i=0;i<button.length;i++)
{
button[i]=new Button(""+colors[i]);
fr.add(button[i]);
}
fr.add(B1);
fr.add(B2);
}
}

10.How to create a menu in frame?

To create a menu in a Java AWT frame, follow these steps:

1. Create a MenuBar: Instantiate a MenuBar object.


2. Add Menus and Menu Items:
o Create Menu objects (e.g., Menu fileMenu = new Menu("File");).
o Create MenuItem objects (e.g., MenuItem exitItem = new MenuItem("Exit");).
o Add the MenuItem objects to the Menu using menu.add(menuItem);.
3. Set the MenuBar: Attach the MenuBar to the frame with frame.setMenuBar(menuBar);.

PART B
1. Discuss the following with example programs.
Generic class and Generic method
2. Explain in details about swing components
3. Implement a Java Program to display User Authentication page using AWT/Swing.
4. Explain in details about event handling?
5. Illustrate in detail about working with 2D shapes in Java.

6. Implement a Java program to display the following picture in frame.

Note: An ellipse should be inside a Rectangle. Colors also can be used.


7. Explain layout manager with its types which is available in Java Swing with suitable program
8. Write a program to create a frame with the following menus, such that the corresponding
geometric object is created when a menu is clicked. a. Circle. b. Rectangle. c. Line. d. Diagonal
for the rectangle.
9. Analyze and write a simple calculator using mouse events that restrict only addition, subtraction,
multiplication and division.
10. Develop the java code to simulates a traffic light

You might also like