GTU Object Oriented Programming - I (Java) Summer 2020 PYQ with solutions

Download Question Paper : click here

Q.1

(a) Explain JRE, JDK and JIT.

  • JRE stands for Java Runtime Environment. It is a software package that is used to run Java applications on a computer. It includes the Java Virtual Machine (JVM), and other components required to run Java programs
  • JDK stands for Java Development Kit. It is a software package that includes the JRE and additional tools and libraries for developing Java applications.
  • JIT stands for Just-In-Time compiler. The JIT compiler compiles the Java bytecode into machine code at runtime, which can significantly improve the speed of execution

(b) Explain static keyword with example

The static keyword is used to create a variable or method that belongs to the class itself, rather than to any instance of the class. This means that a static variable or method can be accessed directly from the class name, without needing to create an object of the class.

public class Example {
  public static int count = 0;
  public Example() {
    count++;
  }
}

In this example, we have a class called 'Example' that contains a static variable called 'count'. Every time a new instance of the 'Example' class is created, the constructor increments the value of 'count'. Because 'count' is a static variable, it belongs to the class itself and not to any particular instance of the class. This means that we can access the 'count' variable directly from the class name, like this:

int totalInstances = Example.count;

Here's an example of a static method:

public class Example {
  public static void printMessage() {
    System.out.println("This is a static method");
  }
}

In this example, we have a class called 'Example' that contains a static method called 'printMessage()'. Because the method is static, it can be called directly from the class name, like this:

Example.printMessage();

Static variables and methods can be useful when you want to create a value or behavior that is shared by all instances of a class.

(c) Explain inheritance with its types and give suitable example

Inheritance is a fundamental concept in object-oriented programming, where a new class is created from an existing class by inheriting the properties and methods of the parent class. The new class is called a derived or subclass, and the existing class is called a base or superclass. In Java, inheritance is achieved using the extends keyword. The syntax for creating a subclass is as follows:

class Subclass extends Superclass {
    // subclass members
}

There are several types of inheritance in Java:

  1. Single inheritance: where a subclass extends a single superclass.
  2. Multilevel inheritance: where a subclass extends another subclass, creating a chain of inheritance.
  3. Hierarchical inheritance: where multiple subclasses extend a single superclass.
  4. Multiple inheritance: where a subclass extends multiple superclasses (not supported in Java, but can be achieved using interfaces).
  • Single inheritance:
class Shape {
public void draw() {
System.out.println("Drawing shape...");
}
}

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

public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.draw(); // Output: "Drawing rectangle..."
}
}
  • Multilevel inheritance:
class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}

class Mammal extends Animal {
public void walk() {
System.out.println("The mammal is walking.");
}
}

class Cat extends Mammal {
public void meow() {
System.out.println("Meow!");
}
}

public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.eat(); // Output: "The animal is eating."
cat.walk(); // Output: "The mammal is walking."
cat.meow(); // Output: "Meow!"
}
}
  • Hierarchical inheritance:
class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}

class Dog extends Animal {
    public void bark() {
        System.out.println("Woof!");
    }
}

class Cat extends Animal {
    public void meow() {
        System.out.println("Meow!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        dog.eat(); // Output: "The animal is eating."
        dog.bark(); // Output: "Woof!"
        cat.eat(); // Output: "The animal is eating."
        cat.meow(); // Output: "Meow!"
    }
}
  • Multiple inheritance using interfaces:
interface Drawable {
public void draw();
}

interface Movable {
public void move();
}

class Rectangle implements Drawable, Movable {
public void draw() {
System.out.println("Drawing rectangle...");
}
public void move() {
System.out.println("Moving rectangle...");
}
}

public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.draw(); // Output: "Drawing rectangle..."
rectangle.move(); // Output: "Moving rectangle..."
}
}

Q.2

(a) Compare object-oriented programming with sequential programming

Featureobject-oriented programmingsequential programming
Program DesignProgram is designed around objects that interact with each other to perform a specific taskProgram is divided into smaller tasks or procedures and each task is executed in order
Data HandlingData and behaviors are encapsulated into objects which communicate with each other to perform tasksData and functions are separated and operate independently
Code ReusabilityCode can be reused through inheritance and polymorphismCode has to be rewritten if required in other parts of the program
InheritanceNew classes can be created by inheriting properties and behaviors from existing classesNo concept of inheritance
ExamplesJava, Python, C++C, Fortran, Basic

(b) Method main is a public static method. Justify

The ‘main’ method is a public static method because it is the entry point of the program, which means that it is the first method that is called when the program is executed.

