0% found this document useful (0 votes)
6 views8 pages

Java OOP Detailed Answers

The document provides a comprehensive overview of Java programming and Object-Oriented Programming (OOP) concepts, covering key differences between Procedure-Oriented and OOP, benefits and applications of OOP, and fundamental Java features. It discusses classes, inheritance, method overriding, polymorphism, exception handling, multithreading, and I/O operations, along with practical examples. Additionally, it explains the significance of packages, interfaces, constructors, and the String class in Java.

Uploaded by

meghna23456786
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)
6 views8 pages

Java OOP Detailed Answers

The document provides a comprehensive overview of Java programming and Object-Oriented Programming (OOP) concepts, covering key differences between Procedure-Oriented and OOP, benefits and applications of OOP, and fundamental Java features. It discusses classes, inheritance, method overriding, polymorphism, exception handling, multithreading, and I/O operations, along with practical examples. Additionally, it explains the significance of packages, interfaces, constructors, and the String class in Java.

Uploaded by

meghna23456786
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

Java Programming & OOP

Detailed Answers — All Units (5 Marks Each)

UNIT 1

Q1. Difference between Object-Oriented and Procedure-Oriented Programming


Programming paradigms define how a programmer structures and writes code. The two major paradigms
are Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP).

Aspect Procedure-Oriented (POP) Object-Oriented (OOP)

Approach Top-down Bottom-up

Focus Functions/Procedures Objects & Classes

Data Security Data is globally accessible Data is encapsulated & hidden

Code Reuse Limited (function calls) High (inheritance, polymorphism)

Maintenance Difficult for large programs Easier due to modularity

Examples C, Pascal, FORTRAN Java, C++, Python

Real-world model Not closely modelled Closely models real world

Q2. OOPs — Benefits and Applications


Benefits of OOP:
• Encapsulation: Data and methods are bundled together. Internal details are hidden from outside,
improving security and reducing complexity.
• Reusability: Classes and objects can be reused across different programs via inheritance, saving
development time.
• Modularity: Code is divided into self-contained objects, making it easier to manage, debug and
maintain.
• Polymorphism: A single interface can represent different types. Reduces code duplication and
increases flexibility.
• Abstraction: Shows only essential information and hides background details, reducing
programming complexity.
• Scalability: OOP systems are easier to scale and extend because new classes can be added with
minimal changes to existing code.

Applications of OOP:
• GUI Applications: Windows, buttons, menus are modeled as objects (e.g., Java Swing, JavaFX).
• Web Development: Frameworks like Spring (Java) use OOP extensively.
• Game Development: Game entities (players, enemies) are objects with properties and behaviors.
• Database Systems: ORM tools like Hibernate map Java objects to database tables.
• Embedded Systems: C++ is used in embedded OOP applications.
• Simulation & Modelling: Real-world entities are represented as objects.

Q3. Classes, Inheritance, Method Overriding & Polymorphism


(a) Classes in Java:
A class is a blueprint for creating objects. It defines attributes (fields) and behaviors (methods). Objects are
instances of a class.
class Animal { String name; void sound() { [Link]("Some sound"); } }

(b) Inheritance:
Inheritance allows a child class to acquire properties and methods of a parent class using the 'extends'
keyword. Types: Single, Multilevel, Hierarchical, and (through interfaces) Multiple.
class Dog extends Animal { void sound() { [Link]("Bark"); } // overrides
}

(c) Method Overriding:


When a subclass provides a specific implementation of a method already defined in its parent class, it is
called method overriding. The method must have the same name, return type, and parameters. @Override
annotation is recommended.

(d) Polymorphism:
Polymorphism means 'many forms'. In Java:

• Compile-time (Static): Method Overloading — same method name, different parameters.


• Runtime (Dynamic): Method Overriding — resolved at runtime based on object type.
Animal a = new Dog(); // runtime polymorphism [Link](); // calls Dog's sound()
UNIT 2

Q1. Java — Basic Features & Why Java is More Suitable


