Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information Technology Engineering/
  4. IT Semester 4/
  5. Object Oriented Programming With Java (4341602)/

Object Oriented Programming With Java (4341602) - Summer 2023 Solution

·
Study-Material Solutions Java Oop 4341602 2023 Summer
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

Question 1(a) [3 marks]
#

Differentiate between Procedure-Oriented Programming (POP) and Object-Oriented Programming (OOP).

Answer:

Table:

AspectPOPOOP
FocusFunctions/ProceduresObjects and Classes
Data SecurityLess secure, global dataMore secure, data encapsulation
Problem SolvingTop-down approachBottom-up approach
Code ReusabilityLimitedHigh through inheritance
ExamplesC, PascalJava, C++, Python
  • POP: Program divided into functions, data flows between functions
  • OOP: Program organized around objects that contain both data and methods

Mnemonic: “POP Functions, OOP Objects”


Question 1(b) [4 marks]
#

Explain Super keyword in inheritance with suitable example.

Answer:

Super keyword is used to access parent class members from child class.

Table: Super keyword uses

UsePurposeExample
super()Call parent constructorsuper(name, age)
super.method()Call parent methodsuper.display()
super.variableAccess parent variablesuper.name

Code Block:

class Animal {
    String name = "Animal";
    void eat() { System.out.println("Animal eats"); }
}

class Dog extends Animal {
    String name = "Dog";
    void eat() {
        super.eat(); // calls parent method
        System.out.println("Dog eats bones");
    }
    void display() {
        System.out.println(super.name); // prints "Animal"
    }
}

Mnemonic: “Super calls Parent”


Question 1(c) [7 marks]
#

Define: Method Overriding. List out Rules for method overriding. Write a java program that implements method overriding.

Answer:

Method Overriding: Child class provides specific implementation of parent class method with same signature.

Table: Method Overriding Rules

RuleDescription
Same nameMethod name must be identical
Same parametersParameter list must match exactly
IS-A relationshipMust have inheritance
Access modifierCannot reduce visibility
Return typeMust be same or covariant

Code Block:

class Shape {
    void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle");
    }
}

class Main {
    public static void main(String[] args) {
        Shape s = new Circle();
        s.draw(); // Output: Drawing a circle
    }
}

Mnemonic: “Override Same Signature”


Question 1(c OR) [7 marks]
#

Describe: Interface. Write a java program using interface to demonstrate multiple inheritance.

Answer:

Interface: Blueprint containing abstract methods and constants. Classes implement interfaces to achieve multiple inheritance.

Table: Interface Features

FeatureDescription
Abstract methodsNo implementation (before Java 8)
ConstantsAll variables are public static final
Multiple inheritanceClass can implement multiple interfaces
Default methodsConcrete methods (Java 8+)

Code Block:

interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck implements Flyable, Swimmable {
    public void fly() {
        System.out.println("Duck flies");
    }
    
    public void swim() {
        System.out.println("Duck swims");
    }
}

class Main {
    public static void main(String[] args) {
        Duck d = new Duck();
        d.fly();
        d.swim();
    }
}

Mnemonic: “Interface Multiple Implementation”


Question 2(a) [3 marks]
#

Explain the Java Program Structure with example.

Answer:

Java Program Structure consists of package, imports, class declaration, and main method.

Diagram:

PICamlcpaVMkosaearsrtgtihedaosebdstclstaleatasteremametenintotsn

Code Block:

package com.example;        // Package
import java.util.*;         // Import

public class HelloWorld {   // Class
    static int count = 0;   // Variable
    
    public static void main(String[] args) { // Main method
        System.out.println("Hello World");
    }
}

Mnemonic: “Package Import Class Main”


Question 2(b) [4 marks]
#

Explain static keyword with suitable example.

Answer:

Static keyword belongs to class rather than instance. Memory allocated once.

Table: Static Uses

TypeDescriptionExample
Static variableShared by all objectsstatic int count
Static methodCalled without objectstatic void display()
Static blockExecutes before mainstatic { }

Code Block:

class Student {
    static String college = "GTU";  // static variable
    String name;
    
    static void showCollege() {     // static method
        System.out.println(college);
    }
    