public is used to make the main method accessible to other classes in the same package or even in other packages, so that the JVM can find and execute the main method.

static is used to indicate that the main method belongs to the class itself and not to any instance of the class. This means that the main method can be called without creating an instance of the class.

So, the combination of public and static in the main method signature ensures that the method can be called by the JVM and other classes, without the need to create an instance of the class. This is necessary for the main method to serve as the entry point of the program.

Example -

public class MainExample {
    public static void main(String[] args) {
        // This is the main method
        System.out.println("Hello, World!");
    }
}

(c) Write a program, which shows an example of function overloading. Also, differentiate between function overloading and overriding.

Example program that demonstrates function overloading -

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

    public static double add(double a, double b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(add(1, 2)); // prints 3
        System.out.println(add(1.5, 2.5)); // prints 4.0
    }
}

In this example, we have defined two methods with the same name add, but with different parameter types. The first method add takes two integer parameters, and the second method add takes two double parameters. This is an example of function overloading.

When we call the add method with integer arguments, the first add method is called and when we call the add method with double arguments, the second add method is called.

Difference between function overloading and overriding:

Function OverloadingFunction Overriding
SyntaxMultiple methods with the same name, but different parameters or return types.A subclass provides a new implementation for an existing method in a superclass.
UsageUsed when we need multiple methods with the same name, but different parameters or return types.Used when we need to provide a new implementation for a method that is already defined in a superclass.
VisibilityCan occur within a single class or across different classes.Occurs only in subclasses that inherit from a superclass.
ScopeOccurs at compile-time.Occurs at runtime.
ParametersParameters must differ in number, type, or order.Parameters must match in number, type, and order.
Return typeReturn type can differ.Return type must be the same as, or a subtype of, the superclass method's return type.
InheritanceNot related to inheritance.Related to inheritance.

Function overloading and function overriding are two different techniques in Java that allow developers to write more flexible and reusable code. Function overloading is used when we need multiple methods with the same name, but different parameters or return types, while function overriding is used when we need to provide a new implementation for a method that is already defined in a superclass.

OR

(c) Write a program to take string input as command line argument. In addition, count occurrence of each character in a given string.

public class CharacterCount {
    public static void main(String[] args) {
        if(args.length == 0) {
            System.out.println("Please provide a string input as command-line argument");
            return;
        }

        String input = args[0];
        int[] count = new int[256];

        for(int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            count[ch]++;
        }

        System.out.println("Character count:");
        for(int i = 0; i < count.length; i++) {
            if(count[i] != 0) {
                System.out.println((char)i + " = " + count[i]);
            }
        }
    }
}

In this program, we first check if any command-line arguments have been provided. If not, we print an error message and exit. Otherwise, we take the first command-line argument as the input string.

We then create an integer array count of size 256, which will store the count of each character. We iterate over each character in the input string and increment the count of that character in the count array. Finally, we iterate over the count array and print the count of each non-zero index, along with the corresponding character.

For example, if we run the program with the command java CharacterCount "hello world", the output will be:

Character count:
 = 1
d = 1
e = 1
h = 1
l = 3
o = 2
r = 1
w = 1

Q.3

(a) Write difference between String class and StringBuffer class

String ClassStringBuffer Class
MutabilityImmutableMutable
PerformanceLess efficient for frequent modificationsMore efficient for frequent modifications
MethodsContains methods for manipulation and comparison of stringsContains methods for manipulation and modification of string buffers
OperationsLimited to string operationsSupports both string and buffer operations
MemoryString objects are stored in a string pool, which can improve memory efficiencyStringBuffer objects are not stored in a pool and can use more memory

(b) Explain super keyword with example.

The super keyword is used to refer to the parent class of a subclass. It can be used to call a method or a constructor from the parent class, or to access a variable or method that is defined in the parent class.

Here is an example of how the super keyword can be used in Java:

class Parent {
    int x = 5;

    public void printX() {
        System.out.println("x = " + x);
    }
}

class Child extends Parent {
    int x = 10;

    public void printX() {
        super.printX(); // calling the printX() method of the Parent class
        System.out.println("x = " + x); // printing the value of x in the Child class
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child();
        child.printX(); // output: x = 5, x = 10
    }
}

The Child class overrides the printX() method of the Parent class and calls the printX() method of the Parent class using the super keyword. This ensures that the value of x in the Parent class is also printed.

(c) Describe abstract class called Shape, which has three subclasses say Triangle, Rectangle, and Circle. Define one method area() in the abstract class and override this area() in these three subclasses to calculate for specific object i.e. area() of Triangle subclass should calculate area of triangle likewise for Rectangle and Circle.

