You are on page 1of 14

Q1 What is OOP? Explain properties of OOP.

Object-Oriented Programming (OOP): OOP is a programming paradigm that revolves around the
concept of "objects," which can contain data and code to manipulate that data. It is based on four
main principles: Encapsulation, Abstraction, Inheritance, and Polymorphism.

Properties of OOP:

Encapsulation: Encapsulation is the bundling of data and the methods that operate on that data into
a single unit called a class. It restricts direct access to some of an object's components and can
prevent the accidental modification of data.

Abstraction: Abstraction is the concept of simplifying complex systems by modeling classes based on
the essential properties and behaviors they share. It involves showing only the necessary features of
an object while hiding its implementation details.

Inheritance: Inheritance is a mechanism that allows a class to inherit properties and behaviors from
another class. It promotes code reusability and establishes a relationship between a superclass and
its subclasses.

Polymorphism: Polymorphism allows objects of different types to be treated as objects of a common


type. It provides a way to use a single interface to represent different types of objects and their
behaviors.

Q2: What is an operator? Explain different types of Operator.

Operator: An operator in programming is a symbol that represents an operation or computation.


Operators are used to perform various operations on variables and values.

Types of Operators:

Arithmetic Operators: Perform basic arithmetic operations (e.g., +, -, *, /).

Relational Operators: Compare values and return a boolean result (e.g., ==, !=, <, >).

Logical Operators: Perform logical operations and return a boolean result (e.g., &&, ||, !).

Assignment Operators: Assign values to variables (e.g., =, +=, -=).

Increment/Decrement Operators: Increase or decrease the value of a variable (e.g., ++, --).

Bitwise Operators: Perform bitwise operations on integers (e.g., &, |, ^).

Conditional (Ternary) Operator: A shorthand way of writing an if-else statement (e.g., condition ?
true_expression : false_expression).
Q3: What is a data type? Explain different types of data types.

Data Type: In programming, a data type is an attribute of a variable that defines the kind of data it
can hold. It specifies the size and type of values that a variable can store.

Types of Data Types:

Primitive Data Types: Represent basic values and include int, float, char, boolean, etc.Composite Data
Types: Combine multiple primitive data types. Examples include arrays, structures, and classes.

Derived Data Types: Derived from primitive or composite types. Examples include pointers and
arrays.

Abstract Data Types: Defined by the user and implemented using primitive or composite types.
Examples include stacks, queues, and lists.

Q4: What is JVM? Explain the architecture of JVM.

JVM (Java Virtual Machine): JVM is a virtual machine that enables a computer to run Java programs.
It provides a runtime environment in which Java bytecode can be executed.

JVM Architecture:

Class Loader Subsystem: Loads class files into memory.

Memory Area: Divided into Heap, Stack, Method Area, and PC Registers.

Execution Engine: Executes Java bytecode.

Java Native Interface (JNI): Provides a bridge between Java and native applications.

Native Method Interface: Allows Java code to call and be called by native applications.

Java API: A collection of pre-written classes and methods.

Q5: What is an access modifier? Explain with an example.

Access Modifier: In Java, access modifiers define the visibility or accessibility of a class, method, or
variable. There are four types: public,private, protected, and default (package-private).
Q6: What is a constructor? What is constructor overloading? Explain different types of constructors.

Constructor: A constructor in Java is a special method that is used to initialize objects. It is called
when an object of a class is created and has the same name as the class.

Constructor Overloading: Constructor overloading is the ability to define multiple constructors with
different parameter lists within the same class. This allows for the creation of objects in different
ways.

Types of Constructors:

Default Constructor: Has no parameters. Automatically provided by Java if no constructor is defined.

Parameterized Constructor: Takes parameters to initialize the object with specific values.

Copy Constructor: Constructs an object by copying values from another object of the same class.

Q7: What is a wrapper class? Explain different types of wrapper classes. Explain autoboxing and
unboxing.

Wrapper Class: In Java, wrapper classes are used to convert primitive data types into objects. The
eight primitive data types (int, char, etc.) have corresponding wrapper classes (Integer, Character,
etc.).

Types of Wrapper Classes:

1.Integer

2.Double

3.Boolean

4.Byte

5.Short

6.Long

7.Float

8.Character

Autoboxing and Unboxing:

Autoboxing: The process of converting a primitive data type into its corresponding wrapper class
object automatically by the Java compiler.

Unboxing: The process of converting a wrapper class object back to its corresponding primitive data
type automatically by the Java compiler.
Q8: What is inheritance? Explain types and significance of inheritance with an example.

Inheritance: Inheritance is a mechanism in Java where a class inherits properties and behaviors from
another class. It promotes code reusability and establishes a relationship between a superclass and
its subclasses.

Types of Inheritance:

Single Inheritance: A class inherits from only one superclass.

Multiple Inheritance: A class inherits from more than one superclass (Java doesn't support this
directly).