Key Features of Java:
• Platform Independent: Java code is compiled to bytecode, which runs on any machine with JVM —
'Write Once, Run Anywhere'.
• Object-Oriented: Everything in Java is based on objects and classes.
• Robust: Strong type checking, exception handling, and garbage collection make Java reliable.
• Secure: Java has a security manager and no pointer arithmetic, preventing unauthorized memory
access.
• Multithreaded: Java supports built-in multithreading for concurrent execution.
• Simple: Syntax is similar to C/C++ but removes complex features like pointers.
• High Performance: Just-In-Time (JIT) compiler converts bytecode to machine code at runtime.
• Distributed: Java has libraries for distributed computing (RMI, sockets).
Why Java is More Suitable:
Java is preferred for enterprise, web, and mobile development because of its platform independence
(JVM), automatic memory management (GC), rich standard library (Java API), strong community support,
and wide use in Android development. It is also type-safe, reducing runtime errors.

Q2. Data Types and Variables, Operators


Data Types:
Category Type Size Example

Primitive int 4 bytes 42

Primitive double 8 bytes 3.14

Primitive char 2 bytes 'A'

Primitive boolean 1 bit true/false

Primitive byte/short/long/float varies depends

Non-Primitive String, Array, Class varies "Hello"

Variables: Named memory locations. Types: Local, Instance, Static.


int x = 10; // local variable static int count = 0; // static variable

Operators in Java:
• Arithmetic: +, -, *, /, % (e.g., 10 % 3 = 1)
• Relational: ==, !=, >, <, >=, <= (returns boolean)
• Logical: && (AND), || (OR), ! (NOT)
• Bitwise: &, |, ^, ~, <<, >> (operate on bits)
• Assignment: =, +=, -=, *=, /=
• Unary: ++, -- (increment/decrement)
• Ternary: condition ? expr1 : expr2
Q3. Constructor, Method Overloading, Garbage Collection, Arrays
(a) Constructor:
A constructor is a special method called automatically when an object is created. It has the same name as
the class and no return type. Types: Default, Parameterized, Copy.
class Car { String model; Car(String m) { [Link] = m; } // parameterized
constructor }

(b) Method Overloading:


Multiple methods with the same name but different parameters (number/type). Resolved at compile time
(static polymorphism).
int add(int a, int b) { return a+b; } double add(double a, double b) { return a+b; }

(c) Garbage Collection:


Java automatically manages memory. Objects no longer referenced are automatically deleted by the
Garbage Collector (GC), freeing heap memory. The programmer can suggest GC with [Link]() but
cannot force it. This prevents memory leaks.

(d) Arrays:
Arrays are fixed-size collections of elements of the same type.
int[] arr = {10, 20, 30}; // 1D array int[][] matrix = new int[3][3]; // 2D array
[Link]([Link]); // 3

Q4. Abstract Class & Argument Passing


(a) Abstract Class:
An abstract class is declared with the 'abstract' keyword. It cannot be instantiated directly. It may contain
abstract methods (without body) that must be overridden by subclasses. It can also have concrete
methods.
abstract class Shape { abstract double area(); // no body void display() {
[Link]("Shape"); } // concrete } class Circle extends Shape { double r;
double area() { return 3.14 * r * r; } // must implement }

(b) Argument Passing:


• Pass by Value: For primitive types. A copy is passed; original is unchanged.
• Pass by Reference: For objects. The reference (address) is passed; changes affect original object.
void change(int x) { x = 100; } // primitive - original unchanged void change(int[]
arr) { arr[0]=100; } // array ref - original changes
UNIT 3

Q1. Packages in Detail


A package is a namespace that organizes a set of related classes and interfaces. It avoids naming
conflicts and provides access control.

Types of Packages:
• Built-in Packages: [Link], [Link], [Link], [Link], [Link], [Link]
• User-defined Packages: Created by the programmer for project organization.

Creating and Using a Package:


// File: mypackage/[Link] package mypackage; public class Hello { public void
greet() { [Link]("Hello!"); } } // Using the package import
[Link]; Hello h = new Hello(); [Link]();

Access Modifiers with Packages:


• public: accessible everywhere | protected: same package + subclasses | default: same package only
| private: same class only

Q2. Interface in Detail


An interface is a fully abstract type — it contains only abstract method declarations (and constants). A
class 'implements' an interface and must define all its methods. Java supports multiple inheritance through
interfaces.
interface Drawable { void draw(); // abstract by default } interface Resizable { void
resize(int factor); } class Square implements Drawable, Resizable { public void
draw() { [Link]("Drawing square"); } public void resize(int f) {
[Link]("Resizing by " + f); } }

Interface vs Abstract Class:


• Interface: all methods abstract (until Java 8 default methods), multiple implementation allowed.
• Abstract Class: can have concrete methods, only single inheritance.

Q3. Exception Handling in Detail