abstract class Shape {
    abstract double area();
}

class Triangle extends Shape {
    double base, height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    double area() {
        return 0.5 * base * height;
    }
}

class Rectangle extends Shape {
    double length, width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    double area() {
        return length * width;
    }
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    double area() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape s1 = new Triangle(10, 5);
        System.out.println("Area of Triangle: " + s1.area()); // output: 25.0

        Shape s2 = new Rectangle(6, 4);
        System.out.println("Area of Rectangle: " + s2.area()); // output: 24.0

        Shape s3 = new Circle(3);
        System.out.println("Area of Circle: " + s3.area()); // output: 28.274333882308138
    }
}

We have defined three subclasses of Shape - Triangle, Rectangle, and Circle. Each of these subclasses implements its own area() method to calculate the area of a specific shape - triangle, rectangle, or circle.

OR

Q.3 (a) How can we protect sub class to override the method of super class? Explain with example.

We can prevent a subclass from overriding a method of its superclass by using the final keyword.

If we mark a method in the superclass as final, the subclass will not be able to override that method.

Here's an example:

public class Animal {
    public final void makeSound() {
        System.out.println("The animal makes a sound.");
    }
}

public class Dog extends Animal {
    // This will result in a compile-time error because makeSound() in Animal is final
    public void makeSound() {
        System.out.println("The dog barks.");
    }
}

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

(b) Define Interface and explain how it differs from the class.

InterfaceClass
DefinitionA collection of abstract methods and constants that can be implemented by a classA blueprint or template for creating objects that contain data and methods
InheritanceCan extend multiple interfacesCan extend only one class and can implement multiple interfaces
ImplementationCannot be instantiated directlyCan be instantiated using the new keyword
ConstructorsCannot have constructorsCan have constructors
MethodsCan contain only abstract or default methodsCan contain any type of method
PolymorphismCan be used to achieve polymorphismCan also be used to achieve polymorphism

(c) What do you mean by run time polymorphism? Write a program to demonstrate run time polymorphism.

Runtime polymorphism, also known as dynamic polymorphism, is a mechanism in Java where a call to an overridden method is resolved at runtime, rather than at compile-time. This allows a subclass to provide its own implementation of a method that is already defined in its superclass, and to use that implementation when the method is called on an object of the subclass.

Here's an example program that demonstrates runtime polymorphism in Java:

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

class Dog extends Animal {
    public void makeSound() {
        System.out.println("The dog barks");
    }
}

class Cat extends Animal {
    public void makeSound() {
        System.out.println("The cat meows");
    }
}

public class PolymorphismExample {
    public static void main(String[] args) {
        Animal animal1 = new Animal();
        Animal animal2 = new Dog();
        Animal animal3 = new Cat();

        animal1.makeSound();
        animal2.makeSound();
        animal3.makeSound();
    }
}

In this example, we have an Animal class with a makeSound() method that prints "The animal makes a sound". We also have two subclasses of Animal called Dog and Cat, each with their own implementation of the makeSound() method.

In the main() method, we create three objects: one of type Animal, one of type Dog, and one of type Cat. We then call the makeSound() method on each of these objects. Because the makeSound() method is overridden in the Dog and Cat classes, the specific implementation of the method for each subclass is used when the method is called on an object of that subclass. This is an example of runtime polymorphism, where the implementation of the method that is executed is determined at runtime based on the actual type of the object.

Q.4

(a) Differentiate between Text I/O and Binary I/O.

FeatureText I/OBinary I/O
Data representationASCII or UnicodeBinary format
ReadabilityHuman-readableNot human-readable
Data sizeLarger than binary dataSmaller than text data
EfficiencyLess efficient than binary I/OMore efficient than text I/O
PortabilityMore portable between platformsLess portable between platforms

(b) Explain ArrayList class.

ArrayList is a class that implements the List interface and provides a dynamic array that can grow or shrink as needed. It is a resizable array implementation that provides better flexibility and efficiency than traditional arrays.

Here are some important features of the ArrayList class:

  1. Dynamic sizing: The size of an ArrayList can be dynamically increased or decreased as elements are added or removed from the list.
  2. Random access: The elements in an ArrayList can be accessed randomly using an index, similar to a traditional array.
  3. Methods: The ArrayList class provides many methods to manipulate its elements, such as add(), remove(), clear(), size(), get(), set(), indexOf(), contains(), and more.

Here's an example of how to create an ArrayList and add elements to it:

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        // Create an ArrayList of integers
        ArrayList<Integer> numbers = new ArrayList<Integer>();

        // Add elements to the list
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        // Print the elements of the list
        System.out.println("Numbers: " + numbers);
    }
}