Multilevel Inheritance: A class is derived from another class, which is derived from another class.
Q9: What is polymorphism? Explain implementation [method overloading and overriding] using an
example.

Polymorphism: Polymorphism allows objects of different types to be treated as objects of a common


type. In Java, there are two types of polymorphism: compile-time (method overloading) and runtime
(method overriding).

Method Overloading:

Method Overriding:
Q10: What is dynamic method dispatch? Explain with an example.

Dynamic Method Dispatch: It is a mechanism in Java where the method called on an object is
determined at runtime. It is achieved through method overriding.

Q11: What is data abstraction? Explain interface and abstract class with an example.

Data Abstraction: Abstraction is the process of hiding the implementation details and showing only
the essential features of an object.

Interface:

Abstract Class:
Q12: Explain error and Exception. What is exception handling? Describe exception handling blocks
with an example.

Error: Errors in Java are exceptional scenarios that typically cannot be handled by the program.
Examples include OutOfMemoryError and StackOverflowError.

Exception: Exceptions are abnormal events or runtime errors that occur during the execution of a
program. Examples include NullPointerException and ArrayIndexOutOfBoundsException.

Exception Handling:Exception handling in Java is done using try, catch, finally, and throw keywords.

Q13: What is multithreading? How is multithreading different from multitasking? Explain different
techniques to create a thread.

Multithreading: Multithreading is the concurrent execution of two or more threads. A thread is a


lightweight process, and multithreading allows multiple tasks to run concurrently within a program.

difference from Multitasking: Multitasking involves executing multiple processes or programs


simultaneously, while multithreading involves executing multiple threads within a single process.

Creating a Thread:

Extending Thread Class:

1. class MyThread extends Thread {


2. public void run() {
3. System.out.println("Thread is running");
4. }
5. }

Implementing Runnable interface:

1. class MyRunnable implements Runnable {


2. public void run() {
3. System.out.println("Thread is running");
4. }
5. }
Q14: What is the thread execution prevention method? Define yield(), join(), sleep() with an
example.

Thread Execution Prevention:

yield(): Allows the currently executing thread to voluntarily pause and give other threads a chance to
execute.

Thread.yield();

join(): Waits for a thread to die before the current thread continues its execution.

Thread thread1 = new Thread();

thread1.join();

sleep(): Suspends the execution of the current thread for a specified amount of time.

Thread.sleep(1000);

Q15: What is an inner class? Explain different types of inner classes with an example.

Inner Class: An inner class is a class defined inside another class.

Types of Inner Classes:

1. class Outer {
2. class Inner {
3. // Inner class code
4. }
5. }

Member Inner Class:

1. class Outer {
2. static class Nested {
3. // Nested class code
4. }
5. }

Local Inner Class:

1. class Outer {
2. void outerMethod() {
3. class Inner {
4. // Local inner class code
5. }
6. }
7. }

Anonymous Inner Class:

1. interface Greeting {
2. void greet();
3. }
4.
5. class Example {
6. Greeting greeting = new Greeting() {
7. @Override
8. public void greet() {
9. System.out.println("Hello!");
10. }
11. };
12. }

Q16: What is the collection framework? Explain List, Set, Map interface with an example.

Collection Framework: It provides a set of classes and interfaces to represent a group of objects as a
single unit.

List Interface:

1. List<String> myList = new ArrayList<>();


2. myList.add("Item 1");
3. myList.add("Item 2");

Set Interface:

1. Set<Integer> mySet = new HashSet<>();


2. mySet.add(1);
3. mySet.add(2);

Map Interface:

1. Map<String, Integer> myMap = new HashMap<>();


2. myMap.put("Key 1", 100);
3. myMap.put("Key 2", 200);

Q17: What is Applet? Explain the applet life cycle with a diagram.

Applet: An applet is a small Java program that runs within a web browser.

Applet Life Cycle:

Initialization (init()): Initializes the applet and is called once when the applet is loaded.

Starting (start()): Invoked after init() and each time the applet is revisited.

Stopping (stop()): Called when the applet is no longer visible.

Destroying (destroy()): Called when the browser unloads the applet.


Q18: Explain the class hierarchy of the Exception class. Differentiate Error and Exception.

Class Hierarchy of Exception:

• Throwable (Superclass of all exceptions and errors)


- Error (Irrecoverable situations)
a) OutOfMemoryError
b) StackOverflowError
• Exception (Recoverable situations)
- Unchecked Exceptions (RuntimeException, etc.)
a) NullPointerException
- Checked Exceptions (IOException, etc.)
a) FileNotFoundException

Difference between Error and Exception:

Error: Irrecoverable, often caused by the environment. For example, OutOfMemoryError.

Exception: Recoverable, caused by the application. Can be checked or unchecked.


Q19: What is event handling? Explain the event delegation model. Write a Java program to handle a
mouse click event using an anonymous inner class.

Event Handling: In Java, event handling involves responding to user actions (events) such as button
clicks or mouse movements.

Event Delegation Model: In this model, an object (delegate) listens and responds to events on behalf
of another object. It helps to centralize and manage event handling.