An exception is an unexpected event during program execution that disrupts normal flow. Java provides a
robust mechanism to handle exceptions using try-catch-finally blocks.

Exception Hierarchy:
Throwable → Error (serious, not handled) | Exception → Checked / Unchecked (RuntimeException)

Keywords:
• try: Block of code that might throw an exception.
• catch: Handles a specific exception type.
• finally: Always executes (cleanup code), whether exception occurs or not.
• throw: Manually throw an exception.
• throws: Declares exceptions a method may throw.
try { int result = 10 / 0; } catch (ArithmeticException e) {
[Link]("Error: " + [Link]()); } finally {
[Link]("Always runs"); }
Custom Exception:
class AgeException extends Exception { AgeException(String msg) { super(msg); } } //
throw new AgeException("Age must be > 0");
UNIT 4

Q1. Multithreading — Main Thread, Java Thread Model, Priorities


Multithreading allows multiple threads to execute concurrently within a single program, maximizing CPU
utilization.

Main Thread:
When a Java program starts, the JVM creates a main thread automatically. It is the thread from which all
other threads are spawned.

Creating Threads — Two Ways:


// Method 1: Extend Thread class class MyThread extends Thread { public void run() {
[Link]("Thread running"); } } // Method 2: Implement Runnable interface
class MyRunnable implements Runnable { public void run() {
[Link]("Runnable running"); } } Thread t = new Thread(new MyRunnable());
[Link]();

Thread Life Cycle: New → Runnable → Running → Blocked/Waiting → Dead


Thread Priorities:
• Range: 1 (MIN_PRIORITY) to 10 (MAX_PRIORITY), default is 5 (NORM_PRIORITY).
• Higher priority threads get more CPU time, but it's not guaranteed.
• Set using: [Link](Thread.MAX_PRIORITY);

Java Thread Model — Key Methods:


• start(): Starts thread
• run(): Thread body
• sleep(ms): Pauses thread
• join(): Waits for thread to finish
• yield(): Temporarily pauses
• isAlive(): Checks if running
• synchronized: Prevents race condition

Q2. I/O — Char Stream, Stream Classes, Reading/Writing Files


Java I/O is handled via [Link] package. Two types of streams:

• Byte Streams: Handle binary data. Classes: InputStream, OutputStream and subclasses
(FileInputStream, FileOutputStream).
• Character Streams: Handle text data (Unicode). Classes: Reader, Writer and subclasses
(FileReader, FileWriter, BufferedReader, BufferedWriter).

Reading a File (Character Stream):


import [Link].*; BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line; while ((line = [Link]()) != null) { [Link](line); }
[Link]();

Writing to a File:
BufferedWriter bw = new BufferedWriter(new FileWriter("[Link]"));
[Link]("Hello, File!"); [Link](); [Link]();
Always close streams (or use try-with-resources) to avoid resource leaks.

Q3. String Class, Operations & StringBuffer Class/Methods


String Class:
Strings in Java are immutable objects of the [Link] class. Once created, they cannot be modified
— any operation returns a new String.

Common String Operations:


Method Description Example

length() Returns length of string "Hello".length() → 5

charAt(i) Returns char at index i "Hello".charAt(1) → e

substring(i,j) Extracts substring "Hello".substring(1,3) → el

toUpperCase() Converts to uppercase "hello".toUpperCase() → HELLO

equals() Compares strings "a".equals("a") → true

indexOf() Finds position "Hello".indexOf("l") → 2

replace() Replaces characters "Hello".replace("l","r") → Herro

trim() Removes whitespace " Hi ".trim() → "Hi"

split() Splits into array "a,b".split(",") → ["a","b"]

StringBuffer Class (Mutable Strings):


Unlike String, StringBuffer is mutable — it can be modified without creating new objects. It is thread-safe
(synchronized). StringBuilder is similar but not thread-safe (faster).
StringBuffer sb = new StringBuffer("Hello"); [Link](" World"); // Hello World
[Link](5, ","); // Hello, World [Link](0, 5, "Hi"); // Hi, World [Link](2,
4); // Hi World [Link](); // dlroW iH [Link]([Link]()); // length
[Link]([Link]()); // convert to String

String vs StringBuffer vs StringBuilder:


Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread Safe Yes Yes No

Performance Slow (many strings) Medium Fast

Use Case Fixed strings Multi-threaded Single-threaded

All Units Covered | Java OOP Detailed Answers | 5 Marks Each Question

You might also like