    static {                        // static block
        System.out.println("Static block executed");
    }
}

class Main {
    public static void main(String[] args) {
        Student.showCollege(); // No object needed
    }
}

Mnemonic: “Static Shared by Class”


Question 2(c) [7 marks]
#

Define: Constructor. List out types of it. Explain Parameterized and copy constructor with suitable example.

Answer:

Constructor: Special method to initialize objects, same name as class, no return type.

Table: Constructor Types

TypeDescriptionExample
DefaultNo parametersStudent()
ParameterizedWith parametersStudent(String name)
CopyCreates copy of objectStudent(Student s)

Code Block:

class Student {
    String name;
    int age;
    
    // Parameterized constructor
    Student(String n, int a) {
        name = n;
        age = a;
    }
    
    // Copy constructor
    Student(Student s) {
        name = s.name;
        age = s.age;
    }
    
    void display() {
        System.out.println(name + " " + age);
    }
}

class Main {
    public static void main(String[] args) {
        Student s1 = new Student("John", 20);  // Parameterized
        Student s2 = new Student(s1);          // Copy
        s1.display();
        s2.display();
    }
}

Mnemonic: “Constructor Initializes Objects”


Question 2(a OR) [3 marks]
#

Explain the Primitive Data Types and User Defined Data Types in java.

Answer:

Primitive Data Types: Built-in types provided by Java language. User Defined Types: Custom types created by programmer using classes.

Table: Data Types

CategoryTypesSizeExample
Primitivebyte, short, int, long1,2,4,8 bytesint x = 10;
Primitivefloat, double4,8 bytesdouble d = 3.14;
Primitivechar, boolean2,1 byteschar c = ‘A’;
User DefinedClass, Interface, ArrayVariableStudent s;
  • Primitive: Stored in stack, faster access
  • User Defined: Stored in heap, complex operations

Mnemonic: “Primitive Built-in, User Custom”


Question 2(b OR) [4 marks]
#

Explain this keyword with suitable example.

Answer:

This keyword refers to current object instance, used to distinguish between instance and local variables.

Table: This keyword uses

UsePurposeExample
this.variableAccess instance variablethis.name = name;
this.method()Call instance methodthis.display();
this()Call constructorthis(name, age);

Code Block:

class Student {
    String name;
    int age;
    
    Student(String name, int age) {
        this.name = name;    // this distinguishes
        this.age = age;      // instance from parameter
    }
    
    void setData(String name) {
        this.name = name;    // this refers to current object
    }
    
    void display() {
        System.out.println(this.name + " " + this.age);
    }
}

Mnemonic: “This Current Object”


Question 2(c OR) [7 marks]
#

Define Inheritance. List out types of it. Explain multilevel and hierarchical inheritance with suitable example.

Answer:

Inheritance: Mechanism where child class acquires properties and methods of parent class.

Table: Inheritance Types

TypeDescriptionStructure
SingleOne parent, one childA → B
MultilevelChain of inheritanceA → B → C
HierarchicalOne parent, multiple childrenA → B, A → C
MultipleMultiple parents (via interfaces)B,C → A

Diagram - Multilevel:

graph TD
    A[Animal] --> B[Mammal]
    B --> C[Dog]

Code Block - Multilevel:

class Animal {
    void eat() { System.out.println("Animal eats"); }
}

class Mammal extends Animal {
    void breathe() { System.out.println("Mammal breathes"); }
}

class Dog extends Mammal {
    void bark() { System.out.println("Dog barks"); }
}

Diagram - Hierarchical:

graph TD
    A[Shape] --> B[Circle]
    A --> C[Rectangle]
    A --> D[Triangle]

Code Block - Hierarchical:

class Shape {
    void draw() { System.out.println("Drawing shape"); }
}

class Circle extends Shape {
    void drawCircle() { System.out.println("Drawing circle"); }
}

class Rectangle extends Shape {
    void drawRectangle() { System.out.println("Drawing rectangle"); }
}

Mnemonic: “Inheritance Shares Properties”


Question 3(a) [3 marks]
#

Explain Type Conversion and Casting in java.

Answer:

Type Conversion: Converting one data type to another. Casting: Explicit type conversion by programmer.

Table: Type Conversion

TypeDescriptionExample
Implicit (Widening)Automatic, smaller to largerint to double
Explicit (Narrowing)Manual, larger to smallerdouble to int

Code Block:

// Implicit conversion
int i = 10;
double d = i;        // int to double (automatic)

// Explicit casting
double x = 10.5;
int y = (int) x;     // double to int (manual)

// String conversion
String s = String.valueOf(i);    // int to String
int z = Integer.parseInt("123"); // String to int

Mnemonic: “Implicit Auto, Explicit Manual”


Question 3(b) [4 marks]
#

Explain different visibility controls used in Java.

Answer:

Visibility Controls (Access Modifiers): Control access to classes, methods, and variables.

Table: Access Modifiers

ModifierSame ClassSame PackageSubclassDifferent Package
private
default
protected
public

Code Block:

class Example {
    private int x = 10;      // Only within class
    int y = 20;              // Package level
    protected int z = 30;    // Package + subclass
    public int w = 40;       // Everywhere
    
    private void method1() { }    // Private method
    public void method2() { }     // Public method
}

Mnemonic: “Private Package Protected Public”


Question 3(c) [7 marks]
#

Define: Thread. List different methods used to create Thread. Explain Thread life cycle in detail.

Answer:

Thread: Lightweight subprocess that allows concurrent execution of multiple parts of program.

Table: Thread Creation Methods

MethodDescriptionExample
Extending ThreadInherit Thread classclass MyThread extends Thread
Implementing RunnableImplement Runnable interfaceclass MyTask implements Runnable

Diagram: Thread Life Cycle

stateDiagram-v2
    [*] --> NEW
    NEW --> RUNNABLE : start()
    RUNNABLE --> RUNNING : CPU allocation
    RUNNING --> RUNNABLE : yield()
    RUNNING --> BLOCKED : wait()/sleep()
    BLOCKED --> RUNNABLE : notify()/interrupt()
    RUNNING --> TERMINATED : completion
    TERMINATED --> [*]

Table: Thread States

StateDescription
NEWThread created but not started
RUNNABLEReady to run, waiting for CPU
RUNNINGCurrently executing
BLOCKEDWaiting for resource or sleep
TERMINATEDExecution completed

Code Block:

// Method 1: Extending Thread
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}

// Method 2: Implementing Runnable
class MyTask implements Runnable {
    public void run() {
        System.out.println("Task running");
    }
}

class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        Thread t2 = new Thread(new MyTask());
        t1.start();
        t2.start();
    }
}

Mnemonic: “Thread Concurrent Execution”


Question 3(a OR) [3 marks]
#

Explain the purpose of JVM in java.

Answer:

JVM (Java Virtual Machine): Runtime environment that executes Java bytecode and provides platform independence.

Table: JVM Components

ComponentPurpose
Class LoaderLoads .class files into memory
Execution EngineExecutes bytecode
Memory AreaManages heap and stack memory
Garbage CollectorAutomatic memory management

Diagram:

JJ(BJ(a.ajy.VPSvjvatcMlpaaavelaevacatcSaCcosfio)o)dsofume)rirpmcci)eler
  • Platform Independence: “Write Once, Run Anywhere”
  • Memory Management: Automatic garbage collection
  • Security: Bytecode verification

Mnemonic: “JVM Java Virtual Machine”


Question 3(b OR) [4 marks]
#

Define: Package. Write the steps to create a Package with suitable example.

Answer:

Package: Collection of related classes and interfaces grouped together, providing namespace and access control.

Table: Package Benefits

BenefitDescription
NamespaceAvoid name conflicts
Access ControlBetter encapsulation
OrganizationLogical grouping
ReusabilityEasy to maintain

Steps to create Package:

  1. Declare package at top of file
  2. Create directory structure matching package name
  3. Compile with package structure
  4. Import in other classes

Code Block:

// File: com/company/utilities/Calculator.java
package com.company.utilities;

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

// File: Main.java
import com.company.utilities.Calculator;

class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 3));
    }
}

Directory Structure:

com/
  company/
    utilities/
      Calculator.class