Example: Handling Mouse Click Event with an Anonymous Inner Class:

1. import java.awt.event.*;
2.
3. class ClickHandler implements ActionListener {
4. public void actionPerformed(ActionEvent e) {
5. System.out.println("Button clicked!");
6. }
7. }
8.
9. class GUI {
10. public static void main(String[] args) {
11. javax.swing.JButton button = new javax.swing.JButton("Click Me");
12. ClickHandler handler = new ClickHandler();
13.
14. // Event registration using an anonymous inner class
15. button.addActionListener(new ActionListener() {
16. public void actionPerformed(ActionEvent e) {
17. System.out.println("Button clicked (Anonymous Inner Class)!");
18. }
19. });
20.
21. // Event registration using a separate class
22. button.addActionListener(handler);
23.
24. javax.swing.JFrame frame = new javax.swing.JFrame("Event Handling Example");
25. frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
26. frame.getContentPane().add(button);
27. frame.setSize(300, 200);
28. frame.setVisible(true);
29. }
30. }
Q20: What is an adapter class? Write a program to handle a ,key-typed event using an anonymous
inner class.

Adapter Class: An adapter class in Java provides default implementations of methods for listener
interfaces. It allows you to implement only the methods you need.

Example: Handling Key-Typed Event with an Anonymous Inner Class:

1. import java.awt.event.*;
2.
3. class KeyAdapterExample {
4. public static void main(String[] args) {
5. javax.swing.JFrame frame = new javax.swing.JFrame("Key Event Example");
6.
7. javax.swing.JTextField textField = new javax.swing.JTextField();
8. textField.addKeyListener(new KeyAdapter() {
9. public void keyTyped(KeyEvent e) {
10. System.out.println("Key Typed: " + e.getKeyChar());
11. }
12. });
13.
14. frame.getContentPane().add(textField);
15. frame.setSize(300, 200);
16. frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
17. frame.setVisible(true);
18. }
19. }
Q21: Differentiate AWT and Swing. Write a program to demonstrate the use of TextField,
JTextField, Label, JLabel, Button, JButton.

AWT vs. Swing:

AWT (Abstract Window Toolkit): Part of Java's core libraries, platform-dependent, heavyweight
components.

Swing: Part of the Java Foundation Classes (JFC), platform-independent, lightweight components.

Example: Using AWT and Swing Components:

1. import javax.swing.*;
2.
3. public class GUIExample {
4. public static void main(String[] args) {
5. // AWT Components
6. java.awt.Frame awtFrame = new java.awt.Frame("AWT Frame");
7. java.awt.TextField awtTextField = new java.awt.TextField();
8. java.awt.Label awtLabel = new java.awt.Label("AWT Label");
9. java.awt.Button awtButton = new java.awt.Button("AWT Button");
10.
11. awtFrame.add(awtTextField);
12. awtFrame.add(awtLabel);
13. awtFrame.add(awtButton);
14. awtFrame.setSize(300, 200);
15. awtFrame.setLayout(new java.awt.FlowLayout());
16. awtFrame.setVisible(true);
17.
18. // Swing Components
19. javax.swing.JFrame swingFrame = new javax.swing.JFrame("Swing Frame");
20. javax.swing.JTextField swingTextField = new javax.swing.JTextField();
21. javax.swing.JLabel swingLabel = new javax.swing.JLabel("Swing Label");
22. javax.swing.JButton swingButton = new javax.swing.JButton("Swing Button");
23.
24. swingFrame.add(swingTextField);
25. swingFrame.add(swingLabel);
26. swingFrame.add(swingButton);
27. swingFrame.setSize(300, 200);
28. swingFrame.setLayout(new javax.swing.FlowLayout());
29. swingFrame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
30. swingFrame.setVisible(true);
31. }
32. }
Q22: Differentiate ByteStream and CharacterStream. Explain BufferedReader class with an example.
Write a program to accept two numbers using BufferedReader class and print their sum.

ByteStream vs. CharacterStream:

ByteStream (InputStream, OutputStream): Used for handling binary data.

CharacterStream (Reader, Writer): Used for handling character data.

BufferedReader Example:

1. import java.io.*;
2.
3. public class BufferedReaderExample {
4. public static void main(String[] args) {
5. try {
6. // InputStreamReader converts bytes to characters
7. // BufferedReader reads characters efficiently
8. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
9.
10. System.out.print("Enter the first number: ");
11. String input1 = reader.readLine();
12. int num1 = Integer.parseInt(input1);
13.
14. System.out.print("Enter the second number: ");
15. String input2 = reader.readLine();
16. int num2 = Integer.parseInt(input2);
17.
18. int sum = num1 + num2;
19. System.out.println("Sum: " + sum);
20.
21. // Close the BufferedReader
22. reader.close();
23. } catch (IOException | NumberFormatException e) {
24. e.printStackTrace();
25. }
26. }
27. }

You might also like