(c) What is an Exception? List out various built-in exceptions in JAVA and explain any one Exception class with suitable example.

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It is an error condition that can arise during the program's execution and must be handled appropriately to prevent the program from crashing.

There are many built-in exception classes in Java that are provided by the Java API. Some of the commonly used ones include:

  1. ArithmeticException - thrown when an arithmetic operation produces an error, such as division by zero.
  2. NullPointerException - thrown when a null reference is used in a program.
  3. ArrayIndexOutOfBoundsException - thrown when an array index is out of bounds.
  4. ClassCastException - thrown when an object is cast to an incompatible class.
  5. IllegalArgumentException - thrown when an illegal argument is passed to a method.
  6. IOException - thrown when an I/O operation fails.

Let's take an example of the IOException class to understand how exceptions work in Java. The IOException class is a checked exception that is thrown when an input or output operation fails. This can occur, for example, when trying to read from a file that doesn't exist, or when writing to a file that is read-only.

Here's an example that demonstrates how to handle an IOException when reading from a file:

import java.io.*;

public class Example {
    public static void main(String[] args) {
        try {
            // Open the file
            FileReader file = new FileReader("input.txt");

            // Read the contents of the file
            int ch;
            while ((ch = file.read()) != -1) {
                System.out.print((char) ch);
            }

            // Close the file
            file.close();
        } catch (IOException e) {
            // Handle the exception
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}

In this example, we are attempting to read the contents of a file called "input.txt". However, if the file doesn't exist or there is an error while reading it, an IOException will be thrown.

OR

Q.4

(a) How do you declare a generic type in a class? Explain.

To declare a generic type in a class, you need to use the angle brackets "<>" followed by the type parameter name. Here is an example:

public class MyGenericClass<T> {
    private T myValue;

    public MyGenericClass(T value) {
        myValue = value;
    }

    public T getValue() {
        return myValue;
    }

    public void setValue(T value) {
        myValue = value;
    }
}

By using a generic type parameter, the class can work with any type of object without specifying the type explicitly. The type is determined at the time of instantiation of the class.

(b) Write a JAVA program to read student.txt file and display the content.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadStudentFile {
    public static void main(String[] args) {
        String fileName = "student.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;

            while ((line = br.readLine()) != null) {
                String[] fields = line.split(",");
                String name = fields[0];
                String rollNumber = fields[1];
                String grade = fields[2];

                System.out.printf("Name: %s, Roll Number: %s, Grade: %s\n", name, rollNumber, grade);
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

(c) Explain Thread life cycle in detail. Write a program to create a child thread to print integer numbers 1 to 10.

Thread lifecycle represents the various states that a thread goes through during its lifetime. In Java, the thread lifecycle consists of six states: New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated.

https://www.scientecheasy.com/wp-content/uploads/2020/06/thread-life-cycle.png

  1. New: When a thread is created, it is in the new state. The thread is not yet scheduled for execution and has not started running.
  2. Runnable: When the thread scheduler selects the thread to run, it enters the runnable state. The thread is now eligible to run but may not be currently executing due to other threads running on the CPU.
  3. Blocked: If a thread is waiting for a monitor lock or a resource held by another thread, it enters the blocked state. The thread is temporarily suspended until the lock is available.
  4. Waiting: When a thread is waiting for some condition to occur, it enters the waiting state. A waiting thread can be notified to wake up by another thread.
  5. Timed Waiting: When a thread waits for a certain amount of time, it enters the timed waiting state. A timed waiting thread can be notified to wake up by another thread or it can wake up automatically when the time expires.
  6. Terminated: When a thread completes its execution, it enters the terminated state.

Here's an example program to create a child thread to print integer numbers 1 to 10:

public class ChildThread extends Thread {
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        ChildThread childThread = new ChildThread();
        childThread.start();
    }
}

Q.5

(a) Explain in brief: Color class and its methods

  • The Color class in Java is used to work with colors in graphical user interfaces.
  • It provides a range of static and non-static methods to create, manipulate and compare color objects.
  • Some commonly used methods in Color class include getRed(), getGreen(), getBlue(), which return the red, green, and blue components of a color, and getRGB(), which returns the RGB value of a color.
import java.awt.Color;
import javax.swing.JFrame;

public class ColorExample {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Color Example");
    Color color = new Color(255, 0, 0); // Creates a red color object using RGB values
    frame.getContentPane().setBackground(color); // Sets the background color of the frame
    frame.setSize(400, 400);
    frame.setVisible(true);
  }
}

(b) What method do you use to obtain an element in the collection from an iterator? Explain with example.

To obtain an element in a collection from an iterator, you can use the next() method of the Iterator interface. The next() method returns the next element in the collection and advances the iterator to the next position.

Here's an example that demonstrates how to use an iterator to obtain elements from an ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("John");
        names.add("Jane");
        names.add("Bob");

        Iterator<String> it = names.iterator();
        while (it.hasNext()) {
            String name = it.next();
            System.out.println(name);
        }
    }
}

Output -

John
Jane
Bob

(c) Enlist various layout panes and explain any two in detail.

In JavaFX, layout panes are used to arrange the nodes or controls in the scene graph. Some of the commonly used layout panes in JavaFX are:

  1. BorderPane
  2. FlowPane
  3. GridPane
  4. HBox
  5. VBox
  6. StackPane
  7. AnchorPane

Two of the commonly used layout panes are explained below in detail:

  • BorderPane: The BorderPane layout pane divides the scene graph into five regions: top, bottom, left, right, and center. Each region can contain a single node or control. The center region is the largest and expands to fill the available space. The other regions can have a fixed width or height.

Example:

BorderPane borderPane = new BorderPane();
Button button1 = new Button("Top");
Button button2 = new Button("Bottom");
Button button3 = new Button("Left");
Button button4 = new Button("Right");
Button button5 = new Button("Center");

borderPane.setTop(button1);
borderPane.setBottom(button2);
borderPane.setLeft(button3);
borderPane.setRight(button4);
borderPane.setCenter(button5);
  • GridPane: The GridPane layout pane divides the scene graph into a grid of rows and columns. Each cell of the grid can contain a single node or control. The size of each cell can be fixed or can be based on the size of its content. The GridPane layout pane is useful for creating forms or tables.
GridPane gridPane = new GridPane();
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
Button button3 = new Button("Button 3");

gridPane.add(button1, 0, 0);
gridPane.add(button2, 1, 0);
gridPane.add(button3, 0, 1, 2, 1);

OR

Q.5

(a) Compare Set and List interfaces.

Set and List are two interfaces in Java that are used to store and manipulate collections of objects. The main differences between Set and List are as follows:

  1. Duplicate elements: Set does not allow duplicate elements, while List allows duplicate elements.
  2. Ordering: Set does not maintain any order of elements, while List maintains the order of elements based on their insertion.
  3. Accessing elements: In Set, elements are accessed using their value, while in List, elements are accessed using their index.

(b) Write importance of JAVAFX compare to AWT and Swing.

JavaFX is a modern UI toolkit for Java applications that provides a rich set of visual and interactive components. It has several advantages over AWT and Swing, including:

  1. Richer User Interface: JavaFX provides a rich set of UI components that are visually appealing and can be customized to fit the specific needs of the application. It supports advanced features such as animations, 3D graphics, and multimedia.
  2. Improved Performance: JavaFX is designed to take advantage of modern hardware acceleration and can provide better performance than AWT and Swing for complex and graphics-intensive applications.
  3. Cross-Platform Compatibility: JavaFX applications can run on a variety of platforms, including Windows, Mac, Linux, and mobile devices.
  4. Separation of UI and Logic: JavaFX follows the Model-View-Controller (MVC) architecture, which separates the user interface (view) from the application logic (model). This separation makes it easier to maintain and update the application.

(c) How do you create a Scene object? How do you set a scene in a stage? Is it possible to create multiple scenes? Write a program to place a circle in the scene and fill circle with red color.

To create a Scene object, you need to pass the root node and the size of the scene as parameters to its constructor. The root node is typically a layout pane or a parent node that contains other nodes. Here's an example:

Pane root = new Pane();
Scene scene = new Scene(root, 400, 400);

To set a scene in a stage, you can use the setScene() method of the Stage class. Here's an example:

Stage primaryStage = new Stage();
primaryStage.setScene(scene);

Yes, it is possible to create multiple scenes and switch between them. Here's an example:

Pane root1 = new Pane();
Scene scene1 = new Scene(root1, 400, 400);

Pane root2 = new Pane();
Scene scene2 = new Scene(root2, 400, 400);

primaryStage.setScene(scene1);
primaryStage.show();

// later, switch to scene2
primaryStage.setScene(scene2);

To place a circle in the scene and fill it with red color, you can use the Circle class and the setFill() method of the Shape class. Here's an example:

Circle circle = new Circle(200, 200, 50);
circle.setFill(Color.RED);
root.getChildren().add(circle);

This creates a circle with center at (200, 200) and radius 50, sets its fill color to red, and adds it to the root pane of the scene.