Main.class

Mnemonic: “Package Groups Classes”


Question 3(c OR) [7 marks]
#

Explain Synchronization in Thread with suitable example.

Answer:

Synchronization: Mechanism to control access to shared resources by multiple threads to avoid data inconsistency.

Table: Synchronization Types

TypeDescriptionUsage
Synchronized methodEntire method lockedsynchronized void method()
Synchronized blockSpecific code block lockedsynchronized(object) { }
Static synchronizationClass level lockingsynchronized static void method()

Diagram: Without vs With Synchronization

graph LR
    subgraph "Without Sync"
        T1[Thread 1] --> R[Shared Resource]
        T2[Thread 2] --> R
        R --> C[Data Corruption]
    end
    
    subgraph "With Sync"
        T3[Thread 1] --> L[Lock]
        T4[Thread 2] --> W[Wait]
        L --> R2[Shared Resource]
        R2 --> S[Safe Access]
    end

Code Block:

class Counter {
    private int count = 0;
    
    // Synchronized method
    public synchronized void increment() {
        count++;
    }
    
    // Synchronized block
    public void decrement() {
        synchronized(this) {
            count--;
        }
    }
    
    public int getCount() {
        return count;
    }
}

class CounterThread extends Thread {
    Counter counter;
    
    CounterThread(Counter c) {
        counter = c;
    }
    
    public void run() {
        for(int i = 0; i < 1000; i++) {
            counter.increment();
        }
    }
}

class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter c = new Counter();
        CounterThread t1 = new CounterThread(c);
        CounterThread t2 = new CounterThread(c);
        
        t1.start();
        t2.start();
        
        t1.join();
        t2.join();
        
        System.out.println("Final count: " + c.getCount());
    }
}

Mnemonic: “Synchronization Prevents Race Conditions”


Question 4(a) [3 marks]
#

Differentiate between String class and StringBuffer class.

Answer:

Table: String vs StringBuffer

AspectStringStringBuffer
MutabilityImmutable (cannot change)Mutable (can change)
PerformanceSlower for concatenationFaster for concatenation
MemoryCreates new object each timeModifies existing object
Thread SafetyThread safeThread safe
Methodsconcat(), substring()append(), insert(), delete()

Code Block:

// String - Immutable
String s1 = "Hello";
s1 = s1 + " World";  // Creates new String object

// StringBuffer - Mutable
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");  // Modifies existing object
  • String: Use when content doesn’t change frequently
  • StringBuffer: Use when frequent modifications needed

Mnemonic: “String Immutable, StringBuffer Mutable”


Question 4(b) [4 marks]
#

Write a Java Program to find sum and average of 10 numbers of an array.

Answer:

Code Block:

class ArraySum {
    public static void main(String[] args) {
        // Initialize array with 10 numbers
        int[] numbers = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        
        int sum = 0;
        
        // Calculate sum
        for(int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        
        // Calculate average
        double average = (double) sum / numbers.length;
        
        // Display results
        System.out.println("Array elements: ");
        for(int num : numbers) {
            System.out.print(num + " ");
        }
        
        System.out.println("\nSum: " + sum);
        System.out.println("Average: " + average);
    }
}

Output:

Array elements: 10 20 30 40 50 60 70 80 90 100
Sum: 550
Average: 55.0

Logic Steps:

  1. Initialize array with 10 numbers
  2. Loop through array to calculate sum
  3. Calculate average = sum / length
  4. Display results

Mnemonic: “Loop Sum Divide Average”


Question 4(c) [7 marks]
#

I) Explain abstract class with suitable example. II) Explain final class with suitable example.

Answer:

I) Abstract Class: Class that cannot be instantiated, contains abstract methods that must be implemented by subclasses.

Table: Abstract Class Features

FeatureDescription
Cannot instantiateNo object creation
Abstract methodsMethods without implementation
Concrete methodsMethods with implementation
InheritanceSubclasses must implement abstract methods

Code Block - Abstract Class:

abstract class Shape {
    String color;
    
    // Abstract method
    abstract void draw();
    
    // Concrete method
    void setColor(String c) {
        color = c;
    }
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing Circle");
    }
}

