Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

OOP with java past gtu paper question with solutions, Study notes of Object Oriented Programming

OOP with java past gtu paper question with solutions

Typology: Study notes

2023/2024

Uploaded on 04/13/2025

roshni-raichandani
roshni-raichandani 🇮🇳

1 document

1 / 164

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
2020
Paper CO Question
S2020 1Q.1 (a) Explain JRE, JDK and JIT.
JRE (Java Runtime Environment)
JRE provides the environment required to run Java applications.
It includes the JVM (Java Virtual Machine), libraries, and other
components necessary to execute Java programs.
JRE does not include development tools like the compiler (javac).
JDK (Java Development Kit)
JDK is a complete software development kit for Java application
development.
It includes JRE + development tools like javac (Java compiler),
debugger, and other utilities.
Different versions of JDK are available, such as JDK 8, JDK 11, and
JDK 17 (LTS versions).
JIT (Just-In-Time Compiler)
JIT is a part of JVM that improves performance by compiling
bytecode into native machine code at runtime.
Instead of interpreting each line, JIT translates frequently
executed code into faster machine code.
This reduces execution time and improves efficiency.
S2020 1Q.1 (b) Explain static keyword with example.
Static Keyword in Java
The static keyword in Java is used for memory management. It can be
applied to variables, methods, blocks, and nested classes.
1. Static Variable
A static variable belongs to the class, not to any specific object.
It is shared among all objects of the class.
2. Static Method
A static method can be called without creating an object of the
class.
It can only access static variables and static methods directly.
3. Static Block
The static block is executed only once when the class is loaded
into memory.
Example Program
class StaticExample {
static int count = 0; // Static variable
// Static method
static void displayCount() {
System.out.println("Count: " + count);
}
// Constructor
StaticExample() {
count++;
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download OOP with java past gtu paper question with solutions and more Study notes Object Oriented Programming in PDF only on Docsity!

Paper CO Question

S2020 1 Q.1 (a) Explain JRE, JDK and JIT.

JRE (Java Runtime Environment)  JRE provides the environment required to run Java applications.  It includes the JVM (Java Virtual Machine) , libraries, and other components necessary to execute Java programs.  JRE does not include development tools like the compiler (javac). JDK (Java Development Kit)  JDK is a complete software development kit for Java application development.  It includes JRE + development tools like javac (Java compiler), debugger, and other utilities.  Different versions of JDK are available, such as JDK 8, JDK 11, and JDK 17 (LTS versions). JIT (Just-In-Time Compiler)  JIT is a part of JVM that improves performance by compiling bytecode into native machine code at runtime.  Instead of interpreting each line, JIT translates frequently executed code into faster machine code.  This reduces execution time and improves efficiency.

S2020 1 Q.1 (b) Explain static keyword with example.

Static Keyword in Java The static keyword in Java is used for memory management. It can be applied to variables, methods, blocks, and nested classes.

1. Static Variable  A static variable belongs to the class, not to any specific object.  It is shared among all objects of the class. 2. Static Method  A static method can be called without creating an object of the class.  It can only access static variables and static methods directly. 3. Static Block  The static block is executed only once when the class is loaded into memory. Example Program class StaticExample { static int count = 0; // Static variable // Static method static void displayCount() { System.out.println("Count: " + count); } // Constructor StaticExample() { count++;

// Static block static { System.out.println("Static block executed."); } public static void main(String[] args) { StaticExample obj1 = new StaticExample(); StaticExample obj2 = new StaticExample(); StaticExample.displayCount(); // Calling static method without object } } Output: Static block executed. Count: 2 Explanation:

  1. The static block runs when the class is first loaded.
  2. The static variable count is shared among all objects.
  3. The static method displayCount() is called without an object.

S2020 2 Q.1 (c) Explain inheritance with its types and give suitable

example.

Inheritance in Java

Inheritance is a fundamental concept in Object-Oriented

Programming (OOP) that allows one class to acquire the properties

and behaviors of another class. It promotes code reusability and

System.out.println("Model: " + model); } } // Main class public class InheritanceExample { public static void main(String[] args) { Car myCar = new Car(); myCar.showBrand(); // Accessing parent class method myCar.showDetails(); // Accessing child class method } }

Output:

Brand: Toyota Model: Corolla Key Benefits of Inheritance:

✔ Code reusability – Avoids redundant code.

✔ Improved maintainability – Changes in the parent class are

reflected in child classes.

✔ Supports hierarchical organization – Helps define relationships

between classes.

S2020,W

1 Q.2 (a) Compare object-oriented programming with sequential

programming

Q.1 (a) What is the difference between oop and procedural

oriented language?

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

Justification: main() is a public static method in Java

The main() method in Java is the entry point of any Java application.

Its declaration follows a specific syntax:

public static void main(String[] args)

Let’s break down why main() is declared as public , static , and void :

1. public – Accessible from anywhere