class Main {
    public static void main(String[] args) {
        // Shape s = new Shape(); // Error: Cannot instantiate
        Circle c = new Circle();
        c.draw();
    }
}

II) Final Class: Class that cannot be extended (no inheritance allowed).

Table: Final Class Features

FeatureDescription
No inheritanceCannot be extended
SecurityPrevents modification
PerformanceBetter optimization
ExamplesString, Integer, System

Code Block - Final Class:

final class FinalClass {
    void display() {
        System.out.println("This is final class");
    }
}

// class SubClass extends FinalClass { } // Error: Cannot extend

class Main {
    public static void main(String[] args) {
        FinalClass obj = new FinalClass();
        obj.display();
    }
}

Mnemonic: “Abstract Incomplete, Final Complete”


Question 4(a OR) [3 marks]
#

Explain Garbage Collection in Java.

Answer:

Garbage Collection: Automatic memory management process that removes unused objects from heap memory.

Table: GC Benefits

BenefitDescription
AutomaticNo manual memory management
Memory leak preventionRemoves unreferenced objects
PerformanceOptimizes memory usage
SafetyPrevents memory errors

Diagram:

O(O(N(GrbnbhoeaejejalrmewesriboccegavtktrfigeeeebescyifrlrwneeeCoeornobaruecfljtdsneolee)ecsrecdectsGt)Co)r
  • When occurs: When heap memory is low or System.gc() called
  • Process: Mark and Sweep algorithm
  • Cannot guarantee: Exact timing of garbage collection

Mnemonic: “GC Automatic Memory Cleanup”


Question 4(b OR) [4 marks]
#

Write a Java program to handle user defined exception for ‘Divide by Zero’ error.

Answer:

Code Block:

// User defined exception class
class DivideByZeroException extends Exception {
    public DivideByZeroException(String message) {
        super(message);
    }
}

class Calculator {
    public static double divide(int a, int b) throws DivideByZeroException {
        if(b == 0) {
            throw new DivideByZeroException("Cannot divide by zero!");
        }
        return (double) a / b;
    }
}

class Main {
    public static void main(String[] args) {
        try {
            int num1 = 10;
            int num2 = 0;
            
            double result = Calculator.divide(num1, num2);
            System.out.println("Result: " + result);
            
        } catch(DivideByZeroException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Error: Cannot divide by zero!

Steps:

  1. Create custom exception class extending Exception
  2. Throw exception when condition occurs
  3. Handle exception with try-catch block

Mnemonic: “Custom Exception Handle Error”


Question 4(c OR) [7 marks]
#

Write a java program to demonstrate multiple try block and multiple catch block exception.

Answer:

Code Block:

class MultipleExceptionDemo {
    public static void main(String[] args) {
        // First try block
        try {
            int[] arr = {1, 2, 3};
            System.out.println("Array element: " + arr[5]); // ArrayIndexOutOfBounds
        } 
        catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index error: " + e.getMessage());
        }
        catch(Exception e) {
            System.out.println("General exception: " + e.getMessage());
        }
        
        // Second try block
        try {
            String str = null;
            System.out.println("String length: " + str.length()); // NullPointer
        }
        catch(NullPointerException e) {
            System.out.println("Null pointer error: " + e.getMessage());
        }
        
        // Third try block with multiple catch
        try {
            int a = 10;
            int b = 0;
            int result = a / b;  // ArithmeticException
            
            String s = "abc";
            int num = Integer.parseInt(s);  // NumberFormatException
        }
        catch(ArithmeticException e) {
            System.out.println("Arithmetic error: " + e.getMessage());
        }
        catch(NumberFormatException e) {
            System.out.println("Number format error: " + e.getMessage());
        }
        catch(Exception e) {
            System.out.println("Other error: " + e.getMessage());
        }
        finally {
            System.out.println("Program completed");
        }
    }
}

Output:

Array index error: Index 5 out of bounds for length 3
Null pointer error: null
Arithmetic error: / by zero
Program completed

Features demonstrated:

  • Multiple try blocks: Each handles different operations
  • Multiple catch blocks: Each handles specific exception type
  • Exception hierarchy: General Exception catches all
  • Finally block: Always executes

Mnemonic: “Multiple Try Multiple Catch”


Question 5(a) [3 marks]
#

Write a program in Java to create a file and perform write operation on this file.

Answer:

Code Block:

import java.io.*;

class FileWriteDemo {
    public static void main(String[] args) {
        try {
            // Create file
            File file = new File("demo.txt");
            
            // Create FileWriter object
            FileWriter writer = new FileWriter(file);
            
            // Write data to file
            writer.write("Hello World!\n");
            writer.write("This is Java file writing demo.\n");
            writer.write("File created successfully.");
            
            // Close the writer
            writer.close();
            
            System.out.println("File created and data written successfully!");
            
        } catch(IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Steps:

  1. Import java.io package
  2. Create File object with filename
  3. Create FileWriter object
  4. Write data using write() method
  5. Close writer to save changes

Mnemonic: “File Writer Write Close”


Question 5(b) [4 marks]
#

Explain throw and finally in Exception Handling with example.

Answer:

Throw: Keyword used to explicitly throw an exception. Finally: Block that always executes regardless of exception occurrence.

Table: Throw vs Finally

KeywordPurposeUsage
throwExplicitly throw exceptionthrow new Exception()
finallyAlways execute cleanup codefinally { }

Code Block:

class ThrowFinallyDemo {
    public static void checkAge(int age) throws Exception {
        if(age < 18) {
            throw new Exception("Age must be 18 or above");
        }
        System.out.println("Valid age: " + age);
    }
    
    public static void main(String[] args) {
        try {
            checkAge(15);  // Will throw exception
        }
        catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        finally {
            System.out.println("Finally block always executes");
        }
    }
}

Output:

Error: Age must be 18 or above
Finally block always executes
  • Throw: Forces exception to occur
  • Finally: Cleanup code, closes resources

Mnemonic: “Throw Exception, Finally Always”


Question 5(c) [7 marks]
#

Describe: Polymorphism. Explain run time polymorphism with suitable example in java.

Answer:

Polymorphism: One interface, multiple implementations. Object behaves differently based on its actual type.

Table: Polymorphism Types

TypeDescriptionWhen Decided
Compile-timeMethod overloadingAt compilation
Run-timeMethod overridingAt execution

Run-time Polymorphism: Method call resolved at runtime based on actual object type.

Diagram:

graph TD
    A[Animal reference] --> B[Dog object]
    A --> C[Cat object]
    B --> D[Dog sound]
    C --> E[Cat sound]

Code Block:

class Animal {
    void makeSound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

class Main {
    public static void main(String[] args) {
        Animal animal1 = new Dog();  // Upcasting
        Animal animal2 = new Cat();  // Upcasting
        
        animal1.makeSound();  // Output: Dog barks
        animal2.makeSound();  // Output: Cat meows
        
        // Array of animals
        Animal[] animals = {new Dog(), new Cat(), new Dog()};
        for(Animal a : animals) {
            a.makeSound();  // Dynamic method dispatch
        }
    }
}

Output:

Dog barks
Cat meows
Dog barks
Cat meows
Dog barks

Features:

  • Dynamic Method Dispatch: JVM decides which method to call at runtime
  • Upcasting: Child object referenced by parent reference
  • Flexibility: Same code works with different object types

Mnemonic: “Polymorphism Many Forms Runtime”


Question 5(a OR) [3 marks]
#

Write a program in Java that read the content of a file byte by byte and copy it into another file.

Answer:

Code Block:

import java.io.*;

class FileCopyDemo {
    public static void main(String[] args) {
        try {
            // Create input stream to read from source file
            FileInputStream input = new FileInputStream("source.txt");
            
            // Create output stream to write to destination file
            FileOutputStream output = new FileOutputStream("destination.txt");
            
            int byteData;
            
            // Read byte by byte and copy
            while((byteData = input.read()) != -1) {
                output.write(byteData);
            }
            
            // Close streams
            input.close();
            output.close();
            
            System.out.println("File copied successfully!");
            
        } catch(IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Steps:

  1. Create FileInputStream for reading
  2. Create FileOutputStream for writing
  3. Read byte by byte using read()
  4. Write each byte using write()
  5. Close both streams

Mnemonic: “Read Byte Write Byte”


Question 5(b OR) [4 marks]
#

Explain the different I/O Classes available with Java.

Answer:

Table: Java I/O Classes

Class TypeClass NamePurpose
Byte StreamFileInputStreamRead bytes from file
Byte StreamFileOutputStreamWrite bytes to file
Character StreamFileReaderRead characters from file
Character StreamFileWriterWrite characters to file
BufferedBufferedReaderEfficient character reading
BufferedBufferedWriterEfficient character writing

Diagram: I/O Class Hierarchy

OIuntppRWuuerttaiSSdttteerFBrFBrFBrFBeiueiuiuiualfalflflfmefmefefefIeOeReWenrurerrrpeteaeieudpdddtdtIuOeReWSnturerrtpStairutpdtetrueeaSetrrmtaSrmteraemam

Code Example:

// Byte streams
FileInputStream fis = new FileInputStream("file.txt");
FileOutputStream fos = new FileOutputStream("output.txt");

// Character streams
FileReader fr = new FileReader("file.txt");
FileWriter fw = new FileWriter("output.txt");

// Buffered streams
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));

Mnemonic: “Byte Character Buffered Streams”


Question 5(c OR) [7 marks]
#

Write a java program that executes two threads. One thread displays “Java Programming” every 3 seconds, and the other displays “Semester - 4th IT” every 6 seconds.(Create the threads by extending the Thread class)

Answer:

Code Block:

class JavaThread extends Thread {
    public void run() {
        try {
            while(true) {
                System.out.println("Java Programming");
                Thread.sleep(3000);  // Sleep for 3 seconds
            }
        } catch(InterruptedException e) {
            System.out.println("JavaThread interrupted");
        }
    }
}

class SemesterThread extends Thread {
    public void run() {
        try {
            while(true) {
                System.out.println("Semester - 4th IT");
                Thread.sleep(6000);  // Sleep for 6 seconds
            }
        } catch(InterruptedException e) {
            System.out.println("SemesterThread interrupted");
        }
    }
}

class Main {
    public static void main(String[] args) {
        // Create thread objects
        JavaThread javaThread = new JavaThread();
        SemesterThread semesterThread = new SemesterThread();
        
        // Start both threads
        javaThread.start();
        semesterThread.start();
        
        // Let threads run for 20 seconds then stop
        try {
            Thread.sleep(20000);
            javaThread.interrupt();
            semesterThread.interrupt();
        } catch(InterruptedException e) {
            System.out.println("Main thread interrupted");
        }
    }
}

Sample Output:

Java Programming
Semester - 4th IT
Java Programming
Java Programming
Semester - 4th IT
Java Programming
Java Programming
Semester - 4th IT
...

Features:

  • Two separate threads: Each with different timing
  • Thread.sleep(): Pauses execution for specified milliseconds
  • Concurrent execution: Both threads run simultaneously
  • Extending Thread class: Override run() method

Execution Pattern:

  • JavaThread: Displays every 3 seconds
  • SemesterThread: Displays every 6 seconds
  • Both run concurrently showing different timing

Mnemonic: “Two Threads Different Timing”

Related

Digital Communication (4341102) - Summer 2023 Solution
20 mins
Study-Material Solutions Digital-Communication 4341102 2023 Summer
Essentials of Digital Marketing (4341601) - Summer 2023 Solution
Study-Material Solutions Digital-Marketing 4341601 2023 Summer
Microprocessor and Microcontroller (4341101) - Summer 2023 Solution
23 mins
Study-Material Solutions Microprocessor 4341101 2023 Summer
Electronic Circuits & Applications (4321103) - Winter 2023 Solution
16 mins
Study-Material Solutions Electronics 4321103 2023 Winter
Principles of Electronic Communication (4331104) - Winter 2023 Solution
Study-Material Solutions Electronic-Communication 4331104 2023 Winter
Fundamentals of Electrical Engineering (4311101) - Winter 2023 Solution
12 mins
Study-Material Solutions Electrical-Engineering 4311101 2023 Winter