 The main() method must be accessible to the JVM (Java

Virtual Machine) to start program execution.

 If it were private or protected , the JVM wouldn't be able to

access it.

2. static – No need to create an object

 static means the method belongs to the class itself , not to

any object.

 This allows the JVM to call main() without creating an

object of the class.

 If main() were non-static , an instance of the class would be

required, leading to unnecessary complexity.

3. void – No return value

 The main() method does not return any value to the JVM.

 Since its purpose is to execute the program, returning a

value is unnecessary.

Example Program

class MainMethodExample {

public static void main(String[] args) {

System.out.println("Java program executed successfully!");

Output:

Java program executed successfully!

Conclusion

✔ public – So the JVM can access main().

✔ static – So main() can run without creating an object.

✔ void – Because main() does not return a value.

S2020 2 Q.2 (c) Write a program, which shows an example of function

overloading.

Command Line Argument

class CharCountSimple {

public static void main(String[] args) {

if (args.length == 0) {

System.out.println("Please provide a string as a command-

line argument.");

return;

String input = args[0];

for (char ch = 'a'; ch <= 'z'; ch++) {

int count = 0;

for (char c : input.toCharArray()) {

if (c == ch) count++;

if (count > 0) System.out.println(ch + " : " + count);

How to Run the Program?

javac CharCountSimple.java

java CharCountSimple HelloWorld

Sample Output

Input: "hello"

e : 1

h : 1

l : 2

o : 1

Explanation

1. Takes the input string from command-line arguments

(args[0]).

2. Iterates through lowercase letters ('a' to 'z') and counts

occurrences in the string.

3. Prints only characters that appear in the string.

S2020 2 Q.3 (a) Write difference between String class and StringBuffer

class.

Difference Between String and StringBuffer Class in Java

String Class StringBuffer Class

Mutability Immutable (cannot be

changed after creation)

Mutable (can be

modified without

creating a new

object)

Performance Slower when performing

multiple modifications

(creates new objects)

Faster for string

modifications

(modifies existing

object)

Memory

Usage

High (creates new objects

for every modification)

Low (modifies the

same object)

Thread

Safety

No built-in

synchronization

Synchronized

(thread-safe)

Usage When few modifications

are needed

When frequent

modifications are

required

Example: String vs StringBuffer

public class StringVsStringBuffer {

public static void main(String[] args) {

// Using String (Immutable)

String str = "Hello";

str = str + " World"; // Creates a new object

System.out.println("String: " + str);

// Using StringBuffer (Mutable)

StringBuffer sb = new StringBuffer("Hello");

sb.append(" World"); // Modifies existing object

System.out.println("StringBuffer: " + sb);

Output:

String: Hello World

StringBuffer: Hello Worl

S2020 2 Q.3 (b) Explain super keyword with example

Explanation of super Keyword in Java

The super keyword in Java is used to refer to the parent class. It is

mainly used for:

1. Calling the parent class constructor

2. Accessing parent class methods

3. Accessing parent class variables

Example: Using super in Java

class Parent {

String name = "Parent Class";

this.height = h; } void area() { System.out.println("Triangle Area: " + (0.5 * base * height)); } } // Subclass Rectangle class Rectangle extends Shape { double length, width; Rectangle(double l, double w) { this.length = l; this.width = w; } void area() { System.out.println("Rectangle Area: " + (length * width)); } } // Subclass Circle class Circle extends Shape { double radius; Circle(double r) { this.radius = r; } void area() { System.out.println("Circle Area: " + (Math.PI * radius * radius)); } } // Main class public class ShapeDemo { public static void main(String[] args) { Shape t = new Triangle(5, 10); Shape r = new Rectangle(4, 6); Shape c = new Circle(7); t.area(); r.area(); c.area(); } } Output Triangle Area: 25. Rectangle Area: 24. Circle Area: 153. Explanation

  1. Shape is an abstract class with an abstract method area().
  2. Triangle, Rectangle, and Circle inherit Shape and override area().
  1. Objects are created using the parent class reference (Shape).
  2. Each subclass calculates its respective area.

S2020 2 Q.3 (a) How can we protect sub class to override the method of

super class? Explain with example.

How to Prevent Method Overriding in a Subclass?

In Java, we can prevent a subclass from overriding a method of the

superclass by using the final keyword.

When a method is declared as final, it cannot be overridden in any

subclass.

Example: Preventing Overriding with final

class Parent {

final void show() { // final method cannot be overridden

System.out.println("This is a final method in the Parent class.");

class Child extends Parent {

// Uncommenting below will cause an error

// void show() {

// System.out.println("Trying to override final method.");

public class FinalMethodExample {

public static void main(String[] args) {

Child obj = new Child();

obj.show();

Output

This is a final method in the Parent class.

Key Points

✔ Using final on a method prevents overriding in subclasses.

✔ If we try to override, the compiler will give an error.

✔ This ensures that critical methods remain unchanged in

subclasses.

S2020 2 Q.3 (b) Define Interface and explain how it differs from the class.

Definition of Interface in Java An interface in Java is a blueprint of a class that contains only abstract

inheritance.

S2020 2 Q.3 (c) What do you mean by run time polymorphism? Write a

program to demonstrate run time polymorphism.

What is Run-Time Polymorphism? Run-time polymorphism in Java occurs when a method is overridden in a subclass and the method to be executed is determined at run time based on the object’s reference. This is achieved using method overriding and dynamic method dispatch. Key Features of Run-Time PolymorphismAchieved through method overriding (same method name, different behavior in child class)Uses parent class reference to call overridden method in child classDecided at run-time, not compile-time Java Program Demonstrating Run-Time Polymorphism // Parent class class Animal { void makeSound() { // Method to be overridden System.out.println("Animal makes a sound"); } } // Child class 1 class Dog extends Animal { void makeSound() { // Overriding method System.out.println("Dog barks"); } } // Child class 2 class Cat extends Animal { void makeSound() { // Overriding method System.out.println("Cat meows"); } } // Main class public class RuntimePolymorphismExample { public static void main(String[] args) { Animal a; // Parent class reference a = new Dog(); // Dog object a.makeSound(); // Calls Dog's method a = new Cat(); // Cat object a.makeSound(); // Calls Cat's method } }

Output Dog barks Cat meows Explanation

  1. The method makeSound() is defined in the parent class (Animal).
  2. It is overridden in child classes (Dog and Cat).
  3. At runtime, the method execution depends on the object assigned to Animal reference.

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

Difference Between Text I/O and Binary I/O in Java Feature Text I/O Binary I/O Data Format Stores data as human- readable text (characters) Stores data in raw binary format (bytes) Classes Used Uses FileReader, FileWriter, BufferedReader, PrintWriter Uses FileInputStream, FileOutputStream, DataInputStream, DataOutputStream File Size Larger, as text encoding (like UTF-8) is used Smaller, as it stores data in compact binary format Performa nce Slower because of encoding/decoding Faster as no conversion is needed Usage Used for text-based files (.txt, .csv, .json) Used for images, audio, video, and object files (.jpg, .mp3, .dat) Example of Text I/O import java.io.; public class TextIOExample { public static void main(String[] args) throws IOException { FileWriter writer = new FileWriter("textfile.txt"); writer.write("Hello, World!"); writer.close(); } } Example of Binary I/O import java.io.; public class BinaryIOExample { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("binaryfile.dat"); fos.write(65); // Writing a single byte (ASCII of 'A') fos.close(); } }

S2020 3 Q.4 (c) What is an Exception? List out various built-in exceptions in

JAVA and explain any one Exception class with suitable example.

What is an Exception in Java? An exception in Java is an unexpected event that occurs during the execution of a program and disrupts the normal flow of the program. Exceptions typically occur due to:  Invalid user input  Dividing by zero  Accessing an array element out of bounds  Attempting to open a file that does not exist  Network connectivity failures Java provides a built-in mechanism to handle such errors and prevent the program from crashing. This is done using exception handling techniques. Types of Exceptions in Java

1. Checked Exceptions (Compile-time Exceptions) These exceptions must be handled using try-catch or declared using throws, otherwise the program will not compile. They occur due to external factors like file handling or database operations. Examples:  IOException (File not found, read/write error)  SQLException (Database access issues)  ClassNotFoundException (Class not found in runtime) 2. Unchecked Exceptions (Runtime Exceptions) These exceptions occur due to logical programming errors and do not need to be handled explicitly. The program will compile but fail at runtime if not handled properly. Examples:  ArithmeticException (Dividing by zero)  NullPointerException (Accessing a null object)  ArrayIndexOutOfBoundsException (Accessing an invalid array index)  NumberFormatException (Invalid conversion of string to a number) 3. Errors (Serious Issues) Errors are not exceptions but critical problems that cannot be recovered from. They indicate issues that should not be handled by normal exception handling techniques. Examples:  StackOverflowError (Infinite recursion)  OutOfMemoryError (Insufficient memory)  VirtualMachineError (JVM internal error) Common Built-in Exceptions in Java Exception Name Description ArithmeticException Occurs when dividing by zero NullPointerException Occurs when accessing an object reference that is null

ArrayIndexOutOfBoundsException Occurs when trying to access an index outside the array range FileNotFoundException Occurs when a file does not exist IOException General Input/Output exception NumberFormatException Occurs when converting an invalid string to a number ClassNotFoundException Occurs when JVM cannot find the specified class Explaining ArithmeticException with Example The ArithmeticException occurs when a mathematical operation is not allowed , such as dividing by zero. Example: Handling Divide by Zero using try-catch public class ArithmeticExceptionExample { public static void main(String[] args) { try { int num1 = 10; int num2 = 0; int result = num1 / num2; // This will cause an exception System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero!"); } } } Output Error: Cannot divide by zero! Explanation of Code

  1. Inside the try block , we attempt to divide num1 by num2 (which is zero).
  2. Since division by zero is not allowed , Java throws an ArithmeticException.
  3. The catch block catches this exception and prints a meaningful error message instead of crashing the program. How to Handle Exceptions in Java? Java provides 5 key keywords for exception handling:
  4. try – Defines the block of code where an exception may occur.
  5. catch – Defines the block to handle the exception if it occurs.
  6. finally – Defines a block that always executes, even if an exception occurs.
  7. throw – Used to manually throw an exception.
  8. throws – Declares an exception that a method might throw. Example: Handling Multiple Exceptions public class MultipleExceptions { public static void main(String[] args) { try { int[] arr = {1, 2, 3};

(like Integer, String, etc.).  data is a variable of type T.  The constructor initializes data, and getData() returns the value of data. Example: Using a Generic Class public class GenericExample { public static void main(String[] args) { GenericClass intObj = new GenericClass<>(10); // Integer type GenericClass strObj = new GenericClass<>("Hello"); // String type System.out.println("Integer Value: " + intObj.getData()); System.out.println("String Value: " + strObj.getData()); } } 🔹 Output: Integer Value: 10 String Value: Hello Why Use Generics?

  1. Code Reusability – The same class works with different data types.
  2. Type Safety – Prevents runtime errors by ensuring type consistency at compile time.
  3. Eliminates Type Casting – No need to cast objects manually.

S2020 4 Q.4 (b) Write a JAVA program to read student.txt file and display

the content.

Java Program to Read and Display Content of student.txt File This program reads the content of a file named student.txt using FileReader and BufferedReader , then displays its content on the console. Java Code: import java.io.*; public class ReadStudentFile { public static void main(String[] args) { try { // Open the file for reading FileReader fileReader = new FileReader("student.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; System.out.println("Contents of student.txt:"); // Read and display the file content line by line while ((line = bufferedReader.readLine()) != null) { System.out.println(line); }

// Close the reader bufferedReader.close(); } catch (FileNotFoundException e) { System.out.println("File not found! Please check if 'student.txt' exists."); } catch (IOException e) { System.out.println("Error reading the file."); } } } Explanation:

  1. FileReader and BufferedReader are used to read the file efficiently.
  2. The program reads the file line by line using readLine().
  3. Exception Handling : o If the file is not found , a message is displayed. o If there's an I/O error , it is handled gracefully. Sample Content of student.txt ID: 101, Name: Alice, Grade: A ID: 102, Name: Bob, Grade: B ID: 103, Name: Charlie, Grade: A Expected Output (if student.txt exists) Contents of student.txt: ID: 101, Name: Alice, Grade: A ID: 102, Name: Bob, Grade: B ID: 103, Name: Charlie, Grade: A

S2020 3 Q.4 (c) Explain Thread life cycle in detail. Write a program to create

a child thread to print integer numbers 1 to 10.

Thread Life Cycle in Java A thread in Java goes through different stages in its life cycle. The Thread Life Cycle consists of the following states:

1. New (Created) State  A thread is in the new state when it is created but not yet started.  It is created using the Thread class but has not been executed using start().  Example: Thread t = new Thread(); 2. Runnable State  When the start() method is called, the thread enters the runnable